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
Big brushes: dab normals from the query's BVH leaves, parallel upload runs
islandmed3ac6122a42fb
diff --git a/src/core/BVH.h b/src/core/BVH.hindex 4b391268..fe5110a8 100644--- a/src/core/BVH.h+++ b/src/core/BVH.h@@ -39,6 +39,12 @@ public:// The leaves holding the vertices the last queryVertices() returned, and refit() given such leaves (from// one or more queries, each once: the Move brush keeps them for its whole stroke).std::span<const uint32_t> queriedLeaves() const { return queryLeaves_; }+ // The triangles of a leaf (empty for an inner node): every triangle with a vertex a query found is in one of+ // the leaves it listed.+ std::span<const uint32_t> leafTriangles(uint32_t leaf) const {+ const Node& n = nodes_[leaf];+ return n.count > 0 ? std::span<const uint32_t>(triIndices_.data() + n.first, n.count) : std::span<const uint32_t>();+ }void refitLeaves(const Mesh& mesh, std::span<const uint32_t> leaves);// Recomputes every box (same tree) after most of the mesh moved, e.g. a whole SubTool transformed.void refitAll(const Mesh& mesh);diff --git a/src/core/Mesh.cpp b/src/core/Mesh.cppindex 5db2d9be..2dc24c97 100644--- a/src/core/Mesh.cpp+++ b/src/core/Mesh.cpp@@ -605,10 +605,7 @@ void Mesh::updateNormals(std::span<const uint32_t> verts) {// The vertices whose normal changes: the moved ones and every neighbour, gathered as a set and listed in// index order; then each one's normal from its faces, in its triangle order (as recomputeAllNormals sums// them). The set, and every normal computed from it, doesn't depend on the thread count.- const size_t nv = positions.size();- if (!implicit_ && adjOffsets_.size() != nv + 1) return; // no topology- growDirtyBlocks((nv + kDirtyBlock - 1) / kDirtyBlock);- if (normalBits_.capacity() < nv) normalBits_.resize(nv);+ if (!beginNormalSet()) return;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];@@ -616,6 +613,24 @@ void Mesh::updateNormals(std::span<const uint32_t> verts) {for (uint32_t u : neighbors(v)) set.insertLocal(u);}});+ finishNormals();+}++void Mesh::updateNormalsAround(size_t count, size_t grain, const std::function<void(size_t, size_t, IndexBits&)>& fill) {+ if (!beginNormalSet()) return;+ normalBits_.insertParallel(count, grain, fill);+ finishNormals();+}++bool Mesh::beginNormalSet() {+ const size_t nv = positions.size();+ if (!implicit_ && adjOffsets_.size() != nv + 1) return false; // no topology+ growDirtyBlocks((nv + kDirtyBlock - 1) / kDirtyBlock);+ if (normalBits_.capacity() < nv) normalBits_.resize(nv);+ return true;+}++void Mesh::finishNormals() {// 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);diff --git a/src/core/Mesh.h b/src/core/Mesh.hindex cfbe9458..2fe4cdf7 100644--- a/src/core/Mesh.h+++ b/src/core/Mesh.h@@ -10,6 +10,7 @@#include <cstdint>#include <limits>#include <memory>+#include <functional>#include <span>#include <string>#include <utility>@@ -205,6 +206,10 @@ public:void recomputeAllNormals();// Recompute normals of the faces around `verts` and of every vertex they touch.void updateNormals(std::span<const uint32_t> verts);+ // The same, given the vertices whose normals may have changed (any superset: the others come out the+ // same): fill(begin, end, set) adds those of jobs [begin, end) of `count` with set.insertLocal(). A brush+ // gives the corners of the BVH leaves its query listed, which is cheaper than every moved vertex's ring.+ void updateNormalsAround(size_t count, size_t grain, const std::function<void(size_t, size_t, IndexBits&)>& fill);// The vertices sharing an edge with `v`, and the triangles around it, in ascending order.IndexRing neighbors(uint32_t v) const {@@ -274,6 +279,8 @@ public:private:void finishTopology();+ bool beginNormalSet(); // updateNormals: room for the set (false: no topology)+ void finishNormals(); // ... then each member's normalIndexRing implicitTriangles(uint32_t v) const;IndexRing implicitNeighbors(uint32_t v) const;diff --git a/src/core/Sculpt.cpp b/src/core/Sculpt.cppindex 5fa231c9..389b0545 100644--- a/src/core/Sculpt.cpp+++ b/src/core/Sculpt.cpp@@ -459,6 +459,7 @@ void Sculptor::dab(Mesh& mesh, BVH& bvh, BrushType type, const DabParams& p, SymremeshDab(mesh, bvh, p, sym, type == BrushType::Smooth ? 2.0f : 1.0f, reach);}dabVerts_.clear();+ dabLeaves_.clear();for (const glm::vec3& m : mirrors(sym)) {DabParams mp = p;mp.center *= m;@@ -468,7 +469,7 @@ void Sculptor::dab(Mesh& mesh, BVH& bvh, BrushType type, const DabParams& p, Symif (type == BrushType::Vdm) dabVdmSingle(mesh, bvh, mp, m.x * m.y * m.z);else dabSingle(mesh, bvh, type, mp);}- updateDabNormals(mesh);+ updateDabNormals(mesh, bvh);if (type != BrushType::Move) repairDab(mesh, bvh);}@@ -647,11 +648,30 @@ void Sculptor::finishDab(Mesh& mesh, BVH& bvh, std::chrono::steady_clock::time_p++timings.dabs;timings.vertices += verts_.size();dabVerts_.insert(dabVerts_.end(), verts_.begin(), verts_.end()); // a vertex twice is fine: updateNormals dedups+ const auto leaves = bvh.queriedLeaves(); // (the query that found verts_)+ dabLeaves_.insert(dabLeaves_.end(), leaves.begin(), leaves.end());}-void Sculptor::updateDabNormals(Mesh& mesh) {+// The normals that the dab's moves change: those of every corner of the triangles in the leaves the queries+// listed (each triangle with a moved vertex is in one), a set found faster than from each moved vertex's ring+// (implicit rings on levels made by Divide cost 7 ms a dab for 3M vertices). Dynamic topology changed the tree+// as it remeshed, so there the rings are used.+void Sculptor::updateDabNormals(Mesh& mesh, const BVH& bvh) {auto clock = std::chrono::steady_clock::now();- mesh.updateNormals(dabVerts_);+ if (dynTopo_.active() || dabLeaves_.empty()) {+ mesh.updateNormals(dabVerts_);+ } else {+ mesh.updateNormalsAround(dabLeaves_.size(), 64, [&](size_t b, size_t e, IndexBits& set) {+ for (size_t i = b; i < e; ++i)+ for (uint32_t t : bvh.leafTriangles(dabLeaves_[i])) {+ const glm::uvec3& tri = mesh.triangles[t];+ set.insertLocal(tri.x);+ set.insertLocal(tri.y);+ set.insertLocal(tri.z);+ }+ });+ }+ dabLeaves_.clear();timings.normalsMs += lapMs(clock);}@@ -662,6 +682,7 @@ void Sculptor::dabRecipe(Mesh& mesh, BVH& bvh, const BrushRecipe& recipe, constbase.pressure = std::pow(std::clamp(p.pressure, 0.0f, 1.0f), recipe.pressureCurve);base.frontFacesOnly = p.frontFacesOnly || recipe.frontFacesOnly;dabVerts_.clear();+ dabLeaves_.clear();for (const glm::vec3& m : mirrors(sym)) {DabParams mp = base;mp.center *= m;@@ -670,7 +691,7 @@ void Sculptor::dabRecipe(Mesh& mesh, BVH& bvh, const BrushRecipe& recipe, constmp.alphaUp *= m;dabRecipeSingle(mesh, bvh, recipe, mp);}- updateDabNormals(mesh);+ updateDabNormals(mesh, bvh);repairDab(mesh, bvh);}diff --git a/src/core/Sculpt.h b/src/core/Sculpt.hindex 34952cd0..674e5c8a 100644--- a/src/core/Sculpt.h+++ b/src/core/Sculpt.h@@ -131,7 +131,7 @@ private:// The Vdm brush (defined in Vdm.cpp); `handedness` -1 for a mirrored pass, so the stamp mirrors exactly.void dabVdmSingle(Mesh& mesh, BVH& bvh, const DabParams& p, float handedness);void finishDab(Mesh& mesh, BVH& bvh, std::chrono::steady_clock::time_point clock);- void updateDabNormals(Mesh& mesh);+ void updateDabNormals(Mesh& mesh, const BVH& bvh);void touch(Mesh& mesh, uint32_t v);// The one place brushes move vertices: scales `d` by vertexInfluence().void displace(Mesh& mesh, uint32_t v, const glm::vec3& d);@@ -160,6 +160,7 @@ private:void clearRecorded();std::vector<uint32_t> verts_, dabVerts_; // one mirror's vertices; every mirror's (for the normals)+ std::vector<uint32_t> dabLeaves_; // the BVH leaves every mirror's query listed (the normals' set)std::vector<glm::vec3> scratch_;std::vector<float> weights_, influence_;std::vector<uint8_t> firstTouch_;diff --git a/src/core/UploadOrder.cpp b/src/core/UploadOrder.cppindex 0da2558b..007fa067 100644--- a/src/core/UploadOrder.cpp+++ b/src/core/UploadOrder.cpp@@ -10,6 +10,10 @@namespace sf {+namespace {+constexpr size_t kParallelDirtyVertices = 65536; // fewer: the serial walk, no threads woken+}+namespace {// Mesh vertex -> local index within one cluster: an open-addressing table, cleared by bumping a stamp. Big@@ -292,7 +296,32 @@ void UploadOrder::dirtyRuns(const Mesh& mesh, std::vector<std::pair<uint32_t, uiblocks_.push_back(g);}};- // The GPU blocks of every slot of every marked vertex.+ // The GPU blocks of every slot of every marked vertex. Many marks (a big brush, 3M vertices at 21M triangles:+ // 3.7 ms on one thread): the mesh's dirty blocks in parallel, each GPU block flagged, then the flags read in+ // order (the same sorted blocks).+ if (dirty >= kParallelDirtyVertices) {+ poolFor(lastBlock - firstBlock, [&](size_t b0, size_t b1) {+ for (size_t b = firstBlock + b0; b < firstBlock + b1; ++b) {+ if (!mesh.dirtyBlocks[b]) continue;+ for (size_t w = b * kWordsPerBlock; w < (b + 1) * kWordsPerBlock && w < mesh.dirtyBits.size(); ++w) {+ const uint64_t copies = w < hasCopy_.size() ? hasCopy_[w] : 0;+ for (uint64_t bits = mesh.dirtyBits[w]; bits; bits &= bits - 1) {+ const int bit = std::countr_zero(bits);+ const size_t v = w * 64 + size_t(bit);+ if (v >= nv) break;+ if (toGpu_[v] == kNone) continue;+ AtomicRef<uint8_t>(marked_[toGpu_[v] >> kBlockShift]).store(1, std::memory_order_relaxed);+ if ((copies >> bit) & 1)+ for (auto it = std::lower_bound(copies_.begin(), copies_.end(), std::make_pair(uint32_t(v), 0u));+ it != copies_.end() && it->first == v; ++it)+ AtomicRef<uint8_t>(marked_[it->second >> kBlockShift]).store(1, std::memory_order_relaxed);+ }+ }+ }+ }, 64);+ for (uint32_t g = 0; g < uint32_t(marked_.size()); ++g)+ if (marked_[g]) blocks_.push_back(g);+ } elsefor (size_t b = firstBlock; b < lastBlock; ++b) {if (!mesh.dirtyBlocks[b]) continue;for (size_t w = b * kWordsPerBlock; w < (b + 1) * kWordsPerBlock && w < mesh.dirtyBits.size(); ++w) {diff --git a/tests/test_performance.cpp b/tests/test_performance.cppindex 8fba40cc..d2a70753 100644--- a/tests/test_performance.cpp+++ b/tests/test_performance.cpp@@ -10,6 +10,7 @@#include "core/Benchmark.h"#include "core/BrushRecipe.h"#include "core/IndexBits.h"+#include "core/Multires.h"#include "core/Primitives.h"#include "core/ThreadPool.h"#include "core/UploadOrder.h"@@ -148,6 +149,81 @@ TEST(parallel_normals_match_full_recompute) {CHECK(worst < 1e-5f);}+TEST(upload_runs_of_a_big_brush_match_one_thread) {+ // A brush over a good part of the mesh (more marked vertices than dirtyRuns walks on one thread, under the+ // three quarters it uploads whole): the GPU blocks are marked in parallel, and the runs are exactly the ones+ // a single thread finds, every slot of every marked vertex in one.+ Mesh m = makeBenchSphere(1600000);+ BVH bvh;+ bvh.build(m);+ UploadOrder order;+ order.build(m);+ m.clearDirty();+ Sculptor s;+ s.beginStroke(m, "Standard");+ DabParams p;+ p.center = glm::vec3(0.0f, 0.0f, 1.0f);+ p.radius = 1.0f;+ s.dab(m, bvh, BrushType::Standard, p, Symmetry{});+ size_t dirty = 0;+ for (uint32_t v = 0; v < m.vertexCount(); ++v) dirty += m.vertexDirty(v);+ CHECK(dirty > 65536 && dirty * 4 < m.vertexCount() * 3);+ std::vector<std::pair<uint32_t, uint32_t>> par, ser;+ order.dirtyRuns(m, par);+ serially([&] { order.dirtyRuns(m, ser); });+ CHECK(par == ser && !par.empty());+ CHECK(!(par.size() == 1 && par[0].first == 0 && par[0].second == order.size())); // (not everything)+ std::vector<uint8_t> inRun(order.size(), 0);+ for (const auto& [b, e] : par)+ for (uint32_t g = b; g < e; ++g) inRun[g] = 1;+ bool covered = true;+ std::vector<uint32_t> slots;+ for (uint32_t v = 0; v < m.vertexCount() && covered; ++v)+ if (m.vertexDirty(v)) {+ order.slotsOf(v, slots);+ for (uint32_t g : slots) covered = covered && inRun[g];+ }+ CHECK(covered);+}++TEST(dab_normals_from_the_query_leaves_match_a_full_recompute) {+ // A dab's normals are recomputed for the corners of the BVH leaves its queries listed: every normal comes+ // out exactly as recomputeAllNormals has it, and every vertex whose normal changed is marked for upload.+ // On a plain mesh and on a level made by Divide (implicit adjacency), with symmetry, for several brushes.+ for (int divided = 0; divided < 2; ++divided) {+ Mesh m = divided ? makeIcosphere(4) : makeBenchSphere(300000);+ if (divided) {+ std::string err;+ CHECK(subdivDivide(m, true, err) && subdivDivide(m, true, err));+ CHECK(m.implicitAdjacency());+ }+ BVH bvh;+ bvh.build(m);+ Sculptor s;+ s.beginStroke(m, "Standard");+ bool same = true, marked = true;+ for (BrushType type : {BrushType::Standard, BrushType::Smooth, BrushType::Clay, BrushType::Vdm}) {+ const std::vector<glm::vec3> before = m.normals;+ m.clearDirty();+ DabParams p;+ p.center = glm::normalize(glm::vec3(0.4f, 0.3f, 0.8f));+ p.viewDir = -p.center;+ p.radius = 0.5f;+ p.strength = 0.7f;+ s.dab(m, bvh, type, p, Symmetry{});+ Mesh fresh = m;+ fresh.recomputeAllNormals();+ for (uint32_t v = 0; v < m.vertexCount(); ++v) {+ same = same && m.normals[v] == fresh.normals[v];+ if (m.normals[v] != before[v]) marked = marked && m.vertexDirty(v);+ }+ }+ CHECK(same);+ CHECK(marked);+ s.endStroke();+ }+}+TEST(upload_runs_cover_changed_vertices) {// A subdivided mesh, whose vertex numbering scatters any region over the index range.Mesh m = makeBenchSphere(200000);