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
BVH vertex query: split the sphere's subtrees until there are enough tasks, each parallel job marks a bitmap of its own
islandmed8e8b77d6a66b
diff --git a/src/core/BVH.cpp b/src/core/BVH.cppindex 2863db56..ee507cc6 100644--- a/src/core/BVH.cpp+++ b/src/core/BVH.cpp@@ -28,6 +28,12 @@ bool sphereBox(const AABB& b, const glm::vec3& c, float r2) {return glm::dot(d, d) <= r2;}+// The box lies wholly within the sphere (its farthest corner does).+bool boxInSphere(const AABB& b, const glm::vec3& c, float r2) {+ const glm::vec3 d = glm::max(glm::abs(b.min - c), glm::abs(b.max - c));+ return glm::dot(d, d) <= r2;+}+// Two-sided Moller-Trumbore.bool rayTriangle(const glm::vec3& o, const glm::vec3& d, const glm::vec3& a, const glm::vec3& b,const glm::vec3& c, float& t) {@@ -251,26 +257,30 @@ void BVH::queryVertices(const Mesh& mesh, const glm::vec3& center, float radius,if (vertBits_.capacity() < mesh.vertexCount()) vertBits_.resize(mesh.vertexCount());const float r2 = radius * radius;- // The subtrees the sphere touches at a fixed depth (in depth-first order), the units of parallel work.- constexpr int kTaskDepth = 9;+ // The units of parallel work: the subtrees the sphere touches, split breadth first until there are enough+ // of them (the same ones for any thread count).+ constexpr size_t kTasks = 128;std::vector<uint32_t>& tasks = queryTasks_;tasks.clear();- std::vector<std::pair<uint32_t, int>> stack{{0u, 0}};- while (!stack.empty()) {- const auto [ni, depth] = stack.back();- stack.pop_back();- const Node& n = nodes_[ni];- if (!sphereBox(n.box, center, r2)) continue;- if (n.count > 0 || depth == kTaskDepth) {- tasks.push_back(ni);- continue;+ if (sphereBox(nodes_[0].box, center, r2)) tasks.push_back(0);+ for (bool split = true; split && tasks.size() < kTasks;) {+ split = false;+ queryNext_.clear();+ for (uint32_t ni : tasks) {+ const Node& n = nodes_[ni];+ if (n.count > 0) {+ queryNext_.push_back(ni);+ continue;+ }+ split = true;+ for (uint32_t c : {n.first, n.first + 1})+ if (sphereBox(nodes_[c].box, center, r2)) queryNext_.push_back(c);}- stack.push_back({n.first, depth + 1});- stack.push_back({n.first + 1, depth + 1});+ tasks.swap(queryNext_);}// Adds the vertices inside the sphere of the triangles under node `root` that the sphere's boxes touch, and// lists (depth first) the leaves holding any of them.- auto walk = [&](uint32_t root, std::vector<uint32_t>& nodeStack, std::vector<uint32_t>& leaves) {+ auto walk = [&](uint32_t root, std::vector<uint32_t>& nodeStack, std::vector<uint32_t>& leaves, IndexBits& found) {nodeStack.assign(1, root);while (!nodeStack.empty()) {const uint32_t ni = nodeStack.back();@@ -282,18 +292,28 @@ void BVH::queryVertices(const Mesh& mesh, const glm::vec3& center, float radius,nodeStack.push_back(n.first + 1);continue;}+ if (boxInSphere(n.box, center, r2)) { // every corner is inside+ for (uint32_t i = n.first; i < n.first + n.count; ++i) {+ const auto& t = mesh.triangles[triIndices_[i]];+ found.insertLocal(t.x);+ found.insertLocal(t.y);+ found.insertLocal(t.z);+ }+ leaves.push_back(ni);+ continue;+ }bool any = false;for (uint32_t i = n.first; i < n.first + n.count; ++i) {const auto& t = mesh.triangles[triIndices_[i]];for (int c = 0; c < 3; ++c) {const uint32_t v = t[c];- if (vertBits_.contains(v)) { // only vertices inside are ever added+ if (found.contains(v)) { // only vertices inside are ever addedany = true;continue;}const glm::vec3 d = mesh.positions[v] - center;if (glm::dot(d, d) <= r2) {- vertBits_.insert(v);+ found.insertLocal(v);any = true;}}@@ -302,30 +322,26 @@ void BVH::queryVertices(const Mesh& mesh, const glm::vec3& center, float radius,}};// The set doesn't depend on which thread found what, take() lists it in index order, and the leaves are- // joined in task order (the serial order).- if (tasks.size() < 8 || ThreadPool::shared().serial()) {- for (uint32_t root : tasks) walk(root, stack_, queryLeaves_);- } else {- if (queryParts_.size() < tasks.size()) queryParts_.resize(tasks.size());- poolFor(tasks.size(), [&](size_t b, size_t e) {- std::vector<uint32_t> nodeStack;- for (size_t k = b; k < e; ++k) {- queryParts_[k].clear();- walk(tasks[k], nodeStack, queryParts_[k]);- }- }, 1, 2);- for (size_t k = 0; k < tasks.size(); ++k) queryLeaves_.insert(queryLeaves_.end(), queryParts_[k].begin(), queryParts_[k].end());- }+ // joined in task order.+ if (queryParts_.size() < tasks.size()) queryParts_.resize(tasks.size());+ vertBits_.insertParallel(tasks.size(), 1, [&](size_t b, size_t e, IndexBits& found) {+ std::vector<uint32_t> nodeStack;+ for (size_t k = b; k < e; ++k) {+ queryParts_[k].clear();+ walk(tasks[k], nodeStack, queryParts_[k], found);+ }+ });+ for (size_t k = 0; k < tasks.size(); ++k) queryLeaves_.insert(queryLeaves_.end(), queryParts_[k].begin(), queryParts_[k].end());vertBits_.take(out);}void BVH::refit(const Mesh& mesh, std::span<const uint32_t> movedVerts) {if (nodes_.empty()) return;if (leafBits_.capacity() < nodes_.size()) leafBits_.resize(nodes_.size());- poolFor(movedVerts.size(), [&](size_t b, size_t e) {+ leafBits_.insertParallel(movedVerts.size(), 4096, [&](size_t b, size_t e, IndexBits& leaves) {for (size_t i = b; i < e; ++i)- for (uint32_t ti : mesh.vertexTriangles(movedVerts[i])) leafBits_.insert(triLeaf_[ti]);- }, 4096);+ for (uint32_t ti : mesh.vertexTriangles(movedVerts[i])) leaves.insertLocal(triLeaf_[ti]);+ });scratchLeaves_.clear();leafBits_.take(scratchLeaves_);refitLeaves(mesh, scratchLeaves_);diff --git a/src/core/BVH.h b/src/core/BVH.hindex abbea262..485f3013 100644--- a/src/core/BVH.h+++ b/src/core/BVH.h@@ -60,7 +60,7 @@ private: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_;+ mutable std::vector<uint32_t> queryTasks_, queryNext_;mutable std::vector<std::vector<uint32_t>> queryParts_;IndexBits leafBits_; // refit: the leaves to recomputestd::vector<uint32_t> scratchLeaves_;diff --git a/src/core/IndexBits.cpp b/src/core/IndexBits.cppindex 333fa1d3..ae1035a3 100644--- a/src/core/IndexBits.cpp+++ b/src/core/IndexBits.cpp@@ -4,7 +4,10 @@#include "core/ThreadPool.h"+#include <algorithm>+#include <atomic>#include <bit>+#include <mutex>namespace sf {@@ -26,6 +29,59 @@ void IndexBits::chunks(std::vector<uint32_t>& out) const {for (uint64_t bits = summary_[i]; bits; bits &= bits - 1) out.push_back(uint32_t(i * 64 + size_t(std::countr_zero(bits))));}+namespace {+std::mutex scratchMutex;+std::vector<IndexBits> scratchParts;+} // namespace++void IndexBits::insertParallel(size_t n, size_t block, const std::function<void(size_t, size_t, IndexBits&)>& add) {+ block = std::max<size_t>(block, 1);+ const size_t blocks = (n + block - 1) / block;+ const size_t jobs = std::min<size_t>(size_t(ThreadPool::shared().threads()), blocks);+ std::unique_lock lock(scratchMutex, std::defer_lock);+ if (jobs < 2 || blocks < 4 || ThreadPool::shared().serial() || !lock.try_lock()) {+ for (size_t b = 0; b < n; b += block) add(b, std::min(n, b + block), *this);+ return;+ }+ std::vector<IndexBits>& parts = scratchParts;+ if (parts.size() < jobs) parts.resize(jobs);+ for (size_t j = 0; j < jobs; ++j)+ if (parts[j].capacity() < capacity()) parts[j].resize(capacity());+ std::atomic<size_t> next{0};+ poolFor(jobs, [&](size_t jb, size_t je) {+ for (size_t j = jb; j < je; ++j)+ for (size_t b; (b = next.fetch_add(1, std::memory_order_relaxed)) < blocks;)+ add(b * block, std::min(n, (b + 1) * block), parts[j]);+ }, 1, 2);+ absorb(std::span(parts.data(), jobs));+}++void IndexBits::absorb(std::span<IndexBits> parts) {+ // The chunks any part holds (as summary words), then each chunk's words ORed together on one thread.+ std::vector<uint64_t> any(summary_.size(), 0);+ for (const IndexBits& p : parts)+ for (size_t i = 0; i < p.summary_.size() && i < any.size(); ++i) any[i] |= p.summary_[i];+ std::vector<uint32_t>& list = chunks_;+ list.clear();+ for (size_t i = 0; i < any.size(); ++i)+ for (uint64_t bits = any[i]; bits; bits &= bits - 1) list.push_back(uint32_t(i * 64 + size_t(std::countr_zero(bits))));+ for (size_t i = 0; i < any.size(); ++i) summary_[i] |= any[i];+ poolFor(list.size(), [&](size_t b, size_t e) {+ for (size_t k = b; k < e; ++k) {+ const size_t first = size_t(list[k]) * kChunkWords;+ const uint64_t sbit = uint64_t(1) << (list[k] & 63);+ for (IndexBits& p : parts) {+ if (!(p.summary_[list[k] >> 6] & sbit)) continue;+ for (uint32_t j = 0; j < kChunkWords; ++j) {+ words_[first + j] |= p.words_[first + j];+ p.words_[first + j] = 0;+ }+ }+ }+ }, 8);+ for (IndexBits& p : parts) std::fill(p.summary_.begin(), p.summary_.end(), 0);+}+void IndexBits::take(std::vector<uint32_t>& out, const std::function<void(size_t, uint64_t)>& perWord) {chunks(chunks_);const size_t nc = chunks_.size();diff --git a/src/core/IndexBits.h b/src/core/IndexBits.hindex 82569b5f..b69a139a 100644--- a/src/core/IndexBits.h+++ b/src/core/IndexBits.h@@ -7,6 +7,9 @@// same with any thread count, and passes over the list walk the mesh's arrays front to back instead of// jumping around (the indices a dab touches lie in a few dozen runs).//+// Threads add with insert() (atomic), or each into a set of its own with insertParallel(), which is faster when+// many threads add a lot.+//// A summary bit per kChunk indices marks the chunks holding members, so take() only visits those: its cost// follows the size of the set, not of the mesh.#pragma once@@ -16,6 +19,7 @@#include <cstddef>#include <cstdint>#include <functional>+#include <span>#include <vector>namespace sf {@@ -48,6 +52,24 @@ public:return true;}+ // insert() for a set only one thread writes (no atomics).+ bool insertLocal(uint32_t i) {+ uint64_t& w = words_[i >> 6];+ const uint64_t bit = uint64_t(1) << (i & 63);+ if (w & bit) return false;+ if (w == 0) summary_[(i / kChunk) >> 6] |= uint64_t(1) << ((i / kChunk) & 63);+ w |= bit;+ return true;+ }+ // Calls add(begin, end, set) for the blocks [b * block, (b + 1) * block) of [0, n) on the shared pool; `add`+ // marks members with set.insertLocal(). Each job adds to a scratch set of its own (no atomics, and no cache+ // lines bouncing between cores), merged into this one at the end. Small or serial runs add here directly,+ // as do runs while another thread is using the scratch sets (shared by every IndexBits, a bit per index of+ // the largest one, per thread).+ void insertParallel(size_t n, size_t block, const std::function<void(size_t, size_t, IndexBits&)>& add);+ // Moves every member of `parts` (each as big as this set) into this one, in parallel by chunk.+ void absorb(std::span<IndexBits> parts);+// Appends the members to `out` in increasing order and empties the set (in parallel on the shared pool// for big sets). `perWord(wordIndex, bits)`, if given, sees every non-zero word once (from any thread, but// each 64-word chunk on one thread), e.g. to OR the set into another bitmap of the same layout.diff --git a/src/core/Mesh.cpp b/src/core/Mesh.cppindex 522f5d4c..c7c6b0a1 100644--- a/src/core/Mesh.cpp+++ b/src/core/Mesh.cpp@@ -243,13 +243,13 @@ void Mesh::updateNormals(std::span<const uint32_t> verts) {if (adjOffsets_.size() != nv + 1) return; // no topologygrowDirtyBlocks((nv + kDirtyBlock - 1) / kDirtyBlock);if (normalBits_.capacity() < nv) normalBits_.resize(nv);- poolFor(verts.size(), [&](size_t b, size_t e) {+ normalBits_.insertParallel(verts.size(), 4096, [&](size_t b, size_t e, IndexBits& set) {for (size_t i = b; i < e; ++i) {const uint32_t v = verts[i];- normalBits_.insert(v);- for (uint32_t u : neighbors(v)) normalBits_.insert(u);+ set.insertLocal(v);+ for (uint32_t u : neighbors(v)) set.insertLocal(u);}- }, 4096);+ });// Listing the set also marks it dirty: its words are laid out like dirtyBits, and each 2048-vertex dirty// block lies in one of its chunks (so no two threads write the same word).static_assert(IndexBits::kChunk % kDirtyBlock == 0);