BVH frustum culling over instances

Re-wires the BVH acceleration structure on top of the new instanced
renderer.  Per model, build a BVH over per-instance world AABBs at
finalize (and on sidecar apply).  Each frame, traverse the BVH against
the camera frustum to produce a visible-instance index list, bucket by
mesh_id, and upload to a per-model SSBO at binding=1.  The main and
pick vertex shaders do a double-indirection
`instances[visible[u_offset + gl_InstanceID]]` so draws only touch
instances that passed the frustum test.

Models with fewer than BVH_MIN_OBJECTS instances skip the BVH build
and fall back to a linear per-instance frustum test.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
This commit is contained in:
Dion Moult
2026-04-12 20:23:50 +10:00
parent ababb49ae7
commit 1f17d73f3e
4 changed files with 204 additions and 12 deletions
+25
View File
@@ -34,6 +34,7 @@
#include <mutex>
#include <memory>
#include "BvhAccel.h"
#include "InstancedGeometry.h"
#include "SidecarCache.h"
@@ -63,6 +64,20 @@ struct ModelGpuData {
std::vector<InstanceCpu> instances; // unsorted until finalize
uint32_t ssbo_instance_count = 0;
// Per-instance world AABB + BVH (built at finalize). The BVH is the
// same ordering as `instances`; bvh_items[i] corresponds to instances[i].
std::vector<BvhItem> bvh_items;
ModelBvh bvh;
// Dynamic visible-instance index buffer (std430, binding = 1).
// Re-uploaded each frame from frame_visible_scratch_.
GLuint visible_ssbo = 0;
size_t visible_ssbo_capacity = 0; // bytes
// Per-mesh visible-list offset/count, rebuilt each frame.
std::vector<uint32_t> mesh_vis_first;
std::vector<uint32_t> mesh_vis_count;
bool finalized = false;
bool hidden = false;
};
@@ -135,6 +150,10 @@ private:
bool growModelEbo(ModelGpuData& m, size_t needed_total);
ModelGpuData& getOrCreateModel(uint32_t model_id);
// Populate m.mesh_vis_first / mesh_vis_count and upload visible indices
// to m.visible_ssbo. Uses BVH when available, else linear scan.
void cullAndUploadVisible(ModelGpuData& m, const float planes[6][4]);
// Mouse interaction
void handleMousePress(QMouseEvent* event);
void handleMouseRelease(QMouseEvent* event);
@@ -171,6 +190,12 @@ private:
uint32_t visible_objects_ = 0;
uint32_t instanced_draws_ = 0;
// Reused scratch: visible-instance index lists per mesh, flattened into
// `visible_flat_` for upload. Both live in the parent object to avoid
// per-frame allocation.
std::vector<std::vector<uint32_t>> visible_by_mesh_;
std::vector<uint32_t> visible_flat_;
// Camera
QVector3D camera_target_{0, 0, 0};
float camera_distance_ = 50.0f;