diff --git a/src/ifcviewer-full/MainWindow.cpp b/src/ifcviewer-full/MainWindow.cpp index 57e60282cc..2510ad799c 100644 --- a/src/ifcviewer-full/MainWindow.cpp +++ b/src/ifcviewer-full/MainWindow.cpp @@ -206,6 +206,16 @@ void MainWindow::setupUi() { setCentralWidget(viewport_container_); connect(viewport_, &ViewportWindow::objectPicked, this, &MainWindow::onObjectPicked); + connect(viewport_, &ViewportWindow::surfacePickedInTool, this, + [this](int x, int y, int modifiers) { + const bool alt = (modifiers & Qt::AltModifier) != 0; + area_measurement_.onPick(*viewport_, x, y, alt); + }); + connect(viewport_, &ViewportWindow::areaToolToggled, this, + [this](bool active) { + area_measurement_.clear(); + qInfo("Area tool %s", active ? "on (LMB to add patch, Alt+LMB single tri, click again to remove, Esc exits)" : "off"); + }); auto* tree_dock = new QDockWidget("Elements", this); tree_dock->setAllowedAreas(Qt::LeftDockWidgetArea | Qt::RightDockWidgetArea); @@ -283,6 +293,9 @@ void MainWindow::setupMenus() { view_menu->addAction("Print Selected &Coords", this, [this]() { viewport_->printSelectedObjectCoords(); }, QKeySequence("Ctrl+Shift+P")); + view_menu->addAction("&Measure Area", this, [this]() { + viewport_->toggleAreaTool(); + }, QKeySequence("Ctrl+Shift+A")); view_menu->addSeparator(); view_menu->addAction("Set &Home View", this, &MainWindow::onSetHomeView); view_menu->addAction("&Go to Home View", this, &MainWindow::onGoHomeView); diff --git a/src/ifcviewer-full/MainWindow.h b/src/ifcviewer-full/MainWindow.h index ff395fe51f..fa1bc35f91 100644 --- a/src/ifcviewer-full/MainWindow.h +++ b/src/ifcviewer-full/MainWindow.h @@ -32,6 +32,7 @@ #include #include +#include "Measurement.h" #include "ViewportWindow.h" #include "SceneLoader.h" @@ -198,6 +199,8 @@ private: QString pending_camera_; int pending_benchmark_ = 0; + + AreaMeasurement area_measurement_; }; #endif // MAINWINDOW_H diff --git a/src/ifcviewer-full/Measurement.cpp b/src/ifcviewer-full/Measurement.cpp index 1283fcd9d4..0fff48cda1 100644 --- a/src/ifcviewer-full/Measurement.cpp +++ b/src/ifcviewer-full/Measurement.cpp @@ -21,9 +21,14 @@ #include "ViewportWindow.h" +#include + +#include #include #include +#include #include +#include #include namespace { @@ -87,3 +92,232 @@ double volumeOfObjects(ViewportWindow& vp, } return total; } + +namespace { + +// edge_key: undirected edge between two mesh-local vertex indices. +uint64_t edgeKey(uint32_t a, uint32_t b) { + if (a > b) std::swap(a, b); + return (uint64_t(a) << 32) | uint64_t(b); +} + +// Triangle area = 0.5 * |(b - a) × (c - a)|. Also returns the unit normal +// (zeroed for degenerate tris). +double triAreaAndNormal(const float* a, const float* b, const float* c, + float n_out[3]) { + const double bax = double(b[0]) - a[0]; + const double bay = double(b[1]) - a[1]; + const double baz = double(b[2]) - a[2]; + const double cax = double(c[0]) - a[0]; + const double cay = double(c[1]) - a[1]; + const double caz = double(c[2]) - a[2]; + const double nx = bay * caz - baz * cay; + const double ny = baz * cax - bax * caz; + const double nz = bax * cay - bay * cax; + const double len = std::sqrt(nx * nx + ny * ny + nz * nz); + if (len > 0.0) { + n_out[0] = float(nx / len); + n_out[1] = float(ny / len); + n_out[2] = float(nz / len); + } else { + n_out[0] = n_out[1] = n_out[2] = 0.0f; + } + return 0.5 * len; +} + +// Squared distance from `p` to triangle (a, b, c) — clipped to the +// triangle's interior or boundary, whichever is closest. Standard +// implementation (Ericson, "Real-Time Collision Detection"). +double pointTriangleDistSq(const float p[3], + const float a[3], const float b[3], const float c[3]) { + auto sub = [](const float u[3], const float v[3], double r[3]) { + r[0] = double(u[0]) - v[0]; + r[1] = double(u[1]) - v[1]; + r[2] = double(u[2]) - v[2]; + }; + auto dot = [](const double u[3], const double v[3]) { + return u[0] * v[0] + u[1] * v[1] + u[2] * v[2]; + }; + double ab[3], ac[3], ap[3]; + sub(b, a, ab); + sub(c, a, ac); + sub(p, a, ap); + const double d1 = dot(ab, ap); + const double d2 = dot(ac, ap); + if (d1 <= 0.0 && d2 <= 0.0) { + return ap[0]*ap[0] + ap[1]*ap[1] + ap[2]*ap[2]; + } + double bp[3]; + sub(p, b, bp); + const double d3 = dot(ab, bp); + const double d4 = dot(ac, bp); + if (d3 >= 0.0 && d4 <= d3) { + return bp[0]*bp[0] + bp[1]*bp[1] + bp[2]*bp[2]; + } + const double vc = d1 * d4 - d3 * d2; + if (vc <= 0.0 && d1 >= 0.0 && d3 <= 0.0) { + const double v = d1 / (d1 - d3); + const double qx = ap[0] - v * ab[0]; + const double qy = ap[1] - v * ab[1]; + const double qz = ap[2] - v * ab[2]; + return qx*qx + qy*qy + qz*qz; + } + double cp[3]; + sub(p, c, cp); + const double d5 = dot(ab, cp); + const double d6 = dot(ac, cp); + if (d6 >= 0.0 && d5 <= d6) { + return cp[0]*cp[0] + cp[1]*cp[1] + cp[2]*cp[2]; + } + const double vb = d5 * d2 - d1 * d6; + if (vb <= 0.0 && d2 >= 0.0 && d6 <= 0.0) { + const double w = d2 / (d2 - d6); + const double qx = ap[0] - w * ac[0]; + const double qy = ap[1] - w * ac[1]; + const double qz = ap[2] - w * ac[2]; + return qx*qx + qy*qy + qz*qz; + } + const double va = d3 * d6 - d5 * d4; + if (va <= 0.0 && (d4 - d3) >= 0.0 && (d5 - d6) >= 0.0) { + const double w = (d4 - d3) / ((d4 - d3) + (d5 - d6)); + const double qx = double(b[0]) + w * (double(c[0]) - b[0]) - p[0]; + const double qy = double(b[1]) + w * (double(c[1]) - b[1]) - p[1]; + const double qz = double(b[2]) + w * (double(c[2]) - b[2]) - p[2]; + return qx*qx + qy*qy + qz*qz; + } + // Inside the triangle — return perpendicular distance to its plane. + const double denom = 1.0 / (va + vb + vc); + const double v = vb * denom; + const double w = vc * denom; + const double qx = double(a[0]) + v * ab[0] + w * ac[0] - p[0]; + const double qy = double(a[1]) + v * ab[1] + w * ac[1] - p[1]; + const double qz = double(a[2]) + v * ab[2] + w * ac[2] - p[2]; + return qx*qx + qy*qy + qz*qz; +} + +constexpr double kCoplanarDot = 0.9999; // ~0.81° tolerance + +} // namespace + +AreaMeasurement::AreaMeasurement() = default; + +void AreaMeasurement::clear() { + mesh_cache_.clear(); + selected_.clear(); + total_area_m2_ = 0.0; +} + +AreaMeasurement::MeshCache* AreaMeasurement::meshCache(ViewportWindow& vp, + uint32_t model_id, + uint32_t mesh_id) { + const uint64_t key = (uint64_t(model_id) << 32) | uint64_t(mesh_id); + auto it = mesh_cache_.find(key); + if (it != mesh_cache_.end()) return &it->second; + + ViewportWindow::MeshTriangles tris; + if (!vp.readbackMeshTriangles(model_id, mesh_id, tris)) return nullptr; + + MeshCache c; + c.positions = std::move(tris.positions); + c.indices = std::move(tris.indices); + const size_t n_tris = c.indices.size() / 3; + c.tri_normals.resize(n_tris * 3); + c.tri_areas.resize(n_tris); + c.edges.reserve(n_tris * 3); + for (size_t t = 0; t < n_tris; ++t) { + const uint32_t ia = c.indices[3 * t + 0]; + const uint32_t ib = c.indices[3 * t + 1]; + const uint32_t ic = c.indices[3 * t + 2]; + const float* a = &c.positions[3 * ia]; + const float* b = &c.positions[3 * ib]; + const float* cc = &c.positions[3 * ic]; + float n[3]; + c.tri_areas[t] = triAreaAndNormal(a, b, cc, n); + c.tri_normals[3 * t + 0] = n[0]; + c.tri_normals[3 * t + 1] = n[1]; + c.tri_normals[3 * t + 2] = n[2]; + c.edges[edgeKey(ia, ib)].push_back(uint32_t(t)); + c.edges[edgeKey(ib, ic)].push_back(uint32_t(t)); + c.edges[edgeKey(ic, ia)].push_back(uint32_t(t)); + } + return &mesh_cache_.emplace(key, std::move(c)).first->second; +} + +void AreaMeasurement::onPick(ViewportWindow& vp, int x, int y, bool alt) { + ViewportWindow::MeshLocalPick pick; + if (!vp.pickMeshLocalAt(x, y, pick)) return; + + MeshCache* cache = meshCache(vp, pick.model_id, pick.mesh_id); + if (!cache) return; + const size_t n_tris = cache->indices.size() / 3; + if (n_tris == 0) return; + + // Find the seed triangle: the one whose interior (or boundary) is + // closest to the pick's mesh-local point. + uint32_t seed = 0; + double best = std::numeric_limits::infinity(); + for (size_t t = 0; t < n_tris; ++t) { + const uint32_t ia = cache->indices[3 * t + 0]; + const uint32_t ib = cache->indices[3 * t + 1]; + const uint32_t ic = cache->indices[3 * t + 2]; + const double d = pointTriangleDistSq(pick.mesh_local, + &cache->positions[3 * ia], + &cache->positions[3 * ib], + &cache->positions[3 * ic]); + if (d < best) { + best = d; + seed = uint32_t(t); + } + } + + // Expand to coplanar patch (BFS over shared edges). Alt skips it. + std::vector patch; + if (alt) { + patch.push_back(seed); + } else { + const float* sn = &cache->tri_normals[3 * seed]; + std::unordered_set visited; + visited.insert(seed); + std::queue frontier; + frontier.push(seed); + while (!frontier.empty()) { + const uint32_t t = frontier.front(); frontier.pop(); + patch.push_back(t); + for (int e = 0; e < 3; ++e) { + const uint32_t ia = cache->indices[3 * t + e]; + const uint32_t ib = cache->indices[3 * t + (e + 1) % 3]; + auto it = cache->edges.find(edgeKey(ia, ib)); + if (it == cache->edges.end()) continue; + for (uint32_t nt : it->second) { + if (nt == t || visited.count(nt)) continue; + const float* nn = &cache->tri_normals[3 * nt]; + const double dot = double(sn[0]) * nn[0] + + double(sn[1]) * nn[1] + + double(sn[2]) * nn[2]; + if (dot < kCoplanarDot) continue; + visited.insert(nt); + frontier.push(nt); + } + } + } + } + + // Toggle: if the seed was already in the set, remove the patch; + // otherwise add it. + const uint64_t seed_key = triKey(pick.model_id, pick.mesh_id, seed); + const bool removing = selected_.count(seed_key) > 0; + double delta = 0.0; + for (uint32_t t : patch) { + const uint64_t k = triKey(pick.model_id, pick.mesh_id, t); + if (removing) { + if (selected_.erase(k) > 0) delta -= cache->tri_areas[t]; + } else { + if (selected_.insert(k).second) delta += cache->tri_areas[t]; + } + } + total_area_m2_ += delta; + + qInfo("Area %s%.6f m^2 (total: %.6f m^2, %zu tris)", + delta >= 0.0 ? "+" : "", delta, + total_area_m2_, selected_.size()); +} diff --git a/src/ifcviewer-full/Measurement.h b/src/ifcviewer-full/Measurement.h index 847fcd7d69..e88f650bd6 100644 --- a/src/ifcviewer-full/Measurement.h +++ b/src/ifcviewer-full/Measurement.h @@ -21,6 +21,8 @@ #define IFCVIEWER_FULL_MEASUREMENT_H #include +#include +#include #include class ViewportWindow; @@ -35,4 +37,56 @@ class ViewportWindow; double volumeOfObjects(ViewportWindow& vp, const std::vector& object_ids); +// Click-to-accumulate area measurement. Each pick resolves the screen +// click to a (model, mesh, triangle) using ViewportWindow's primitives, +// expands it into the connected coplanar patch (BFS over shared edges, +// dot(normal, seed_normal) > 0.9999), then either adds or removes that +// patch from the running set depending on whether the seed triangle was +// already in. Alt-click skips the BFS expansion (single-triangle). +// Picks across different meshes are kept as separate patches and their +// areas are summed. +// +// State is cleared on construction, on clear(), and is expected to be +// reset by the host (e.g. when the viewport's area tool toggles off). +class AreaMeasurement { +public: + AreaMeasurement(); + + // Main entry point: handle one click in area-tool mode. alt = true + // suppresses BFS expansion. Logs the per-click delta and running total + // via qInfo. Misses are silent. + void onPick(ViewportWindow& vp, int x, int y, bool alt); + + // Wipe all accumulated triangles and per-mesh adjacency caches. + void clear(); + + double totalArea() const { return total_area_m2_; } + size_t triangleCount() const { return selected_.size(); } + +private: + // Cached per-mesh data: triangles + edge→triangles adjacency. Keyed + // by (model_id << 32) | mesh_id. Filled lazily on first pick of that + // mesh, dropped on clear(). + struct MeshCache { + std::vector positions; // 3 * N_verts + std::vector indices; // 3 * N_tris + std::vector tri_normals; // 3 * N_tris (unit, mesh-local) + std::vector tri_areas; // N_tris + // edge_key (min<<32 | max) → list of triangle indices touching it. + std::unordered_map> edges; + }; + MeshCache* meshCache(ViewportWindow& vp, uint32_t model_id, uint32_t mesh_id); + + // Selection key: (uint64) packing model_id (high 24), mesh_id (mid 24), + // triangle index (low 16). 16 bits is enough — meshes with > 65k tris + // are rare and the streamer chunks them anyway. + static uint64_t triKey(uint32_t model_id, uint32_t mesh_id, uint32_t tri) { + return (uint64_t(model_id) << 40) | (uint64_t(mesh_id) << 16) | uint64_t(tri); + } + + std::unordered_map mesh_cache_; + std::unordered_set selected_; + double total_area_m2_ = 0.0; +}; + #endif // IFCVIEWER_FULL_MEASUREMENT_H diff --git a/src/ifcviewer/ViewportWindow.cpp b/src/ifcviewer/ViewportWindow.cpp index cd64ad2510..907f4c6a02 100644 --- a/src/ifcviewer/ViewportWindow.cpp +++ b/src/ifcviewer/ViewportWindow.cpp @@ -1688,6 +1688,13 @@ void ViewportWindow::keyPressEvent(QKeyEvent* event) { return; } } + // Esc also exits the area tool. + if (area_tool_active_ + && key == Qt::Key_Escape + && !event->isAutoRepeat()) { + toggleAreaTool(); + return; + } QWindow::keyPressEvent(event); } @@ -3473,10 +3480,15 @@ void ViewportWindow::handleMouseRelease(QMouseEvent* e) { if (active_button_ == Qt::LeftButton && !section_tool_active_ && (e->pos() - last_mouse_pos_).manhattanLength() < 5) { - uint32_t id = pickObjectAt(e->pos().x(), e->pos().y()); - selected_object_id_ = id; - emit objectPicked(id); - requestUpdate(); // selection highlight changed + if (area_tool_active_) { + emit surfacePickedInTool(e->pos().x(), e->pos().y(), + int(e->modifiers())); + } else { + uint32_t id = pickObjectAt(e->pos().x(), e->pos().y()); + selected_object_id_ = id; + emit objectPicked(id); + requestUpdate(); // selection highlight changed + } } const bool was_navigating = (active_button_ == Qt::MiddleButton); active_button_ = Qt::NoButton; @@ -3809,3 +3821,40 @@ bool ViewportWindow::findInstance(uint32_t object_id, InstanceLookup& out) const } return false; } + +bool ViewportWindow::pickMeshLocalAt(int x, int y, MeshLocalPick& out) { + uint32_t obj_id = 0; + QVector3D world_pos, world_normal; + if (!pickSurfaceAt(x, y, obj_id, world_pos, world_normal)) return false; + + for (const auto& kv : models_gpu_) { + const ModelGpuData& m = kv.second; + for (const InstanceCpu& inst : m.instances) { + if (inst.object_id != obj_id) continue; + using Mat4f = Eigen::Matrix; + const Eigen::Matrix4f T = Eigen::Map(inst.transform); + const Eigen::Matrix4f Ti = T.inverse(); + const Eigen::Vector4f wp(world_pos.x(), world_pos.y(), world_pos.z(), 1.0f); + const Eigen::Vector4f mp = Ti * wp; + out.object_id = obj_id; + out.model_id = inst.model_id; + out.mesh_id = inst.mesh_id; + out.mesh_local[0] = mp.x(); + out.mesh_local[1] = mp.y(); + out.mesh_local[2] = mp.z(); + out.world_pos[0] = world_pos.x(); + out.world_pos[1] = world_pos.y(); + out.world_pos[2] = world_pos.z(); + out.world_normal[0] = world_normal.x(); + out.world_normal[1] = world_normal.y(); + out.world_normal[2] = world_normal.z(); + return true; + } + } + return false; +} + +void ViewportWindow::toggleAreaTool() { + area_tool_active_ = !area_tool_active_; + emit areaToolToggled(area_tool_active_); +} diff --git a/src/ifcviewer/ViewportWindow.h b/src/ifcviewer/ViewportWindow.h index 09f89a03b8..c436dda57c 100644 --- a/src/ifcviewer/ViewportWindow.h +++ b/src/ifcviewer/ViewportWindow.h @@ -208,6 +208,29 @@ public: }; bool findInstance(uint32_t object_id, InstanceLookup& out) const; + // Pick + resolve to mesh-local space. Runs pickSurfaceAt to get the + // world-space hit, then inverts the instance's composed transform + // (FederatedFalseOrigin · ModelTransformation · CoordinateOperation + // · placement_transformation) to express the hit in the mesh's own + // coordinates — what readbackMeshTriangles returns. Returns false if + // the click missed geometry or its object_id has no live instance. + struct MeshLocalPick { + uint32_t object_id = 0; + uint32_t model_id = 0; + uint32_t mesh_id = 0; + float mesh_local[3] = {0, 0, 0}; + float world_pos[3] = {0, 0, 0}; + float world_normal[3]= {0, 0, 0}; + }; + bool pickMeshLocalAt(int x, int y, MeshLocalPick& out); + + // Area tool: while active, LMB clicks emit surfacePickedInTool with + // the click coordinates instead of swapping object selection — the + // app interprets them (typically by calling pickMeshLocalAt and + // accumulating triangle area). Esc exits. + void toggleAreaTool(); + bool areaToolActive() const { return area_tool_active_; } + // Federation pipeline: composed instance transform = // FederatedFalseOrigin · ModelTransformation · CoordinateOperation // · placement_transformation @@ -302,6 +325,14 @@ signals: void objectPicked(uint32_t object_id); void initialized(); void frameStatsUpdated(const ViewportWindow::FrameStats& stats); + // Emitted instead of objectPicked when the area tool is active. The + // app is expected to call pickMeshLocalAt(x, y, ...) and accumulate. + // modifiers carries the Qt::KeyboardModifiers held at click time so + // the app can branch on Alt etc. + void surfacePickedInTool(int x, int y, int modifiers); + // Emitted whenever toggleAreaTool flips the mode. The app uses this + // to reset accumulator state on entry/exit. + void areaToolToggled(bool active); protected: void exposeEvent(QExposeEvent* event) override; @@ -601,6 +632,9 @@ private: // Selection uint32_t selected_object_id_ = 0; + // Area-measurement tool: see toggleAreaTool / surfacePickedInTool. + bool area_tool_active_ = false; + // Active section planes. Uploaded as uniform array each frame to the // main + pick programs; capped at MaxSectionPlanes. std::vector section_planes_;