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
Dynamic topology core: local split/collapse/flip/relax under the brush with mirrored operations, editable adjacency, incremental BVH edits, slot-level undo; tests
islandmedea16d56f00ea
diff --git a/CMakeLists.txt b/CMakeLists.txtindex 3b2e654a..1ebdf4b2 100644--- a/CMakeLists.txt+++ b/CMakeLists.txt@@ -33,6 +33,7 @@ add_library(sculptforge_core STATICsrc/core/UploadOrder.cppsrc/core/Benchmark.cppsrc/core/Sculpt.cpp+ src/core/Dyntopo.cppsrc/core/Undo.cppsrc/core/Primitives.cppsrc/core/Document.cppdiff --git a/src/core/BVH.cpp b/src/core/BVH.cppindex f5eb9fe9..1606f291 100644--- a/src/core/BVH.cpp+++ b/src/core/BVH.cpp@@ -57,6 +57,10 @@ bool rayTriangle(const glm::vec3& o, const glm::vec3& d, const glm::vec3& a, convoid BVH::build(const Mesh& mesh) {const size_t nt = mesh.triangleCount();nodes_.clear();+ std::vector<uint32_t>().swap(leafCap_);+ editedLeaves_.clear();+ leafEdited_.clear();+ unusedEntries_ = editsSinceBuild_ = 0;triIndices_.resize(nt);triLeaf_.assign(nt, 0);vertBits_.resize(mesh.vertexCount());@@ -207,7 +211,7 @@ bool BVH::raycast(const Mesh& mesh, const glm::vec3& origin, const glm::vec3& difound = true;}}- } else {+ } else if (n.first != kNoLeaf) { // (kNoLeaf: a leaf dynamic edits emptied)stack_.push_back(n.first);stack_.push_back(n.first + 1);}@@ -243,7 +247,7 @@ void BVH::queryTriangles(const Mesh& mesh, const glm::vec3& center, float radiusb.expand(mesh.positions[t.z]);if (sphereBox(b, center, r2)) out.push_back(triIndices_[i]);}- } else {+ } else if (n.first != kNoLeaf) {stack_.push_back(n.first);stack_.push_back(n.first + 1);}@@ -269,7 +273,7 @@ void BVH::queryVertices(const Mesh& mesh, const glm::vec3& center, float radius,queryNext_.clear();for (uint32_t ni : tasks) {const Node& n = nodes_[ni];- if (n.count > 0) {+ if (n.count > 0 || n.first == kNoLeaf) {queryNext_.push_back(ni);continue;}@@ -287,7 +291,7 @@ void BVH::queryVertices(const Mesh& mesh, const glm::vec3& center, float radius,const uint32_t ni = nodeStack.back();const Node& n = nodes_[ni];nodeStack.pop_back();- if (!sphereBox(n.box, center, r2)) continue;+ if (!sphereBox(n.box, center, r2) || (n.count == 0 && n.first == kNoLeaf)) continue;if (n.count == 0) {nodeStack.push_back(n.first);nodeStack.push_back(n.first + 1);@@ -376,9 +380,154 @@ void BVH::refitLeaves(const Mesh& mesh, std::span<const uint32_t> leaves) {}}+void BVH::editLeaf(uint32_t leaf) {+ if (leafCap_.size() < nodes_.size()) { // the first edit: every leaf full+ const size_t from = leafCap_.size();+ leafCap_.resize(nodes_.size());+ for (size_t i = from; i < nodes_.size(); ++i) leafCap_[i] = nodes_[i].count;+ }+ if (leafEdited_.size() < nodes_.size()) leafEdited_.resize(nodes_.size(), 0);+ if (!leafEdited_[leaf]) {+ leafEdited_[leaf] = 1;+ editedLeaves_.push_back(leaf);+ }+ ++editsSinceBuild_;+}++void BVH::insertTriangle(const Mesh& mesh, uint32_t t, uint32_t near) {+ if (nodes_.empty()) {+ nodes_.push_back(Node{AABB{}, kNoLeaf, 0, 0});+ leafBits_.resize(nodes_.size());+ }+ uint32_t leaf = near < triLeaf_.size() ? triLeaf_[near] : kNoLeaf;+ if (leaf == kNoLeaf) { // down the tree towards the triangle's centroid+ const glm::uvec3& tri = mesh.triangles[t];+ const glm::vec3 c = (mesh.positions[tri.x] + mesh.positions[tri.y] + mesh.positions[tri.z]) / 3.0f;+ leaf = 0;+ while (nodes_[leaf].count == 0 && nodes_[leaf].first != kNoLeaf) {+ const Node& n = nodes_[leaf];+ auto dist = [&](const AABB& b) {+ if (!b.valid()) return std::numeric_limits<float>::max();+ const glm::vec3 d = glm::max(glm::max(b.min - c, c - b.max), glm::vec3(0.0f));+ return glm::dot(d, d);+ };+ leaf = dist(nodes_[n.first].box) <= dist(nodes_[n.first + 1].box) ? n.first : n.first + 1;+ }+ }+ editLeaf(leaf);+ Node& n = nodes_[leaf];+ if (n.count == leafCap_[leaf]) { // full: move the leaf's entries to the end, with room to grow+ const uint32_t cap = std::max(2 * n.count, kLeafSize);+ const uint32_t first = uint32_t(triIndices_.size());+ triIndices_.resize(triIndices_.size() + cap);+ if (n.count > 0) std::copy_n(triIndices_.begin() + n.first, n.count, triIndices_.begin() + first);+ unusedEntries_ += leafCap_[leaf];+ n.first = first;+ leafCap_[leaf] = cap;+ }+ triIndices_[n.first + n.count++] = t;+ if (t >= triLeaf_.size()) triLeaf_.resize(size_t(t) + 1, kNoLeaf);+ triLeaf_[t] = leaf;+}++void BVH::removeTriangle(uint32_t t) {+ const uint32_t leaf = t < triLeaf_.size() ? triLeaf_[t] : kNoLeaf;+ if (leaf == kNoLeaf) return;+ editLeaf(leaf);+ Node& n = nodes_[leaf];+ for (uint32_t i = n.first; i < n.first + n.count; ++i)+ if (triIndices_[i] == t) {+ triIndices_[i] = triIndices_[n.first + n.count - 1];+ --n.count;+ break;+ }+ if (n.count == 0) { // an empty leaf is marked so traversals don't take it for an inner node+ unusedEntries_ += leafCap_[leaf];+ n.first = kNoLeaf;+ leafCap_[leaf] = 0;+ }+ triLeaf_[t] = kNoLeaf;+}++void BVH::renumberTriangle(uint32_t from, uint32_t to) {+ const uint32_t leaf = from < triLeaf_.size() ? triLeaf_[from] : kNoLeaf;+ if (leaf == kNoLeaf) return;+ const Node& n = nodes_[leaf];+ for (uint32_t i = n.first; i < n.first + n.count; ++i)+ if (triIndices_[i] == from) triIndices_[i] = to;+ if (to >= triLeaf_.size()) triLeaf_.resize(size_t(to) + 1, kNoLeaf);+ triLeaf_[to] = leaf;+ triLeaf_[from] = kNoLeaf;+}++void BVH::resizeTriangles(size_t count) { triLeaf_.resize(count, kNoLeaf); }++void BVH::touchTriangle(uint32_t t) {+ if (t < triLeaf_.size() && triLeaf_[t] != kNoLeaf) editLeaf(triLeaf_[t]);+}++// Splits an overfull leaf at the median centroid along its longest axis: its two halves become new leaves+// (appended, so children still follow their parents), each keeping its part of the leaf's room.+void BVH::splitLeaf(const Mesh& mesh, uint32_t leaf) {+ const uint32_t first = nodes_[leaf].first, count = nodes_[leaf].count;+ auto centroid = [&](uint32_t t) {+ const glm::uvec3& tri = mesh.triangles[t];+ return mesh.positions[tri.x] + mesh.positions[tri.y] + mesh.positions[tri.z];+ };+ AABB cb;+ for (uint32_t i = first; i < first + count; ++i) cb.expand(centroid(triIndices_[i]));+ const glm::vec3 ext = cb.extent();+ const int axis = ext.x > ext.y ? (ext.x > ext.z ? 0 : 2) : (ext.y > ext.z ? 1 : 2);+ if (ext[axis] <= 0.0f) return;+ const uint32_t mid = first + count / 2;+ std::nth_element(triIndices_.begin() + first, triIndices_.begin() + mid, triIndices_.begin() + first + count,+ [&](uint32_t a, uint32_t b) { return centroid(a)[axis] < centroid(b)[axis]; });+ const uint32_t left = uint32_t(nodes_.size()), cap = leafCap_[leaf];+ nodes_.push_back(Node{AABB{}, first, mid - first, leaf});+ nodes_.push_back(Node{AABB{}, mid, first + count - mid, leaf});+ leafCap_.push_back(mid - first);+ leafCap_.push_back(cap - (mid - first));+ leafEdited_.resize(nodes_.size(), 0);+ nodes_[leaf].first = left;+ nodes_[leaf].count = 0;+ leafCap_[leaf] = 0;+ for (uint32_t c : {left, left + 1}) {+ recomputeLeaf(mesh, nodes_[c]);+ AABB box = nodes_[c].box;+ for (uint32_t ni = c; ni != 0;) { // the ancestors hold it (as they held the leaf), but grow them anyway+ ni = nodes_[ni].parent;+ nodes_[ni].box.expand(box);+ box = nodes_[ni].box;+ }+ }+ leafBits_.resize(nodes_.size());+}++void BVH::refitChanged(const Mesh& mesh) {+ constexpr uint32_t kMaxLeaf = 3 * kLeafSize;+ scratchLeaves_.clear();+ for (uint32_t leaf : editedLeaves_) {+ leafEdited_[leaf] = 0;+ if (nodes_[leaf].count > 0) recomputeLeaf(mesh, nodes_[leaf]);+ else nodes_[leaf].box = AABB();+ scratchLeaves_.push_back(leaf);+ }+ editedLeaves_.clear();+ // (refitLeaves recomputes the boxes again: cheap for a few leaves, and it grows the ancestors.)+ refitLeaves(mesh, scratchLeaves_);+ for (uint32_t leaf : scratchLeaves_)+ if (nodes_[leaf].count > kMaxLeaf) splitLeaf(mesh, leaf);+}++bool BVH::degraded() const {+ // Rebuild once the edits rival the tree: boxes only grow, and moved leaves leave entries unused.+ const size_t live = triLeaf_.size();+ return unusedEntries_ > live / 2 + 1024 || editsSinceBuild_ > live + 4096;+}+size_t BVH::memoryBytes() const {auto bytes = [](const auto& v) { return v.capacity() * sizeof(v[0]); };- return bytes(nodes_) + bytes(triIndices_) + bytes(triLeaf_) + vertBits_.memoryBytes() + leafBits_.memoryBytes() ++ return bytes(nodes_) + bytes(triIndices_) + bytes(triLeaf_) + bytes(leafCap_) + bytes(editedLeaves_) + bytes(leafEdited_) + vertBits_.memoryBytes() + leafBits_.memoryBytes() +bytes(queryLeaves_) + bytes(scratchLeaves_) + bytes(stack_);}@@ -387,6 +536,8 @@ void BVH::refitAll(const Mesh& mesh) {Node& n = nodes_[i];if (n.count > 0) {recomputeLeaf(mesh, n);+ } else if (n.first == kNoLeaf) {+ n.box = AABB();} else {n.box = nodes_[n.first].box;n.box.expand(nodes_[n.first + 1].box);diff --git a/src/core/BVH.h b/src/core/BVH.hindex ac155476..69f4469b 100644--- a/src/core/BVH.h+++ b/src/core/BVH.h@@ -2,7 +2,6 @@// SPDX-License-Identifier: GPL-3.0-or-later#pragma once-#include "core/IndexBits.h"#include "core/IndexBits.h"#include "core/Mesh.h"@@ -43,6 +42,21 @@ public:// Recomputes every box (same tree) after most of the mesh moved, e.g. a whole SubTool transformed.void refitAll(const Mesh& mesh);+ // Dynamic topology (core/Dyntopo.h): a few triangles at a time added, removed or renumbered without a+ // rebuild. insertTriangle puts triangle t (a new last index, or one removeTriangle freed) in the leaf of+ // triangle `near` (or, if that isn't in the tree, the leaf its centroid falls in); refitChanged() then+ // recomputes the boxes of every leaf edited since the last call (growing ancestors, as refit does) and+ // splits leaves that grew too big. Boxes only grow, so after many edits rebuild when degraded() says so.+ void insertTriangle(const Mesh& mesh, uint32_t t, uint32_t near);+ void removeTriangle(uint32_t t);+ // Triangle `from` is now numbered `to` (a free index); a freed last index can then be dropped with resizeTriangles.+ void renumberTriangle(uint32_t from, uint32_t to);+ void resizeTriangles(size_t count);+ // Marks the leaf holding t for refitChanged (its triangle moved).+ void touchTriangle(uint32_t t);+ void refitChanged(const Mesh& mesh);+ bool degraded() const;+size_t nodeCount() const { return nodes_.size(); }size_t memoryBytes() const;@@ -61,6 +75,16 @@ private:std::vector<uint32_t> triIndices_;std::vector<uint32_t> triLeaf_;+ // Dynamic edits: per node the room its leaf has in triIndices_ (empty until the first edit), the leaves+ // edited since refitChanged (each once, flagged in leafEdited_), and how many entries of triIndices_ are no+ // longer used (leaves that moved to make room) or were added since the build.+ std::vector<uint32_t> leafCap_, editedLeaves_;+ std::vector<uint8_t> leafEdited_;+ size_t unusedEntries_ = 0, editsSinceBuild_ = 0;+ static constexpr uint32_t kNoLeaf = ~0u;+ void editLeaf(uint32_t leaf);+ void splitLeaf(const Mesh& mesh, uint32_t leaf);+mutable IndexBits vertBits_; // queryVertices: the vertices found so farmutable std::vector<uint32_t> queryLeaves_; // the leaves holding them, for refitQueried()mutable std::vector<uint32_t> queryTasks_, queryNext_;diff --git a/src/core/Dyntopo.cpp b/src/core/Dyntopo.cppnew file mode 100644index 00000000..e7ca0c59--- /dev/null+++ b/src/core/Dyntopo.cpp@@ -0,0 +1,1193 @@+// SculptForge - open source digital sculpting+// SPDX-License-Identifier: GPL-3.0-or-later+#include "core/Dyntopo.h"++#include <algorithm>+#include <chrono>+#include <cmath>+#include <limits>++namespace sf {++namespace {++constexpr uint32_t kNone = ~0u;++// Calls f(meshArray, storedArray) for every per-vertex array of `m` an undo keeps (normals are recomputed).+template <class F>+void zipVertexArrays(Mesh& m, TopologyVertexValues& v, F&& f) {+ f(m.positions, v.positions);+ f(m.mask, v.mask);+ f(m.colors, v.colors);+ f(m.base, v.base);+ f(m.paintBase, v.paintBase);+ v.deltas.resize(m.layers.size());+ for (size_t i = 0; i < m.layers.size(); ++i) f(m.layers[i].delta, v.deltas[i]);+ v.paintColors.resize(m.paintLayers.size());+ v.paintAlphas.resize(m.paintLayers.size());+ for (size_t i = 0; i < m.paintLayers.size(); ++i) {+ f(m.paintLayers[i].color, v.paintColors[i]);+ f(m.paintLayers[i].alpha, v.paintAlphas[i]);+ }+}++template <class F>+void zipTriangleArrays(Mesh& m, TopologyTriangleValues& t, F&& f) {+ f(m.triangles, t.triangles);+ f(m.polygroups, t.polygroups);+ f(m.quadPartners, t.quadPartners);+ f(m.hidden, t.hidden);+}++// Calls f(array) for every per-vertex array of `m` (normals included).+template <class F>+void forVertexArrays(Mesh& m, F&& f) {+ f(m.positions);+ f(m.normals);+ f(m.mask);+ f(m.colors);+ f(m.base);+ f(m.paintBase);+ for (auto& l : m.layers) f(l.delta);+ for (auto& l : m.paintLayers) {+ f(l.color);+ f(l.alpha);+ }+}++template <class F>+void forTriangleArrays(Mesh& m, F&& f) {+ f(m.triangles);+ f(m.polygroups);+ f(m.quadPartners);+ f(m.hidden);+}++// Exchanges the values of `a` at `slots` with `stored` (the values of another state at the slots below+// `count`, in slot order) and resizes `a` to `count`. Absent arrays stay absent.+template <class T>+void swapSlots(std::vector<T>& a, const std::vector<uint32_t>& slots, std::vector<T>& stored, size_t count) {+ if (a.empty()) return;+ std::vector<T> current;+ current.reserve(slots.size());+ for (uint32_t s : slots)+ if (s < a.size()) current.push_back(a[s]);+ a.resize(count);+ size_t k = 0;+ for (uint32_t s : slots)+ if (s < count && k < stored.size()) a[s] = stored[k++];+ stored.swap(current);+}++template <class T>+size_t bytesOf(const std::vector<T>& v) {+ return v.size() * sizeof(T);+}++bool setBit(std::vector<uint64_t>& bits, uint32_t i) {+ if (size_t(i >> 6) >= bits.size()) bits.resize(size_t(i >> 6) + 1 + bits.size() / 4, 0);+ const uint64_t b = uint64_t(1) << (i & 63);+ if (bits[i >> 6] & b) return false;+ bits[i >> 6] |= b;+ return true;+}++float quality(const glm::vec3& a, const glm::vec3& b, const glm::vec3& c) {+ // 1 for an equilateral triangle, 0 for a degenerate one.+ const float area2 = glm::length(glm::cross(b - a, c - a));+ const float sum = glm::dot(b - a, b - a) + glm::dot(c - b, c - b) + glm::dot(a - c, a - c);+ return sum > 0.0f ? 3.4641016f * area2 / sum : 0.0f; // 4 sqrt(3) * area / sum, area = area2 / 2+}++} // namespace++float dyntopoEdgeLength(const DyntopoSettings& s, float radius, float diagonal) {+ const float d = std::clamp(s.detail, 0.0f, 1.0f);+ if (s.constantDetail) return std::max(diagonal, 1e-6f) * 0.05f * std::pow(0.04f, d); // diag/20 .. diag/500+ return std::max(radius, 1e-7f) * 0.4f * std::pow(0.1f, d); // 0.4 .. 0.04 x the radius+}++std::string dyntopoBlocker(const Mesh& mesh) {+ if (mesh.multires || mesh.implicitAdjacency())+ return "Dynamic topology needs a mesh without subdivision levels: delete the lower (or higher) levels first";+ if (mesh.triangleCount() == 0) return "The mesh has no triangles";+ return {};+}++size_t TopologyVertexValues::bytes() const {+ size_t n = bytesOf(positions) + bytesOf(colors) + bytesOf(base) + bytesOf(paintBase) + bytesOf(mask);+ for (const auto& d : deltas) n += bytesOf(d);+ for (const auto& d : paintColors) n += bytesOf(d);+ for (const auto& d : paintAlphas) n += bytesOf(d);+ return n;+}++size_t TopologyTriangleValues::bytes() const {+ return bytesOf(triangles) + bytesOf(polygroups) + bytesOf(quadPartners) + bytesOf(hidden);+}++size_t TopologyUndo::bytes() const {+ return vertices.bytes() + triangles.bytes() + bytesOf(vertexSlots) + bytesOf(triangleSlots) + bytesOf(uvs);+}++void TopologyUndo::swapWith(Mesh& mesh) {+ const uint32_t nv = uint32_t(mesh.vertexCount()), nt = uint32_t(mesh.triangleCount());+ zipVertexArrays(mesh, vertices, [&](auto& a, auto& stored) { swapSlots(a, vertexSlots, stored, vertexCount); });+ zipTriangleArrays(mesh, triangles, [&](auto& a, auto& stored) { swapSlots(a, triangleSlots, stored, triangleCount); });+ mesh.normals.resize(vertexCount, glm::vec3(0.0f, 1.0f, 0.0f));+ std::swap(uvs, mesh.uvs);+ vertexCount = nv;+ triangleCount = nt;+}++// ---------------------------------------------------------------------------+// Recording and elements+// ---------------------------------------------------------------------------++void DynamicTopology::recordVertex(uint32_t v) {+ if (!setBit(vertRec_, v)) return;+ undo_->vertexSlots.push_back(v);+ recordedNow_.push_back(v);+ if (v < startVertices_)+ zipVertexArrays(*mesh_, undo_->vertices, [&](auto& a, auto& stored) {+ if (!a.empty()) stored.push_back(a[v]);+ });+}++void DynamicTopology::recordTriangle(uint32_t t) {+ if (!setBit(triRec_, t)) return;+ undo_->triangleSlots.push_back(t);+ if (t < startTriangles_)+ zipTriangleArrays(*mesh_, undo_->triangles, [&](auto& a, auto& stored) {+ if (!a.empty()) stored.push_back(a[t]);+ });+}++void DynamicTopology::markVertex(uint32_t v) {+ if (v >= changedVFlag_.size()) changedVFlag_.resize(size_t(v) + 1, 0);+ if (changedVFlag_[v]) return;+ changedVFlag_[v] = 1;+ changedV_.push_back(v);+}++void DynamicTopology::markTriangle(uint32_t t) { changedT_.push_back(t); }++uint32_t DynamicTopology::newVertex() {+ Mesh& m = *mesh_;+ if (!freeV_.empty()) {+ const uint32_t v = freeV_.back();+ freeV_.pop_back();+ deadV_[v] = 0;+ return v; // (recorded when it died)+ }+ const uint32_t v = uint32_t(m.vertexCount());+ recordVertex(v);+ forVertexArrays(m, [&](auto& a) {+ if (!a.empty()) a.emplace_back();+ });+ m.normals.resize(m.positions.size(), glm::vec3(0.0f, 1.0f, 0.0f)); // (a mesh without normals gets them)+ m.addVertexSlot();+ deadV_.push_back(0);+ return v;+}++void DynamicTopology::interpolateVertex(uint32_t v, uint32_t a, uint32_t b, float t, const glm::vec3& position) {+ Mesh& m = *mesh_;+ recordVertex(v);+ forVertexArrays(m, [&](auto& arr) {+ if (!arr.empty()) arr[v] = arr[a] + (arr[b] - arr[a]) * t;+ });+ m.positions[v] = position;+ const glm::vec3 n = m.normals[v];+ const float len = glm::length(n);+ m.normals[v] = len > 1e-20f ? n / len : glm::vec3(0.0f, 1.0f, 0.0f);+ markVertex(v);+}++void DynamicTopology::killVertex(uint32_t v) {+ recordVertex(v);+ deadV_[v] = 1;+ freeV_.push_back(v);+ mesh_->setVertexTriangles(v, {});+ mesh_->setNeighbors(v, {});+ for (size_t k = 0; k < mirrorMaps_.size(); ++k) {+ auto it = mirrorMaps_[k].find(v);+ if (it == mirrorMaps_[k].end()) continue;+ const uint32_t w = it->second;+ mirrorMaps_[k].erase(it);+ auto back = mirrorMaps_[k].find(w);+ if (back != mirrorMaps_[k].end() && back->second == v) mirrorMaps_[k].erase(back);+ }+}++void DynamicTopology::vtInsert(uint32_t v, uint32_t t) {+ const IndexRing r = mesh_->vertexTriangles(v);+ scratch_.assign(r.begin(), r.end());+ scratch_.insert(std::upper_bound(scratch_.begin(), scratch_.end(), t), t);+ mesh_->setVertexTriangles(v, scratch_);+}++void DynamicTopology::vtErase(uint32_t v, uint32_t t) {+ const IndexRing r = mesh_->vertexTriangles(v);+ scratch_.assign(r.begin(), r.end());+ auto it = std::lower_bound(scratch_.begin(), scratch_.end(), t);+ if (it == scratch_.end() || *it != t) return;+ scratch_.erase(it);+ mesh_->setVertexTriangles(v, scratch_);+}++void DynamicTopology::vtReplace(uint32_t v, uint32_t from, uint32_t to) {+ const IndexRing r = mesh_->vertexTriangles(v);+ scratch_.assign(r.begin(), r.end());+ auto it = std::lower_bound(scratch_.begin(), scratch_.end(), from);+ if (it != scratch_.end() && *it == from) scratch_.erase(it);+ scratch_.insert(std::upper_bound(scratch_.begin(), scratch_.end(), to), to);+ mesh_->setVertexTriangles(v, scratch_);+}++void DynamicTopology::unpairQuad(uint32_t t) {+ Mesh& m = *mesh_;+ if (m.quadPartners.empty() || t >= m.quadPartners.size()) return;+ const uint32_t p = m.quadPartners[t];+ if (p == Mesh::kNoQuad) return;+ recordTriangle(t);+ m.quadPartners[t] = Mesh::kNoQuad;+ if (p < m.quadPartners.size() && m.quadPartners[p] == t) {+ recordTriangle(p);+ m.quadPartners[p] = Mesh::kNoQuad;+ markTriangle(p); // its wireframe now shows the old diagonal+ }+}++uint32_t DynamicTopology::newTriangle(const glm::uvec3& tri, uint32_t like) {+ Mesh& m = *mesh_;+ uint32_t t;+ if (!freeT_.empty()) {+ t = freeT_.back();+ freeT_.pop_back();+ deadT_[t] = 0;+ } else {+ t = uint32_t(m.triangleCount());+ recordTriangle(t);+ forTriangleArrays(m, [&](auto& a) {+ if (!a.empty()) a.emplace_back();+ });+ deadT_.push_back(0);+ }+ recordTriangle(t);+ m.triangles[t] = tri;+ if (!m.polygroups.empty()) m.polygroups[t] = m.polygroups[like];+ if (!m.hidden.empty()) m.hidden[t] = m.hidden[like];+ if (!m.quadPartners.empty()) m.quadPartners[t] = Mesh::kNoQuad;+ for (int c = 0; c < 3; ++c) {+ vtInsert(tri[c], t);+ markVertex(tri[c]);+ }+ bvh_->insertTriangle(m, t, like);+ markTriangle(t);+ return t;+}++void DynamicTopology::setTriangle(uint32_t t, const glm::uvec3& tri) {+ Mesh& m = *mesh_;+ recordTriangle(t);+ unpairQuad(t);+ const glm::uvec3 old = m.triangles[t];+ auto has = [](const glm::uvec3& x, uint32_t v) { return x.x == v || x.y == v || x.z == v; };+ for (int c = 0; c < 3; ++c) {+ if (!has(tri, old[c])) vtErase(old[c], t);+ markVertex(old[c]);+ }+ for (int c = 0; c < 3; ++c) {+ if (!has(old, tri[c])) vtInsert(tri[c], t);+ markVertex(tri[c]);+ }+ m.triangles[t] = tri;+ bvh_->touchTriangle(t);+ markTriangle(t);+}++void DynamicTopology::killTriangle(uint32_t t) {+ Mesh& m = *mesh_;+ recordTriangle(t);+ unpairQuad(t);+ const glm::uvec3 tri = m.triangles[t];+ for (int c = 0; c < 3; ++c) {+ vtErase(tri[c], t);+ markVertex(tri[c]);+ }+ bvh_->removeTriangle(t);+ deadT_[t] = 1;+ freeT_.push_back(t);+ markTriangle(t);+}++void DynamicTopology::moveTriangle(uint32_t from, uint32_t to) {+ Mesh& m = *mesh_;+ recordTriangle(to);+ recordTriangle(from);+ forTriangleArrays(m, [&](auto& a) {+ if (!a.empty()) a[to] = a[from];+ });+ if (!m.quadPartners.empty()) {+ const uint32_t p = m.quadPartners[to];+ if (p != Mesh::kNoQuad && p < m.quadPartners.size() && m.quadPartners[p] == from) {+ recordTriangle(p);+ m.quadPartners[p] = to;+ }+ }+ const glm::uvec3 tri = m.triangles[to];+ for (int c = 0; c < 3; ++c) vtReplace(tri[c], from, to);+ bvh_->renumberTriangle(from, to);+ markTriangle(to);+ markTriangle(from);+}++void DynamicTopology::moveVertex(uint32_t from, uint32_t to) {+ Mesh& m = *mesh_;+ recordVertex(to);+ recordVertex(from);+ forVertexArrays(m, [&](auto& a) {+ if (!a.empty()) a[to] = a[from];+ });+ const IndexRing tr = m.vertexTriangles(from);+ scratch2_.assign(tr.begin(), tr.end());+ m.setVertexTriangles(to, scratch2_);+ for (uint32_t t : scratch2_) {+ recordTriangle(t);+ glm::uvec3& tri = m.triangles[t];+ for (int c = 0; c < 3; ++c) {+ if (tri[c] == from) tri[c] = to;+ else markVertex(tri[c]); // its ring names `from`+ }+ markTriangle(t);+ }+ m.setVertexTriangles(from, {});+ markVertex(to);+ moved_.emplace_back(from, to);+}++// Fills the slots this remesh freed with the elements at the end of the arrays, so the mesh has no dead+// entries; then drops the end.+void DynamicTopology::compact() {+ Mesh& m = *mesh_;+ std::sort(freeT_.begin(), freeT_.end());+ size_t nt = m.triangleCount();+ for (uint32_t t : freeT_) {+ while (nt > 0 && deadT_[nt - 1]) --nt;+ if (t >= nt) break;+ moveTriangle(uint32_t(nt - 1), t);+ deadT_[t] = 0;+ --nt;+ }+ forTriangleArrays(m, [&](auto& a) {+ if (!a.empty()) a.resize(nt);+ });+ bvh_->resizeTriangles(nt);+ deadT_.assign(nt, 0);+ freeT_.clear();++ std::sort(freeV_.begin(), freeV_.end());+ const size_t before = m.vertexCount();+ size_t nv = before;+ for (uint32_t v : freeV_) {+ while (nv > 0 && deadV_[nv - 1]) --nv;+ if (v >= nv) break;+ moveVertex(uint32_t(nv - 1), v);+ deadV_[v] = 0;+ --nv;+ }+ forVertexArrays(m, [&](auto& a) {+ if (!a.empty()) a.resize(nv);+ });+ for (size_t i = nv; i < before; ++i) m.removeLastVertexSlot();+ deadV_.assign(nv, 0);+ freeV_.clear();+}++// ---------------------------------------------------------------------------+// Queries+// ---------------------------------------------------------------------------++int DynamicTopology::edgeTriangles(uint32_t a, uint32_t b, uint32_t* out) const {+ int n = 0;+ for (uint32_t t : mesh_->vertexTriangles(a)) {+ const glm::uvec3& tri = mesh_->triangles[t];+ if (tri.x == b || tri.y == b || tri.z == b) {+ if (n < 4) out[n] = t;+ ++n;+ }+ }+ return n;+}++void DynamicTopology::ring(uint32_t v, std::vector<uint32_t>& out) const {+ out.clear();+ for (uint32_t t : mesh_->vertexTriangles(v)) {+ const glm::uvec3& tri = mesh_->triangles[t];+ for (int c = 0; c < 3; ++c)+ if (tri[c] != v) out.push_back(tri[c]);+ }+ std::sort(out.begin(), out.end());+ out.erase(std::unique(out.begin(), out.end()), out.end());+}++float DynamicTopology::len2(uint32_t a, uint32_t b) const {+ const glm::vec3 d = mesh_->positions[a] - mesh_->positions[b];+ return glm::dot(d, d);+}++// The edge passes within the brush radius of the dab's centre.+bool DynamicTopology::inside(uint32_t a, uint32_t b) const {+ const glm::vec3 p = mesh_->positions[a], d = mesh_->positions[b] - p;+ const float dd = glm::dot(d, d);+ const float t = dd > 0.0f ? std::clamp(glm::dot(center_ - p, d) / dd, 0.0f, 1.0f) : 0.0f;+ const glm::vec3 q = p + d * t - center_;+ return glm::dot(q, q) <= radius_ * radius_;+}++// Left alone: fully masked, next to a hidden triangle, on a non-manifold edge, or without triangles.+bool DynamicTopology::locked(uint32_t v) const {+ const Mesh& m = *mesh_;+ if (deadV_[v]) return true;+ if (m.maskAt(v) >= 1.0f - 1e-4f) return true;+ const IndexRing tris = m.vertexTriangles(v);+ if (tris.empty()) return true;+ if (m.hasHidden())+ for (uint32_t t : tris)+ if (m.hidden[t]) return true;+ // Each neighbour shares one (boundary) or two triangles with v; more is non-manifold.+ uint32_t count[64], other[64];+ int n = 0;+ for (uint32_t t : tris) {+ const glm::uvec3& tri = m.triangles[t];+ for (int c = 0; c < 3; ++c) {+ if (tri[c] == v) continue;+ int i = 0;+ while (i < n && other[i] != tri[c]) ++i;+ if (i == n) {+ if (n == 64) return true;+ other[n] = tri[c];+ count[n++] = 0;+ }+ if (++count[i] > 2) return true;+ }+ }+ return false;+}++bool DynamicTopology::planeVertex(uint32_t v) const {+ for (size_t k = 0; k < mirrorMaps_.size(); ++k)+ if (mirrorOf(k, v) == v) return true;+ return false;+}++// Boundary, polygroup border, non-manifold, or lying in a symmetry plane.+bool DynamicTopology::featureEdge(uint32_t a, uint32_t b) const {+ uint32_t tris[4];+ const int n = edgeTriangles(a, b, tris);+ if (n != 2) return true;+ if (mesh_->polygroupAt(tris[0]) != mesh_->polygroupAt(tris[1])) return true;+ for (size_t k = 0; k < mirrorMaps_.size(); ++k)+ if (mirrorOf(k, a) == a && mirrorOf(k, b) == b) return true;+ return false;+}++// The number of feature edges at v (the other ends of the first two in `other`), or 3 for a corner: a vertex+// in a symmetry plane is a corner unless exactly two of its edges lie in that plane.+int DynamicTopology::featureEdges(uint32_t v, uint32_t* other) const {+ ring(v, scratch_);+ int n = 0;+ for (uint32_t u : scratch_)+ if (featureEdge(v, u)) {+ if (n < 2) other[n] = u;+ ++n;+ }+ if (n == 0 && planeVertex(v)) return 3;+ return std::min(n, 3);+}++bool DynamicTopology::boundaryVertex(uint32_t v) const {+ ring(v, scratch2_);+ uint32_t tris[4];+ for (uint32_t u : scratch2_)+ if (edgeTriangles(v, u, tris) == 1) return true;+ return false;+}++glm::vec3 DynamicTopology::faceNormalAt(uint32_t v) const {+ glm::vec3 n(0.0f);+ const auto& p = mesh_->positions;+ for (uint32_t t : mesh_->vertexTriangles(v)) {+ const glm::uvec3& tri = mesh_->triangles[t];+ n += glm::cross(p[tri.y] - p[tri.x], p[tri.z] - p[tri.x]);+ }+ const float len = glm::length(n);+ return len > 1e-30f ? n / len : glm::vec3(0.0f);+}++// ---------------------------------------------------------------------------+// Symmetry+// ---------------------------------------------------------------------------++uint32_t DynamicTopology::mirrorOf(size_t k, uint32_t v) const {+ const auto it = mirrorMaps_[k].find(v);+ return it == mirrorMaps_[k].end() ? kNone : it->second;+}++void DynamicTopology::setMirror(size_t k, uint32_t v, uint32_t w) {+ mirrorMaps_[k][v] = w;+ mirrorMaps_[k][w] = v;+}++// Pairs each vertex with the vertex at its mirror image (within eps_), for every mirror; only pairs that+// find each other both ways count.+void DynamicTopology::matchMirrors(const std::vector<uint32_t>& verts) {+ const Mesh& m = *mesh_;+ const float cell = std::max(eps_ * 4.0f, 1e-12f);+ auto key = [cell](const glm::vec3& p) {+ const glm::ivec3 q = glm::ivec3(glm::floor(p / cell));+ return (uint64_t(uint32_t(q.x) & 0x1FFFFF) << 42) | (uint64_t(uint32_t(q.y) & 0x1FFFFF) << 21) |+ uint64_t(uint32_t(q.z) & 0x1FFFFF);+ };+ std::unordered_multimap<uint64_t, uint32_t> grid;+ grid.reserve(verts.size() * 2);+ for (uint32_t v : verts) grid.emplace(key(m.positions[v]), v);+ auto nearest = [&](const glm::vec3& p) {+ uint32_t best = kNone;+ float bestD = eps_ * eps_;+ const glm::ivec3 q = glm::ivec3(glm::floor(p / cell));+ for (int dz = -1; dz <= 1; ++dz)+ for (int dy = -1; dy <= 1; ++dy)+ for (int dx = -1; dx <= 1; ++dx) {+ const glm::ivec3 c = q + glm::ivec3(dx, dy, dz);+ const uint64_t k = (uint64_t(uint32_t(c.x) & 0x1FFFFF) << 42) | (uint64_t(uint32_t(c.y) & 0x1FFFFF) << 21) |+ uint64_t(uint32_t(c.z) & 0x1FFFFF);+ auto [b, e] = grid.equal_range(k);+ for (auto it = b; it != e; ++it) {+ const glm::vec3 d = m.positions[it->second] - p;+ const float dd = glm::dot(d, d);+ if (dd <= bestD && (best == kNone || dd < bestD || it->second < best)) {+ bestD = dd;+ best = it->second;+ }+ }+ }+ return best;+ };+ for (size_t k = 0; k < mirrorSigns_.size(); ++k) {+ auto& map = mirrorMaps_[k];+ map.clear();+ const glm::vec3 s = mirrorSigns_[k];+ for (uint32_t v : verts) {+ const uint32_t w = nearest(m.positions[v] * s);+ if (w == kNone) continue;+ if (nearest(m.positions[w] * s) != v) continue;+ map[v] = w;+ }+ }+}++// The edge a-b and its distinct mirror images (each once, either direction).+void DynamicTopology::orbit(uint32_t a, uint32_t b, std::vector<std::pair<uint32_t, uint32_t>>& out) const {+ out.assign(1, {a, b});+ orbitIncomplete_ = false;+ uint32_t tris[4];+ for (size_t k = 0; k < mirrorMaps_.size(); ++k) {+ const uint32_t ma = mirrorOf(k, a), mb = mirrorOf(k, b);+ if (ma == kNone || mb == kNone || ma == mb || edgeTriangles(ma, mb, tris) == 0) {+ orbitIncomplete_ = true;+ continue;+ }+ bool seen = false;+ for (const auto& e : out) seen = seen || (e.first == ma && e.second == mb) || (e.first == mb && e.second == ma);+ if (!seen && edgeTriangles(ma, mb, tris) > 0) out.emplace_back(ma, mb);+ }+}++bool DynamicTopology::orbitSharesTriangle(const std::vector<std::pair<uint32_t, uint32_t>>& edges) const {+ uint32_t ti[4], tj[4];+ for (size_t i = 0; i < edges.size(); ++i) {+ const int ni = std::min(4, edgeTriangles(edges[i].first, edges[i].second, ti));+ for (size_t j = i + 1; j < edges.size(); ++j) {+ const int nj = std::min(4, edgeTriangles(edges[j].first, edges[j].second, tj));+ for (int x = 0; x < ni; ++x)+ for (int y = 0; y < nj; ++y)+ if (ti[x] == tj[y]) return true;+ // Sharing a vertex is enough to make the order of the two operations matter.+ const auto& e = edges[i];+ const auto& f = edges[j];+ if (e.first == f.first || e.first == f.second || e.second == f.first || e.second == f.second) return true;+ }+ }+ return false;+}++// ---------------------------------------------------------------------------+// Operations+// ---------------------------------------------------------------------------++// Splits edge a-b at its midpoint: each triangle on it becomes two. Returns the new vertex (kNone if the+// edge isn't a manifold one).+uint32_t DynamicTopology::split(uint32_t a, uint32_t b) {+ Mesh& m = *mesh_;+ uint32_t tris[4];+ const int n = edgeTriangles(a, b, tris);+ if (n < 1 || n > 2) return kNone;+ const glm::vec3 mid = (m.positions[a] + m.positions[b]) * 0.5f;+ const uint32_t v = newVertex();+ interpolateVertex(v, a, b, 0.5f, mid);+ for (int i = 0; i < n; ++i) {+ const uint32_t t = tris[i];+ glm::uvec3 tri = m.triangles[t];+ int k = 0;+ while (k < 3 && !((tri[k] == a && tri[(k + 1) % 3] == b) || (tri[k] == b && tri[(k + 1) % 3] == a))) ++k;+ if (k == 3) continue;+ const uint32_t x = tri[k], y = tri[(k + 1) % 3], c = tri[(k + 2) % 3];+ glm::uvec3 first = tri;+ first[(k + 1) % 3] = v; // (x, v, c) in t's own rotation+ setTriangle(t, first);+ newTriangle(glm::uvec3(v, y, c), t);+ (void)x;+ }+ ++stats.splits;+ ++ops_;+ return v;+}++void DynamicTopology::pushEdgesAround(uint32_t v, bool longer) {+ ring(v, scratch2_);+ for (uint32_t u : scratch2_) {+ if (deadV_[u] || !inside(v, u)) continue;+ const float l = len2(v, u);+ if (longer ? l > splitLen2_ : l < collapseLen2_) {+ heap_.push_back({longer ? l : -l, std::min(u, v), std::max(u, v)});+ std::push_heap(heap_.begin(), heap_.end(), [](const Edge& x, const Edge& y) {+ return x.len2 != y.len2 ? x.len2 < y.len2 : x.a != y.a ? x.a > y.a : x.b > y.b;+ });+ }+ }+}++void DynamicTopology::splitOrbit(uint32_t a, uint32_t b, int depth) {+ std::vector<std::pair<uint32_t, uint32_t>> edges;+ orbit(a, b, edges);+ // Two images of the edge on one triangle (a triangle across the symmetry plane): split its third edge,+ // which crosses the plane, first, so the two images end up apart and the result stays mirrored.+ if (edges.size() > 1 && depth < 3) {+ uint32_t ti[4], tj[4];+ bool again = false;+ for (size_t i = 0; i < edges.size() && !again; ++i) {+ const int ni = std::min(4, edgeTriangles(edges[i].first, edges[i].second, ti));+ for (size_t j = i + 1; j < edges.size() && !again; ++j) {+ const int nj = std::min(4, edgeTriangles(edges[j].first, edges[j].second, tj));+ for (int x = 0; x < ni && !again; ++x)+ for (int y = 0; y < nj && !again; ++y) {+ if (ti[x] != tj[y]) continue;+ const glm::uvec3 tri = mesh_->triangles[ti[x]];+ // The corner on neither edge... the third edge joins the two corners other than the shared one.+ uint32_t shared = kNone;+ for (uint32_t c : {edges[i].first, edges[i].second})+ if (c == edges[j].first || c == edges[j].second) shared = c;+ if (shared == kNone) continue;+ uint32_t p = kNone, q = kNone;+ for (int c = 0; c < 3; ++c)+ if (tri[c] != shared) (p == kNone ? p : q) = tri[c];+ if (p != kNone && q != kNone && !locked(p) && !locked(q)) {+ splitOrbit(p, q, depth + 1);+ again = true;+ }+ }+ }+ }+ if (again) orbit(a, b, edges);+ }+ if (orbitIncomplete_ && !mirrorMaps_.empty()) ++stats.unpaired;+ std::vector<uint32_t> made(edges.size(), kNone);+ uint32_t tris[4];+ for (size_t i = 0; i < edges.size(); ++i) {+ const auto [x, y] = edges[i];+ const int n = edgeTriangles(x, y, tris);+ if (n < 1 || n > 2 || locked(x) || locked(y)) continue;+ made[i] = split(x, y);+ }+ // The new vertices are each other's mirror images as their edges were.+ for (size_t k = 0; k < mirrorMaps_.size(); ++k)+ for (size_t i = 0; i < edges.size(); ++i) {+ if (made[i] == kNone) continue;+ const uint32_t ma = mirrorOf(k, edges[i].first), mb = mirrorOf(k, edges[i].second);+ for (size_t j = 0; j < edges.size(); ++j)+ if (made[j] != kNone && ((edges[j].first == ma && edges[j].second == mb) ||+ (edges[j].first == mb && edges[j].second == ma)))+ setMirror(k, made[i], made[j]);+ }+ for (uint32_t v : made)+ if (v != kNone) pushEdgesAround(v, true);+}++void DynamicTopology::splitPass() {+ heap_.clear();+ uint32_t tris[4];+ for (uint32_t t : regionTris_) {+ const glm::uvec3 tri = mesh_->triangles[t];+ for (int c = 0; c < 3; ++c) {+ const uint32_t a = tri[c], b = tri[(c + 1) % 3];+ // Each edge once: from the triangle where it runs upwards (a boundary edge from its only one).+ if (a > b && edgeTriangles(a, b, tris) != 1) continue;+ const float l = len2(a, b);+ if (l > splitLen2_ && inside(a, b)) heap_.push_back({l, std::min(a, b), std::max(a, b)});+ }+ }+ auto less = [](const Edge& x, const Edge& y) {+ return x.len2 != y.len2 ? x.len2 < y.len2 : x.a != y.a ? x.a > y.a : x.b > y.b;+ };+ std::make_heap(heap_.begin(), heap_.end(), less);+ while (!heap_.empty() && ops_ < maxOps_) {+ std::pop_heap(heap_.begin(), heap_.end(), less);+ const Edge e = heap_.back();+ heap_.pop_back();+ if (deadV_[e.a] || deadV_[e.b]) continue;+ const int n = edgeTriangles(e.a, e.b, tris);+ if (n < 1 || n > 2 || len2(e.a, e.b) <= splitLen2_) continue;+ if (locked(e.a) || locked(e.b)) continue;+ splitOrbit(e.a, e.b, 0);+ }+}++// Which end of edge a-b goes and where the other one ends up: a free vertex (no feature edges) goes onto a+// feature vertex, or both meet at the midpoint; a vertex on a feature curve (two feature edges) only slides+// along it onto the next vertex of the curve; corners stay.+bool DynamicTopology::collapseTarget(uint32_t a, uint32_t b, uint32_t& keep, uint32_t& drop, glm::vec3& p) const {+ uint32_t oa[2], ob[2];+ const int fa = featureEdges(a, oa), fb = featureEdges(b, ob);+ const auto& pos = mesh_->positions;+ if (fa == 0 && fb == 0) {+ keep = std::min(a, b);+ drop = std::max(a, b);+ p = (pos[a] + pos[b]) * 0.5f;+ return true;+ }+ if (fa == 0) {+ keep = b, drop = a, p = pos[b];+ return true;+ }+ if (fb == 0) {+ keep = a, drop = b, p = pos[a];+ return true;+ }+ if (!featureEdge(a, b)) return false;+ if (fa == 2 && (oa[0] == b || oa[1] == b)) {+ keep = b, drop = a, p = pos[b];+ return true;+ }+ if (fb == 2 && (ob[0] == a || ob[1] == a)) {+ keep = a, drop = b, p = pos[a];+ return true;+ }+ return false;+}++bool DynamicTopology::canCollapse(uint32_t keep, uint32_t drop, const glm::vec3& p) const {+ const Mesh& m = *mesh_;+ uint32_t tris[4];+ const int n = edgeTriangles(keep, drop, tris);+ if (n < 1 || n > 2) return false;+ uint32_t opposite[2] = {kNone, kNone};+ for (int i = 0; i < n; ++i) {+ const glm::uvec3& tri = m.triangles[tris[i]];+ for (int c = 0; c < 3; ++c)+ if (tri[c] != keep && tri[c] != drop) opposite[i] = tri[c];+ if (opposite[i] == kNone) return false;+ }+ if (n == 2 && opposite[0] == opposite[1]) return false;+ std::vector<uint32_t> rk, rd;+ ring(keep, rk);+ ring(drop, rd);+ // Link condition: the ends share exactly the neighbours across the edge's triangles (else the surface+ // would pinch).+ size_t common = 0;+ for (uint32_t u : rk)+ if (std::binary_search(rd.begin(), rd.end(), u)) {+ if (u != opposite[0] && u != opposite[1]) return false;+ ++common;+ }+ if (common != size_t(n)) return false;+ // Nobody left with fewer than three neighbours (no flat double triangles).+ if (rk.size() + rd.size() - size_t(n) - 2 < 3) return false;+ std::vector<uint32_t> ro;+ for (int i = 0; i < n; ++i) {+ ring(opposite[i], ro);+ if (ro.size() <= 3) return false;+ }+ if (n == 1 && (rk.size() < 3 || rd.size() < 3)) return false;+ // No long edge, no triangle turned over or made degenerate or much worse.+ const auto& pos = m.positions;+ for (const std::vector<uint32_t>* r : {&rk, &rd})+ for (uint32_t u : *r)+ if (u != keep && u != drop) {+ const glm::vec3 d = pos[u] - p;+ if (glm::dot(d, d) >= splitLen2_) return false;+ }+ const float minArea = 1e-4f * target_ * target_;+ for (uint32_t v : {keep, drop})+ for (uint32_t t : m.vertexTriangles(v)) {+ if (t == tris[0] || (n == 2 && t == tris[1])) continue;+ const glm::uvec3& tri = m.triangles[t];+ glm::vec3 q[3], o[3];+ for (int c = 0; c < 3; ++c) {+ o[c] = pos[tri[c]];+ q[c] = tri[c] == keep || tri[c] == drop ? p : o[c];+ }+ const glm::vec3 nOld = glm::cross(o[1] - o[0], o[2] - o[0]);+ const glm::vec3 nNew = glm::cross(q[1] - q[0], q[2] - q[0]);+ const float lNew = glm::length(nNew), lOld = glm::length(nOld);+ if (lNew < minArea) return false;+ if (glm::dot(nOld, nNew) <= 0.3f * lOld * lNew) return false;+ const float qNew = quality(q[0], q[1], q[2]);+ if (qNew < 0.1f && qNew < quality(o[0], o[1], o[2])) return false;+ }+ return true;+}++void DynamicTopology::collapse(uint32_t keep, uint32_t drop, const glm::vec3& p) {+ Mesh& m = *mesh_;+ uint32_t tris[4];+ const int n = edgeTriangles(keep, drop, tris);+ for (int i = 0; i < n && i < 2; ++i) killTriangle(tris[i]);+ const IndexRing around = m.vertexTriangles(drop);+ std::vector<uint32_t> list(around.begin(), around.end());+ for (uint32_t t : list) {+ glm::uvec3 tri = m.triangles[t];+ for (int c = 0; c < 3; ++c)+ if (tri[c] == drop) tri[c] = keep;+ setTriangle(t, tri);+ }+ const bool midpoint = p != m.positions[keep];+ if (midpoint) interpolateVertex(keep, keep, drop, 0.5f, p);+ markVertex(keep);+ killVertex(drop);+ ++stats.collapses;+ ++ops_;+}++void DynamicTopology::collapsePass() {+ heap_.clear();+ uint32_t tris[4];+ for (uint32_t t : regionTris_) {+ if (t >= mesh_->triangleCount() || deadT_[t]) continue;+ const glm::uvec3 tri = mesh_->triangles[t];+ for (int c = 0; c < 3; ++c) {+ const uint32_t a = tri[c], b = tri[(c + 1) % 3];+ if (a > b && edgeTriangles(a, b, tris) != 1) continue;+ const float l = len2(a, b);+ if (l < collapseLen2_ && inside(a, b)) heap_.push_back({-l, std::min(a, b), std::max(a, b)});+ }+ }+ auto less = [](const Edge& x, const Edge& y) {+ return x.len2 != y.len2 ? x.len2 < y.len2 : x.a != y.a ? x.a > y.a : x.b > y.b;+ };+ std::make_heap(heap_.begin(), heap_.end(), less);+ std::vector<std::pair<uint32_t, uint32_t>> edges;+ struct Plan {+ uint32_t keep, drop;+ glm::vec3 p;+ };+ std::vector<Plan> plans;+ while (!heap_.empty() && ops_ < maxOps_) {+ std::pop_heap(heap_.begin(), heap_.end(), less);+ const Edge e = heap_.back();+ heap_.pop_back();+ if (deadV_[e.a] || deadV_[e.b]) continue;+ const int n = edgeTriangles(e.a, e.b, tris);+ if (n < 1 || n > 2 || len2(e.a, e.b) >= collapseLen2_) continue;+ if (locked(e.a) || locked(e.b)) continue;+ orbit(e.a, e.b, edges);+ if (edges.size() > 1 && orbitSharesTriangle(edges)) continue; // at the symmetry plane: leave it+ plans.clear();+ bool ok = true;+ for (const auto& [x, y] : edges) {+ Plan pl;+ if (locked(x) || locked(y) || !collapseTarget(x, y, pl.keep, pl.drop, pl.p) || !canCollapse(pl.keep, pl.drop, pl.p)) {+ ok = false;+ break;+ }+ plans.push_back(pl);+ }+ if (!ok) continue;+ if (orbitIncomplete_ && !mirrorMaps_.empty()) ++stats.unpaired;+ for (size_t i = 0; i < plans.size(); ++i) {+ const Plan& pl = plans[i];+ if (deadV_[pl.keep] || deadV_[pl.drop]) continue;+ if (i > 0 && !canCollapse(pl.keep, pl.drop, pl.p)) continue; // (the first changed its surroundings)+ collapse(pl.keep, pl.drop, pl.p);+ pushEdgesAround(pl.keep, false);+ }+ }+}++// Flipping a-b (between triangles a,b,c and b,a,d) to c-d: worth it when it brings the four valences closer+// to 6 (4 on a boundary) without folding or flattening the surface.+bool DynamicTopology::flipGain(uint32_t a, uint32_t b, uint32_t& c, uint32_t& d) const {+ const Mesh& m = *mesh_;+ uint32_t tris[4];+ if (edgeTriangles(a, b, tris) != 2 || featureEdge(a, b)) return false;+ c = d = kNone;+ for (int i = 0; i < 2; ++i) {+ const glm::uvec3& tri = m.triangles[tris[i]];+ int k = 0;+ while (k < 3 && tri[k] != a) ++k;+ if (k == 3) return false;+ const uint32_t next = tri[(k + 1) % 3], third = tri[(k + 2) % 3];+ if (next == b) c = third; // a -> b: the triangle a, b, c+ else d = next; // b -> a: the triangle b, a, d+ }+ if (c == kNone || d == kNone || c == d) return false;+ uint32_t tmp[4];+ if (edgeTriangles(c, d, tmp) > 0) return false;+ std::vector<uint32_t> r;+ auto valence = [&](uint32_t v, int& target) {+ ring(v, r);+ target = boundaryVertex(v) ? 4 : 6;+ return int(r.size());+ };+ int ta, tb, tc, td;+ const int va = valence(a, ta), vb = valence(b, tb), vc = valence(c, tc), vd = valence(d, td);+ if (va <= 3 || vb <= 3) return false;+ auto sq = [](int x) { return x * x; };+ const int before = sq(va - ta) + sq(vb - tb) + sq(vc - tc) + sq(vd - td);+ const int after = sq(va - 1 - ta) + sq(vb - 1 - tb) + sq(vc + 1 - tc) + sq(vd + 1 - td);+ if (after >= before) return false;+ const auto& p = m.positions;+ const glm::vec3 n1 = glm::cross(p[b] - p[a], p[c] - p[a]), n2 = glm::cross(p[a] - p[b], p[d] - p[b]);+ const float l1 = glm::length(n1), l2 = glm::length(n2);+ if (glm::dot(n1, n2) <= 0.94f * l1 * l2) return false; // a crease: flipping would change the shape+ const glm::vec3 m1 = glm::cross(p[a] - p[c], p[d] - p[c]), m2 = glm::cross(p[b] - p[d], p[c] - p[d]);+ const float k1 = glm::length(m1), k2 = glm::length(m2);+ const float minArea = 1e-4f * target_ * target_;+ if (k1 < minArea || k2 < minArea) return false;+ const glm::vec3 nSum = n1 + n2;+ if (glm::dot(m1, nSum) <= 0.0f || glm::dot(m2, nSum) <= 0.0f || glm::dot(m1, m2) <= 0.9f * k1 * k2) return false;+ const float qOld = std::min(quality(p[a], p[b], p[c]), quality(p[b], p[a], p[d]));+ const float qNew = std::min(quality(p[c], p[a], p[d]), quality(p[d], p[b], p[c]));+ return qNew >= 0.5f * qOld;+}++void DynamicTopology::flip(uint32_t a, uint32_t b, uint32_t c, uint32_t d) {+ uint32_t tris[4];+ if (edgeTriangles(a, b, tris) != 2) return;+ const Mesh& m = *mesh_;+ uint32_t t1 = tris[0], t2 = tris[1];+ // t1 holds a -> b.+ {+ const glm::uvec3& tri = m.triangles[t1];+ int k = 0;+ while (k < 3 && tri[k] != a) ++k;+ if (tri[(k + 1) % 3] != b) std::swap(t1, t2);+ }+ setTriangle(t1, glm::uvec3(c, a, d));+ setTriangle(t2, glm::uvec3(d, b, c));+ ++stats.flips;+ ++ops_;+}++void DynamicTopology::flipPass() {+ // The interior edges of the triangles around changed vertices inside the brush, in a fixed order.+ std::vector<std::pair<uint32_t, uint32_t>> candidates;+ for (uint32_t v : changedV_) {+ if (deadV_[v]) continue;+ for (uint32_t t : mesh_->vertexTriangles(v)) {+ const glm::uvec3& tri = mesh_->triangles[t];+ for (int c = 0; c < 3; ++c) {+ const uint32_t a = tri[c], b = tri[(c + 1) % 3];+ if (a < b && inside(a, b)) candidates.emplace_back(a, b);+ }+ }+ }+ std::sort(candidates.begin(), candidates.end());+ candidates.erase(std::unique(candidates.begin(), candidates.end()), candidates.end());+ std::vector<std::pair<uint32_t, uint32_t>> edges;+ struct Plan {+ uint32_t a, b, c, d;+ };+ std::vector<Plan> plans;+ for (const auto& [a0, b0] : candidates) {+ if (ops_ >= maxOps_) break;+ if (deadV_[a0] || deadV_[b0] || locked(a0) || locked(b0)) continue;+ uint32_t c, d;+ if (!flipGain(a0, b0, c, d)) continue;+ orbit(a0, b0, edges);+ if (edges.size() > 1 && orbitSharesTriangle(edges)) continue;+ plans.clear();+ bool ok = true;+ for (const auto& [x, y] : edges) {+ Plan pl{x, y, 0, 0};+ if (locked(x) || locked(y) || !flipGain(x, y, pl.c, pl.d)) {+ ok = false;+ break;+ }+ plans.push_back(pl);+ }+ if (!ok) continue;+ if (orbitIncomplete_ && !mirrorMaps_.empty()) ++stats.unpaired;+ for (const Plan& pl : plans) flip(pl.a, pl.b, pl.c, pl.d);+ }+}++// Moves each changed vertex inside the brush halfway to the centre of its neighbours, along the surface+// (free vertices only), which evens out the triangles the splits and collapses made.+void DynamicTopology::relaxPass() {+ Mesh& m = *mesh_;+ std::vector<std::pair<uint32_t, glm::vec3>> moves;+ std::vector<uint32_t> r;+ uint32_t other[2];+ const float r2 = radius_ * radius_;+ for (uint32_t v : changedV_) {+ if (deadV_[v] || locked(v)) continue;+ bool in = glm::dot(m.positions[v] - center_, m.positions[v] - center_) <= r2;+ for (const glm::vec3& s : mirrorSigns_) {+ const glm::vec3 d0 = m.positions[v] - center_ * s;+ in = in || glm::dot(d0, d0) <= r2;+ }+ if (!in) continue;+ if (featureEdges(v, other) != 0) continue;+ ring(v, r);+ if (r.size() < 3) continue;+ glm::vec3 avg(0.0f);+ for (uint32_t u : r) avg += m.positions[u];+ avg /= float(r.size());+ const glm::vec3 n = faceNormalAt(v);+ glm::vec3 d = avg - m.positions[v];+ d -= n * glm::dot(d, n);+ moves.emplace_back(v, d * 0.5f);+ }+ for (const auto& [v, d] : moves) {+ recordVertex(v);+ m.positions[v] += d;+ if (!m.base.empty()) m.base[v] += d;+ }+}++void DynamicTopology::gatherRegion() {+ bvh_->queryTriangles(*mesh_, center_, radius_, regionTris_);+ if (mirrorSigns_.empty()) return;+ // Every vertex of the triangles under each mirror image of the brush, to pair up.+ std::vector<uint32_t> verts, tris;+ auto addCorners = [&](const std::vector<uint32_t>& ts) {+ for (uint32_t t : ts)+ for (int c = 0; c < 3; ++c) verts.push_back(mesh_->triangles[t][c]);+ };+ addCorners(regionTris_);+ // (A margin: the mirror images of the corners found here must be among those found there, though+ // the two sides never match exactly.)+ const float reach = radius_ * 1.25f + target_ * 2.0f;+ for (const glm::vec3& s : mirrorSigns_) {+ bvh_->queryTriangles(*mesh_, center_ * s, reach, tris);+ addCorners(tris);+ }+ std::sort(verts.begin(), verts.end());+ verts.erase(std::unique(verts.begin(), verts.end()), verts.end());+ matchMirrors(verts);+}++bool DynamicTopology::remesh(Mesh& mesh, BVH& bvh, const glm::vec3& center, float radius, float edgeLength,+ std::span<const glm::vec3> mirrors) {+ const auto clock = std::chrono::steady_clock::now();+ moved_.clear();+ recordedNow_.clear();+ if (!dyntopoBlocker(mesh).empty() || !(edgeLength > 0.0f) || !(radius > 0.0f)) return false;+ if (mesh_ && mesh_ != &mesh) return false; // (another mesh mid-stroke)+ if (!mesh_) {+ if (!mesh.beginDynamicAdjacency()) return false;+ mesh_ = &mesh;+ bvh_ = &bvh;+ startVertices_ = uint32_t(mesh.vertexCount());+ startTriangles_ = uint32_t(mesh.triangleCount());+ undo_ = std::make_unique<TopologyUndo>();+ vertRec_.assign((mesh.vertexCount() + 63) / 64, 0);+ triRec_.assign((mesh.triangleCount() + 63) / 64, 0);+ deadV_.assign(mesh.vertexCount(), 0);+ deadT_.assign(mesh.triangleCount(), 0);+ changedVFlag_.assign(mesh.vertexCount(), 0);+ if (!mesh.uvs.empty()) { // a remeshed surface has no UVs: they come back with undo+ undo_->uvs = std::move(mesh.uvs);+ mesh.uvs.clear();+ mesh.topologyDirty = true;+ }+ }+ center_ = center;+ radius_ = radius;+ target_ = edgeLength;+ splitLen2_ = (edgeLength * 4.0f / 3.0f) * (edgeLength * 4.0f / 3.0f);+ collapseLen2_ = (edgeLength * 0.6f) * (edgeLength * 0.6f);+ // Mirror images are matched loosely: overlapping mirrored dabs near the plane don't move both sides+ // exactly alike, but vertices are rarely closer than half an edge.+ eps_ = std::max(edgeLength * 0.3f, 1e-7f);+ mirrorSigns_.assign(mirrors.size() > 1 ? mirrors.begin() + 1 : mirrors.end(), mirrors.end());+ mirrorMaps_.resize(mirrorSigns_.size());+ for (auto& map : mirrorMaps_) map.clear();+ ops_ = 0;+ maxOps_ = 6000; // (bounds a dab's time: a big brush over fine triangles coarsens them over several dabs)++ gatherRegion();+ if (regionTris_.empty()) return false;+ splitPass();+ bvh.refitChanged(mesh);+ bvh.queryTriangles(mesh, center_, radius_, regionTris_);+ collapsePass();+ flipPass();+ relaxPass();+ const bool changed = !changedV_.empty() || !changedT_.empty();+ compact();++ // Rings and normals of everything that changed, the BVH's boxes, and what the renderer must patch.+ const uint32_t nv = uint32_t(mesh.vertexCount());+ for (uint32_t v : changedV_)+ if (v < changedVFlag_.size()) changedVFlag_[v] = 0;+ std::vector<uint32_t> verts;+ verts.reserve(changedV_.size());+ for (uint32_t v : changedV_) {+ if (v < nv) {+ verts.push_back(v);+ continue;+ }+ for (const auto& [from, to] : moved_)+ if (from == v) verts.push_back(to);+ }+ std::sort(verts.begin(), verts.end());+ verts.erase(std::unique(verts.begin(), verts.end()), verts.end());+ changedV_.clear();+ changedVFlag_.resize(nv, 0);+ for (uint32_t v : verts) {+ ring(v, scratch2_);+ mesh.setNeighbors(v, scratch2_);+ mesh.markDirty(v);+ for (uint32_t t : mesh.vertexTriangles(v)) bvh.touchTriangle(t); // (moved vertices: relaxed, collapsed)+ }+ mesh.updateNormals(verts);+ bvh.refitChanged(mesh);+ mesh.changedTriangles.insert(mesh.changedTriangles.end(), changedT_.begin(), changedT_.end());+ changedT_.clear();+ lastMs = std::chrono::duration<double, std::milli>(std::chrono::steady_clock::now() - clock).count();+ return changed;+}++std::unique_ptr<TopologyUndo> DynamicTopology::finish(Mesh& mesh, BVH& bvh) {+ if (!mesh_) return nullptr;+ mesh.endDynamicAdjacency();+ if (bvh.degraded()) bvh.build(mesh);+ std::unique_ptr<TopologyUndo> undo = std::move(undo_);+ undo->vertexCount = startVertices_;+ undo->triangleCount = startTriangles_;+ mesh_ = nullptr;+ bvh_ = nullptr;+ std::vector<uint64_t>().swap(vertRec_);+ std::vector<uint64_t>().swap(triRec_);+ std::vector<uint8_t>().swap(deadV_);+ std::vector<uint8_t>().swap(deadT_);+ std::vector<uint8_t>().swap(changedVFlag_);+ for (auto& map : mirrorMaps_) map.clear();+ if (undo->vertexSlots.empty() && undo->triangleSlots.empty() && undo->uvs.empty()) return nullptr;+ return undo;+}++} // namespace sfdiff --git a/src/core/Dyntopo.h b/src/core/Dyntopo.hnew file mode 100644index 00000000..0ff5cd5e--- /dev/null+++ b/src/core/Dyntopo.h@@ -0,0 +1,192 @@+// SculptForge - open source digital sculpting+// SPDX-License-Identifier: GPL-3.0-or-later+//+// Dynamic topology (ZBrush's Sculptris Pro, Blender's Dyntopo): with it on, every brush dab first remeshes the+// surface under the brush towards one edge length, so a sphere can be pulled into horns or fingers without+// stretching its triangles, and a blockout needs no remeshing.+//+// Each dab, inside the brush radius only: edges longer than 4/3 of the target are split at their midpoint+// (longest first), edges shorter than 3/5 of it are collapsed (shortest first, where that keeps the surface+// manifold, turns no triangle over, makes no long edge and leaves no vertex with fewer than three neighbours),+// edges are flipped where that evens out the valences, and the vertices that changed are relaxed along the+// surface. Boundaries, polygroup borders and the symmetry plane are kept: their vertices only slide along them.+// Masked and hidden parts are left alone. With symmetry on, every operation is done on its mirror images at the+// same time, so mirrored dabs make mirrored topology.+//+// Quads under the brush become triangles; UVs are dropped (a remeshed surface has none) and come back on undo.+// Meshes with subdivision levels can't be remeshed (as in ZBrush, delete the levels first).+//+// The mesh stays valid after every dab (no dead entries): elements a dab removed are filled from the end of+// the arrays. The BVH and the renderer follow incrementally (BVH::insertTriangle..., Mesh::changedTriangles), and+// the stroke's undo step keeps only the vertex and triangle slots it touched (TopologyUndo).+#pragma once++#include "core/BVH.h"+#include "core/Mesh.h"++#include <glm/glm.hpp>++#include <cstdint>+#include <memory>+#include <span>+#include <string>+#include <unordered_map>+#include <utility>+#include <vector>++namespace sf {++struct DyntopoSettings {+ bool enabled = false;+ // false: the detail follows the brush size (Sculptris Pro: zoom in or shrink the brush for finer triangles);+ // true: one detail size for the whole mesh, relative to its size.+ bool constantDetail = false;+ float detail = 0.5f; // 0 (coarse) .. 1 (fine)+};++// The edge length dabs of world radius `radius` remesh towards, on a mesh whose bounding box diagonal is `diagonal`.+float dyntopoEdgeLength(const DyntopoSettings& s, float radius, float diagonal);++// Why `mesh` can't be remeshed by dynamic topology ("" when it can).+std::string dyntopoBlocker(const Mesh& mesh);++// Per-vertex and per-triangle values of a mesh at some slots (arrays the mesh doesn't have stay empty).+struct TopologyVertexValues {+ std::vector<glm::vec3> positions, colors, base, paintBase;+ std::vector<float> mask;+ std::vector<std::vector<glm::vec3>> deltas, paintColors; // per sculpt layer / paint layer+ std::vector<std::vector<float>> paintAlphas;+ size_t bytes() const;+};+struct TopologyTriangleValues {+ std::vector<glm::uvec3> triangles;+ std::vector<uint32_t> polygroups, quadPartners;+ std::vector<uint8_t> hidden;+ size_t bytes() const;+};++// The undo of a dynamic-topology stroke: the vertex and triangle slots it touched (in either state), the+// element counts of the other state and its values at those slots (those below its counts). Applying swaps+// them with the mesh's, so the record then holds the inverse; the caller rebuilds topology, normals and BVH.+struct TopologyUndo {+ uint32_t vertexCount = 0, triangleCount = 0;+ std::vector<uint32_t> vertexSlots, triangleSlots;+ TopologyVertexValues vertices;+ TopologyTriangleValues triangles;+ std::vector<glm::vec2> uvs; // the whole UVs of the other state, when it had them (dynamic topology drops them)+ void swapWith(Mesh& mesh);+ size_t bytes() const;+};++struct DyntopoStats {+ size_t splits = 0, collapses = 0, flips = 0;+ size_t unpaired = 0; // operations whose mirror image wasn't found (an asymmetric mesh, or one edited without symmetry)+};++// Remeshes the surface under brush dabs (see the top of this file). One per Sculptor; a stroke's first remesh+// starts recording, finish() ends the stroke.+class DynamicTopology {+public:+ // Remeshes within `radius` of `center` and of its mirror images (`mirrors` as Sculptor::mirrors makes them,+ // the identity first) towards edges of `edgeLength`. Returns false when nothing changed.+ bool remesh(Mesh& mesh, BVH& bvh, const glm::vec3& center, float radius, float edgeLength,+ std::span<const glm::vec3> mirrors);+ // The vertices the last remesh renumbered (old slot, new slot), for per-vertex stroke state.+ std::span<const std::pair<uint32_t, uint32_t>> movedVertices() const { return moved_; }+ // The vertex slots the last remesh added to the stroke's undo record (their stroke-start state is there).+ std::span<const uint32_t> recordedVertices() const { return recordedNow_; }+ // The stroke changed the mesh's topology (or recorded it).+ bool active() const { return mesh_ != nullptr; }+ // Vertex slot v is in the stroke's undo record (its stroke-start state is kept there).+ bool recordedVertex(uint32_t v) const { return v < vertRec_.size() * 64 && ((vertRec_[v >> 6] >> (v & 63)) & 1); }+ // Ends the stroke: packs the mesh's adjacency, rebuilds the BVH if the edits wore it down, and returns the+ // undo record (null when the stroke didn't remesh).+ std::unique_ptr<TopologyUndo> finish(Mesh& mesh, BVH& bvh);+ // finish() for the mesh the stroke remeshed (null when none).+ Mesh* strokeMesh() const { return mesh_; }+ BVH* strokeBvh() const { return bvh_; }++ DyntopoStats stats; // since the last reset+ double lastMs = 0.0; // the last remesh's time++private:+ struct Edge {+ float len2;+ uint32_t a, b;+ };++ // Recording (the stroke's undo), and what changed this remesh (for rings, normals, BVH and renderer).+ void recordVertex(uint32_t v);+ void recordTriangle(uint32_t t);+ void markVertex(uint32_t v);+ void markTriangle(uint32_t t);+ // Elements.+ uint32_t newVertex();+ void interpolateVertex(uint32_t v, uint32_t a, uint32_t b, float t, const glm::vec3& position);+ void killVertex(uint32_t v);+ uint32_t newTriangle(const glm::uvec3& tri, uint32_t like);+ void setTriangle(uint32_t t, const glm::uvec3& tri);+ void killTriangle(uint32_t t);+ void unpairQuad(uint32_t t);+ void vtInsert(uint32_t v, uint32_t t);+ void vtErase(uint32_t v, uint32_t t);+ void vtReplace(uint32_t v, uint32_t from, uint32_t to);+ void moveVertex(uint32_t from, uint32_t to);+ void moveTriangle(uint32_t from, uint32_t to);+ void compact();+ // Queries (from the triangle lists, which are always current).+ int edgeTriangles(uint32_t a, uint32_t b, uint32_t* out) const; // up to 4+ void ring(uint32_t v, std::vector<uint32_t>& out) const;+ bool locked(uint32_t v) const;+ bool planeVertex(uint32_t v) const;+ bool featureEdge(uint32_t a, uint32_t b) const;+ int featureEdges(uint32_t v, uint32_t* other) const;+ bool boundaryVertex(uint32_t v) const;+ float len2(uint32_t a, uint32_t b) const;+ bool inside(uint32_t a, uint32_t b) const;+ glm::vec3 faceNormalAt(uint32_t v) const;+ // Symmetry: the mirror images of vertex v (kNone where unknown).+ uint32_t mirrorOf(size_t mirror, uint32_t v) const;+ void setMirror(size_t mirror, uint32_t v, uint32_t w);+ void matchMirrors(const std::vector<uint32_t>& verts);+ void orbit(uint32_t a, uint32_t b, std::vector<std::pair<uint32_t, uint32_t>>& out) const;+ bool orbitSharesTriangle(const std::vector<std::pair<uint32_t, uint32_t>>& edges) const;+ // Operations.+ void splitPass();+ void splitOrbit(uint32_t a, uint32_t b, int depth);+ uint32_t split(uint32_t a, uint32_t b);+ void collapsePass();+ bool collapseTarget(uint32_t a, uint32_t b, uint32_t& keep, uint32_t& drop, glm::vec3& p) const;+ bool canCollapse(uint32_t keep, uint32_t drop, const glm::vec3& p) const;+ void collapse(uint32_t keep, uint32_t drop, const glm::vec3& p);+ void flipPass();+ bool flipGain(uint32_t a, uint32_t b, uint32_t& c, uint32_t& d) const;+ void flip(uint32_t a, uint32_t b, uint32_t c, uint32_t d);+ void relaxPass();+ void pushEdgesAround(uint32_t v, bool longer);+ void gatherRegion();++ Mesh* mesh_ = nullptr;+ BVH* bvh_ = nullptr;+ uint32_t startVertices_ = 0, startTriangles_ = 0;+ std::unique_ptr<TopologyUndo> undo_; // stroke-start values of the recorded slots (in the undo's layout)+ std::vector<uint64_t> vertRec_, triRec_;++ // The current remesh.+ glm::vec3 center_{0.0f};+ float radius_ = 0.0f, target_ = 0.0f, splitLen2_ = 0.0f, collapseLen2_ = 0.0f, eps_ = 0.0f;+ std::vector<glm::vec3> mirrorSigns_; // without the identity+ std::vector<std::unordered_map<uint32_t, uint32_t>> mirrorMaps_;+ std::vector<uint8_t> deadV_, deadT_;+ std::vector<uint32_t> freeV_, freeT_;+ std::vector<uint32_t> changedV_, changedT_, regionTris_;+ std::vector<uint8_t> changedVFlag_;+ std::vector<Edge> heap_;+ std::vector<std::pair<uint32_t, uint32_t>> moved_;+ std::vector<uint32_t> recordedNow_;+ mutable bool orbitIncomplete_ = false; // the last orbit() missed a mirror image+ size_t ops_ = 0, maxOps_ = 0;+ mutable std::vector<uint32_t> scratch_, scratch2_;+};++} // namespace sfdiff --git a/src/core/Mesh.cpp b/src/core/Mesh.cppindex 135e74cf..cc15ac8b 100644--- a/src/core/Mesh.cpp+++ b/src/core/Mesh.cpp@@ -9,6 +9,7 @@#include <algorithm>#include <atomic>#include <cmath>+#include <tuple>#include <unordered_map>namespace sf {@@ -174,6 +175,7 @@ void Mesh::sanitizeAttributes() {void Mesh::rebuildTopology() {sanitizeAttributes();+ for (auto* v : {&adjEnds_, &adjCaps_, &vtEnds_, &vtCaps_}) std::vector<uint32_t>().swap(*v);const size_t nv = positions.size();finishTopology(); // (the normal set, normals and dirty bits first: they don't depend on the adjacency)@@ -232,6 +234,85 @@ void Mesh::rebuildTopology() {});}+bool Mesh::beginDynamicAdjacency() {+ const size_t nv = positions.size();+ if (implicit_ || adjOffsets_.size() != nv + 1 || vtOffsets_.size() != nv + 1) return false;+ if (dynamicAdjacency()) return true;+ adjEnds_.assign(adjOffsets_.begin() + 1, adjOffsets_.end());+ vtEnds_.assign(vtOffsets_.begin() + 1, vtOffsets_.end());+ adjCaps_.resize(nv);+ vtCaps_.resize(nv);+ for (size_t v = 0; v < nv; ++v) {+ adjCaps_[v] = adjOffsets_[v + 1] - adjOffsets_[v];+ vtCaps_[v] = vtOffsets_[v + 1] - vtOffsets_[v];+ }+ return true;+}++void Mesh::endDynamicAdjacency() {+ if (!dynamicAdjacency()) return;+ const size_t nv = positions.size();+ auto pack = [nv](std::vector<uint32_t>& offsets, std::vector<uint32_t>& ends, std::vector<uint32_t>& caps,+ std::vector<uint32_t>& list) {+ std::vector<uint32_t> packed;+ size_t total = 0;+ for (size_t v = 0; v < nv; ++v) total += ends[v] - offsets[v];+ packed.reserve(total);+ for (size_t v = 0; v < nv; ++v) {+ const uint32_t b = offsets[v], e = ends[v];+ offsets[v] = uint32_t(packed.size());+ packed.insert(packed.end(), list.begin() + b, list.begin() + e);+ }+ offsets.resize(nv + 1);+ offsets[nv] = uint32_t(packed.size());+ list.swap(packed);+ std::vector<uint32_t>().swap(ends);+ std::vector<uint32_t>().swap(caps);+ };+ pack(adjOffsets_, adjEnds_, adjCaps_, adjList_);+ pack(vtOffsets_, vtEnds_, vtCaps_, vtList_);+}++void Mesh::setList(std::vector<uint32_t>& offsets, std::vector<uint32_t>& ends, std::vector<uint32_t>& caps,+ std::vector<uint32_t>& list, uint32_t v, std::span<const uint32_t> values) {+ const uint32_t n = uint32_t(values.size());+ if (n > caps[v]) { // no room: a new place at the end, with some to spare+ const uint32_t cap = std::max(n + 2, n + n / 2);+ offsets[v] = uint32_t(list.size());+ caps[v] = cap;+ list.resize(list.size() + cap);+ }+ std::copy(values.begin(), values.end(), list.begin() + offsets[v]);+ ends[v] = offsets[v] + n;+}++void Mesh::setVertexTriangles(uint32_t v, std::span<const uint32_t> tris) {+ setList(vtOffsets_, vtEnds_, vtCaps_, vtList_, v, tris);+}++void Mesh::setNeighbors(uint32_t v, std::span<const uint32_t> ring) {+ setList(adjOffsets_, adjEnds_, adjCaps_, adjList_, v, ring);+}++void Mesh::addVertexSlot() {+ // offsets[nv] is the spare last entry: it becomes the new vertex's (empty) list, and a new one follows.+ for (auto [offsets, ends, caps, list] : {std::tie(adjOffsets_, adjEnds_, adjCaps_, adjList_),+ std::tie(vtOffsets_, vtEnds_, vtCaps_, vtList_)}) {+ offsets.back() = uint32_t(list.size());+ offsets.push_back(uint32_t(list.size()));+ ends.push_back(uint32_t(list.size()));+ caps.push_back(0);+ }+}++void Mesh::removeLastVertexSlot() {+ for (auto [offsets, ends, caps] : {std::tie(adjOffsets_, adjEnds_, adjCaps_), std::tie(vtOffsets_, vtEnds_, vtCaps_)}) {+ offsets.pop_back();+ ends.pop_back();+ caps.pop_back();+ }+}+void Mesh::finishTopology() {const size_t nv = positions.size();normalBits_.resize(nv);@@ -492,6 +573,7 @@ void Mesh::clearDirty() {dirtyEnd = 0;topologyDirty = false;facesDirty = false;+ changedTriangles.clear();}void Mesh::recomputeAllNormals() {@@ -626,7 +708,7 @@ size_t Mesh::memoryBytes() const {auto bytes = [](const auto& v) { return v.capacity() * sizeof(v[0]); };size_t n = bytes(positions) + bytes(normals) + bytes(triangles) + bytes(mask) + bytes(colors) + bytes(polygroups) +bytes(hidden) + bytes(uvs) + bytes(quadPartners) + bytes(base) + bytes(paintBase) + bytes(adjOffsets_) +- bytes(adjList_) + bytes(vtOffsets_) + bytes(vtList_) + normalBits_.memoryBytes() + bytes(scratchVerts_) + bytes(dirtyBlocks) + bytes(dirtyBits);+ bytes(adjList_) + bytes(vtOffsets_) + bytes(vtList_) + bytes(adjEnds_) + bytes(adjCaps_) + bytes(vtEnds_) + bytes(vtCaps_) + normalBits_.memoryBytes() + bytes(scratchVerts_) + bytes(dirtyBlocks) + bytes(dirtyBits);for (const auto& l : layers) n += bytes(l.delta);for (const auto& l : paintLayers) n += bytes(l.color) + bytes(l.alpha);if (implicit_) n += implicit_->bytes(); // (the level topology itself is counted with the subdivision levels)diff --git a/src/core/Mesh.h b/src/core/Mesh.hindex ab5e4839..98b7079c 100644--- a/src/core/Mesh.h+++ b/src/core/Mesh.h@@ -196,15 +196,29 @@ public:// The vertices sharing an edge with `v`, and the triangles around it, in ascending order.IndexRing neighbors(uint32_t v) const {if (implicit_) return implicitNeighbors(v);- return {adjList_.data() + adjOffsets_[v], adjList_.data() + adjOffsets_[v + 1]};+ return {adjList_.data() + adjOffsets_[v], adjList_.data() + (adjEnds_.empty() ? adjOffsets_[v + 1] : adjEnds_[v])};}IndexRing vertexTriangles(uint32_t v) const {if (implicit_) return implicitTriangles(v);- return {vtList_.data() + vtOffsets_[v], vtList_.data() + vtOffsets_[v + 1]};+ return {vtList_.data() + vtOffsets_[v], vtList_.data() + (vtEnds_.empty() ? vtOffsets_[v + 1] : vtEnds_[v])};}// True when the adjacency follows from the subdivision level this mesh is (see rebuildTopology).bool implicitAdjacency() const { return bool(implicit_); }+ // Dynamic topology (core/Dyntopo.h): adjacency lists that can be rewritten one vertex at a time, so local+ // remeshing under the brush doesn't rebuild the whole mesh's. Between begin and end each vertex's lists+ // have their own capacity (a list that outgrows it moves to the end of the arrays); end packs them back+ // into the usual form. rebuildTopology() also ends it. Not for meshes with implicit adjacency.+ bool beginDynamicAdjacency();+ void endDynamicAdjacency();+ bool dynamicAdjacency() const { return !adjEnds_.empty(); }+ // Replace vertex v's triangles / ring (ascending). v may be vertexCount() - 1 after addVertexSlot().+ void setVertexTriangles(uint32_t v, std::span<const uint32_t> tris);+ void setNeighbors(uint32_t v, std::span<const uint32_t> ring);+ // Appends empty lists for a new last vertex, or drops the last vertex's (the caller sizes the vertex arrays).+ void addVertexSlot();+ void removeLastVertexSlot();+AABB bounds() const;// Bytes this mesh holds (every array, topology included; not the shared texture or subdivision stack).size_t memoryBytes() const;@@ -222,6 +236,10 @@ public:static constexpr uint32_t kDirtyBlockShift = 11, kDirtyBlock = 1u << kDirtyBlockShift; // 2048 verticesstd::vector<uint8_t> dirtyBlocks;std::vector<uint64_t> dirtyBits;+ // Dynamic topology (core/Dyntopo.h): triangle slots whose corners changed (in place, added, removed or+ // renumbered, so possibly >= triangleCount()) since the last upload. A renderer can patch those instead of+ // a full upload; topologyDirty still means everything. Cleared by clearDirty().+ std::vector<uint32_t> changedTriangles;void markDirty(uint32_t v) {dirtyBegin = std::min(dirtyBegin, v);@@ -253,6 +271,11 @@ private:std::vector<uint32_t> adjOffsets_, adjList_;std::vector<uint32_t> vtOffsets_, vtList_;std::shared_ptr<const ImplicitAdjacency> implicit_; // (core/Mesh.cpp)+ // Dynamic adjacency (beginDynamicAdjacency): each list starts at its offset and ends at its end, with+ // room up to offset + cap. Empty otherwise.+ std::vector<uint32_t> adjEnds_, adjCaps_, vtEnds_, vtCaps_;+ static void setList(std::vector<uint32_t>& offsets, std::vector<uint32_t>& ends, std::vector<uint32_t>& caps,+ std::vector<uint32_t>& list, uint32_t v, std::span<const uint32_t> values);// updateNormals: the vertices to update, as a set and as a list.IndexBits normalBits_;diff --git a/src/core/Sculpt.cpp b/src/core/Sculpt.cppindex 6e41f95a..8ba94d1d 100644--- a/src/core/Sculpt.cpp+++ b/src/core/Sculpt.cpp@@ -8,6 +8,7 @@#include <algorithm>#include <cmath>+#include <unordered_map>namespace sf {@@ -204,10 +205,96 @@ bool Sculptor::beginStroke(const Mesh& mesh, std::string label, int layer) {colored_.assign(words, 0);}++strokeId_;+ strokeDiagonal_ = 0.0f;active_ = true;return true;}+void Sculptor::remeshDab(Mesh& mesh, BVH& bvh, const DabParams& p, Symmetry sym, float scale) {+ if (!dyntopo.enabled) return;+ auto clock = std::chrono::steady_clock::now();+ if (dyntopo.constantDetail && strokeDiagonal_ <= 0.0f) strokeDiagonal_ = glm::length(mesh.bounds().extent());+ const float edge = dyntopoEdgeLength(dyntopo, p.radius, strokeDiagonal_) * scale;+ const std::vector<glm::vec3> ms = mirrors(sym);+ dynTopo_.remesh(mesh, bvh, p.center, p.radius, edge, ms);+ // The stroke's per-vertex state follows: the remesher's record holds the stroke-start state of every slot it+ // touched, so this stroke's own undo entries never name them; the Layer brush's heights move with their vertices.+ const size_t words = (mesh.vertexCount() + 63) / 64;+ if (touched_.size() < words) {+ touched_.resize(words, 0);+ masked_.resize(words, 0);+ colored_.resize(words, 0);+ }+ for (uint32_t v : dynTopo_.recordedVertices()) {+ if (size_t(v >> 6) >= touched_.size()) {+ touched_.resize(size_t(v >> 6) + 1, 0);+ masked_.resize(size_t(v >> 6) + 1, 0);+ colored_.resize(size_t(v >> 6) + 1, 0);+ }+ const uint64_t bit = uint64_t(1) << (v & 63);+ touched_[v >> 6] |= bit;+ masked_[v >> 6] |= bit;+ colored_[v >> 6] |= bit;+ }+ if (!layerStamp_.empty() && layerStamp_.size() != mesh.vertexCount()) {+ const size_t nv = mesh.vertexCount();+ for (const auto& [from, to] : dynTopo_.movedVertices())+ if (from < layerStamp_.size() && to < layerStamp_.size()) {+ layerStamp_[to] = layerStamp_[from];+ layerDone_[to] = layerDone_[from];+ layerDir_[to] = layerDir_[from];+ }+ layerStamp_.resize(nv, 0);+ layerDone_.resize(nv, 0.0f);+ layerDir_.resize(nv, glm::vec3(0.0f));+ }+ timings.remeshMs += lapMs(clock);+}++// This stroke's undo entries for slots the remesher recorded later hold their true stroke-start values (the+// remesher's copies are from when it first touched them): they move into its record.+void Sculptor::mergeTopologyUndo(TopologyUndo& topo, const Mesh& mesh) {+ std::unordered_map<uint32_t, uint32_t> at; // slot -> index into the record's stored values+ uint32_t k = 0;+ for (uint32_t v : topo.vertexSlots)+ if (v < topo.vertexCount) at.emplace(v, k++);+ auto merge = [&](auto& channel, auto&& store) {+ size_t out = 0;+ for (size_t i = 0; i < channel.indices.size(); ++i) {+ const auto it = at.find(channel.indices[i]);+ if (it != at.end()) {+ store(it->second, channel.values[i]);+ continue;+ }+ channel.indices[out] = channel.indices[i];+ channel.values[out++] = channel.values[i];+ }+ channel.indices.resize(out);+ channel.values.resize(out);+ };+ TopologyVertexValues& tv = topo.vertices;+ const int layer = record_.layer;+ merge(record_.positions, [&](uint32_t i, const glm::vec3& value) {+ std::vector<glm::vec3>& target = layer >= 0 && size_t(layer) < tv.deltas.size() ? tv.deltas[size_t(layer)]+ : mesh.layers.empty() ? tv.positions+ : tv.base;+ if (i < target.size()) target[i] = value;+ });+ merge(record_.mask, [&](uint32_t i, float value) {+ if (i < tv.mask.size()) tv.mask[i] = value;+ });+ const int pl = record_.paintLayer;+ merge(record_.colors, [&](uint32_t i, const glm::vec3& value) {+ std::vector<glm::vec3>& target = mesh.paintLayers.empty() ? tv.colors+ : pl < 0 || size_t(pl) >= tv.paintColors.size() ? tv.paintBase+ : tv.paintColors[size_t(pl)];+ if (i < target.size()) target[i] = value;+ });+ merge(record_.paintAlpha, [&](uint32_t i, float value) {+ if (pl >= 0 && size_t(pl) < tv.paintAlphas.size() && i < tv.paintAlphas[size_t(pl)].size()) tv.paintAlphas[size_t(pl)][i] = value;+ });+}+void Sculptor::touch(Mesh& mesh, uint32_t v) {if (markBit(touched_, v)) record_.positions.add(v, mesh.layerTarget(layer_)[v]);}@@ -287,6 +374,14 @@ void Sculptor::displaceAll(Mesh& mesh, std::span<const uint32_t> verts, std::spa}UndoRecord Sculptor::endStroke() {+ if (dynTopo_.active()) {+ Mesh& mesh = *dynTopo_.strokeMesh();+ std::unique_ptr<TopologyUndo> topo = dynTopo_.finish(mesh, *dynTopo_.strokeBvh());+ if (topo) {+ mergeTopologyUndo(*topo, mesh);+ record_.topology = std::move(topo);+ }+ }clearRecorded();active_ = false;grabVerts_.clear();@@ -296,6 +391,7 @@ UndoRecord Sculptor::endStroke() {void Sculptor::dab(Mesh& mesh, BVH& bvh, BrushType type, const DabParams& p, Symmetry sym) {if (!active_) return;+ if (type != BrushType::Move) remeshDab(mesh, bvh, p, sym, type == BrushType::Smooth ? 2.0f : 1.0f);dabVerts_.clear();for (const glm::vec3& m : mirrors(sym)) {DabParams mp = p;@@ -493,6 +589,7 @@ void Sculptor::updateDabNormals(Mesh& mesh) {void Sculptor::dabRecipe(Mesh& mesh, BVH& bvh, const BrushRecipe& recipe, const DabParams& p, Symmetry sym) {if (!active_) return;+ remeshDab(mesh, bvh, p, sym, 1.0f);DabParams base = p;base.pressure = std::pow(std::clamp(p.pressure, 0.0f, 1.0f), recipe.pressureCurve);base.frontFacesOnly = p.frontFacesOnly || recipe.frontFacesOnly;diff --git a/src/core/Sculpt.h b/src/core/Sculpt.hindex 7e280740..160be5d7 100644--- a/src/core/Sculpt.h+++ b/src/core/Sculpt.h@@ -4,6 +4,7 @@#include "core/BVH.h"#include "core/BrushRecipe.h"+#include "core/Dyntopo.h"#include "core/Mesh.h"#include "core/Undo.h"@@ -69,6 +70,7 @@ float focalRingFraction(float focal);// counters were last zeroed. kernel = finding the vertices and moving / masking / painting them.struct SculptTimings {double kernelMs = 0.0, normalsMs = 0.0, bvhMs = 0.0;+ double remeshMs = 0.0; // dynamic topology (core/Dyntopo.h)uint64_t dabs = 0, vertices = 0;};// Milliseconds since `t`, which moves on to now (for SculptTimings).@@ -105,6 +107,11 @@ public:SculptTimings timings;+ // Dynamic topology (core/Dyntopo.h): while enabled, dab() and dabRecipe() remesh the surface under the+ // brush first (Smooth towards twice the edge length, so it simplifies, as in ZBrush). Not the Move brush.+ DyntopoSettings dyntopo;+ DynamicTopology& dynamicTopology() { return dynTopo_; }+// Mirror sign vectors for the enabled symmetry axes (always starts with (1,1,1)).static std::vector<glm::vec3> mirrors(Symmetry sym);@@ -122,6 +129,12 @@ private:void displace(Mesh& mesh, uint32_t v, const glm::vec3& d);void displaceAll(Mesh& mesh, std::span<const uint32_t> verts, std::span<const glm::vec3> d);+ // Dynamic topology: remeshes before a dab, and keeps the stroke's per-vertex state in step with it.+ void remeshDab(Mesh& mesh, BVH& bvh, const DabParams& p, Symmetry sym, float scale);+ void mergeTopologyUndo(TopologyUndo& topo, const Mesh& mesh);+ DynamicTopology dynTopo_;+ float strokeDiagonal_ = 0.0f;+bool active_ = false;int layer_ = -1;UndoRecord record_;diff --git a/src/core/Undo.cpp b/src/core/Undo.cppindex cb159cf7..eb1b3163 100644--- a/src/core/Undo.cpp+++ b/src/core/Undo.cpp@@ -10,7 +10,7 @@ size_t UndoRecord::approxBytes() const {size_t bytes = positions.bytes() + mask.bytes() + colors.bytes() + paintAlpha.bytes() + hidden.bytes() +polygroups.bytes() + (paint ? paint->bytes() : 0) +(textureTiles ? textureTiles->bytes() : 0) + (texture ? texture->bytes() : 0) +- (subdiv ? subdiv->bytes() : 0);+ (subdiv ? subdiv->bytes() : 0) + (topology ? topology->bytes() : 0);for (const auto& l : layerOffsets) bytes += l.bytes();if (mesh)bytes += mesh->vertexCount() * ((2 + (mesh->base.empty() ? 0 : 1 + mesh->layers.size())) * sizeof(glm::vec3) +@@ -158,6 +158,19 @@ void UndoStack::apply(UndoRecord& r, Mesh& mesh, BVH& bvh) {bvh.build(mesh);return;}+ if (r.topology) {+ // A dynamic-topology stroke: its slots back, then what follows from them (the other channels name+ // slots it didn't touch).+ r.topology->swapWith(mesh);+ mesh.rebuildTopology();+ std::vector<uint32_t> restored;+ for (uint32_t v : r.topology->vertexSlots)+ if (v < mesh.vertexCount()) restored.push_back(v);+ if (!mesh.layers.empty()) mesh.evaluate(restored);+ if (!mesh.paintLayers.empty()) compositePaint(mesh, restored);+ mesh.recomputeAllNormals();+ bvh.build(mesh);+ }if (!r.positions.empty()) {r.positions.swapWithUnique(mesh.layerTarget(r.layer));for (size_t i = 0; i < r.layerOffsets.size() && i < mesh.layers.size(); ++i)diff --git a/src/core/Undo.h b/src/core/Undo.hindex 90ade228..861b2d7c 100644--- a/src/core/Undo.h+++ b/src/core/Undo.h@@ -3,6 +3,7 @@#pragma once#include "core/BVH.h"+#include "core/Dyntopo.h"#include "core/Mesh.h"#include "core/Multires.h"#include "core/ThreadPool.h"@@ -103,6 +104,7 @@ inline constexpr int kActivePaintLayer = -2;// - hidden / polygroups: per-triangle visibility and group ids// - textureTiles / texture: texture-paint tiles of one layer, or the whole texture// - subdiv: a subdivision level step or level edit (core/Multires.h), applied on its own+// - topology: the slots a dynamic-topology stroke changed (core/Dyntopo.h), applied before the channels// Record old values before changing them (ensureX() the attribute first);// undo allocates a missing attribute so values can always be restored.struct UndoRecord {@@ -123,10 +125,11 @@ struct UndoRecord {std::unique_ptr<TextureStackUndo> texture;std::unique_ptr<Mesh> mesh;std::unique_ptr<SubdivUndo> subdiv;+ std::unique_ptr<TopologyUndo> topology;bool empty() const {return positions.empty() && mask.empty() && colors.empty() && paintAlpha.empty() && hidden.empty() &&- polygroups.empty() && !mesh && !paint && !textureTiles && !texture && !subdiv;+ polygroups.empty() && !mesh && !paint && !textureTiles && !texture && !subdiv && !topology;}size_t approxBytes() const;diff --git a/tests/test_dyntopo.cpp b/tests/test_dyntopo.cppnew file mode 100644index 00000000..2e8c1933--- /dev/null+++ b/tests/test_dyntopo.cpp@@ -0,0 +1,487 @@+// SculptForge - open source digital sculpting+// SPDX-License-Identifier: GPL-3.0-or-later+//+// Dynamic topology (core/Dyntopo.h): strokes remesh the surface under the brush and leave a valid mesh+// (manifold, no degenerate or flipped triangles, Euler characteristic kept, adjacency and BVH matching a fresh+// build) after every dab; symmetry makes mirrored topology; undo and redo restore exactly; attributes are+// carried; boundaries, polygroup borders, masks and subdivision levels are respected.+#include "TestHarness.h"++#include "core/Commands.h"+#include "core/Multires.h"+#include "core/PathStroke.h"+#include "core/Primitives.h"+#include "core/ThreadPool.h"++#include <algorithm>+#include <cmath>+#include <map>+#include <set>+#include <tuple>++using namespace sf;++namespace {++// Why `m` isn't a valid mesh ("" if it is): corners in range and distinct, no degenerate triangles, every+// vertex used, every edge on one or two triangles wound oppositely (closed: exactly two), the adjacency lists+// as a rebuild makes them, and for a closed mesh V - E + F == euler.+std::string invalid(const Mesh& m, bool closed, int euler = 2) {+ const size_t nv = m.vertexCount(), nt = m.triangleCount();+ std::vector<int> used(nv, 0);+ std::map<std::pair<uint32_t, uint32_t>, int> directed;+ for (size_t t = 0; t < nt; ++t) {+ const glm::uvec3 tri = m.triangles[t];+ for (int c = 0; c < 3; ++c)+ if (tri[c] >= nv) return "corner out of range";+ if (tri.x == tri.y || tri.y == tri.z || tri.x == tri.z) return "repeated corner";+ const glm::vec3 n = glm::cross(m.positions[tri.y] - m.positions[tri.x], m.positions[tri.z] - m.positions[tri.x]);+ if (!(glm::length(n) > 1e-12f)) return "degenerate triangle " + std::to_string(t);+ for (int c = 0; c < 3; ++c) {+ used[tri[c]] = 1;+ if (++directed[{tri[c], tri[(c + 1) % 3]}] > 1) return "edge used twice in one direction";+ }+ }+ for (size_t v = 0; v < nv; ++v)+ if (!used[v]) return "unused vertex " + std::to_string(v);+ size_t edges = 0;+ for (const auto& [e, n] : directed) {+ const bool twin = directed.count({e.second, e.first}) > 0;+ if (closed && !twin) return "open edge";+ if (!twin || e.first < e.second) ++edges;+ }+ if (closed && long(nv) - long(edges) + long(nt) != euler) return "Euler characteristic changed";+ Mesh fresh = m;+ fresh.rebuildTopology();+ for (uint32_t v = 0; v < nv; ++v) {+ const IndexRing a = m.vertexTriangles(v), b = fresh.vertexTriangles(v);+ if (!std::equal(a.begin(), a.end(), b.begin(), b.end())) return "triangle list of vertex " + std::to_string(v);+ const IndexRing c = m.neighbors(v), d = fresh.neighbors(v);+ if (!std::equal(c.begin(), c.end(), d.begin(), d.end())) return "ring of vertex " + std::to_string(v);+ }+ if (m.normals.size() != nv) return "normals";+ return {};+}++// The BVH finds what a brute-force search finds (vertex queries and ray casts) at a few spots.+bool bvhMatches(const Mesh& m, const BVH& bvh) {+ for (int i = 0; i < 12; ++i) {+ const glm::vec3 c = m.positions[(size_t(i) * 7919) % m.vertexCount()];+ const float r = 0.3f;+ std::vector<uint32_t> got, want;+ bvh.queryVertices(m, c, r, got);+ for (uint32_t v = 0; v < m.vertexCount(); ++v)+ if (glm::dot(m.positions[v] - c, m.positions[v] - c) <= r * r) want.push_back(v);+ if (got != want) return false;+ const glm::vec3 origin = c * 3.0f + glm::vec3(0.01f, 0.02f, 0.0f);+ const glm::vec3 dir = glm::normalize(-origin);+ RayHit hit;+ const bool found = bvh.raycast(m, origin, dir, hit);+ float best = 1e30f;+ for (const glm::uvec3& t : m.triangles) {+ const glm::vec3 a = m.positions[t.x], e1 = m.positions[t.y] - a, e2 = m.positions[t.z] - a;+ const glm::vec3 pv = glm::cross(dir, e2);+ const float det = glm::dot(e1, pv);+ if (std::abs(det) < 1e-12f) continue;+ const glm::vec3 s = origin - a;+ const float u = glm::dot(s, pv) / det;+ const glm::vec3 q = glm::cross(s, e1);+ const float w = glm::dot(dir, q) / det, tt = glm::dot(e2, q) / det;+ if (u >= 0 && w >= 0 && u + w <= 1 && tt > 0) best = std::min(best, tt);+ }+ if (found != (best < 1e30f) || (found && std::abs(hit.t - best) > 1e-4f)) return false;+ }+ return true;+}++// A dab where a ray from `from` towards the origin hits the surface.+bool dabToward(Document& d, glm::vec3 from, float radius, BrushType type, Symmetry sym, float strength = 0.5f,+ glm::vec3 delta = glm::vec3(0.0f), bool invert = false) {+ RayHit hit;+ const glm::vec3 dir = glm::normalize(-from);+ if (!d.bvh.raycast(d.mesh, from, dir, hit)) return false;+ DabParams p;+ p.center = hit.position;+ p.viewDir = dir;+ p.radius = radius;+ p.strength = strength;+ p.strokeDelta = delta;+ p.invert = invert;+ d.sculptor.dab(d.mesh, d.bvh, type, p, sym);+ return true;+}++Document sphereDoc(int subdivisions = 3) {+ Document d = makeDoc(makeIcosphere(subdivisions, 1.0f));+ d.sculptor.dyntopo.enabled = true;+ return d;+}++// Mirror image of every vertex across x = 0 within `tol` (nearest, both ways), or empty when some vertex has none.+std::vector<uint32_t> mirrorMap(const Mesh& m, float tol) {+ std::vector<uint32_t> map(m.vertexCount(), ~0u);+ auto nearest = [&](const glm::vec3& p) {+ uint32_t best = ~0u;+ float bd = tol * tol;+ for (uint32_t w = 0; w < m.vertexCount(); ++w) {+ const glm::vec3 d = m.positions[w] - p;+ if (glm::dot(d, d) < bd) {+ bd = glm::dot(d, d);+ best = w;+ }+ }+ return best;+ };+ const glm::vec3 s(-1.0f, 1.0f, 1.0f);+ for (uint32_t v = 0; v < m.vertexCount(); ++v) {+ const uint32_t w = nearest(m.positions[v] * s);+ if (w == ~0u || nearest(m.positions[w] * s) != v) {+ std::printf(" no mirror image for vertex %u at %f %f %f\n", v, m.positions[v].x, m.positions[v].y, m.positions[v].z);+ return {};+ }+ map[v] = w;+ }+ return map;+}++// Every triangle's mirror image (reversed winding) is a triangle too.+bool mirroredTopology(const Mesh& m, const std::vector<uint32_t>& map) {+ std::set<std::tuple<uint32_t, uint32_t, uint32_t>> tris;+ auto canon = [](uint32_t a, uint32_t b, uint32_t c) {+ // Rotation starting at the smallest corner.+ if (b < a && b < c) return std::make_tuple(b, c, a);+ if (c < a && c < b) return std::make_tuple(c, a, b);+ return std::make_tuple(a, b, c);+ };+ for (const glm::uvec3& t : m.triangles) tris.insert(canon(t.x, t.y, t.z));+ int bad = 0;+ for (const glm::uvec3& t : m.triangles)+ if (!tris.count(canon(map[t.x], map[t.z], map[t.y]))) {+ if (bad++ < 4) {+ const glm::vec3 c = (m.positions[t.x] + m.positions[t.y] + m.positions[t.z]) / 3.0f;+ std::printf(" unmirrored triangle at %f %f %f\n", c.x, c.y, c.z);+ }+ }+ return bad == 0;+}++} // namespace++TEST(dyntopo_edge_length_follows_brush_or_mesh) {+ DyntopoSettings s;+ CHECK(std::abs(dyntopoEdgeLength(s, 0.1f, 2.0f) - 0.1f * 0.4f * std::pow(0.1f, 0.5f)) < 1e-6f);+ s.detail = 1.0f;+ const float fine = dyntopoEdgeLength(s, 0.1f, 2.0f);+ s.detail = 0.0f;+ CHECK(dyntopoEdgeLength(s, 0.1f, 2.0f) > fine * 9.0f);+ CHECK(dyntopoEdgeLength(s, 0.2f, 2.0f) > dyntopoEdgeLength(s, 0.1f, 2.0f) * 1.9f); // follows the brush+ s.constantDetail = true;+ CHECK(dyntopoEdgeLength(s, 0.2f, 2.0f) == dyntopoEdgeLength(s, 0.1f, 2.0f)); // follows the mesh+ CHECK(std::abs(dyntopoEdgeLength(s, 0.1f, 2.0f) - 0.1f) < 1e-6f); // diagonal / 20+}++TEST(dyntopo_adds_detail_under_the_brush_only) {+ Document d = sphereDoc(2); // 320 triangles, edges ~0.3+ const size_t before = d.mesh.triangleCount();+ const glm::vec3 far = d.mesh.positions[0];+ d.sculptor.dyntopo.detail = 0.8f;+ CHECK(d.sculptor.beginStroke(d.mesh, "Standard"));+ for (int i = 0; i < 6; ++i) CHECK(dabToward(d, glm::vec3(0.1f * float(i), 0.2f, 3.0f), 0.35f, BrushType::Standard, Symmetry{false, false, false}));+ CHECK(invalid(d.mesh, true).empty());+ CHECK(bvhMatches(d.mesh, d.bvh));+ UndoRecord r = d.sculptor.endStroke();+ CHECK(r.topology != nullptr);+ CHECK(d.mesh.triangleCount() > before * 2);+ CHECK(invalid(d.mesh, true).empty());+ CHECK(!d.mesh.dynamicAdjacency());+ // Edges near the stroke are about the detail size, the far side kept its coarse triangles.+ const float target = dyntopoEdgeLength(d.sculptor.dyntopo, 0.35f, 2.0f);+ float longestNear = 0.0f;+ for (const glm::uvec3& t : d.mesh.triangles)+ for (int c = 0; c < 3; ++c) {+ const glm::vec3 a = d.mesh.positions[t[c]], b = d.mesh.positions[t[(c + 1) % 3]];+ if (glm::distance((a + b) * 0.5f, glm::vec3(0.0f, 0.1f, 1.0f)) < 0.15f) longestNear = std::max(longestNear, glm::distance(a, b));+ }+ CHECK(longestNear <= target * 4.0f / 3.0f * 1.25f);+ CHECK(d.mesh.positions[0] == far);+}++TEST(dyntopo_random_strokes_stay_valid) {+ Document d = sphereDoc(3);+ uint32_t rng = 12345;+ auto rnd = [&rng] {+ rng ^= rng << 13;+ rng ^= rng >> 17;+ rng ^= rng << 5;+ return float(rng & 0xffff) / 65535.0f;+ };+ const BrushType types[] = {BrushType::Standard, BrushType::SnakeHook, BrushType::Smooth, BrushType::Clay,+ BrushType::Pinch, BrushType::Inflate, BrushType::Crease, BrushType::Flatten};+ bool allValid = true, bvhOk = true;+ std::string why;+ for (int stroke = 0; stroke < 24; ++stroke) {+ const BrushType type = types[stroke % 8];+ d.sculptor.dyntopo.detail = rnd();+ d.sculptor.dyntopo.constantDetail = stroke % 5 == 4;+ const Symmetry sym{stroke % 3 == 0, false, stroke % 7 == 0};+ CHECK(d.sculptor.beginStroke(d.mesh, brushName(type)));+ glm::vec3 dir = glm::normalize(glm::vec3(rnd() - 0.5f, rnd() - 0.5f, rnd() - 0.5f) + glm::vec3(0.0f, 0.0f, 0.01f));+ const glm::vec3 step = glm::normalize(glm::cross(dir, glm::vec3(0.3f, 1.0f, 0.1f))) * 0.08f;+ const float radius = 0.15f + 0.35f * rnd();+ for (int i = 0; i < 8; ++i) {+ dabToward(d, (dir + step * float(i)) * 3.0f, radius, type, sym, 0.6f, step * 0.5f, rnd() < 0.3f);+ if (allValid) {+ why = invalid(d.mesh, true);+ allValid = why.empty();+ if (!allValid) std::printf(" stroke %d dab %d: %s\n", stroke, i, why.c_str());+ }+ }+ bvhOk = bvhOk && bvhMatches(d.mesh, d.bvh);+ d.undo.push(d.sculptor.endStroke());+ if (allValid) {+ why = invalid(d.mesh, true);+ allValid = why.empty();+ if (!allValid) std::printf(" after stroke %d: %s\n", stroke, why.c_str());+ }+ }+ CHECK(allValid);+ CHECK(bvhOk);+ // Undo all the way back gives the sphere again, exactly.+ const Mesh sphere = makeIcosphere(3, 1.0f);+ while (d.undo.canUndo()) d.undo.undo(d.mesh, d.bvh);+ CHECK(d.mesh.triangles == sphere.triangles);+ CHECK(d.mesh.positions == sphere.positions);+ CHECK(bvhMatches(d.mesh, d.bvh));+}++TEST(dyntopo_undo_redo_restore_exactly) {+ Document d = sphereDoc(3);+ d.mesh.ensureMask();+ d.mesh.ensureColors(glm::vec3(0.2f, 0.5f, 0.9f));+ for (uint32_t v = 0; v < d.mesh.vertexCount(); ++v) d.mesh.mask[v] = d.mesh.positions[v].y > 0.5f ? 0.5f : 0.0f;+ const Mesh before = d.mesh;+ d.sculptor.dyntopo.detail = 0.7f;+ for (int s = 0; s < 3; ++s) {+ CHECK(d.sculptor.beginStroke(d.mesh, "Standard"));+ for (int i = 0; i < 6; ++i) dabToward(d, glm::vec3(0.15f * float(i) - 0.4f, 0.3f * float(s), 3.0f), 0.3f, BrushType::Standard, Symmetry{});+ d.undo.push(d.sculptor.endStroke());+ }+ const Mesh after = d.mesh;+ CHECK(after.triangleCount() != before.triangleCount());+ while (d.undo.canUndo()) d.undo.undo(d.mesh, d.bvh);+ CHECK(d.mesh.triangles == before.triangles);+ CHECK(d.mesh.positions == before.positions);+ CHECK(d.mesh.mask == before.mask);+ CHECK(d.mesh.colors == before.colors);+ CHECK(invalid(d.mesh, true).empty());+ while (d.undo.canRedo()) d.undo.redo(d.mesh, d.bvh);+ CHECK(d.mesh.triangles == after.triangles);+ CHECK(d.mesh.positions == after.positions);+ CHECK(d.mesh.mask == after.mask);+ CHECK(invalid(d.mesh, true).empty());+ CHECK(bvhMatches(d.mesh, d.bvh));+}++TEST(dyntopo_x_symmetry_makes_mirrored_topology) {+ Document d = sphereDoc(3);+ d.sculptor.dyntopo.detail = 0.75f;+ const Symmetry sym{true, false, false};+ // Strokes on one side, across the middle and pulling with Snake Hook.+ for (int s = 0; s < 3; ++s) {+ const BrushType type = s == 2 ? BrushType::SnakeHook : BrushType::Standard;+ CHECK(d.sculptor.beginStroke(d.mesh, brushName(type)));+ for (int i = 0; i < 8; ++i) {+ const glm::vec3 from = s == 0 ? glm::vec3(0.5f, 0.1f * float(i) - 0.3f, 1.0f)+ : s == 1 ? glm::vec3(0.1f * float(i) - 0.35f, -0.2f, 1.0f)+ : glm::vec3(0.6f, 0.4f, 0.8f);+ dabToward(d, from * 3.0f, 0.3f, type, sym, 0.5f, s == 2 ? glm::vec3(0.02f, 0.02f, 0.03f) : glm::vec3(0.0f));+ }+ d.undo.push(d.sculptor.endStroke());+ CHECK(invalid(d.mesh, true).empty());+ const std::vector<uint32_t> map = mirrorMap(d.mesh, dyntopoEdgeLength(d.sculptor.dyntopo, 0.3f, 2.0f) * 0.3f);+ CHECK(map.size() == d.mesh.vertexCount() && mirroredTopology(d.mesh, map));+ CHECK(d.sculptor.dynamicTopology().stats.unpaired == 0);+ }+ CHECK(d.mesh.triangleCount() > 1280 * 2);+ const float target = dyntopoEdgeLength(d.sculptor.dyntopo, 0.3f, 2.0f);+ const std::vector<uint32_t> map = mirrorMap(d.mesh, target * 0.3f);+ CHECK(map.size() == d.mesh.vertexCount());+ if (map.size() == d.mesh.vertexCount()) CHECK(mirroredTopology(d.mesh, map));+}++TEST(dyntopo_carries_attributes_and_drops_uvs) {+ Document d = sphereDoc(2);+ Mesh& m = d.mesh;+ m.ensureColors();+ m.ensurePolygroups();+ m.uvs.assign(m.triangleCount() * 3, glm::vec2(0.5f));+ for (uint32_t v = 0; v < m.vertexCount(); ++v) m.colors[v] = glm::vec3(m.positions[v].x * 0.5f + 0.5f, 0.2f, 0.1f);+ for (uint32_t t = 0; t < m.triangleCount(); ++t) {+ const glm::uvec3 tri = m.triangles[t];+ m.polygroups[t] = (m.positions[tri.x] + m.positions[tri.y] + m.positions[tri.z]).y > 0.0f ? 7u : 3u;+ }+ d.activeLayer = m.addLayer("Detail");+ m.rebuildTopology();+ d.bvh.build(m);+ // Group border vertices, and the border's length and each group's area (base positions).+ auto borderVerts = [](const Mesh& mesh) {+ std::set<uint32_t> out;+ for (uint32_t v = 0; v < mesh.vertexCount(); ++v) {+ std::set<uint32_t> groups;+ for (uint32_t t : mesh.vertexTriangles(v)) groups.insert(mesh.polygroups[t]);+ if (groups.size() > 1) out.insert(v);+ }+ return out;+ };+ auto borderLength = [](const Mesh& mesh) {+ std::map<std::pair<uint32_t, uint32_t>, std::set<uint32_t>> groups;+ for (uint32_t t = 0; t < mesh.triangleCount(); ++t)+ for (int c = 0; c < 3; ++c) {+ const uint32_t a = mesh.triangles[t][c], b = mesh.triangles[t][(c + 1) % 3];+ groups[{std::min(a, b), std::max(a, b)}].insert(mesh.polygroups[t]);+ }+ float len = 0.0f;+ for (const auto& [e, g] : groups)+ if (g.size() > 1) len += glm::distance(mesh.base[e.first], mesh.base[e.second]);+ return len;+ };+ auto groupArea = [](const Mesh& mesh, uint32_t group) {+ float area = 0.0f;+ for (uint32_t t = 0; t < mesh.triangleCount(); ++t) {+ if (mesh.polygroups[t] != group) continue;+ const glm::uvec3 tri = mesh.triangles[t];+ area += 0.5f * glm::length(glm::cross(mesh.base[tri.y] - mesh.base[tri.x], mesh.base[tri.z] - mesh.base[tri.x]));+ }+ return area;+ };+ const float lengthBefore = borderLength(m), area7 = groupArea(m, 7), area3 = groupArea(m, 3);+ const size_t borderBefore = borderVerts(m).size();+ d.sculptor.dyntopo.detail = 0.9f;+ CHECK(d.sculptor.beginStroke(m, "Standard", d.activeLayer));+ for (int i = 0; i < 8; ++i) dabToward(d, glm::vec3(0.1f * float(i) - 0.4f, 0.05f, 3.0f), 0.35f, BrushType::Standard, Symmetry{});+ d.undo.push(d.sculptor.endStroke());+ CHECK(invalid(m, true).empty());+ CHECK(m.uvs.empty());+ CHECK(m.colors.size() == m.vertexCount());+ CHECK(m.polygroups.size() == m.triangleCount());+ CHECK(m.layers[0].delta.size() == m.vertexCount() && m.base.size() == m.vertexCount());+ // Interpolated colours: red follows x everywhere.+ bool colorsOk = true;+ for (uint32_t v = 0; v < m.vertexCount(); ++v)+ colorsOk = colorsOk && std::abs(m.colors[v].x - (m.positions[v].x * 0.5f + 0.5f)) < 0.12f && m.colors[v].y == 0.2f;+ CHECK(colorsOk);+ // Positions are still base + layer offsets, and the stroke went into the layer.+ bool layered = true;+ float moved = 0.0f;+ for (uint32_t v = 0; v < m.vertexCount(); ++v) {+ layered = layered && glm::distance(m.positions[v], m.base[v] + m.layers[0].delta[v]) < 1e-5f;+ moved = std::max(moved, glm::length(m.layers[0].delta[v]));+ }+ CHECK(layered);+ CHECK(moved > 0.0f);+ // The border is still there, now with more vertices along it, and both groups stayed in their halves.+ CHECK(borderVerts(m).size() > borderBefore);+ CHECK(std::abs(borderLength(m) - lengthBefore) < 0.1f * lengthBefore);+ CHECK(std::abs(groupArea(m, 7) - area7) < 0.05f * area7);+ CHECK(std::abs(groupArea(m, 3) - area3) < 0.05f * area3);+ d.undo.undo(m, d.bvh);+ CHECK(m.uvs.size() == m.triangleCount() * 3);+ CHECK(borderVerts(m).size() == borderBefore);+}++TEST(dyntopo_keeps_boundaries_and_masked_areas) {+ Document d = makeDoc(makePlane(8, 2.0f)); // y = 0, x and z in -1..1+ d.sculptor.dyntopo.enabled = true;+ d.sculptor.dyntopo.detail = 0.8f;+ Mesh& m = d.mesh;+ m.ensureMask();+ for (uint32_t v = 0; v < m.vertexCount(); ++v) m.mask[v] = m.positions[v].x < -0.3f ? 1.0f : 0.0f;+ const Mesh before = m;+ CHECK(d.sculptor.beginStroke(m, "Standard"));+ for (int i = 0; i < 10; ++i) {+ RayHit hit;+ const glm::vec3 from(0.2f * float(i) - 1.0f, 3.0f, 0.9f);+ CHECK(d.bvh.raycast(m, from, glm::vec3(0, -1, 0), hit));+ DabParams p;+ p.center = hit.position;+ p.viewDir = glm::vec3(0, -1, 0);+ p.radius = 0.4f;+ p.strength = 0.3f;+ d.sculptor.dab(m, d.bvh, BrushType::Standard, p, Symmetry{false, false, false});+ }+ d.undo.push(d.sculptor.endStroke());+ CHECK(invalid(m, false).empty());+ CHECK(m.triangleCount() > before.triangleCount());+ // Boundary vertices stay on the square's edges; the edge at z = 1 got new vertices along it.+ size_t onEdge = 0;+ bool boundaryOk = true;+ std::map<std::pair<uint32_t, uint32_t>, int> count;+ for (const glm::uvec3& t : m.triangles)+ for (int c = 0; c < 3; ++c) ++count[{std::min(t[c], t[(c + 1) % 3]), std::max(t[c], t[(c + 1) % 3])}];+ for (const auto& [e, n] : count)+ if (n == 1)+ for (uint32_t v : {e.first, e.second}) {+ const glm::vec3 p = m.positions[v];+ const bool edge = std::abs(std::abs(p.x) - 1.0f) < 2e-3f || std::abs(std::abs(p.z) - 1.0f) < 2e-3f;+ boundaryOk = boundaryOk && edge;+ onEdge += std::abs(p.z - 1.0f) < 2e-3f;+ }+ CHECK(boundaryOk);+ CHECK(onEdge / 2 > 9); // more than the 9 vertices it started with (each counted on two boundary edges)+ // The fully masked part kept its vertices and triangles exactly.+ auto maskedTriangles = [](const Mesh& mesh) {+ std::multiset<std::vector<float>> out;+ for (const glm::uvec3& t : mesh.triangles) {+ if (mesh.mask[t.x] < 1.0f || mesh.mask[t.y] < 1.0f || mesh.mask[t.z] < 1.0f) continue;+ std::vector<float> key;+ for (int c = 0; c < 3; ++c)+ for (int k = 0; k < 3; ++k) key.push_back(mesh.positions[t[c]][k]);+ out.insert(key);+ }+ return out;+ };+ CHECK(!maskedTriangles(before).empty());+ CHECK(maskedTriangles(before) == maskedTriangles(m));+}++TEST(dyntopo_refuses_subdivision_levels) {+ Document d = sphereDoc(1);+ CHECK(dyntopoBlocker(d.mesh).empty());+ CommandRegistry reg;+ CHECK(reg.execute(d, "subdiv_divide", {}).ok);+ CHECK(!dyntopoBlocker(d.mesh).empty());+ const size_t before = d.mesh.triangleCount();+ d.sculptor.dyntopo.enabled = true;+ CHECK(d.sculptor.beginStroke(d.mesh, "Standard"));+ dabToward(d, glm::vec3(0, 0, 3), 0.3f, BrushType::Standard, Symmetry{});+ UndoRecord r = d.sculptor.endStroke();+ CHECK(!r.topology);+ CHECK(d.mesh.triangleCount() == before);+}++TEST(dyntopo_is_deterministic_with_any_thread_count) {+ auto run = [](bool serial) {+ ThreadPool::shared().setSerial(serial);+ Document d = sphereDoc(3);+ d.sculptor.dyntopo.detail = 0.8f;+ CHECK(d.sculptor.beginStroke(d.mesh, "Standard"));+ for (int i = 0; i < 10; ++i) dabToward(d, glm::vec3(0.1f * float(i) - 0.5f, 0.2f, 3.0f), 0.4f, BrushType::Clay, Symmetry{true, false, false});+ d.undo.push(d.sculptor.endStroke());+ ThreadPool::shared().setSerial(false);+ return d.mesh;+ };+ const Mesh a = run(true), b = run(false);+ CHECK(a.triangles == b.triangles);+ CHECK(a.positions == b.positions);+}++TEST(dyntopo_smooth_simplifies) {+ Document d = sphereDoc(4); // 5120 triangles+ const size_t before = d.mesh.triangleCount();+ d.sculptor.dyntopo.detail = 0.0f;+ CHECK(d.sculptor.beginStroke(d.mesh, "Smooth"));+ for (int i = 0; i < 10; ++i) dabToward(d, glm::vec3(0.05f * float(i), 0.0f, 3.0f), 0.5f, BrushType::Smooth, Symmetry{});+ d.undo.push(d.sculptor.endStroke());+ CHECK(invalid(d.mesh, true).empty());+ CHECK(d.mesh.triangleCount() < before);+}diff --git a/tests/test_main.cpp b/tests/test_main.cppindex 2dfac195..70553260 100644--- a/tests/test_main.cpp+++ b/tests/test_main.cpp@@ -5,11 +5,14 @@#include "TestHarness.h"#include <cstdio>+#include <cstring>#include <exception>-int main() {+// sculptforge_tests [part]: only the tests whose name contains `part`.+int main(int argc, char** argv) {using namespace sf::test;for (const auto& t : registry()) {+ if (argc > 1 && !std::strstr(t.name, argv[1])) continue;std::printf("[ RUN] %s\n", t.name);std::fflush(stdout); // so a crash still shows which test was runningint before = g_failures;