Skip to content

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.

Spike: coarse levels on global nested grids (Rossignac-Borrel), not per-cluster seam-pinned ones

islandmed6d18ad3af47e
diff --git a/src/render/Clusters.cpp b/src/render/Clusters.cpp
index ef0cfa6c..50106908 100644
--- a/src/render/Clusters.cpp
+++ b/src/render/Clusters.cpp
@@ -298,120 +298,171 @@ bool clusterProxy(const Mesh& mesh, const UploadOrder& order, uint32_t c, size_t
return true;
}
-bool clusterLodChain(const Mesh& mesh, const UploadOrder& order, uint32_t c, size_t maxIndices, std::vector<uint16_t>& out,
- ClusterLod& lod, ClusterBounds& bounds) {
- out.clear();
- lod = ClusterLod();
- const uint32_t n = order.clusterTriangles(c);
- const UploadOrder::Cluster& cl = order.clusters()[c];
- const auto fromGpu = order.fromGpu();
- thread_local std::vector<uint16_t> local, rep;
- thread_local std::vector<uint8_t> pinned;
- local.resize(size_t(n) * 3);
- order.localTriangles(mesh, c, local.data());
- const uint32_t nl = cl.vertexCount;
- pinned.assign(nl, 0);
- AABB box;
- for (uint32_t l = 0; l < nl; ++l) {
- const uint32_t v = fromGpu[cl.firstVertex + l];
- pinned[l] = order.shared(v);
- box.expand(mesh.positions[v]);
+namespace {
+
+// Sorts by key: blocks in parallel, then merged pairwise.
+void sortByKey(std::vector<std::pair<uint64_t, uint32_t>>& v) {
+ const size_t blocks = 16, n = v.size(), step = (n + blocks - 1) / blocks;
+ if (n < 65536) {
+ std::sort(v.begin(), v.end());
+ return;
}
- auto pos = [&](uint32_t l) { return mesh.positions[fromGpu[cl.firstVertex + l]]; };
- const bool hidden = mesh.hidden.size() == mesh.triangleCount();
+ poolFor(blocks, [&](size_t b0, size_t b1) {
+ for (size_t b = b0; b < b1; ++b) std::sort(v.begin() + std::ptrdiff_t(std::min(n, b * step)), v.begin() + std::ptrdiff_t(std::min(n, (b + 1) * step)));
+ }, 1, 1);
+ for (size_t width = step; width < n; width *= 2) {
+ const size_t pairs = (n + 2 * width - 1) / (2 * width);
+ poolFor(pairs, [&](size_t p0, size_t p1) {
+ for (size_t p = p0; p < p1; ++p) {
+ const size_t a = p * 2 * width, m = std::min(n, a + width), e = std::min(n, a + 2 * width);
+ if (m < e) std::inplace_merge(v.begin() + std::ptrdiff_t(a), v.begin() + std::ptrdiff_t(m), v.begin() + std::ptrdiff_t(e));
+ }
+ }, 1, 1);
+ }
+}
+
+} // namespace
+
+CoarseLevels buildCoarseLevels(const Mesh& mesh, const UploadOrder& order) {
+ CoarseLevels out;
+ const size_t nv = mesh.vertexCount(), nt = mesh.triangleCount();
+ const uint32_t nc = uint32_t(order.clusters().size());
+ out.clusters.resize(nc);
+ if (nv == 0 || nt == 0 || nc == 0) return out;
+ AABB box;
+ for (const glm::vec3& p : mesh.positions) box.expand(p);
double edges = 0.0;
size_t counted = 0;
- for (uint32_t i = 0; i < n; i += 7) {
- const uint16_t* t = local.data() + size_t(i) * 3;
- edges += glm::distance(pos(t[0]), pos(t[1])) + glm::distance(pos(t[1]), pos(t[2]));
+ for (size_t t = 0; t < nt; t += std::max<size_t>(1, nt / 200000)) {
+ const glm::uvec3 tri = mesh.triangles[t];
+ if (tri.x >= nv || tri.y >= nv || tri.z >= nv) continue;
+ edges += glm::distance(mesh.positions[tri.x], mesh.positions[tri.y]) + glm::distance(mesh.positions[tri.y], mesh.positions[tri.z]);
counted += 2;
}
- if (!counted || !box.valid()) return false;
- float cell = float(edges / double(counted)) * 2.0f; // (about a quarter of the triangles at the first level)
- if (!(cell > 0.0f)) return false;
- thread_local CellTable cells;
- thread_local std::vector<uint32_t> cellOfVertex;
- cellOfVertex.resize(nl);
- rep.resize(nl);
- const float span = glm::length(box.max - box.min);
- size_t previous = 0; // the triangles of the level before (the cluster's own at first)
- for (uint32_t i = 0; i < n; ++i) previous += !(hidden && mesh.hidden[order.triangle(c, i)]);
- glm::vec3 sum(0.0f);
- for (; lod.levels < ClusterLod::kMaxLevels; cell *= 2.0f) {
- cells.clear();
- const float inv = 1.0f / cell;
- for (uint32_t l = 0; l < nl; ++l) {
- if (pinned[l]) continue;
- const glm::vec3 p = pos(l);
- const glm::vec3 q = glm::floor((p - box.min) * inv);
- const glm::vec3 centre = box.min + (q + 0.5f) * cell;
- const uint64_t key = uint64_t(uint32_t(q.x)) | (uint64_t(uint32_t(q.y)) << 21) | (uint64_t(uint32_t(q.z)) << 42);
- const float d = glm::distance(p, centre);
- bool found = false;
- const uint32_t h = cells.slot(key, found);
- if (!found) {
- cells.stamps[h] = cells.stamp;
- cells.keys[h] = key;
- cells.reps[h] = uint16_t(l);
- cells.dists[h] = d;
- } else if (d < cells.dists[h]) {
- cells.reps[h] = uint16_t(l);
- cells.dists[h] = d;
- }
- cellOfVertex[l] = h;
- }
- float error = 0.0f;
- for (uint32_t l = 0; l < nl; ++l) {
- rep[l] = pinned[l] ? uint16_t(l) : cells.reps[cellOfVertex[l]];
- if (rep[l] != l) error = std::max(error, glm::distance(pos(l), pos(rep[l])));
+ if (!counted || !box.valid()) return out;
+ const float cell1 = float(edges / double(counted)) * 2.0f;
+ if (!(cell1 > 0.0f)) return out;
+ const bool hasNormals = mesh.normals.size() == nv;
+ const bool hidden = mesh.hidden.size() == nt;
+ auto pack = [](glm::uvec3 q) { return uint64_t(q.x) | (uint64_t(q.y) << 21) | (uint64_t(q.z) << 42); };
+ auto unpack = [](uint64_t k) { return glm::uvec3(uint32_t(k & 0x1FFFFF), uint32_t((k >> 21) & 0x1FFFFF), uint32_t(k >> 42)); };
+ // The items of a level: the vertices at first, then the cells of the level before (weighted sums).
+ std::vector<uint64_t> itemKey(nv);
+ std::vector<glm::dvec3> itemSum; // (level 0: the mesh's own positions, normals and a weight of 1)
+ std::vector<glm::vec3> itemNormal;
+ std::vector<uint32_t> itemWeight;
+ poolFor(nv, [&](size_t v0, size_t v1) {
+ for (size_t v = v0; v < v1; ++v) {
+ const glm::vec3 q = glm::clamp(glm::floor((mesh.positions[v] - box.min) / cell1), glm::vec3(0.0f), glm::vec3(float(0x1FFFFF)));
+ itemKey[v] = pack(glm::uvec3(q));
}
- const size_t at = out.size();
- for (uint32_t i = 0; i < n; ++i) {
- if (hidden && mesh.hidden[order.triangle(c, i)]) continue;
- const uint16_t* t = local.data() + size_t(i) * 3;
- const uint16_t a = rep[t[0]], b = rep[t[1]], d = rep[t[2]];
- if (a == b || b == d || a == d) continue;
- out.insert(out.end(), {a, b, d});
+ });
+ std::vector<uint32_t> vertexCell(nv); // each vertex's cell at the current level (into out.positions)
+ std::vector<uint32_t> itemCell;
+ std::vector<std::vector<uint32_t>> lists(nc);
+ std::vector<uint8_t> done(nc, 0);
+ std::vector<size_t> previous(nc, 0);
+ for (uint32_t c = 0; c < nc; ++c) previous[c] = order.clusterTriangles(c);
+ std::vector<std::pair<uint64_t, uint32_t>> sorted;
+ for (int level = 0; level < CoarseLevels::kMaxLevels; ++level) {
+ const size_t items = itemKey.size();
+ sorted.resize(items);
+ poolFor(items, [&](size_t i0, size_t i1) {
+ for (size_t i = i0; i < i1; ++i) sorted[i] = {itemKey[i], uint32_t(i)};
+ });
+ sortByKey(sorted);
+ // The cells: runs of one key.
+ const uint32_t base = uint32_t(out.positions.size());
+ itemCell.assign(items, 0);
+ std::vector<uint64_t> cellKey;
+ std::vector<glm::dvec3> cellSum;
+ std::vector<glm::vec3> cellNormal;
+ std::vector<uint32_t> cellWeight;
+ for (size_t i = 0; i < items;) {
+ size_t j = i;
+ glm::dvec3 sum(0.0);
+ glm::vec3 nsum(0.0f);
+ uint32_t w = 0;
+ for (; j < items && sorted[j].first == sorted[i].first; ++j) {
+ const uint32_t it = sorted[j].second;
+ if (level == 0) {
+ sum += glm::dvec3(mesh.positions[it]);
+ if (hasNormals) nsum += mesh.normals[it];
+ ++w;
+ } else {
+ sum += itemSum[it];
+ nsum += itemNormal[it];
+ w += itemWeight[it];
+ }
+ itemCell[it] = uint32_t(cellKey.size());
+ }
+ cellKey.push_back(sorted[i].first);
+ cellSum.push_back(sum);
+ cellNormal.push_back(nsum);
+ cellWeight.push_back(w);
+ i = j;
}
- const size_t tris = (out.size() - at) / 3;
- if (tris * 10 > previous * 7 || out.size() > maxIndices) { // no real gain (the seams), or no room
- out.resize(at);
- if (lod.levels == 0 && tris * 10 > previous * 7 && cell < span) continue; // (the first grid too fine: coarser)
- break;
+ const size_t cells = cellKey.size();
+ for (size_t k = 0; k < cells; ++k) {
+ out.positions.push_back(glm::vec3(cellSum[k] / double(cellWeight[k])));
+ const float l = glm::length(cellNormal[k]);
+ out.normals.push_back(l > 1e-12f ? cellNormal[k] / l : glm::vec3(0.0f, 0.0f, 1.0f));
}
- for (size_t k = at; k < out.size(); k += 3) {
- const glm::vec3 p0 = pos(out[k]);
- const glm::vec3 cr = glm::cross(pos(out[k + 1]) - p0, pos(out[k + 2]) - p0);
- const float l2 = glm::dot(cr, cr);
- if (l2 > 0.0f && std::isfinite(l2)) sum += cr / std::sqrt(l2);
+ poolFor(nv, [&](size_t v0, size_t v1) {
+ for (size_t v = v0; v < v1; ++v) vertexCell[v] = base + itemCell[level == 0 ? v : vertexCell[v] - (base - uint32_t(items))];
+ });
+ // Per cluster: its triangles on these cells, and its error.
+ poolFor(nc, [&](size_t c0, size_t c1) {
+ std::vector<std::array<uint32_t, 3>> tris;
+ for (size_t c = c0; c < c1; ++c) {
+ if (done[c]) continue;
+ const uint32_t n = order.clusterTriangles(uint32_t(c));
+ tris.clear();
+ float error = 0.0f;
+ for (uint32_t i = 0; i < n; ++i) {
+ const uint32_t t = order.triangle(uint32_t(c), i);
+ if (t >= nt || (hidden && mesh.hidden[t])) continue;
+ const glm::uvec3 tri = mesh.triangles[t];
+ if (tri.x >= nv || tri.y >= nv || tri.z >= nv) continue;
+ std::array<uint32_t, 3> m{vertexCell[tri.x], vertexCell[tri.y], vertexCell[tri.z]};
+ for (int k = 0; k < 3; ++k) error = std::max(error, glm::distance(mesh.positions[tri[k]], out.positions[m[size_t(k)]]));
+ if (m[0] == m[1] || m[1] == m[2] || m[0] == m[2]) continue;
+ std::rotate(m.begin(), std::min_element(m.begin(), m.end()), m.end()); // (one rotation per triangle)
+ tris.push_back(m);
+ }
+ std::sort(tris.begin(), tris.end());
+ tris.erase(std::unique(tris.begin(), tris.end()), tris.end());
+ CoarseLevels::Lod& lod = out.clusters[c];
+ if (tris.empty() || tris.size() * 10 > previous[c] * 8) {
+ done[c] = 1;
+ continue;
+ }
+ lod.first[lod.levels] = uint32_t(lists[c].size());
+ lod.count[lod.levels] = uint32_t(tris.size() * 3);
+ lod.error[lod.levels] = std::max(error, lod.levels > 0 ? lod.error[lod.levels - 1] : 0.0f);
+ ++lod.levels;
+ for (const auto& m : tris) lists[c].insert(lists[c].end(), m.begin(), m.end());
+ previous[c] = tris.size();
+ if (tris.size() < 8) done[c] = 1;
+ }
+ }, 16, 1);
+ if (cells < 64) break;
+ // The next level's items: these cells, each axis index halved.
+ itemKey.resize(cells);
+ itemSum = std::move(cellSum);
+ itemNormal = std::move(cellNormal);
+ itemWeight = std::move(cellWeight);
+ for (size_t k = 0; k < cells; ++k) {
+ const glm::uvec3 q = unpack(cellKey[k]);
+ itemKey[k] = pack(q / 2u);
}
- lod.first[lod.levels] = uint32_t(at);
- lod.count[lod.levels] = uint32_t(out.size() - at);
- lod.error[lod.levels] = std::max(error, lod.levels > 0 ? lod.error[lod.levels - 1] : 0.0f);
- ++lod.levels;
- previous = tris;
- if (tris < 8 || cell > span) break;
- }
- if (lod.levels == 0) return false;
- // One normal cone for every level (whichever is drawn, culling stays safe).
- const float sl = glm::length(sum);
- float minDot = 1.0f;
- bool faces = false;
- for (size_t k = 0; k < out.size() && sl > 1e-6f; k += 3) {
- const glm::vec3 p0 = pos(out[k]);
- const glm::vec3 cr = glm::cross(pos(out[k + 1]) - p0, pos(out[k + 2]) - p0);
- const float l2 = glm::dot(cr, cr);
- if (!(l2 > 0.0f) || !std::isfinite(l2)) continue;
- minDot = std::min(minDot, glm::dot(cr / std::sqrt(l2), sum / sl));
- faces = true;
}
- bounds.axis = glm::vec3(0.0f, 0.0f, 1.0f);
- bounds.coneAngle = -1.0f;
- if (faces && minDot > 0.0f) {
- bounds.axis = sum / sl;
- bounds.coneAngle = std::acos(std::min(minDot, 1.0f));
+ for (uint32_t c = 0; c < nc; ++c) {
+ const uint32_t at = uint32_t(out.indices.size());
+ for (int l = 0; l < out.clusters[c].levels; ++l) out.clusters[c].first[l] += at;
+ out.indices.insert(out.indices.end(), lists[c].begin(), lists[c].end());
}
- return true;
+ return out;
}
bool closedOriented(const Mesh& mesh) {
diff --git a/src/render/Clusters.h b/src/render/Clusters.h
index 59a675eb..3cc35f4f 100644
--- a/src/render/Clusters.h
+++ b/src/render/Clusters.h
@@ -73,21 +73,24 @@ ClusterBounds clusterBounds(const Mesh& mesh, const UploadOrder& order, uint32_t
bool clusterProxy(const Mesh& mesh, const UploadOrder& order, uint32_t c, size_t maxTriangles, std::vector<uint16_t>& out,
ClusterBounds& bounds);
-// A cluster's coarse levels (docs/design/micro-coarse-lod.md: Clark 1976, Rossignac-Borrel 1993): versions of it on
-// grids twice as coarse each time, built as clusterProxy builds one (vertices snapped to one per cell, seam vertices
-// kept, so any mix of levels between neighbours stays closed), each with its error: how far its farthest vertex
-// moved. The renderer picks per cluster the coarsest level whose error stays under a pixel or so on screen.
-struct ClusterLod {
+// Coarse levels below the mesh (spike, SF_COARSE_LOD=1; docs/design/micro-coarse-lod.md, Rossignac-Borrel 1993):
+// nested grids over the whole mesh, the first cell twice the mean edge, each next level twice as coarse; a cell's
+// point is the mean of the vertices in it (its normal their normals' sum). Every cluster gets per level its triangles
+// mapped to cells (degenerate and repeated ones dropped) and its error, the farthest any of its vertices moved. Two
+// clusters at one level share their cells' points: no cracks between them. A cluster's chain stops when a level
+// would keep more than 80% of the one before.
+struct CoarseLevels {
static constexpr int kMaxLevels = 6;
- int levels = 0;
- uint32_t first[kMaxLevels] = {}, count[kMaxLevels] = {}; // in the chain's index list (indices, not triangles)
- float error[kMaxLevels] = {}; // world units; grows with the level
+ struct Lod {
+ int levels = 0;
+ uint32_t first[kMaxLevels] = {}, count[kMaxLevels] = {}; // in `indices` (indices, not triangles)
+ float error[kMaxLevels] = {}; // world units
+ };
+ std::vector<glm::vec3> positions, normals; // every level's cell points, one level after the other
+ std::vector<uint32_t> indices; // into positions
+ std::vector<Lod> clusters;
};
-// The levels of cluster c, at most maxIndices indices in all, as indices into the cluster's vertex range. Stops
-// when a level would keep more than 70% of the one before (the seams hold the rest) or fewer than 8 triangles.
-// `bounds` gets a normal cone holding every level's triangles. False (and no levels): not even the first fits.
-bool clusterLodChain(const Mesh& mesh, const UploadOrder& order, uint32_t c, size_t maxIndices, std::vector<uint16_t>& out,
- ClusterLod& lod, ClusterBounds& bounds);
+CoarseLevels buildCoarseLevels(const Mesh& mesh, const UploadOrder& order);
// Every directed edge a->b has as many b->a: the mesh is the closed, consistently wound boundary of a volume
// (it may intersect itself). Wound outwards (a positive signed volume: the sum of ClusterBounds::volume), every
diff --git a/src/render/Renderer.cpp b/src/render/Renderer.cpp
index 644fc589..be46ead8 100644
--- a/src/render/Renderer.cpp
+++ b/src/render/Renderer.cpp
@@ -23,9 +23,8 @@
#include <cmath>
#include <thread>
#include <unordered_map>
-#include <cstdlib>
#include <cstdio>
-#include <string>
+#include <cstdlib>
#include <limits>
#include <vector>
@@ -1184,6 +1183,11 @@ void Renderer::freeSlot(MeshSlot& s) {
gl::DeleteVertexArrays(1, &s.vao);
gl::DeleteVertexArrays(1, &s.lineVao);
gl::DeleteVertexArrays(1, &s.proxyVao);
+ if (s.coarseVao) {
+ gl::DeleteBuffers(1, &s.coarseVertices);
+ gl::DeleteBuffers(1, &s.coarseIndices);
+ gl::DeleteVertexArrays(1, &s.coarseVao);
+ }
s.micro.reset();
if (s.patchVao) {
for (GLuint* b : {&s.patchVertices, &s.patchIndices, &s.patchLines, &s.patchColors, &s.patchMask, &s.patchGroupData})
@@ -1207,7 +1211,7 @@ size_t Renderer::gpuBytes() const {
for (const MeshSlot& s : slots_) {
for (size_t b : s.bytes) total += b;
total += s.patchBytes;
- if (s.proxyAllocated) total += (s.order.triangleCount() / proxyShare()) * 3 * sizeof(uint16_t);
+ if (s.proxyAllocated) total += (s.order.triangleCount() / 4) * 3 * sizeof(uint16_t);
if (s.paintTexture) total += size_t(s.textureW) * size_t(s.textureH) * 4 * 4 / 3; // with mipmaps
total += size_t(std::popcount(s.pbrPlanes)) * size_t(s.textureW) * size_t(s.textureH) * 4 * 4 / 3;
if (s.micro) total += s.micro->gpuBytes();
@@ -1577,6 +1581,7 @@ void Renderer::updateBounds(MeshSlot& s, const Mesh& mesh, bool all, bool comput
}
s.proxyStale.resize(clusters.size(), 1);
for (uint32_t c : cullScratch_) s.proxyStale[c] = 1;
+ if (!cullScratch_.empty()) s.coarseValid = false; // (the spike doesn't rebuild: the normal draw)
if (computed) cullScratch_.clear();
poolFor(cullScratch_.size(), [&](size_t i0, size_t i1) {
for (size_t i = i0; i < i1; ++i) {
@@ -1817,7 +1822,6 @@ void Renderer::buildProxies(MeshSlot& s, const Mesh& mesh) {
const size_t nc = s.order.clusters().size();
s.proxyStale.resize(nc, 1);
s.proxyCount.resize(nc, 0);
- s.proxyLod.resize(nc);
s.proxyBounds.resize(nc);
cullScratch_.clear();
for (uint32_t c = 0; c < nc; ++c) {
@@ -1830,7 +1834,7 @@ void Renderer::buildProxies(MeshSlot& s, const Mesh& mesh) {
if (cullScratch_.empty()) return;
if (!s.proxyAllocated) {
gl::BindVertexArray(s.proxyVao);
- gl::BufferData(GL_ELEMENT_ARRAY_BUFFER, GLsizeiptr((s.order.triangleCount() / proxyShare()) * 3 * sizeof(uint16_t)), nullptr, GL_STATIC_DRAW);
+ gl::BufferData(GL_ELEMENT_ARRAY_BUFFER, GLsizeiptr((s.order.triangleCount() / 4) * 3 * sizeof(uint16_t)), nullptr, GL_STATIC_DRAW);
gl::BindVertexArray(0);
s.proxyAllocated = true;
}
@@ -1838,8 +1842,7 @@ void Renderer::buildProxies(MeshSlot& s, const Mesh& mesh) {
// moving frame stalled the view (180-300 ms at 33M). Stale clusters draw in full detail until theirs is built.
// Batches are sized from the measured cost per cluster: a fixed 1024 took 157 ms a frame on two slow cores.
// Still frames (proxyPrebuild_) get less, as nothing waits for them.
- // (SF_COARSE_LOD=1, the spike: all of it at once, when the mesh is first drawn, timed)
- const double budgetMs = coarseLod_ ? 1e9 : proxyUsed_ ? 8.0 : 4.0;
+ const double budgetMs = proxyUsed_ ? 8.0 : 4.0;
constexpr size_t kProxyBatchMin = 16, kProxyBatchMax = 1024; // clusters per parallel batch
const auto start = std::chrono::steady_clock::now();
auto elapsedMs = [&] { return std::chrono::duration<double, std::milli>(std::chrono::steady_clock::now() - start).count(); };
@@ -1859,14 +1862,7 @@ void Renderer::buildProxies(MeshSlot& s, const Mesh& mesh) {
for (size_t i = i0; i < i1; ++i) {
const uint32_t c = cullScratch_[at + i];
ClusterBounds b = s.bounds[c];
- ClusterLod& lod = s.proxyLod[c];
- if (coarseLod_) { // (the spike: every level)
- if (!clusterLodChain(mesh, s.order, c, size_t(s.order.clusterTriangles(c) / 2) * 3, built[i], lod, b)) built[i].clear();
- } else { // the motion proxy alone, as one level
- lod = ClusterLod();
- if (!clusterProxy(mesh, s.order, c, s.order.clusterTriangles(c) / 4, built[i], b)) built[i].clear();
- else lod.levels = 1, lod.count[0] = uint32_t(built[i].size());
- }
+ if (!clusterProxy(mesh, s.order, c, s.order.clusterTriangles(c) / 4, built[i], b)) built[i].clear();
s.proxyBounds[c] = b;
}
}, 1, 2);
@@ -1875,7 +1871,7 @@ void Renderer::buildProxies(MeshSlot& s, const Mesh& mesh) {
s.proxyCount[c] = uint32_t(built[i].size());
s.proxyStale[c] = 0;
if (!built[i].empty())
- gl::BufferSubData(GL_ELEMENT_ARRAY_BUFFER, GLintptr(size_t(s.order.firstTriangle(c) / proxyShare()) * 3 * sizeof(uint16_t)),
+ gl::BufferSubData(GL_ELEMENT_ARRAY_BUFFER, GLintptr(size_t(s.order.firstTriangle(c) / 4) * 3 * sizeof(uint16_t)),
GLsizeiptr(built[i].size() * sizeof(uint16_t)), built[i].data());
}
at += n;
@@ -1883,12 +1879,6 @@ void Renderer::buildProxies(MeshSlot& s, const Mesh& mesh) {
proxyMsPerCluster_ = proxyMsPerCluster_ > 0.0 ? 0.7 * proxyMsPerCluster_ + 0.3 * perCluster : perCluster;
}
gl::BindVertexArray(0);
- if (coarseLod_) {
- size_t indices = 0;
- for (uint32_t c : cullScratch_) indices += s.proxyCount[c];
- std::fprintf(stderr, "coarse lod: %zu clusters built in %.0f ms (%zu triangles in all levels, %.0f MB)\n", cullScratch_.size(),
- elapsedMs(), indices / 3, double(indices * sizeof(uint16_t)) / 1048576.0);
- }
}
// ---------------------------------------------------------------------------
@@ -2295,8 +2285,8 @@ void Renderer::sync(MeshSlot& s, Mesh& mesh, const NormalMapView* normalMap, boo
}
if (full) {
s.proxyAllocated = false; // sized for the old mesh
+ s.coarseValid = s.coarseTried = false;
s.proxyCount.clear();
- s.proxyLod.clear();
// (closedOriented also accepts unwelded seams, the same point twice, which the layout's check doesn't.)
s.closed = s.order.closed() || closedOriented(mesh);
uploadFaces(s, mesh, wantUvs, indicesDone);
@@ -2325,9 +2315,10 @@ void Renderer::sync(MeshSlot& s, Mesh& mesh, const NormalMapView* normalMap, boo
// Small meshes draw in full while the view moves too (their proxy would save little).
constexpr size_t kProxyMinTriangles = size_t(1) << 18;
if (syncLog) lapMs(lap);
- const bool overBudget = coarseLod_ && lodBudget_ > 0 && s.drawnTriangles > lodBudget_;
- if ((proxyUsed_ || overBudget || (proxyPrebuild_ && s.proxyAllocated)) && !s.outOfMemory && s.drawnTriangles >= kProxyMinTriangles)
+ if ((proxyUsed_ || (proxyPrebuild_ && s.proxyAllocated)) && !s.outOfMemory && s.drawnTriangles >= kProxyMinTriangles)
buildProxies(s, mesh);
+ if (coarseLod_ && !s.coarseTried && !s.outOfMemory && s.drawnTriangles > (lodBudget_ ? lodBudget_ : triangleBudget(RenderSettings())))
+ buildCoarse(s, mesh);
if (syncLog) proxyMs = lapMs(lap);
syncTexture(s, mesh, pbr);
syncNormalMap(s, mesh, normalMap);
@@ -2874,9 +2865,7 @@ void Renderer::endCapture(std::vector<uint8_t>& rgba) {
void Renderer::draw(const Camera& camera, int targetWidth, int targetHeight, const RenderSettings& settings,
const Viewport& viewport) {
- static const bool coarseOn = std::getenv("SF_COARSE_LOD") && std::string(std::getenv("SF_COARSE_LOD")) == "1";
- coarseLod_ = coarseOn;
- if (!settings.motionProxy) lodBudget_ = triangleBudget(settings); // (sync builds the levels of meshes over it)
+ if (!settings.motionProxy) lodBudget_ = triangleBudget(settings); // (sync builds coarse levels of meshes over it)
// SF_FRAME_LOG=ms (App.cpp): a draw slower than that says where its time went (lit spheres, environment, Parts).
static const double drawLogMs = std::getenv("SF_FRAME_LOG") ? std::atof(std::getenv("SF_FRAME_LOG")) : -1.0;
const auto drawStart = std::chrono::steady_clock::now();
@@ -3106,28 +3095,12 @@ void Renderer::draw(const Camera& camera, int targetWidth, int targetHeight, con
// The clusters of `s` inside the view, less those facing away when that can't open a hole: the mesh is closed
// and wound consistently (closedOriented) with nothing hidden, the eye is outside its bounds, and no cluster
// reaches into the near plane's slab (a cut-open front would show the back faces behind it).
-void Renderer::cull(const MeshSlot& s, const CullView& frame, bool proxy, float lodPx, size_t budget) {
+void Renderer::cull(const MeshSlot& s, const CullView& frame, bool proxy) {
drawClusters_.clear();
proxyClusters_.clear();
- proxyLevel_.clear();
- proxy = proxy && s.proxyCount.size() == s.drawCount.size() && s.proxyBounds.size() == s.drawCount.size() &&
- s.proxyLod.size() == s.drawCount.size();
+ proxy = proxy && s.proxyCount.size() == s.drawCount.size() && s.proxyBounds.size() == s.drawCount.size();
CullView v = frame;
const glm::vec3 e = v.eye;
- // Coarse levels (lodPx > 0): the visible clusters first, then the threshold, then each one's level.
- lodScratch_.clear();
- auto keep = [&](uint32_t c) {
- const bool ready = proxy && s.proxyCount[c] > 0 && !s.proxyStale[c];
- const bool fullShows = !facingAway(v, s.bounds[c]);
- const bool coarseShows = ready && !facingAway(v, s.proxyBounds[c]);
- if (!ready) {
- if (fullShows) drawClusters_.push_back(c);
- } else if (lodPx <= 0.0f) { // the motion proxy
- if (coarseShows) proxyClusters_.push_back(c), proxyLevel_.push_back(0);
- } else if (fullShows || coarseShows) {
- lodScratch_.push_back({c, 0.0f, fullShows, coarseShows});
- }
- };
// Backface culling on (#68): back faces go on any mesh from any view, the GPU skipping each one and whole
// clusters facing away going first (in perspective: an orthographic view has no eye to judge them from).
if (forceBackfaces_) {
@@ -3136,9 +3109,12 @@ void Renderer::cull(const MeshSlot& s, const CullView& frame, bool proxy, float
const size_t n = std::min(s.bounds.size(), s.drawCount.size());
for (uint32_t c = 0; c < n; ++c) {
if (s.drawCount[c] == 0 || !insideFrustum(v, s.bounds[c])) continue;
- keep(c);
+ if (proxy && s.proxyCount[c] > 0 && !s.proxyStale[c]) {
+ if (!facingAway(v, s.proxyBounds[c])) proxyClusters_.push_back(c);
+ } else if (!facingAway(v, s.bounds[c])) {
+ drawClusters_.push_back(c);
+ }
}
- pickLevels(s, v, lodPx, budget);
return;
}
v.backfaces = !keepBackfaces_ && !v.ortho && s.closed && s.volume > 0.0 && !s.anyHidden && s.box.valid() &&
@@ -3167,56 +3143,64 @@ void Renderer::cull(const MeshSlot& s, const CullView& frame, bool proxy, float
if (s.drawCount[c] == 0) continue;
const ClusterBounds& b = s.bounds[c];
if (!insideFrustum(v, b)) continue;
- keep(c);
+ if (proxy && s.proxyCount[c] > 0 && !s.proxyStale[c]) {
+ if (!facingAway(v, s.proxyBounds[c])) proxyClusters_.push_back(c);
+ } else if (!facingAway(v, b)) {
+ drawClusters_.push_back(c);
+ }
}
- pickLevels(s, v, lodPx, budget);
}
// Clark 1976 / QSplat: per cluster the coarsest level whose error, projected at the cluster's nearest point, stays
-// under `px` pixels; `px` is raised (x1.5) until the triangles drawn fit `budget`, and when everything fits in
-// full detail, everything is drawn in full.
-void Renderer::pickLevels(const MeshSlot& s, const CullView& v, float px, size_t budget) {
- if (lodScratch_.empty()) return;
- // Pixels per world unit at distance 1 (perspective), or anywhere (orthographic).
+// under `px` pixels; `px` is raised (x1.5) until the triangles drawn fit `budget`. Everything fitting in full detail
+// draws in full. (No normal cones for the coarse levels: their back faces go to the GPU's culling.)
+void Renderer::cullCoarse(const MeshSlot& s, const CullView& frame, float px, size_t budget) {
+ cull(s, frame, false); // (the visible clusters, in full)
+ coarseClusters_.clear();
+ coarseLevel_.clear();
+ lodScratch_.clear();
const bool ortho = frameProj_[3][3] == 1.0f;
- const float unit = 0.5f * frameViewport_.w * frameProj_[1][1];
- size_t fixed = 0, full = 0;
- for (uint32_t c : drawClusters_) fixed += size_t(s.drawCount[c]) / 3;
- for (LodPick& k : lodScratch_) {
- const ClusterBounds& b = s.bounds[k.c];
- const float d = std::max(glm::dot(b.center - v.eye, v.forward) - b.radius, std::max(v.nearDistance, 1e-6f));
- k.scale = ortho ? unit : unit / d;
- if (k.fullShows) full += size_t(s.drawCount[k.c]) / 3;
+ const float unit = 0.5f * frameViewport_.w * frameProj_[1][1]; // pixels per world unit at distance 1
+ // (back-facing clusters cull() dropped may still be wanted coarse: the same frustum test, no cone)
+ size_t full = 0;
+ const size_t nc = std::min(s.bounds.size(), s.drawCount.size());
+ std::vector<uint8_t>& shown = coarseShown_;
+ shown.assign(nc, 0);
+ for (uint32_t c : drawClusters_) shown[c] = 1;
+ for (uint32_t c = 0; c < nc; ++c) {
+ if (s.drawCount[c] == 0 || !insideFrustum(frame, s.bounds[c])) continue;
+ const ClusterBounds& b = s.bounds[c];
+ const float d = std::max(glm::dot(b.center - frame.eye, frame.forward) - b.radius, std::max(frame.nearDistance, 1e-6f));
+ lodScratch_.push_back({c, ortho ? unit : unit / d, shown[c] != 0});
+ if (shown[c]) full += size_t(s.drawCount[c]) / 3;
}
+ drawClusters_.clear();
auto level = [&](const LodPick& k, float t) {
- const ClusterLod& lod = s.proxyLod[k.c];
+ const CoarseLevels::Lod& lod = s.coarse[k.c];
int pick = -1;
while (pick + 1 < lod.levels && lod.error[pick + 1] * k.scale <= t) ++pick;
return pick;
};
float t = px;
- if (budget == 0 || fixed + full > budget) {
- for (int round = 0; round < 24; ++round, t *= 1.5f) {
- size_t total = fixed;
+ if (full > budget) {
+ for (int round = 0; round < 30; ++round, t *= 1.5f) {
+ size_t total = 0;
for (const LodPick& k : lodScratch_) {
const int l = level(k, t);
- if (l < 0) total += k.fullShows ? size_t(s.drawCount[k.c]) / 3 : 0;
- else total += k.coarseShows ? s.proxyLod[k.c].count[l] / 3 : 0;
+ total += l < 0 ? (k.fullShows ? size_t(s.drawCount[k.c]) / 3 : 0) : s.coarse[k.c].count[l] / 3;
}
- if (budget == 0 || total <= budget) break;
+ if (total <= budget) break;
}
- lodPx_ = t;
} else {
- t = 0.0f; // (all of it fits: full detail)
- lodPx_ = 0.0f;
+ t = 0.0f;
}
for (const LodPick& k : lodScratch_) {
const int l = t > 0.0f ? level(k, t) : -1;
if (l < 0) {
if (k.fullShows) drawClusters_.push_back(k.c);
- } else if (k.coarseShows) {
- proxyClusters_.push_back(k.c);
- proxyLevel_.push_back(uint8_t(l));
+ } else {
+ coarseClusters_.push_back(k.c);
+ coarseLevel_.push_back(uint8_t(l));
}
}
}
@@ -3230,7 +3214,7 @@ void Renderer::drawClusters(const MeshSlot& s, const std::vector<uint32_t>& clus
drawBases_.clear();
const auto layout = s.order.clusters();
size_t indices = 0;
- for (const uint32_t& c : clusters) {
+ for (uint32_t c : clusters) {
GLsizei count = 0;
size_t first = 0;
switch (part) {
@@ -3242,14 +3226,11 @@ void Renderer::drawClusters(const MeshSlot& s, const std::vector<uint32_t>& clus
count = GLsizei(s.lineCount[c]);
first = s.lineFirst[c];
break;
- case DrawPart::Proxy: { // (clusters is proxyClusters_: its level in proxyLevel_)
- const ClusterLod& lod = s.proxyLod[c];
- const int l = std::min<int>(proxyLevel_[size_t(&c - clusters.data())], lod.levels - 1);
- count = GLsizei(lod.count[l]);
- first = size_t(s.order.firstTriangle(c) / proxyShare()) * 3 + lod.first[l];
+ case DrawPart::Proxy:
+ count = GLsizei(s.proxyCount[c]);
+ first = size_t(s.order.firstTriangle(c) / 4) * 3;
break;
}
- }
drawCounts_.push_back(count);
drawOffsets_.push_back(reinterpret_cast<const void*>(first * sizeof(uint16_t)));
drawBases_.push_back(GLint(layout[c].firstVertex));
@@ -3285,6 +3266,41 @@ size_t Renderer::triangleBudget(const RenderSettings& settings) const {
return settings.motionProxy ? full / 2 : full;
}
+// The spike's coarse levels (render/Clusters.h): built once, at once, timed; their own vertices and 32-bit indices.
+void Renderer::buildCoarse(MeshSlot& s, const Mesh& mesh) {
+ s.coarseTried = true;
+ const auto start = std::chrono::steady_clock::now();
+ CoarseLevels levels = buildCoarseLevels(mesh, s.order);
+ const double buildMs = std::chrono::duration<double, std::milli>(std::chrono::steady_clock::now() - start).count();
+ if (levels.clusters.size() != s.order.clusters().size() || levels.indices.empty()) return;
+ std::vector<PackedVertex> packed(levels.positions.size());
+ for (size_t i = 0; i < packed.size(); ++i) packVertex(s.grid, levels.positions[i], levels.normals[i], 0.0f, packed[i]);
+ if (!s.coarseVao) {
+ gl::GenVertexArrays(1, &s.coarseVao);
+ gl::GenBuffers(1, &s.coarseVertices);
+ gl::GenBuffers(1, &s.coarseIndices);
+ }
+ gl::BindVertexArray(s.coarseVao);
+ gl::BindBuffer(GL_ARRAY_BUFFER, s.coarseVertices);
+ gl::BufferData(GL_ARRAY_BUFFER, GLsizeiptr(packed.size() * sizeof(PackedVertex)), packed.data(), GL_STATIC_DRAW);
+ gl::EnableVertexAttribArray(0);
+ gl::VertexAttribIPointer(0, 2, GL_UNSIGNED_INT, sizeof(PackedVertex), nullptr);
+ gl::EnableVertexAttribArray(1);
+ gl::VertexAttribIPointer(1, 1, GL_UNSIGNED_INT, sizeof(PackedVertex), reinterpret_cast<const void*>(2 * sizeof(uint32_t)));
+ gl::BindBuffer(GL_ELEMENT_ARRAY_BUFFER, s.coarseIndices);
+ gl::BufferData(GL_ELEMENT_ARRAY_BUFFER, GLsizeiptr(levels.indices.size() * sizeof(uint32_t)), levels.indices.data(), GL_STATIC_DRAW);
+ gl::BindVertexArray(0);
+ gl::BindBuffer(GL_ARRAY_BUFFER, 0);
+ s.coarse = std::move(levels.clusters);
+ s.coarseValid = true;
+ size_t first = 0, coarsest = 0, withLevels = 0;
+ for (const CoarseLevels::Lod& l : s.coarse)
+ if (l.levels > 0) first += l.count[0] / 3, coarsest += l.count[l.levels - 1] / 3, ++withLevels;
+ std::fprintf(stderr, "coarse lod: %zu of %zu clusters, built in %.0f ms; %zu cells, %zu indices (%.0f MB GPU); level 1 %zu, coarsest %zu of %zu triangles\n",
+ withLevels, s.coarse.size(), buildMs, packed.size(), levels.indices.size(),
+ double(packed.size() * sizeof(PackedVertex) + levels.indices.size() * 4) / 1048576.0, first, coarsest, s.order.triangleCount());
+}
+
void Renderer::drawMicro(const MeshSlot& s, bool active, bool flat, const RenderSettings& settings) {
const MeshProgram* p = meshProgram(kMicro | (flat ? kFlat : 0) | (settings.pbr() && envTexture_ ? kPbr : 0));
if (!p) return;
@@ -3413,12 +3429,11 @@ void Renderer::drawSlot(const MeshSlot& s, bool active, bool flat, const RenderS
// full triangles, nor under the wireframe, whose edges would sink into it.
const bool perTriangle = features & (kPrim | kTextured | kNormalMap); // (not kFlat: no per-triangle data)
const bool coarseAllowed = !perTriangle && !(active && settings.wireframe);
- // Coarse levels (coarseLod_, SF_COARSE_LOD=1): a mesh over the budget, or any big one while the view moves.
- const size_t budget = triangleBudget(settings);
- if (coarseLod_ && coarseAllowed && (settings.motionProxy || s.drawnTriangles > budget))
- cull(s, frameCull_, true, kCoarseLodPx * (settings.motionProxy ? 2.0f : 1.0f), budget);
- else
- cull(s, frameCull_, settings.motionProxy && coarseAllowed);
+ const size_t budget = coarseLod_ ? triangleBudget(settings) : 0;
+ const bool coarse = coarseLod_ && coarseAllowed && s.coarseValid && s.coarse.size() == s.drawCount.size() &&
+ (settings.motionProxy || s.drawnTriangles > budget);
+ if (coarse) cullCoarse(s, frameCull_, kCoarseLodPx * (settings.motionProxy ? 2.0f : 1.0f), budget);
+ else cull(s, frameCull_, settings.motionProxy && coarseAllowed);
// The back faces left in clusters along the silhouette: the GPU skips them too when they can't show.
if (cullBackfaces_ || xrayCull_) gl::Enable(GL_CULL_FACE);
if (xrayCull_) gl::CullFace(xrayCull_);
@@ -3466,6 +3481,26 @@ void Renderer::drawSlot(const MeshSlot& s, bool active, bool flat, const RenderS
drawPatches(s, GL_TRIANGLES, DrawPart::Triangles, perTriangle ? p->primBase : -1);
gl::BindVertexArray(s.vao);
}
+ if (coarse && !coarseClusters_.empty()) { // the spike's coarse levels: one multi-draw, 32-bit indices
+ gl::BindVertexArray(s.coarseVao);
+ gl::VertexAttrib4f(2, 1.0f, 1.0f, 1.0f, 1.0f);
+ gl::VertexAttrib1f(3, 0.0f);
+ gl::Uniform1i(p->twoSided, 0);
+ drawCounts_.clear();
+ drawOffsets_.clear();
+ size_t indices = 0;
+ for (size_t i = 0; i < coarseClusters_.size(); ++i) {
+ const CoarseLevels::Lod& l = s.coarse[coarseClusters_[i]];
+ drawCounts_.push_back(GLsizei(l.count[coarseLevel_[i]]));
+ drawOffsets_.push_back(reinterpret_cast<const void*>(size_t(l.first[coarseLevel_[i]]) * sizeof(uint32_t)));
+ indices += l.count[coarseLevel_[i]];
+ }
+ lastDrawn_ += indices / 3;
+ drawBases_.assign(drawCounts_.size(), 0);
+ gl::MultiDrawElementsBaseVertex(GL_TRIANGLES, drawCounts_.data(), GL_UNSIGNED_INT, drawOffsets_.data(), GLsizei(drawCounts_.size()),
+ drawBases_.data());
+ gl::BindVertexArray(s.vao);
+ }
if (!proxyClusters_.empty()) {
gl::BindVertexArray(s.proxyVao);
if (!s.hasColors) gl::VertexAttrib4f(2, 1.0f, 1.0f, 1.0f, 1.0f);
@@ -3733,7 +3768,7 @@ void Renderer::commitStrokeUpload(StrokeUpload& up) {
s.proxyStale.resize(s.bounds.size(), 1);
for (size_t i = 0; i < up.movedClusters.size(); ++i) {
s.bounds[up.movedClusters[i]] = up.bounds[i];
- s.proxyStale[up.movedClusters[i]] = 1;
+ s.proxyStale[up.movedClusters[i]] = 1, s.coarseValid = false;
}
s.looseClusters.insert(s.looseClusters.end(), up.movedClusters.begin(), up.movedClusters.end());
s.looseMark.resize(s.bounds.size(), 0);
diff --git a/src/render/Renderer.h b/src/render/Renderer.h
index e79c4a9a..6274baca 100644
--- a/src/render/Renderer.h
+++ b/src/render/Renderer.h
@@ -14,6 +14,7 @@
#include "render/ScreenStroke.h"
#include <cstdint>
+#include <cstdlib>
#include <functional>
#include <list>
#include <memory>
@@ -350,14 +351,17 @@ private:
std::vector<uint32_t> primBase; // per cluster: its first drawn triangle
std::vector<uint32_t> lineFirst, lineCount; // per cluster: its edges in lineBuffer (in indices)
bool linesValid = false;
- // Coarse levels (clusterLodChain; the first is the motion proxy): per cluster up to half of its triangles
- // in all, at (firstTriangle / 2) * 3.
+ // Motion proxy (clusterProxy): per cluster up to a quarter of its triangles, at (firstTriangle / 4) * 3.
GLuint proxyVao = 0, proxyBuffer = 0;
- std::vector<uint32_t> proxyCount; // indices, every level; 0: none (the cluster draws in full)
- std::vector<ClusterLod> proxyLod; // the levels in that range
+ std::vector<uint32_t> proxyCount; // indices; 0: none (the cluster draws in full)
std::vector<uint8_t> proxyStale; // to rebuild before use
std::vector<ClusterBounds> proxyBounds; // the proxy's normal cone
bool proxyAllocated = false;
+ // Coarse levels (spike, SF_COARSE_LOD=1: buildCoarseLevels at the first sync over the budget). Any edit to
+ // the mesh drops them (the normal draw again): no rebuild in the spike.
+ GLuint coarseVao = 0, coarseVertices = 0, coarseIndices = 0;
+ std::vector<CoarseLevels::Lod> coarse;
+ bool coarseValid = false, coarseTried = false;
std::vector<uint32_t> drawnOrder; // the mesh triangle of each drawn triangle (meshes with UVs only)
size_t drawnTriangles = 0;
size_t vertexCapacity = 0;
@@ -411,8 +415,14 @@ private:
bool proxyPending_ = false; // (proxiesPending)
bool proxyPrebuild_ = false; // (setProxyPrebuild)
double proxyMsPerCluster_ = 0.0; // measured, so a frame's batches fit its budget on slow cores too
- size_t lodBudget_ = 0; // the last draw's triangle budget: sync builds the coarse levels of meshes over it
- float lodPx_ = 0.0f; // the last coarse frame's error threshold (pixels), so the next starts near it
+ // Spike (SF_COARSE_LOD=1, off by default; docs/design/micro-coarse-lod.md): plain meshes over the triangle budget
+ // draw per cluster a coarse level (render/Clusters.h: CoarseLevels), at rest too: the coarsest whose error stays
+ // under kCoarseLodPx on screen, raised until the budget holds; full detail when it all fits.
+ const bool coarseLod_ = std::getenv("SF_COARSE_LOD") && std::string(std::getenv("SF_COARSE_LOD")) == "1";
+ static constexpr float kCoarseLodPx = 0.75f;
+ size_t lodBudget_ = 0; // the last still draw's triangle budget: sync builds the coarse levels of meshes over it
+ void buildCoarse(MeshSlot& s, const Mesh& mesh);
+ size_t triangleBudget(const RenderSettings& settings) const;
// The ghost (setGhost), drawn on the slot ghostId_.
GhostStroke ghost_;
uint32_t ghostId_ = 0;
@@ -457,31 +467,26 @@ private:
int envIndex_ = -1, envFailedIndex_ = -1;
SH9 envSh_;
glm::mat3 frameViewToEnv_{1.0f};
- // The clusters of `s` to draw this frame: in full (drawClusters_), and where built and `proxy`, at a coarse
- // level (proxyClusters_, the level in proxyLevel_): the motion proxy (lodPx <= 0), or per cluster the coarsest
- // level whose error stays under lodPx pixels, raised until at most `budget` triangles are drawn.
- void cull(const MeshSlot& s, const CullView& view, bool proxy = false, float lodPx = 0.0f, size_t budget = 0);
- void drawSlot(const MeshSlot& s, bool active, bool flat, const RenderSettings& settings);
- enum class DrawPart { Triangles, Lines, Proxy };
- void drawPatches(const MeshSlot& s, GLenum mode, DrawPart part, GLint primBaseLocation);
- void drawClusters(const MeshSlot& s, const std::vector<uint32_t>& clusters, GLenum mode, DrawPart part, GLint primBaseLocation);
- std::vector<uint32_t> proxyClusters_;
- std::vector<uint8_t> proxyLevel_;
+ // The clusters of `s` to draw this frame: in full (drawClusters_), and with `proxy` as their motion proxy
+ // where it is built (proxyClusters_).
+ void cull(const MeshSlot& s, const CullView& view, bool proxy = false);
+ // The coarse-level cull (spike): every visible cluster in full (drawClusters_) or at a level (coarseClusters_,
+ // coarseLevel_): per cluster the coarsest whose error stays under `px` pixels, `px` raised until `budget` holds.
+ void cullCoarse(const MeshSlot& s, const CullView& view, float px, size_t budget);
+ std::vector<uint32_t> coarseClusters_;
+ std::vector<uint8_t> coarseLevel_;
struct LodPick {
uint32_t c;
float scale; // pixels per world unit at the cluster's nearest point
- bool fullShows, coarseShows;
+ bool fullShows;
};
std::vector<LodPick> lodScratch_;
- void pickLevels(const MeshSlot& s, const CullView& v, float px, size_t budget);
- size_t triangleBudget(const RenderSettings& settings) const;
- // Spike (SF_COARSE_LOD=1, off by default; docs/design/micro-coarse-lod.md): plain meshes over the triangle budget
- // draw their clusters' coarse levels (render/Clusters.h: ClusterLod), at rest too: the coarsest whose error stays
- // under kCoarseLodPx on screen, raised until the budget holds. Off: the motion proxy while moving, as before.
- bool coarseLod_ = false;
- static constexpr float kCoarseLodPx = 0.75f;
- // A cluster's part of the proxy buffer: 1/proxyShare of its triangles, at (firstTriangle / proxyShare) * 3.
- uint32_t proxyShare() const { return coarseLod_ ? 2 : 4; }
+ std::vector<uint8_t> coarseShown_;
+ void drawSlot(const MeshSlot& s, bool active, bool flat, const RenderSettings& settings);
+ enum class DrawPart { Triangles, Lines, Proxy };
+ void drawPatches(const MeshSlot& s, GLenum mode, DrawPart part, GLint primBaseLocation);
+ void drawClusters(const MeshSlot& s, const std::vector<uint32_t>& clusters, GLenum mode, DrawPart part, GLint primBaseLocation);
+ std::vector<uint32_t> proxyClusters_;
std::vector<GLsizei> drawCounts_;
std::vector<const void*> drawOffsets_;
std::vector<GLint> drawBases_;
diff --git a/tests/test_render_clusters.cpp b/tests/test_render_clusters.cpp
index 7c315caf..9c7161e5 100644
--- a/tests/test_render_clusters.cpp
+++ b/tests/test_render_clusters.cpp
@@ -350,71 +350,3 @@ TEST(motion_proxy_is_closed_and_light) {
ClusterBounds b;
CHECK(clusterProxy(h, order, 0, order.clusterTriangles(0), proxy, b) && proxy.empty());
}
-
-TEST(coarse_lod_chain_closed_at_any_mix_of_levels) {
- // Each cluster's coarse levels (clusterLodChain) keep its seam vertices: whatever level each cluster draws,
- // full detail included, a closed mesh stays closed (no cracks). Each level is lighter than the one before and
- // its error no smaller; the coarsest levels together are a small fraction of the mesh.
- Mesh m = makeBenchSphere(1000000);
- for (size_t v = 0; v < m.vertexCount(); ++v) {
- const glm::vec3 p = m.positions[v];
- m.positions[v] = p * (1.0f + 0.02f * std::sin(p.x * 31.0f) * std::sin(p.z * 29.0f));
- }
- m.recomputeAllNormals();
- UploadOrder order;
- order.build(m);
- const uint32_t nc = uint32_t(order.clusters().size());
- std::vector<std::vector<uint16_t>> chain(nc);
- std::vector<ClusterLod> lods(nc);
- std::vector<uint16_t> local;
- bool built = true, shrinking = true, inRange = true;
- size_t coarsest = 0, first = 0, levels = 0;
- for (uint32_t c = 0; c < nc; ++c) {
- ClusterBounds b = clusterBounds(m, order, c);
- const size_t cap = size_t(order.clusterTriangles(c) / 2) * 3;
- built = built && clusterLodChain(m, order, c, cap, chain[c], lods[c], b) && chain[c].size() <= cap;
- const ClusterLod& l = lods[c];
- if (l.levels == 0) continue;
- levels += size_t(l.levels);
- first += l.count[0] / 3;
- coarsest += l.count[l.levels - 1] / 3;
- shrinking = shrinking && l.count[0] / 3 < order.clusterTriangles(c);
- for (int k = 1; k < l.levels; ++k) shrinking = shrinking && l.count[k] < l.count[k - 1] && l.error[k] >= l.error[k - 1];
- for (uint16_t i : chain[c]) inRange = inRange && i < order.clusters()[c].vertexCount;
- }
- std::printf(" coarse levels: %zu clusters, %.1f levels each; first %zu, coarsest %zu of %zu triangles\n", size_t(nc),
- double(levels) / double(nc), first, coarsest, m.triangleCount());
- CHECK(built);
- CHECK(shrinking);
- CHECK(inRange);
- CHECK(coarsest * 8 < m.triangleCount());
- std::mt19937 rng(7);
- for (int round = 0; round < 4; ++round) {
- std::map<std::pair<uint32_t, uint32_t>, int> edges;
- for (uint32_t c = 0; c < nc; ++c) {
- const auto& cl = order.clusters()[c];
- const int pick = round == 0 ? -1 : int(rng() % uint32_t(lods[c].levels + 1)) - 1; // -1: full detail
- const uint16_t* idx = nullptr;
- size_t count = 0;
- if (pick < 0) {
- local.resize(size_t(order.clusterTriangles(c)) * 3);
- order.localTriangles(m, c, local.data());
- idx = local.data();
- count = local.size();
- } else {
- idx = chain[c].data() + lods[c].first[pick];
- count = lods[c].count[pick];
- }
- for (size_t i = 0; i < count; i += 3)
- for (int k = 0; k < 3; ++k) {
- const uint32_t a = order.fromGpu()[cl.firstVertex + idx[i + size_t(k)]];
- const uint32_t e = order.fromGpu()[cl.firstVertex + idx[i + size_t((k + 1) % 3)]];
- ++edges[{a, e}];
- --edges[{e, a}];
- }
- }
- bool closed = true;
- for (const auto& [e, n] : edges) closed = closed && n == 0;
- CHECK(closed);
- }
-}