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
Micro levels: picks and brushes find candidates through per-node displacement bounds, not the level's largest
islandmede69441b082f4
diff --git a/src/core/BVH.cpp b/src/core/BVH.cppindex 1e8c45bf..6214abae 100644--- a/src/core/BVH.cpp+++ b/src/core/BVH.cpp@@ -58,6 +58,7 @@ 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();+ ++structure_;nodes_.clear();std::vector<uint32_t>().swap(leafCap_);editedLeaves_.clear();@@ -262,6 +263,62 @@ void BVH::queryTriangles(const Mesh& mesh, const glm::vec3& center, float radius}}+void BVH::queryTrianglesPadded(const Mesh& mesh, const glm::vec3& center, float radius, std::span<const float> pad, float extra,+ std::vector<uint32_t>& out) const {+ out.clear();+ if (nodes_.empty() || pad.size() != nodes_.size()) return;+ thread_local std::vector<uint32_t> stack;+ stack.clear();+ stack.push_back(0);+ while (!stack.empty()) {+ const uint32_t ni = stack.back();+ stack.pop_back();+ const Node& n = nodes_[ni];+ const float r = radius + pad[ni] + extra;+ if (!sphereBox(n.box, center, r * r)) continue;+ if (n.count > 0) {+ for (uint32_t i = n.first; i < n.first + n.count; ++i) {+ const auto& t = mesh.triangles[triIndices_[i]];+ AABB b;+ b.expand(mesh.positions[t.x]);+ b.expand(mesh.positions[t.y]);+ b.expand(mesh.positions[t.z]);+ if (sphereBox(b, center, r * r)) out.push_back(triIndices_[i]);+ }+ } else if (n.first != kNoLeaf) {+ stack.push_back(n.first);+ stack.push_back(n.first + 1);+ }+ }+}++void BVH::rayTrianglesPadded(const Mesh& mesh, const glm::vec3& origin, const glm::vec3& dir, std::span<const float> pad, float extra,+ std::vector<uint32_t>& out) const {+ out.clear();+ if (nodes_.empty() || pad.size() != nodes_.size()) return;+ glm::vec3 safeDir = dir;+ for (int i = 0; i < 3; ++i)+ if (std::abs(safeDir[i]) < 1e-20f) safeDir[i] = std::copysign(1e-20f, safeDir[i]);+ const glm::vec3 invDir = 1.0f / safeDir;+ const float far = std::numeric_limits<float>::max();+ thread_local std::vector<uint32_t> stack;+ stack.clear();+ stack.push_back(0);+ while (!stack.empty()) {+ const uint32_t ni = stack.back();+ stack.pop_back();+ const Node& n = nodes_[ni];+ const glm::vec3 g(pad[ni] + extra);+ if (!rayBox(AABB{n.box.min - g, n.box.max + g}, origin, invDir, far)) continue;+ if (n.count > 0) {+ for (uint32_t i = n.first; i < n.first + n.count; ++i) out.push_back(triIndices_[i]);+ } else if (n.first != kNoLeaf) {+ stack.push_back(n.first);+ stack.push_back(n.first + 1);+ }+ }+}+void BVH::forEachLeafInSphere(const glm::vec3& center, float radius,const std::function<void(std::span<const uint32_t>)>& fn) const {if (nodes_.empty()) return;@@ -574,6 +631,7 @@ void BVH::editLeaf(uint32_t leaf) {}void BVH::insertTriangle(const Mesh& mesh, uint32_t t, uint32_t nearby) {+ ++structure_;if (nodes_.empty()) {nodes_.push_back(Node{AABB{}, kNoLeaf, 0, 0});leafBits_.resize(nodes_.size());@@ -610,6 +668,7 @@ void BVH::insertTriangle(const Mesh& mesh, uint32_t t, uint32_t nearby) {}void BVH::removeTriangle(uint32_t t) {+ ++structure_;const uint32_t leaf = t < triLeaf_.size() ? triLeaf_[t] : kNoLeaf;if (leaf == kNoLeaf) return;editLeaf(leaf);@@ -629,6 +688,7 @@ void BVH::removeTriangle(uint32_t t) {}void BVH::renumberTriangle(uint32_t from, uint32_t to) {+ ++structure_;const uint32_t leaf = from < triLeaf_.size() ? triLeaf_[from] : kNoLeaf;if (leaf == kNoLeaf) return;const Node& n = nodes_[leaf];@@ -639,7 +699,10 @@ void BVH::renumberTriangle(uint32_t from, uint32_t to) {triLeaf_[from] = kNoLeaf;}-void BVH::resizeTriangles(size_t count) { triLeaf_.resize(count, kNoLeaf); }+void BVH::resizeTriangles(size_t count) {+ ++structure_;+ triLeaf_.resize(count, kNoLeaf);+}void BVH::touchTriangle(uint32_t t) {if (t < triLeaf_.size() && triLeaf_[t] != kNoLeaf) editLeaf(triLeaf_[t]);@@ -648,6 +711,7 @@ void BVH::touchTriangle(uint32_t 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) {+ ++structure_;const uint32_t first = nodes_[leaf].first, count = nodes_[leaf].count;auto centroid = [&](uint32_t t) {const glm::uvec3& tri = mesh.triangles[t];diff --git a/src/core/BVH.h b/src/core/BVH.hindex f8126312..3a63a541 100644--- a/src/core/BVH.h+++ b/src/core/BVH.h@@ -78,6 +78,22 @@ public:bool degraded() const;size_t nodeCount() const { return nodes_.size(); }++ // Per-node padding (micro levels: the largest displacement under each node, core/Micro.cpp MicroReach). The+ // padded queries grow every node's box, and each leaf triangle's, by pad[node] (one value per node) plus+ // `extra`; the caller then tests each triangle exactly. Leaves and parents for keeping pads up to date:+ // structureSerial() changes whenever nodes or the triangle-to-leaf map do (build, dynamic edits).+ uint64_t structureSerial() const { return structure_; }+ uint32_t leafOf(uint32_t tri) const { return tri < triLeaf_.size() ? triLeaf_[tri] : kNoLeaf; }+ uint32_t parentOf(uint32_t node) const { return nodes_[node].parent; }+ // Child nodes have larger indices than their parent (a reverse sweep sees children first).+ bool isInner(uint32_t node) const { return nodes_[node].count == 0 && nodes_[node].first != kNoLeaf; }+ uint32_t leftChild(uint32_t node) const { return nodes_[node].first; }+ void queryTrianglesPadded(const Mesh& mesh, const glm::vec3& center, float radius, std::span<const float> pad, float extra,+ std::vector<uint32_t>& out) const;+ // The triangles of every leaf whose padded box the ray (from origin along dir, t >= 0) crosses.+ void rayTrianglesPadded(const Mesh& mesh, const glm::vec3& origin, const glm::vec3& dir, std::span<const float> pad, float extra,+ std::vector<uint32_t>& out) const;size_t memoryBytes() const;private:@@ -92,6 +108,7 @@ private:void recomputeLeaf(const Mesh& mesh, Node& n); // its box, and triLeaf_ for its trianglesstd::vector<Node> nodes_;+ uint64_t structure_ = 0;std::vector<uint32_t> triIndices_;std::vector<uint32_t> triLeaf_;diff --git a/src/core/Micro.cpp b/src/core/Micro.cppindex 6fa8166f..ceadf385 100644--- a/src/core/Micro.cpp+++ b/src/core/Micro.cpp@@ -15,6 +15,7 @@#include <algorithm>#include <atomic>+#include <bit>#include <cmath>#include <cstdlib>#include <cstring>@@ -74,6 +75,7 @@ int MicroMesh::widen(float need) {rangeMax = uint16_t(std::min(int(rangeMax) / div + 1, 32767));step *= float(div);rescaled = true;+ reach.all = true;++revision;return div;}@@ -386,7 +388,7 @@ bool microDivide(Mesh& m, int level, std::string& error, int outOfCore) {// level 4). Brushes widen the range when they need more (MicroStroke).mm->step = std::max(avgEdge / 4096.0f, 1e-12f);mm->serial = MicroMesh::newSerial();- mm->allDirty = true;+ mm->markAllDirty();m.micro = std::move(mm);m.topologyDirty = true; // the renderer draws it differentlyreturn true;@@ -443,7 +445,7 @@ bool microAttach(Mesh& m, int level, float step, MicroStore disp, std::vector<uifor (uint16_t r : mm->triRange) mm->rangeMax = std::max(mm->rangeMax, r);mm->ensureTopology(m);mm->serial = MicroMesh::newSerial();- mm->allDirty = true;+ mm->markAllDirty();m.micro = std::move(mm);m.topologyDirty = true;return true;@@ -478,14 +480,73 @@ bool rayTriangle(const glm::vec3& o, const glm::vec3& d, const glm::vec3& a, con} // namespace+namespace {++// Brings m's Reach up to date with `bvh` (call with reach.lock held): a full pass when the BVH, the step or+// everything changed, else the triangles marked since raise their leaves and ancestors.+void syncReach(const Mesh& m, const BVH& bvh) {+ const MicroMesh& mm = *m.micro;+ MicroMesh::Reach& r = mm.reach;+ const size_t words = (size_t(mm.baseTriangles) + 63) / 64;+ const bool full = r.all || r.bvh != &bvh || r.structure != bvh.structureSerial() || r.step != mm.step ||+ r.pad.size() != bvh.nodeCount() || r.bits.size() != words;+ if (full) {+ r.bvh = &bvh, r.structure = bvh.structureSerial(), r.step = mm.step, r.all = false;+ r.bits.assign(words, 0);+ const size_t nodes = bvh.nodeCount();+ r.pad.assign(nodes, 0.0f);+ poolFor(nodes, [&](size_t b, size_t e) {+ for (size_t i = b; i < e; ++i) {+ uint16_t most = 0;+ for (uint32_t t : bvh.leafTriangles(uint32_t(i)))+ if (t < mm.triRange.size()) most = std::max(most, mm.triRange[t]);+ r.pad[i] = float(most) * mm.step;+ }+ }, 1 << 12);+ for (size_t i = nodes; i-- > 0;)+ if (bvh.isInner(uint32_t(i))) {+ const uint32_t c = bvh.leftChild(uint32_t(i));+ r.pad[i] = std::max(r.pad[c], r.pad[c + 1]);+ }+ return;+ }+ for (size_t w = 0; w < words; ++w) {+ if (!r.bits[w]) continue;+ const uint64_t bits = std::atomic_ref<uint64_t>(r.bits[w]).exchange(0);+ for (uint64_t b = bits; b; b &= b - 1) {+ const uint32_t t = uint32_t(w * 64 + size_t(std::countr_zero(b)));+ const float v = float(mm.triRange[t]) * mm.step;+ for (uint32_t node = bvh.leafOf(t); node != ~0u && r.pad[node] < v; node = bvh.parentOf(node)) {+ r.pad[node] = v;+ if (node == 0) break;+ }+ }+ }+}++} // namespace++void microQueryTriangles(const Mesh& m, const BVH& bvh, const glm::vec3& center, float radius, std::vector<uint32_t>& out) {+ const MicroMesh& mm = *m.micro;+ std::lock_guard<std::mutex> hold(mm.reach.lock);+ syncReach(m, bvh);+ bvh.queryTrianglesPadded(m, center, radius, mm.reach.pad, mm.bulgeMax, out);+}++void microRayTriangles(const Mesh& m, const BVH& bvh, const glm::vec3& origin, const glm::vec3& dir, std::vector<uint32_t>& out) {+ const MicroMesh& mm = *m.micro;+ std::lock_guard<std::mutex> hold(mm.reach.lock);+ syncReach(m, bvh);+ bvh.rayTrianglesPadded(m, origin, dir, mm.reach.pad, mm.bulgeMax, out);+}+bool microRaycast(const Mesh& m, const BVH& bvh, const glm::vec3& origin, const glm::vec3& dir, RayHit& hit) {if (!microMatches(m)) return bvh.raycast(m, origin, dir, hit);const MicroMesh& mm = *m.micro;RayHit base;if (!bvh.raycast(m, origin, dir, base)) return false;- const float reach = mm.bulgeMax + float(mm.rangeMax) * mm.step;std::vector<uint32_t> cand;- bvh.queryTriangles(m, base.position, 2.0f * reach + 1e-7f, cand);+ microRayTriangles(m, bvh, origin, dir, cand);// Only the triangles whose own reach (their bulge and displacement range) the ray passes through.const glm::vec3 inv(1.0f / (std::abs(dir.x) > 1e-20f ? dir.x : 1e-20f), 1.0f / (std::abs(dir.y) > 1e-20f ? dir.y : 1e-20f),1.0f / (std::abs(dir.z) > 1e-20f ? dir.z : 1e-20f));@@ -835,7 +896,7 @@ void MicroUndo::swapWith(Mesh& m) {if (swapWhole) {std::swap(m.micro, whole);if (m.micro) {- m.micro->allDirty = true;+ m.micro->markAllDirty();m.micro->ensureTopology(m);if (m.micro->dirtyBits.size() != (size_t(m.micro->baseTriangles) + 63) / 64)m.micro->dirtyBits.assign((size_t(m.micro->baseTriangles) + 63) / 64, 0);@@ -1237,7 +1298,7 @@ void microNoise(Mesh& m, float amplitude, float frequency, uint32_t seed) {}}, 256);for (uint16_t r : mm.triRange) mm.rangeMax = std::max(mm.rangeMax, r);- mm.allDirty = true;+ mm.markAllDirty();++mm.revision;}diff --git a/src/core/Micro.h b/src/core/Micro.hindex 0526e430..868b16d5 100644--- a/src/core/Micro.h+++ b/src/core/Micro.h@@ -41,6 +41,7 @@#include <cstdint>#include <functional>#include <memory>+#include <mutex>#include <span>#include <string>#include <vector>@@ -75,6 +76,26 @@ struct MicroMesh {// neighbouring triangle (tri << 2 | its edge), or kNone on a boundary.std::vector<uint32_t> edgeNeighbor;+ // Picks and brushes find the base triangles a displaced surface may reach through the BVH, each node grown by the+ // largest displacement under it (not the level's largest everywhere: one tall stroke made every query on a+ // dense base visit millions of triangles). Derived, per BVH: microQueryTriangles / microRayTriangles keep it.+ struct Reach {+ std::mutex lock;+ const void* bvh = nullptr;+ uint64_t structure = 0;+ float step = 0.0f;+ std::vector<float> pad; // per BVH node, world units (upper bounds: they only shrink on a full pass)+ std::vector<uint64_t> bits; // base triangles changed since (markDirty)+ bool all = true; // everything (markAllDirty, a rescale, a new level)+ Reach() = default;+ Reach(const Reach&) {} // (a copy starts over: it may be checked against another BVH)+ Reach& operator=(const Reach&) {+ all = true, bvh = nullptr;+ return *this;+ }+ };+ mutable Reach reach;+// What changed since the renderer last looked: per base triangle a bit, or everything.std::vector<uint64_t> dirtyBits;bool allDirty = true;@@ -103,11 +124,14 @@ struct MicroMesh {else if (e == 1) i = n - k, j = k;else i = 0, j = n - k;}- void markDirty(uint32_t tri) { dirtyBits[tri >> 6] |= uint64_t(1) << (tri & 63); }+ void markDirty(uint32_t tri) {+ dirtyBits[tri >> 6] |= uint64_t(1) << (tri & 63);+ if (!reach.bits.empty()) reach.bits[tri >> 6] |= uint64_t(1) << (tri & 63);+ }// Grows `step` (by powers of two, at least 4x) until +/-`need` world units fit, rescaling every value (each// loses its lowest bits). Returns the divisor applied (1 = it fitted already).int widen(float need);- void markAllDirty() { allDirty = true; }+ void markAllDirty() { allDirty = true, reach.all = true; }void clearDirty();// Builds edgeNeighbor for `base` (if it doesn't fit already).void ensureTopology(const Mesh& base);@@ -209,6 +233,11 @@ void microNoise(Mesh& m, float amplitude, float frequency, uint32_t seed = 1);// Ray against the micro surface: the base triangle hit (BVH) and its neighbourhood within the displacement range,// at full micro resolution. hit.triangle is the base triangle; hit.position / normal are on the micro surface.bool microRaycast(const Mesh& m, const BVH& bvh, const glm::vec3& origin, const glm::vec3& dir, RayHit& hit);+// The base triangles whose displaced surface may come within `radius` of `center` (each BVH node grown by the+// largest displacement and bulge under it, MicroMesh::Reach), for the caller's exact test per triangle.+void microQueryTriangles(const Mesh& m, const BVH& bvh, const glm::vec3& center, float radius, std::vector<uint32_t>& out);+// ... and those whose displaced surface the ray may cross.+void microRayTriangles(const Mesh& m, const BVH& bvh, const glm::vec3& origin, const glm::vec3& dir, std::vector<uint32_t>& out);// bvh.raycast, or microRaycast on a mesh with a micro level: what brushes and the cursor pick.bool surfaceRaycast(const Mesh& m, const BVH& bvh, const glm::vec3& origin, const glm::vec3& dir, RayHit& hit);diff --git a/src/core/MicroSculpt.cpp b/src/core/MicroSculpt.cppindex ce1b7e19..e2fc4051 100644--- a/src/core/MicroSculpt.cpp+++ b/src/core/MicroSculpt.cpp@@ -291,7 +291,7 @@ void MicroStroke::dab(Mesh& m, const BVH& bvh, BrushType type, const glm::vec3&std::fill(vertStamp_.begin(), vertStamp_.end(), 0);dabEpoch_ = 1;}- bvh.queryTriangles(m, center, r * reach + mm.bulgeMax + float(mm.rangeMax) * mm.step, cand_);+ microQueryTriangles(m, bvh, center, r * reach, cand_); // (each node grown by the displacement under it)std::erase_if(cand_, [&](uint32_t t) { return m.triangleHidden(t) || !triangleNear(m, mm, t, center, r * reach); });if (cand_.empty()) return;for (uint32_t t : cand_) dabStamp_[t] = dabEpoch_;@@ -548,7 +548,7 @@ void MicroStroke::beginGrab(Mesh& m, const BVH& bvh, const glm::vec3& center, fllastStride = stride;const uint32_t cm = n / stride, cs = (cm + 1) * (cm + 2) / 2;std::vector<uint32_t> cand;- bvh.queryTriangles(m, center, radius + mm.bulgeMax + float(mm.rangeMax) * mm.step, cand);+ microQueryTriangles(m, bvh, center, radius, cand);std::erase_if(cand, [&](uint32_t t) { return m.triangleHidden(t) || !triangleNear(m, mm, t, center, radius); });touch(mm, cand);GrabMirror gm;