diff --git a/src/ifcviewer/BvhAccel.cpp b/src/ifcviewer/BvhAccel.cpp
new file mode 100644
index 0000000000..e0b232a283
--- /dev/null
+++ b/src/ifcviewer/BvhAccel.cpp
@@ -0,0 +1,226 @@
+/********************************************************************************
+ * *
+ * This file is part of IfcOpenShell. *
+ * *
+ * IfcOpenShell is free software: you can redistribute it and/or modify *
+ * it under the terms of the Lesser GNU General Public License as published by *
+ * the Free Software Foundation, either version 3.0 of the License, or *
+ * (at your option) any later version. *
+ * *
+ * IfcOpenShell is distributed in the hope that it will be useful, *
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of *
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *
+ * Lesser GNU General Public License for more details. *
+ * *
+ * You should have received a copy of the Lesser GNU General Public License *
+ * along with this program. If not, see . *
+ * *
+ ********************************************************************************/
+
+#include "BvhAccel.h"
+
+#include
+#include
+#include
+#include
+#include
+
+namespace {
+
+struct Centroid {
+ float x, y, z;
+};
+
+Centroid computeCentroid(const ObjectDrawInfo& obj) {
+ return {
+ (obj.aabb_min[0] + obj.aabb_max[0]) * 0.5f,
+ (obj.aabb_min[1] + obj.aabb_max[1]) * 0.5f,
+ (obj.aabb_min[2] + obj.aabb_max[2]) * 0.5f
+ };
+}
+
+void computeAABB(const std::vector& draw_info,
+ const uint32_t* indices, uint32_t count,
+ float out_min[3], float out_max[3]) {
+ out_min[0] = out_min[1] = out_min[2] = std::numeric_limits::max();
+ out_max[0] = out_max[1] = out_max[2] = -std::numeric_limits::max();
+ for (uint32_t i = 0; i < count; ++i) {
+ const auto& obj = draw_info[indices[i]];
+ for (int a = 0; a < 3; ++a) {
+ if (obj.aabb_min[a] < out_min[a]) out_min[a] = obj.aabb_min[a];
+ if (obj.aabb_max[a] > out_max[a]) out_max[a] = obj.aabb_max[a];
+ }
+ }
+}
+
+// Recursive BVH builder. Writes nodes in pre-order DFS into mbvh.nodes.
+// object_indices[start..start+count) are the indices to partition.
+void buildRecursive(ModelBvh& mbvh,
+ const std::vector& draw_info,
+ uint32_t start, uint32_t count) {
+ uint32_t node_idx = static_cast(mbvh.nodes.size());
+ mbvh.nodes.emplace_back();
+ BvhNode& node = mbvh.nodes[node_idx];
+
+ computeAABB(draw_info, &mbvh.object_indices[start], count,
+ node.aabb_min, node.aabb_max);
+
+ if (count <= BVH_MAX_LEAF_SIZE) {
+ node.right_or_first = start;
+ node.count = static_cast(count);
+ node.axis = 0;
+ return;
+ }
+
+ // Find longest axis of node AABB.
+ float extent[3] = {
+ node.aabb_max[0] - node.aabb_min[0],
+ node.aabb_max[1] - node.aabb_min[1],
+ node.aabb_max[2] - node.aabb_min[2]
+ };
+ int axis = 0;
+ if (extent[1] > extent[axis]) axis = 1;
+ if (extent[2] > extent[axis]) axis = 2;
+
+ // Partition at median centroid on the chosen axis.
+ uint32_t mid = count / 2;
+ std::nth_element(
+ mbvh.object_indices.begin() + start,
+ mbvh.object_indices.begin() + start + mid,
+ mbvh.object_indices.begin() + start + count,
+ [&](uint32_t a, uint32_t b) {
+ Centroid ca = computeCentroid(draw_info[a]);
+ Centroid cb = computeCentroid(draw_info[b]);
+ return (&ca.x)[axis] < (&cb.x)[axis];
+ });
+
+ node.count = 0; // interior
+ node.axis = static_cast(axis);
+
+ // Left child is always node_idx + 1 (implicit in pre-order DFS).
+ // Build left subtree first. Note: &node is invalidated after this call
+ // because the vector may reallocate.
+ buildRecursive(mbvh, draw_info, start, mid);
+
+ // Right child is the next node written after the entire left subtree.
+ uint32_t right_child_idx = static_cast(mbvh.nodes.size());
+ buildRecursive(mbvh, draw_info, start + mid, count - mid);
+
+ // Patch the right child index (left is implicit = node_idx + 1).
+ mbvh.nodes[node_idx].right_or_first = right_child_idx;
+}
+
+} // anonymous namespace
+
+ModelBvh buildModelBvh(const std::vector& draw_info,
+ const std::vector& model_object_indices,
+ uint32_t model_id) {
+ ModelBvh mbvh;
+ mbvh.model_id = model_id;
+ mbvh.object_indices = model_object_indices;
+
+ uint32_t count = static_cast(model_object_indices.size());
+ if (count == 0) return mbvh;
+
+ // Reserve a rough estimate: ~2*n nodes for a balanced binary tree.
+ mbvh.nodes.reserve(count * 2);
+
+ buildRecursive(mbvh, draw_info, 0, count);
+
+ // Verify: every object appears exactly once in the leaves.
+ assert(!mbvh.nodes.empty());
+
+ return mbvh;
+}
+
+std::shared_ptr buildBvhSet(const std::vector& draw_info) {
+ auto bvh_set = std::make_shared();
+
+ // Group object indices by model_id.
+ std::unordered_map> model_objects;
+ for (uint32_t i = 0; i < static_cast(draw_info.size()); ++i) {
+ model_objects[draw_info[i].model_id].push_back(i);
+ }
+
+ // Build per-model BVHs.
+ for (auto& [model_id, obj_indices] : model_objects) {
+ if (obj_indices.size() < BVH_MIN_OBJECTS) continue;
+
+ ModelBvh mbvh = buildModelBvh(draw_info, obj_indices, model_id);
+ bvh_set->bvh_model_ids.insert(model_id);
+ bvh_set->models[model_id] = std::move(mbvh);
+ }
+
+ return bvh_set;
+}
+
+EboReorderResult reorderEbo(const BvhSet& bvh_set,
+ const std::vector& draw_info,
+ const std::vector& original_ebo) {
+ EboReorderResult result;
+ result.reordered_draw_info = draw_info; // copy; we'll update offsets
+ result.reordered_ebo.reserve(original_ebo.size());
+
+ // Track which draw_info entries have been placed.
+ std::vector placed(draw_info.size(), false);
+
+ for (const auto& [model_id, mbvh] : bvh_set.models) {
+ // DFS traversal of BVH to visit leaves in order.
+ uint32_t stack[64];
+ int sp = 0;
+ stack[sp++] = 0;
+
+ while (sp > 0) {
+ uint32_t ni = stack[--sp];
+ const BvhNode& node = mbvh.nodes[ni];
+
+ if (node.count > 0) {
+ // Leaf: emit objects in order.
+ for (uint32_t i = 0; i < node.count; ++i) {
+ uint32_t oi = mbvh.object_indices[node.right_or_first + i];
+ if (placed[oi]) continue;
+ placed[oi] = true;
+
+ const auto& old_info = draw_info[oi];
+ uint32_t new_offset = static_cast(
+ result.reordered_ebo.size() * sizeof(uint32_t));
+
+ // Copy indices from original EBO.
+ uint32_t idx_start = old_info.index_offset / sizeof(uint32_t);
+ uint32_t idx_count = old_info.index_count;
+ for (uint32_t j = 0; j < idx_count; ++j) {
+ result.reordered_ebo.push_back(original_ebo[idx_start + j]);
+ }
+
+ result.reordered_draw_info[oi].index_offset = new_offset;
+ }
+ } else {
+ // Interior: push left (=ni+1) last so it's processed first.
+ stack[sp++] = node.right_or_first; // right child
+ stack[sp++] = ni + 1; // left child
+ }
+ }
+ }
+
+ // Append non-BVH objects (models too small for BVH).
+ for (uint32_t oi = 0; oi < static_cast(draw_info.size()); ++oi) {
+ if (placed[oi]) continue;
+ placed[oi] = true;
+
+ const auto& old_info = draw_info[oi];
+ uint32_t new_offset = static_cast(
+ result.reordered_ebo.size() * sizeof(uint32_t));
+
+ uint32_t idx_start = old_info.index_offset / sizeof(uint32_t);
+ uint32_t idx_count = old_info.index_count;
+ for (uint32_t j = 0; j < idx_count; ++j) {
+ result.reordered_ebo.push_back(original_ebo[idx_start + j]);
+ }
+
+ result.reordered_draw_info[oi].index_offset = new_offset;
+ }
+
+ assert(result.reordered_ebo.size() == original_ebo.size());
+
+ return result;
+}
diff --git a/src/ifcviewer/BvhAccel.h b/src/ifcviewer/BvhAccel.h
new file mode 100644
index 0000000000..21c57c2712
--- /dev/null
+++ b/src/ifcviewer/BvhAccel.h
@@ -0,0 +1,75 @@
+/********************************************************************************
+ * *
+ * This file is part of IfcOpenShell. *
+ * *
+ * IfcOpenShell is free software: you can redistribute it and/or modify *
+ * it under the terms of the Lesser GNU General Public License as published by *
+ * the Free Software Foundation, either version 3.0 of the License, or *
+ * (at your option) any later version. *
+ * *
+ * IfcOpenShell is distributed in the hope that it will be useful, *
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of *
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *
+ * Lesser GNU General Public License for more details. *
+ * *
+ * You should have received a copy of the Lesser GNU General Public License *
+ * along with this program. If not, see . *
+ * *
+ ********************************************************************************/
+
+#ifndef BVHACCEL_H
+#define BVHACCEL_H
+
+#include
+#include
+#include
+#include
+#include
+
+struct ObjectDrawInfo {
+ uint32_t index_offset; // byte offset into EBO
+ uint32_t index_count; // number of indices
+ uint32_t model_id; // which model this object belongs to
+ float aabb_min[3]; // world-space AABB
+ float aabb_max[3];
+};
+
+static constexpr uint32_t BVH_MAX_LEAF_SIZE = 8;
+static constexpr uint32_t BVH_MIN_OBJECTS = 32;
+
+struct BvhNode {
+ float aabb_min[3];
+ float aabb_max[3];
+ uint32_t right_or_first; // interior: right child index (left is always this_index+1); leaf: first object index
+ uint16_t count; // 0 = interior; >0 = leaf with this many objects
+ uint16_t axis; // split axis (0/1/2) for interior; unused for leaf
+};
+static_assert(sizeof(BvhNode) == 32, "BvhNode must be 32 bytes for cache alignment and sidecar format");
+
+struct ModelBvh {
+ uint32_t model_id = 0;
+ std::vector nodes;
+ std::vector object_indices; // indices into object_draw_info_
+};
+
+struct BvhSet {
+ std::unordered_map models;
+ std::unordered_set bvh_model_ids;
+};
+
+struct EboReorderResult {
+ std::vector reordered_ebo;
+ std::vector reordered_draw_info;
+};
+
+// Build BVH trees for all models in the given draw info snapshot.
+// Only builds the tree structure; does not touch EBO data.
+std::shared_ptr buildBvhSet(const std::vector& draw_info);
+
+// Reorder the EBO so objects within each BVH leaf are contiguous.
+// Must be called with the CURRENT run's EBO and draw_info (not cached).
+EboReorderResult reorderEbo(const BvhSet& bvh_set,
+ const std::vector& draw_info,
+ const std::vector& original_ebo);
+
+#endif // BVHACCEL_H
diff --git a/src/ifcviewer/MainWindow.cpp b/src/ifcviewer/MainWindow.cpp
index 3b4e58fbac..b5ee3581c4 100644
--- a/src/ifcviewer/MainWindow.cpp
+++ b/src/ifcviewer/MainWindow.cpp
@@ -20,6 +20,7 @@
#include "MainWindow.h"
#include "AppSettings.h"
#include "SettingsWindow.h"
+#include "SidecarCache.h"
#include
#include
@@ -61,7 +62,14 @@ MainWindow::MainWindow(QWidget* parent)
resize(1400, 900);
}
-MainWindow::~MainWindow() {}
+MainWindow::~MainWindow() {
+ joinSidecarThread();
+}
+
+void MainWindow::joinSidecarThread() {
+ if (sidecar_read_thread_.joinable())
+ sidecar_read_thread_.join();
+}
void MainWindow::setupUi() {
// 3D Viewport as central widget
@@ -158,7 +166,7 @@ void MainWindow::addFiles(const QStringList& paths) {
}
if (loading_model_id_ == 0) {
- startNextLoad();
+ QTimer::singleShot(0, this, &MainWindow::startNextLoad);
}
}
@@ -184,16 +192,133 @@ void MainWindow::startNextLoad() {
load_queue_.pop_front();
auto& model = models_[loading_model_id_];
- connectStreamer(model.streamer);
-
- progress_bar_->setValue(0);
- progress_bar_->setVisible(true);
- status_label_->setText("Loading: " + model.display_name);
load_timer_.restart();
- element_poll_timer_.start();
- model.streamer->loadFile(
- model.file_path.toStdString(), next_object_id_, loading_model_id_);
+ status_label_->setText("Loading: " + model.display_name);
+
+ // Try sidecar on a background thread so the UI stays responsive.
+ std::string ifc_path = model.file_path.toStdString();
+ uint64_t file_size = static_cast(QFileInfo(model.file_path).size());
+ ModelId mid = loading_model_id_;
+
+ joinSidecarThread();
+ sidecar_read_thread_ = std::thread([this, ifc_path, file_size, mid]() {
+ QElapsedTimer rt; rt.start();
+ auto cached = readSidecar(ifc_path, file_size);
+ qDebug(" Sidecar read: %lld ms (%s)", rt.elapsed(), ifc_path.c_str());
+ auto result = std::make_shared>(std::move(cached));
+ QMetaObject::invokeMethod(this, [this, mid, result]() {
+ if (*result && !(*result)->draw_info.empty()) {
+ applySidecarData(mid, std::move(**result));
+ } else {
+ // No sidecar — fall back to streaming from IFC.
+ auto it = models_.find(mid);
+ if (it == models_.end()) return;
+ auto& m = it->second;
+ connectStreamer(m.streamer);
+ progress_bar_->setValue(0);
+ progress_bar_->setVisible(true);
+ status_label_->setText("Loading: " + m.display_name);
+ element_poll_timer_.start();
+ m.streamer->loadFile(
+ m.file_path.toStdString(), next_object_id_, loading_model_id_);
+ }
+ }, Qt::QueuedConnection);
+ });
+}
+
+void MainWindow::applySidecarData(ModelId mid, SidecarData data) {
+ auto it = models_.find(mid);
+ if (it == models_.end()) return;
+ auto& model = it->second;
+
+ QElapsedTimer t;
+
+ qDebug("Sidecar hit: %s (%zu objects, %zu verts, %zu indices, %.1f MB)",
+ model.file_path.toStdString().c_str(), data.draw_info.size(),
+ data.vertices.size() / 8, data.indices.size(),
+ (data.vertices.size() * 4 + data.indices.size() * 4) / (1024.0 * 1024.0));
+
+ // GL upload — fast, single buffer copy.
+ t.start();
+ viewport_->uploadBulk(mid, data.vertices, data.indices,
+ data.draw_info, std::move(data.bvh_set));
+ qDebug(" GL upload: %lld ms", t.elapsed());
+
+ // Update next_object_id_ past all objects in this model.
+ for (const auto& elem : data.elements) {
+ if (elem.object_id >= next_object_id_)
+ next_object_id_ = elem.object_id + 1;
+ }
+
+ // Suppress per-item layout recalcs while building the tree.
+ t.restart();
+ element_tree_->setUpdatesEnabled(false);
+ populateTreeFromSidecar(model, data.elements, data.string_table);
+ element_tree_->setUpdatesEnabled(true);
+ qDebug(" Tree build: %lld ms (%zu elements)", t.elapsed(), data.elements.size());
+
+ progress_bar_->setVisible(false);
+
+ qint64 ms = load_timer_.elapsed();
+ QString elapsed = (ms >= 1000)
+ ? QString::number(ms / 1000.0, 'f', 2) + " s"
+ : QString::number(ms) + " ms";
+
+ status_label_->setText(QString("%1 elements across %2 model(s) — loaded from cache in %3")
+ .arg(element_map_.size())
+ .arg(models_.size())
+ .arg(elapsed));
+
+ loading_model_id_ = 0;
+ QTimer::singleShot(0, this, &MainWindow::startNextLoad);
+}
+
+void MainWindow::populateTreeFromSidecar(ModelHandle& model,
+ const std::vector& elements,
+ const std::string& stbl) {
+ auto str = [&](uint32_t offset, uint32_t length) -> std::string {
+ if (length == 0 || offset + length > stbl.size()) return {};
+ return stbl.substr(offset, length);
+ };
+
+ for (const auto& pe : elements) {
+ ElementInfo info;
+ info.object_id = pe.object_id;
+ info.model_id = pe.model_id;
+ info.ifc_id = pe.ifc_id;
+ info.parent_id = pe.parent_id;
+ info.guid = str(pe.guid_offset, pe.guid_length);
+ info.name = str(pe.name_offset, pe.name_length);
+ info.type = str(pe.type_offset, pe.type_length);
+
+ element_map_[info.object_id] = info;
+ scoped_ifc_id_to_object_id_[scopedKey(info.model_id, info.ifc_id)] = info.object_id;
+
+ // Find parent tree item.
+ QTreeWidgetItem* parent_item = model.tree_root;
+ auto parent_obj_it = scoped_ifc_id_to_object_id_.find(
+ scopedKey(info.model_id, info.parent_id));
+ if (parent_obj_it != scoped_ifc_id_to_object_id_.end()) {
+ auto tree_it = tree_items_.find(parent_obj_it->second);
+ if (tree_it != tree_items_.end()) {
+ parent_item = tree_it->second;
+ }
+ }
+
+ QString display_name = QString::fromStdString(info.name);
+ if (display_name.isEmpty()) {
+ display_name = QString::fromStdString(info.type) + " #" + QString::number(info.ifc_id);
+ }
+
+ auto* item = new QTreeWidgetItem(parent_item);
+ item->setText(0, display_name);
+ item->setText(1, QString::fromStdString(info.type));
+ item->setText(2, QString::fromStdString(info.guid));
+ item->setData(0, Qt::UserRole, info.object_id);
+
+ tree_items_[info.object_id] = item;
+ }
}
void MainWindow::onProgressChanged(int percent) {
@@ -230,6 +355,41 @@ void MainWindow::onStreamingFinished() {
.arg(num_models)
.arg(elapsed));
+ // Build BVH and write sidecar (geometry + metadata + BVH).
+ if (loading_model_id_ != 0) {
+ auto it = models_.find(loading_model_id_);
+ if (it != models_.end()) {
+ std::string ifc_path = it->second.file_path.toStdString();
+ QFileInfo fi(it->second.file_path);
+ uint64_t file_size = static_cast(fi.size());
+
+ // Pack element info for the sidecar (only this model's elements).
+ std::vector packed;
+ std::string stbl;
+ for (const auto& [oid, info] : element_map_) {
+ if (info.model_id != loading_model_id_) continue;
+ PackedElementInfo pe;
+ pe.object_id = info.object_id;
+ pe.model_id = info.model_id;
+ pe.ifc_id = info.ifc_id;
+ pe.parent_id = info.parent_id;
+ pe.guid_offset = static_cast(stbl.size());
+ pe.guid_length = static_cast(info.guid.size());
+ stbl += info.guid;
+ pe.name_offset = static_cast(stbl.size());
+ pe.name_length = static_cast(info.name.size());
+ stbl += info.name;
+ pe.type_offset = static_cast(stbl.size());
+ pe.type_length = static_cast(info.type.size());
+ stbl += info.type;
+ packed.push_back(pe);
+ }
+
+ viewport_->buildBvhAsync(loading_model_id_, ifc_path, file_size,
+ std::move(packed), std::move(stbl));
+ }
+ }
+
// Start next model if queued.
startNextLoad();
}
diff --git a/src/ifcviewer/MainWindow.h b/src/ifcviewer/MainWindow.h
index e9bcc37cb6..f60da70b75 100644
--- a/src/ifcviewer/MainWindow.h
+++ b/src/ifcviewer/MainWindow.h
@@ -31,6 +31,7 @@
#include