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: a stroke's shading writes each changed patch alone (exact), its neighbours after the stroke; outer-ring patches sum only the edges and corners they share
islandmed124b639a43f2
diff --git a/changes/perf-micro-upload.md b/changes/perf-micro-upload.mdnew file mode 100644index 00000000..888dcc7a--- /dev/null+++ b/changes/perf-micro-upload.md@@ -0,0 +1,10 @@+---+changed: Micro levels: big brushes spend about a third less time preparing each frame's shading (a 240 px stroke on+ a 200 million triangle head: 11 to under 8 ms a dab on the floor tier). Each changed patch is shaded on its own;+ its neighbours, whose shared border rarely changes, are brought up to date when the stroke ends.+testers:+ - Any OS, a micro level (Subdivide > Micro): long strokes with a large Clay brush; the shading under and around+ the brush follows as before, and no lines show along patch borders during or after the stroke.+---+Measured with the benchmark's stroke_work_ms (uploads = MicroRenderer::sync). The GL uploads were ~3% of it;+the rest was CPU shading (MicroShader).diff --git a/src/core/Micro.cpp b/src/core/Micro.cppindex 50cad1b7..9d5a4fea 100644--- a/src/core/Micro.cpp+++ b/src/core/Micro.cpp@@ -690,10 +690,11 @@ uint32_t encodeShade(glm::vec3 nrm, float curvature, uint8_t mask) {e = glm::vec2((1.0f - std::abs(nrm.y)) * (nrm.x >= 0.0f ? 1.0f : -1.0f),(1.0f - std::abs(nrm.x)) * (nrm.y >= 0.0f ? 1.0f : -1.0f));}- auto q = [](float v) { return uint32_t(std::clamp(std::lround((v * 0.5f + 0.5f) * 255.0f), 0L, 255L)); };+ // (rounding by +0.5 and truncation: the values are >= 0 there, and lround costs more than the rest of a point)+ auto q = [](float v) { return uint32_t(std::clamp((v * 0.5f + 0.5f) * 255.0f + 0.5f, 0.0f, 255.0f)); };const float c = std::clamp(curvature, -1.0f, 1.0f);const float s = (c >= 0.0f ? 1.0f : -1.0f) * std::sqrt(std::abs(c));- const uint32_t cq = uint32_t(std::clamp(std::lround(s * 127.0f) + 128L, 1L, 255L));+ const uint32_t cq = uint32_t(std::clamp(s * 127.0f + 128.5f, 1.0f, 255.0f));return q(e.x) | q(e.y) << 8 | cq << 16 | uint32_t(mask) << 24;}@@ -722,30 +723,76 @@ struct GridWork {const uint32_t row = MicroMesh::index(0, j, n), next = MicroMesh::index(0, j + 1, n);for (uint32_t i = 0; i + j < n; ++i) {const uint32_t a = row + i, b = row + i + 1, c = next + i;- const glm::vec3 f = glm::cross(pos[b] - pos[a], pos[c] - pos[a]);- nsum[a] += f, nsum[b] += f, nsum[c] += f;- // the lattice edges a-b, a-c, b-c (each once: every edge belongs to one upward triangle)- const float da = g[a], db = g[b], dc = g[c];- dsum[a] += db + dc, dsum[b] += da + dc, dsum[c] += da + db;- cnt[a] += 2.0f, cnt[b] += 2.0f, cnt[c] += 2.0f;- if (i + j + 1 < n) {- const uint32_t d = next + i + 1;- const glm::vec3 f2 = glm::cross(pos[d] - pos[b], pos[c] - pos[b]);- nsum[b] += f2, nsum[d] += f2, nsum[c] += f2;- }+ face(a, b, c, g, true);+ if (i + j + 1 < n) face(b, next + i + 1, c, g, false);}}}+ // The sums at some edge points only (a triangle of the outer ring: the points it shares with the ones written):+ // edges e (bit e: its points between the corners) and corners c (bit 3 + c). The micro triangles touching+ // them alone, added in the same order as compute(), so those sums come out bit-identical to a whole grid's+ // at a fraction of its cost.+ void computePart(const Mesh& m, const MicroMesh& mm, uint32_t tri, unsigned parts) {+ const uint32_t n = mm.n, S = mm.samples;+ pos.resize(S);+ nsum.resize(S);+ dsum.resize(S);+ cnt.resize(S);+ need.assign(S, 0);+ for (int e = 0; e < 3; ++e) {+ uint32_t i, j;+ if (parts & (8u << e)) MicroMesh::edgePoint(e, 0, n, i, j), need[MicroMesh::index(i, j, n)] = 1;+ if (parts & (1u << e))+ for (uint32_t k = 1; k < n; ++k) MicroMesh::edgePoint(e, k, n, i, j), need[MicroMesh::index(i, j, n)] = 1;+ }+ MicroTriangle T;+ T.set(m, tri, n);+ const int16_t* g = mm.disp.data() + size_t(tri) * S;+ auto at = [&](uint32_t i, uint32_t j) { // (each point once, the first time a triangle needs it)+ const uint32_t idx = MicroMesh::index(i, j, n);+ if (need[idx] & 2) return idx;+ need[idx] |= 2;+ glm::vec3 s, nn;+ T.eval(i, j, s, nn);+ pos[idx] = s + nn * (float(g[idx]) * mm.step);+ nsum[idx] = glm::vec3(0.0f), dsum[idx] = 0.0f, cnt[idx] = 0.0f; // (the others aren't read)+ return idx;+ };+ // (the micro triangles that can touch an edge: row 0, and the first and the last two of every other row)+ for (uint32_t j = 0; j < n; ++j) {+ const uint32_t row = MicroMesh::index(0, j, n), next = MicroMesh::index(0, j + 1, n), last = n - j;+ for (uint32_t i = 0; i < last; i = j == 0 || i + 3 >= last ? i + 1 : last - 2) {+ const uint32_t a = row + i, b = row + i + 1, c = next + i;+ if ((need[a] | need[b] | need[c]) & 1) face(at(i, j), at(i + 1, j), at(i, j + 1), g, true);+ if (i + j + 1 < n && ((need[b] | need[next + i + 1] | need[c]) & 1)) face(at(i + 1, j), at(i + 1, j + 1), at(i, j + 1), g, false);+ }+ }+ }++private:+ std::vector<uint8_t> need; // computePart: 1 = a wanted sum, 2 = its position computed+ // Micro triangle a b c (counter-clockwise) into the sums of its corners; `up` also adds its lattice edges a-b,+ // a-c, b-c (each once: every edge belongs to one upward triangle).+ void face(uint32_t a, uint32_t b, uint32_t c, const int16_t* g, bool up) {+ const glm::vec3 f = glm::cross(pos[b] - pos[a], pos[c] - pos[a]);+ nsum[a] += f, nsum[b] += f, nsum[c] += f;+ if (!up) return;+ const float da = g[a], db = g[b], dc = g[c];+ dsum[a] += db + dc, dsum[b] += da + dc, dsum[c] += da + db;+ cnt[a] += 2.0f, cnt[b] += 2.0f, cnt[c] += 2.0f;+ }};} // namespacevoid MicroShader::shade(const Mesh& m, std::span<const uint32_t> dirty, bool all, std::vector<uint32_t>& written,- const std::function<uint32_t*(uint32_t tri)>& out, const Prepare& prepare) {+ const std::function<uint32_t*(uint32_t tri)>& out, const Prepare& prepare, bool grow,+ std::vector<uint32_t>* outer) {written.clear();+ if (outer) outer->clear();if (!m.micro) return;if (!all) {- shadeSet(m, dirty, true, written, out, prepare);+ shadeSet(m, dirty, grow, written, out, prepare, grow ? nullptr : outer);return;}// Everything: in runs of triangles (neighbours by index on levels made by Divide), each with the ring its@@ -761,7 +808,7 @@ void MicroShader::shade(const Mesh& m, std::span<const uint32_t> dirty, bool all}void MicroShader::shadeSet(const Mesh& m, std::span<const uint32_t> dirty, bool grow, std::vector<uint32_t>& written,- const std::function<uint32_t*(uint32_t tri)>& out, const Prepare& prepare) {+ const std::function<uint32_t*(uint32_t tri)>& out, const Prepare& prepare, std::vector<uint32_t>* outer) {const MicroMesh& mm = *m.micro;const uint32_t n = mm.n, S = mm.samples, nt = mm.baseTriangles;if (mm.edgeNeighbor.size() != size_t(nt) * 3) return; // (ensureTopology first)@@ -807,6 +854,7 @@ void MicroShader::shadeSet(const Mesh& m, std::span<const uint32_t> dirty, bool}const uint32_t v2 = ++epoch_;vertexRing(ring_, ring2_, inR2, v2);+ if (outer) outer->insert(outer->end(), ring2_.begin(), ring2_.end());for (size_t i = 0; i < ring_.size(); ++i) slot_[ring_[i]] = uint32_t(i);for (size_t i = 0; i < ring2_.size(); ++i) slot_[ring2_[i]] = uint32_t(ring_.size() + i);if (prepare) prepare(ring_);@@ -821,17 +869,25 @@ void MicroShader::shadeSet(const Mesh& m, std::span<const uint32_t> dirty, boolreturn std::max(e / (3.0f * float(n)), 1e-20f);};auto finish = [&](const glm::vec3& ns, float ds, float c, float d, float h, uint8_t mk) {- const float len = glm::length(ns);- const glm::vec3 nn = len > 0.0f ? ns / len : glm::vec3(0.0f, 0.0f, 1.0f);const float curv = c > 0.0f ? (ds / c - d) * mm.step / h : 0.0f;- return encodeShade(nn, curv, mk);+ return encodeShade(ns, curv, mk); // (unnormalized: the encoding divides by its L1 length; zero = +z either way)};// Phase 1: every R2 triangle's edge partials; R triangles' interior points written.poolFor(slots, [&](size_t b, size_t e) {thread_local GridWork w;for (size_t s = b; s < e; ++s) {const uint32_t tri = tileOf(s);- w.compute(m, mm, tri);+ if (s < ring_.size()) {+ w.compute(m, mm, tri);+ } else { // the outer ring: the sums at the points it shares with R (whose vertices are marked v2)+ const glm::uvec3 tv = m.triangles[tri];+ unsigned parts = 0;+ for (int k = 0; k < 3; ++k) {+ const bool here = vstamp_[tv[k]] == v2, next = vstamp_[tv[(k + 1) % 3]] == v2;+ parts |= (here ? 8u << k : 0u) | (here && next ? 1u << k : 0u);+ }+ w.computePart(m, mm, tri, parts);+ }float* part = partial_.data() + s * edgePoints * kPartialFloats;for (int ed = 0; ed < 3; ++ed)for (uint32_t k = 0; k < n; ++k) {diff --git a/src/core/Micro.h b/src/core/Micro.hindex 53787930..0d118371 100644--- a/src/core/Micro.h+++ b/src/core/Micro.h@@ -252,14 +252,17 @@ public:// and of every base triangle sharing a vertex with one (whose shared edges and corners average with them).// out(tri) gives where that triangle's `samples` values go (each written whole). `written` lists them.// `prepare`, if given, sees the triangles about to be written (before any out() call), once per batch.+ // `grow` false: the dirty triangles alone are written (exact: their neighbours' edge sums are read, not written);+ // the neighbours whose shared points changed (those sharing a vertex) go to `outer`, to write later.using Prepare = std::function<void(std::span<const uint32_t> tris)>;void shade(const Mesh& m, std::span<const uint32_t> dirty, bool all, std::vector<uint32_t>& written,- const std::function<uint32_t*(uint32_t tri)>& out, const Prepare& prepare = {});+ const std::function<uint32_t*(uint32_t tri)>& out, const Prepare& prepare = {}, bool grow = true,+ std::vector<uint32_t>* outer = nullptr);private:// shade() for the triangles `seeds` (grown by the triangles sharing a vertex when `grow`); appends to `written`.void shadeSet(const Mesh& m, std::span<const uint32_t> seeds, bool grow, std::vector<uint32_t>& written,- const std::function<uint32_t*(uint32_t tri)>& out, const Prepare& prepare);+ const std::function<uint32_t*(uint32_t tri)>& out, const Prepare& prepare, std::vector<uint32_t>* outer = nullptr);std::vector<uint32_t> seed_, grown_;std::vector<uint32_t> stamp_, slot_; // per base triangle: in a set of this call (stamp), its partials (slot)std::vector<uint32_t> vstamp_; // per base vertexdiff --git a/src/render/MicroRenderer.cpp b/src/render/MicroRenderer.cppindex c4cc67c0..2de96e4e 100644--- a/src/render/MicroRenderer.cpp+++ b/src/render/MicroRenderer.cpp@@ -307,7 +307,8 @@ void MicroRenderer::buildLayout(const Mesh& mesh) {for (uint32_t c = 0; c < clusters; ++c) all[c] = c;updateClusterBounds(mesh, all);pending_.assign((size_t(nt) + 63) / 64, 0);- pendingCount_ = 0;+ stale_.assign(pending_.size(), 0);+ pendingCount_ = staleCount_ = 0;ensurePatches(mm.level);}@@ -468,12 +469,17 @@ void MicroRenderer::shadePending(const Mesh& mesh, bool all) {}gl::BindBuffer(GL_TEXTURE_BUFFER, 0);std::fill(pending_.begin(), pending_.end(), 0);- pendingCount_ = 0;+ std::fill(stale_.begin(), stale_.end(), 0);+ pendingCount_ = staleCount_ = 0;return;}- // The pending triangles, newest first (scratch_ holds this sync's dirty ones, already marked).+ // The pending triangles, newest first (scratch_ holds this sync's dirty ones, already marked), each written+ // alone: the neighbours whose shared edges and corners they change become stale_, written after them, and not+ // at all while a stroke runs (deferStale): its next dabs change most of them again, and what they'd change is+ // the brush's falloff tail at the patch border (usually nothing: a changed shared point changes both patches).+ // As many a frame as when each one also wrote its ring (~3 patches): shading as current as it was, for less.+ const size_t limit = shadeBudget ? std::max<size_t>(1, shadeBudget / (S * 3)) : SIZE_MAX;std::vector<uint32_t>& seeds = scratch_;- const size_t limit = shadeBudget ? std::max<size_t>(1, shadeBudget / (S * 3)) : SIZE_MAX; // (the ring triples it)const bool full = seeds.size() >= limit; // (this sync's dirty ones fill it: sorted and unique already)if (full) seeds.resize(limit);else if (seeds.size() < limit)@@ -487,8 +493,34 @@ void MicroRenderer::shadePending(const Mesh& mesh, bool all) {seeds.erase(std::unique(seeds.begin(), seeds.end()), seeds.end());if (seeds.size() > limit) seeds.resize(limit);}- if (seeds.empty()) return;const auto started = std::chrono::steady_clock::now();+ size_t shaded = 0;+ if (!seeds.empty()) {+ shaded += shadeSeeds(mesh, seeds, &outer_);+ for (uint32_t t : outer_) {+ uint64_t& w = stale_[t >> 6];+ const uint64_t bit = uint64_t(1) << (t & 63);+ if (!(w & bit)) w |= bit, ++staleCount_;+ }+ }+ if (const size_t room = shaded < limit ? limit - shaded : 0; !deferStale && staleCount_ && room) {+ seeds.clear();+ for (size_t w = 0; w < stale_.size() && seeds.size() < room; ++w)+ for (uint64_t bits = stale_[w] & ~pending_[w]; bits && seeds.size() < room; bits &= bits - 1)+ seeds.push_back(uint32_t(w * 64 + size_t(std::countr_zero(bits))));+ if (!seeds.empty()) shaded += shadeSeeds(mesh, seeds, nullptr);+ }+ if (shaded) { // the cost per point, smoothed (a stroke's shading budget in time follows it)+ const double ns = std::chrono::duration<double, std::nano>(std::chrono::steady_clock::now() - started).count() /+ double(shaded * S);+ shadeNsPerPoint_ = shadeNsPerPoint_ > 0.0 ? shadeNsPerPoint_ * 0.7 + ns * 0.3 : ns;+ }+}++// Shades `seeds` (sorted) alone and sends them; `outer` gets their neighbours to write later. Returns how many.+size_t MicroRenderer::shadeSeeds(const Mesh& mesh, std::span<const uint32_t> seeds, std::vector<uint32_t>* outer) {+ const MicroMesh& mm = *mesh.micro;+ const size_t S = mm.samples;std::vector<uint32_t> sorted;if (stageIndex_.size() != mm.baseTriangles) stageIndex_.assign(mm.baseTriangles, 0);shader_.shade(mesh, seeds, false, written_, [&](uint32_t t) -> uint32_t* {@@ -498,7 +530,7 @@ void MicroRenderer::shadePending(const Mesh& mesh, bool all) {std::sort(sorted.begin(), sorted.end(), [&](uint32_t a, uint32_t b) { return slotOf_[a] < slotOf_[b]; });for (size_t i = 0; i < sorted.size(); ++i) stageIndex_[sorted[i]] = uint32_t(i);staging_.resize(sorted.size() * S * 4);- });+ }, false, outer);const auto* st = reinterpret_cast<const uint32_t*>(staging_.data());for (size_t i = 0; i < sorted.size();) {const uint32_t s0 = slotOf_[sorted[i]], chunk = s0 / chunkSlots_;@@ -510,16 +542,14 @@ void MicroRenderer::shadePending(const Mesh& mesh, bool all) {i = j;}gl::BindBuffer(GL_TEXTURE_BUFFER, 0);- if (!written_.empty()) { // the cost per point, smoothed (a stroke's shading budget in time follows it)- const double ns = std::chrono::duration<double, std::nano>(std::chrono::steady_clock::now() - started).count() /- double(written_.size() * S);- shadeNsPerPoint_ = shadeNsPerPoint_ > 0.0 ? shadeNsPerPoint_ * 0.7 + ns * 0.3 : ns;- }- for (uint32_t t : written_) {- uint64_t& w = pending_[t >> 6];+ for (uint32_t t : written_) { // (written whole and current: neither pending nor stale)const uint64_t bit = uint64_t(1) << (t & 63);+ uint64_t& w = pending_[t >> 6];if (w & bit) w &= ~bit, --pendingCount_;+ uint64_t& v = stale_[t >> 6];+ if (v & bit) v &= ~bit, --staleCount_;}+ return written_.size();}bool MicroRenderer::sync(Mesh& mesh) {@@ -644,7 +674,8 @@ bool MicroRenderer::sync(Mesh& mesh) {// stroke runs or the view moves, no more than strokeShadeMs of it (at least one patch and its ring), so a// slower CPU doesn't spend the frame the dabs or the orbit need on shading; the rest follows.shadeBudget = microShadeBudget(currentTierConfig(), mm.stroking, viewMoving, shadeNsPerPoint_, size_t(mm.samples) * 3);- if (pendingCount_) shadePending(mesh, false);+ deferStale = mm.stroking;+ if (pendingCount_ || staleCount_) shadePending(mesh, false);}}step_ = mm.step;diff --git a/src/render/MicroRenderer.h b/src/render/MicroRenderer.hindex ea257813..e1e437dd 100644--- a/src/render/MicroRenderer.h+++ b/src/render/MicroRenderer.h@@ -25,6 +25,7 @@#include "render/GL.h"#include <cstdint>+#include <span>#include <vector>namespace sf {@@ -44,7 +45,7 @@ public:size_t gpuBytes() const;bool closed() const { return closed_; }// Grid points whose shading still waits for a frame (budget), for tests and the benchmark.- size_t pendingShading() const { return pendingCount_; }+ size_t pendingShading() const { return pendingCount_ + staleCount_; }// Grid points of shading recomputed per sync at most (0 = no limit).size_t shadeBudget = size_t(3) << 20;// The view moves (set by the Renderer before sync: Fast Navigation's proxy frames): shading gets a time cap.@@ -61,6 +62,7 @@ private:void ensurePatches(int level);void uploadDispTiles(const Mesh& mesh, std::vector<uint32_t>& slots, bool all);void shadePending(const Mesh& mesh, bool all);+ size_t shadeSeeds(const Mesh& mesh, std::span<const uint32_t> seeds, std::vector<uint32_t>* outer);uint64_t serial_ = 0;uint32_t baseTriangles_ = 0, baseVertices_ = 0;@@ -95,6 +97,10 @@ private:size_t bytes_ = 0;MicroShader shader_;std::vector<uint64_t> pending_; // per base triangle: shading out of date+ std::vector<uint64_t> stale_; // ... only where a neighbour changed (shared edges and corners: shadePending)+ size_t staleCount_ = 0;+ bool deferStale = false; // a stroke runs: stale_ waits for its end+ std::vector<uint32_t> outer_;double shadeNsPerPoint_ = 0.0; // what shading a grid point (and sending it) took lately (TierConfig::strokeShadeMs)size_t pendingCount_ = 0;std::vector<uint32_t> scratch_, written_, stageIndex_;diff --git a/tests/test_micro.cpp b/tests/test_micro.cppindex d1d5c027..140eef20 100644--- a/tests/test_micro.cpp+++ b/tests/test_micro.cpp@@ -361,6 +361,48 @@ TEST(micro_shading_partial_matches_full) {CHECK(outward >= total * 9 / 10);}+// A stroke's shading writes the changed triangles alone (MicroRenderer: their neighbours wait for the stroke's+// end): those come out exact, the neighbours after them complete it, and until then they're off by the falloff tail.+TEST(micro_shading_alone_then_outer) {+ Document doc = microDoc(3, 5000);+ microNoise(doc.mesh, 0.01f, 10.0f);+ const MicroMesh& mm = *doc.mesh.micro;+ const size_t S = mm.samples;+ std::vector<uint32_t> before(size_t(mm.baseTriangles) * S, 0), full(before.size(), 0);+ MicroShader shader;+ std::vector<uint32_t> written, outer;+ auto into = [&](std::vector<uint32_t>& v) { return [&v, S](uint32_t t) { return v.data() + size_t(t) * S; }; };+ shader.shade(doc.mesh, {}, true, written, into(before));+ Symmetry sym;+ doc.sculptor.beginStroke(doc.mesh, "Standard");+ doc.sculptor.dab(doc.mesh, doc.bvh, BrushType::Standard, dabAt(glm::vec3(0, 0, 1), 0.2f, 1.0f), sym);+ UndoRecord r = doc.sculptor.endStroke();+ std::vector<uint32_t> dirty = r.micro->tris;+ std::sort(dirty.begin(), dirty.end());+ shader.shade(doc.mesh, {}, true, written, into(full));+ std::vector<uint32_t> part = before;+ shader.shade(doc.mesh, dirty, false, written, into(part), {}, false, &outer);+ CHECK(written.size() == dirty.size());+ CHECK(!outer.empty());+ for (uint32_t t : dirty) CHECK(std::equal(part.begin() + std::ptrdiff_t(t * S), part.begin() + std::ptrdiff_t((t + 1) * S),+ full.begin() + std::ptrdiff_t(t * S)));+ // The stale neighbours: a few points along the shared border, by little.+ int worst = 0;+ size_t off = 0;+ for (uint32_t t : outer)+ for (size_t k = 0; k < S; ++k) {+ const uint32_t a = part[t * S + k], b = full[t * S + k];+ if (a == b) continue;+ ++off;+ for (int c = 0; c < 16; c += 8) worst = std::max(worst, std::abs(int((a >> c) & 255) - int((b >> c) & 255)));+ }+ std::printf(" %zu changed, %zu outer, %zu stale points, worst normal code off by %d\n", dirty.size(), outer.size(), off, worst);+ CHECK(off < outer.size() * 3 * mm.n);+ CHECK(worst <= 8);+ shader.shade(doc.mesh, outer, false, written, into(part), {}, false, nullptr);+ CHECK(part == full);+}+TEST(micro_bake_mesh_is_closed_and_matches) {Document doc = microDoc(3, 3000);microNoise(doc.mesh, 0.01f, 10.0f);