ifcviewer: viewport overlay subsystem (highlight tris + HUD text)

New OverlayRenderer module owns every client-supplied overlay primitive
drawn after the main pass: tinted, depth-aware highlight triangles via
its own GL shader, and top-left HUD text via QPainter on a
QOpenGLPaintDevice.  Public surface on ViewportWindow is just two
forwarders (setHighlightTriangles, setHudText).

ViewportWindow's MeshLocalPick now exposes the instance's composed
transform so consumers can map mesh-local geometry back to world
space without re-querying.  AreaMeasurement uses both: its selection
key is now (object_id, tri) so per-instance highlighting works for
two distinct walls sharing a mesh, and on every pick it rebuilds the
world-space tri list and the HUD readout.

Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>
This commit is contained in:
Dion Moult
2026-05-07 16:43:38 +10:00
parent d565dc3ff3
commit ad62dd6d91
7 changed files with 414 additions and 21 deletions
+11 -2
View File
@@ -210,11 +210,20 @@ void MainWindow::setupUi() {
[this](int x, int y, int modifiers) {
const bool alt = (modifiers & Qt::AltModifier) != 0;
area_measurement_.onPick(*viewport_, x, y, alt);
viewport_->setHudText(QString("Area: %1 m² (%2 tris)")
.arg(area_measurement_.totalArea(), 0, 'f', 4)
.arg(area_measurement_.triangleCount()));
});
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");
area_measurement_.clear(*viewport_);
if (active) {
viewport_->setHudText("Area: 0.0000 m² (0 tris)");
status_label_->setText("Area tool: LMB add, Alt+LMB single tri, click again to remove, Esc exits");
} else {
viewport_->setHudText(QString());
status_label_->setText("Ready");
}
});
auto* tree_dock = new QDockWidget("Elements", this);
+49 -5
View File
@@ -201,10 +201,40 @@ constexpr double kCoplanarDot = 0.9999; // ~0.81° tolerance
AreaMeasurement::AreaMeasurement() = default;
void AreaMeasurement::clear() {
void AreaMeasurement::clear(ViewportWindow& vp) {
mesh_cache_.clear();
selected_.clear();
total_area_m2_ = 0.0;
vp.setHighlightTriangles({}, 0, 0, 0, 0);
}
void AreaMeasurement::rebuildHighlight(ViewportWindow& vp) {
// Push every selected triangle's three world-space vertices to the
// overlay. Mesh-local positions × per-instance composed transform.
std::vector<float> world_xyz;
world_xyz.reserve(selected_.size() * 9);
for (const auto& [key, sel] : selected_) {
const uint64_t cache_key = (uint64_t(sel.model_id) << 32)
| uint64_t(sel.mesh_id);
auto cit = mesh_cache_.find(cache_key);
if (cit == mesh_cache_.end()) continue;
const MeshCache& c = cit->second;
if (size_t(sel.tri) * 3 + 2 >= c.indices.size()) continue;
const float* M = sel.composed_transform; // column-major
for (int e = 0; e < 3; ++e) {
const uint32_t vi = c.indices[3 * sel.tri + e];
const float* p = &c.positions[3 * vi];
// World = M * (p, 1). Column-major: M[col*4 + row].
const float wx = M[0]*p[0] + M[4]*p[1] + M[8]*p[2] + M[12];
const float wy = M[1]*p[0] + M[5]*p[1] + M[9]*p[2] + M[13];
const float wz = M[2]*p[0] + M[6]*p[1] + M[10]*p[2] + M[14];
world_xyz.push_back(wx);
world_xyz.push_back(wy);
world_xyz.push_back(wz);
}
}
// Translucent cyan-ish tint — readable on both light and dark surfaces.
vp.setHighlightTriangles(world_xyz, 0.20f, 0.85f, 1.00f, 0.45f);
}
AreaMeasurement::MeshCache* AreaMeasurement::meshCache(ViewportWindow& vp,
@@ -304,19 +334,33 @@ void AreaMeasurement::onPick(ViewportWindow& vp, int x, int y, bool alt) {
// 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 uint64_t seed_key = triKey(pick.object_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);
const uint64_t k = triKey(pick.object_id, t);
if (removing) {
if (selected_.erase(k) > 0) delta -= cache->tri_areas[t];
auto it = selected_.find(k);
if (it != selected_.end()) {
delta -= cache->tri_areas[t];
selected_.erase(it);
}
} else {
if (selected_.insert(k).second) delta += cache->tri_areas[t];
SelectedTri sel;
sel.model_id = pick.model_id;
sel.mesh_id = pick.mesh_id;
sel.tri = t;
std::memcpy(sel.composed_transform, pick.composed_transform,
sizeof(sel.composed_transform));
if (selected_.emplace(k, sel).second) {
delta += cache->tri_areas[t];
}
}
}
total_area_m2_ += delta;
rebuildHighlight(vp);
qInfo("Area %s%.6f m^2 (total: %.6f m^2, %zu tris)",
delta >= 0.0 ? "+" : "", delta,
total_area_m2_, selected_.size());
+29 -14
View File
@@ -22,7 +22,6 @@
#include <cstdint>
#include <unordered_map>
#include <unordered_set>
#include <vector>
class ViewportWindow;
@@ -38,14 +37,16 @@ double volumeOfObjects(ViewportWindow& vp,
const std::vector<uint32_t>& object_ids);
// Click-to-accumulate area measurement. Each pick resolves the screen
// click to a (model, mesh, triangle) using ViewportWindow's primitives,
// click to a (instance, 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.
// Picks on different instances (even of the same mesh) are kept as
// separate patches and their areas are summed.
//
// On every pick the world-space triangles of the running set are pushed
// to ViewportWindow::setHighlightTriangles for in-viewport shading.
// 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 {
@@ -57,8 +58,9 @@ public:
// 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();
// Wipe all accumulated triangles, per-mesh adjacency caches, and the
// viewport overlay.
void clear(ViewportWindow& vp);
double totalArea() const { return total_area_m2_; }
size_t triangleCount() const { return selected_.size(); }
@@ -77,16 +79,29 @@ private:
};
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);
// Per-selected-triangle record. The composed transform is captured at
// pick time so the overlay rebuild doesn't have to re-query the
// viewport for it (and so the overlay keeps working if the picked
// instance later goes hidden).
struct SelectedTri {
uint32_t model_id;
uint32_t mesh_id;
uint32_t tri;
float composed_transform[16];
};
// Selection key: object_id (high 32) | tri index (low 32). Packing
// by object_id rather than mesh_id means two distinct instances of
// the same mesh contribute independently, as the user spec'd.
static uint64_t triKey(uint32_t object_id, uint32_t tri) {
return (uint64_t(object_id) << 32) | uint64_t(tri);
}
std::unordered_map<uint64_t, MeshCache> mesh_cache_;
std::unordered_set<uint64_t> selected_;
double total_area_m2_ = 0.0;
void rebuildHighlight(ViewportWindow& vp);
std::unordered_map<uint64_t, MeshCache> mesh_cache_;
std::unordered_map<uint64_t, SelectedTri> selected_;
double total_area_m2_ = 0.0;
};
#endif // IFCVIEWER_FULL_MEASUREMENT_H
+199
View File
@@ -0,0 +1,199 @@
/********************************************************************************
* *
* 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 <http://www.gnu.org/licenses/>. *
* *
********************************************************************************/
#include "OverlayRenderer.h"
#include <QFont>
#include <QFontMetrics>
#include <QPainter>
#include <QtGlobal>
#include <QtOpenGL/QOpenGLPaintDevice>
namespace {
GLuint compile(QOpenGLFunctions_4_5_Core* gl, GLenum type, const char* src) {
GLuint s = gl->glCreateShader(type);
gl->glShaderSource(s, 1, &src, nullptr);
gl->glCompileShader(s);
GLint ok = 0;
gl->glGetShaderiv(s, GL_COMPILE_STATUS, &ok);
if (!ok) {
char log[2048];
gl->glGetShaderInfoLog(s, sizeof(log), nullptr, log);
qWarning("OverlayRenderer shader compile error: %s", log);
}
return s;
}
GLuint link(QOpenGLFunctions_4_5_Core* gl, GLuint vs, GLuint fs) {
GLuint p = gl->glCreateProgram();
gl->glAttachShader(p, vs);
gl->glAttachShader(p, fs);
gl->glLinkProgram(p);
GLint ok = 0;
gl->glGetProgramiv(p, GL_LINK_STATUS, &ok);
if (!ok) {
char log[2048];
gl->glGetProgramInfoLog(p, sizeof(log), nullptr, log);
qWarning("OverlayRenderer program link error: %s", log);
}
gl->glDeleteShader(vs);
gl->glDeleteShader(fs);
return p;
}
const char* VERT_SRC = R"(
#version 450 core
layout(location = 0) in vec3 in_pos;
uniform mat4 u_view_proj;
void main() {
gl_Position = u_view_proj * vec4(in_pos, 1.0);
}
)";
const char* FRAG_SRC = R"(
#version 450 core
uniform vec4 u_color;
out vec4 frag_color;
void main() {
frag_color = u_color;
}
)";
} // namespace
void OverlayRenderer::initialize(QOpenGLFunctions_4_5_Core* gl) {
if (gl_) return;
gl_ = gl;
GLuint vs = compile(gl_, GL_VERTEX_SHADER, VERT_SRC);
GLuint fs = compile(gl_, GL_FRAGMENT_SHADER, FRAG_SRC);
program_ = link(gl_, vs, fs);
u_view_proj_ = gl_->glGetUniformLocation(program_, "u_view_proj");
u_color_ = gl_->glGetUniformLocation(program_, "u_color");
gl_->glCreateVertexArrays(1, &vao_);
gl_->glCreateBuffers(1, &vbo_);
gl_->glEnableVertexArrayAttrib(vao_, 0);
gl_->glVertexArrayAttribFormat(vao_, 0, 3, GL_FLOAT, GL_FALSE, 0);
gl_->glVertexArrayAttribBinding(vao_, 0, 0);
gl_->glVertexArrayVertexBuffer(vao_, 0, vbo_, 0, 3 * sizeof(float));
}
void OverlayRenderer::release() {
if (!gl_) return;
if (vbo_) gl_->glDeleteBuffers(1, &vbo_);
if (vao_) gl_->glDeleteVertexArrays(1, &vao_);
if (program_) gl_->glDeleteProgram(program_);
program_ = vao_ = vbo_ = 0;
vbo_capacity_ = 0;
vertex_count_ = 0;
gl_ = nullptr;
}
void OverlayRenderer::setHudText(const QString& text) {
hud_text_ = text;
}
void OverlayRenderer::setHighlightTriangles(const std::vector<float>& world_xyz,
float r, float g, float b, float a) {
if (!gl_) return;
color_[0] = r; color_[1] = g; color_[2] = b; color_[3] = a;
vertex_count_ = GLsizei(world_xyz.size() / 3);
if (vertex_count_ == 0) return;
const size_t bytes = world_xyz.size() * sizeof(float);
if (bytes > vbo_capacity_) {
// Grow with a little headroom so frequent appends don't realloc.
const size_t new_cap = bytes + bytes / 2;
gl_->glNamedBufferData(vbo_, GLsizeiptr(new_cap),
nullptr, GL_DYNAMIC_DRAW);
vbo_capacity_ = new_cap;
}
gl_->glNamedBufferSubData(vbo_, 0, GLsizeiptr(bytes), world_xyz.data());
}
void OverlayRenderer::render(const float view_proj[16],
int pixel_w, int pixel_h, qreal dpr) {
if (!gl_) return;
// GL pass: tinted highlight triangles.
if (program_ && vertex_count_ > 0 && color_[3] > 0.0f) {
gl_->glUseProgram(program_);
gl_->glUniformMatrix4fv(u_view_proj_, 1, GL_FALSE, view_proj);
gl_->glUniform4fv(u_color_, 1, color_);
// Save the GL state we touch and restore at the end so the rest of
// the render pass keeps seeing what it expects.
GLboolean prev_blend = gl_->glIsEnabled(GL_BLEND);
GLboolean prev_cull = gl_->glIsEnabled(GL_CULL_FACE);
GLboolean prev_depth_msk = GL_TRUE;
gl_->glGetBooleanv(GL_DEPTH_WRITEMASK, &prev_depth_msk);
GLint prev_depth_func = GL_LESS;
gl_->glGetIntegerv(GL_DEPTH_FUNC, &prev_depth_func);
GLint prev_blend_src = GL_ONE, prev_blend_dst = GL_ZERO;
gl_->glGetIntegerv(GL_BLEND_SRC_ALPHA, &prev_blend_src);
gl_->glGetIntegerv(GL_BLEND_DST_ALPHA, &prev_blend_dst);
gl_->glEnable(GL_BLEND);
gl_->glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
gl_->glDisable(GL_CULL_FACE); // both sides tinted
gl_->glDepthMask(GL_FALSE); // tint, don't occlude
gl_->glDepthFunc(GL_LEQUAL); // win the coplanar fight
gl_->glBindVertexArray(vao_);
gl_->glDrawArrays(GL_TRIANGLES, 0, vertex_count_);
gl_->glBindVertexArray(0);
if (!prev_blend) gl_->glDisable(GL_BLEND);
gl_->glBlendFunc(prev_blend_src, prev_blend_dst);
if (prev_cull) gl_->glEnable(GL_CULL_FACE);
gl_->glDepthMask(prev_depth_msk);
gl_->glDepthFunc(prev_depth_func);
}
// QPainter pass: HUD text. This rebinds programs/VAOs internally, so
// it has to come after every other GL primitive in the overlay.
if (!hud_text_.isEmpty() && pixel_w > 0 && pixel_h > 0) {
QOpenGLPaintDevice device(QSize(pixel_w, pixel_h));
device.setDevicePixelRatio(dpr);
QPainter painter(&device);
painter.setRenderHint(QPainter::Antialiasing);
painter.setRenderHint(QPainter::TextAntialiasing);
QFont font("monospace", 11);
font.setStyleHint(QFont::TypeWriter);
painter.setFont(font);
const QFontMetrics fm(font);
const int pad_x = 10, pad_y = 6, margin = 12;
const int text_w = fm.horizontalAdvance(hud_text_);
const int text_h = fm.height();
const QRect bg(margin, margin,
text_w + 2 * pad_x,
text_h + 2 * pad_y);
painter.setPen(Qt::NoPen);
painter.setBrush(QColor(0, 0, 0, 160));
painter.drawRoundedRect(bg, 4, 4);
painter.setPen(Qt::white);
painter.drawText(bg.adjusted(pad_x, pad_y, -pad_x, -pad_y),
Qt::AlignLeft | Qt::AlignVCenter,
hud_text_);
}
}
+75
View File
@@ -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 <http://www.gnu.org/licenses/>. *
* *
********************************************************************************/
#ifndef IFCVIEWER_OVERLAYRENDERER_H
#define IFCVIEWER_OVERLAYRENDERER_H
#include <QString>
#include <QtOpenGL/QOpenGLFunctions_4_5_Core>
#include <vector>
// Neutral overlay-primitive renderer attached to ViewportWindow. Today it
// draws a single tinted, translucent triangle list in world space — used by
// the area-measurement tool to shade selected coplanar patches. More
// primitives (lines, points, world-anchored labels) will land here as
// future tools require them.
//
// Lifetime: owned by ViewportWindow, initialised in the same context. All
// public methods assume the caller has already made the GL context current.
class OverlayRenderer {
public:
void initialize(QOpenGLFunctions_4_5_Core* gl);
void release();
// Replace the highlight-triangle list. `world_xyz` is 3 floats per
// vertex, 3 verts per triangle, in world space (post-composed-transform).
// Empty disables the overlay. Color is RGBA in [0, 1].
void setHighlightTriangles(const std::vector<float>& world_xyz,
float r, float g, float b, float a);
// Top-left HUD text drawn via QPainter on the GL surface as part of
// render(). Empty hides the HUD.
void setHudText(const QString& text);
// Render every overlay primitive in order: GL highlight triangles
// (using `view_proj`, column-major float[16]), then HUD text via
// QPainter on a QOpenGLPaintDevice sized to (pixel_w × pixel_h)
// with the supplied device pixel ratio. Caller is responsible for
// ensuring glViewport covers the full surface — the QPainter pass
// after this call leaves GL state in an undefined shape, so treat
// this as the last GL operation per frame before swapBuffers (or
// sandwich it before any pass that re-binds its own programs).
void render(const float view_proj[16],
int pixel_w, int pixel_h, qreal device_pixel_ratio);
private:
QOpenGLFunctions_4_5_Core* gl_ = nullptr;
GLuint program_ = 0;
GLuint vao_ = 0;
GLuint vbo_ = 0;
size_t vbo_capacity_ = 0; // bytes
GLsizei vertex_count_ = 0;
float color_[4] = {0, 0, 0, 0};
GLint u_view_proj_ = -1;
GLint u_color_ = -1;
QString hud_text_;
};
#endif // IFCVIEWER_OVERLAYRENDERER_H
+27
View File
@@ -670,6 +670,7 @@ ViewportWindow::~ViewportWindow() {
if (hiz_resolve_depth_tex_) gl_->glDeleteTextures(1, &hiz_resolve_depth_tex_);
if (hiz_downsample_program_) gl_->glDeleteProgram(hiz_downsample_program_);
if (hiz_downsample_vao_) gl_->glDeleteVertexArrays(1, &hiz_downsample_vao_);
overlay_renderer_.release();
}
context_->doneCurrent();
}
@@ -690,6 +691,7 @@ void ViewportWindow::initGL() {
buildAxisGizmo();
buildPivotIndicator();
buildSectionPlaneGizmo();
overlay_renderer_.initialize(gl_);
gl_->glEnable(GL_DEPTH_TEST);
gl_->glEnable(GL_MULTISAMPLE);
@@ -2726,6 +2728,16 @@ void ViewportWindow::render() {
renderEdgePass();
renderPivotIndicator();
renderSectionPlanes();
// Overlay handles highlight tris + HUD text; renderAxisGizmo() must
// come after because it shrinks glViewport to the corner badge and
// does not restore.
{
const qreal dpr = devicePixelRatio();
overlay_renderer_.render(vp.constData(),
int(width() * dpr),
int(height() * dpr),
dpr);
}
renderAxisGizmo();
// Build HiZ from this frame's resolved depth for next frame's cull.
@@ -3848,6 +3860,8 @@ bool ViewportWindow::pickMeshLocalAt(int x, int y, MeshLocalPick& out) {
out.world_normal[0] = world_normal.x();
out.world_normal[1] = world_normal.y();
out.world_normal[2] = world_normal.z();
std::memcpy(out.composed_transform, inst.transform,
sizeof(out.composed_transform));
return true;
}
}
@@ -3858,3 +3872,16 @@ void ViewportWindow::toggleAreaTool() {
area_tool_active_ = !area_tool_active_;
emit areaToolToggled(area_tool_active_);
}
void ViewportWindow::setHighlightTriangles(const std::vector<float>& world_xyz,
float r, float g, float b, float a) {
if (!gl_initialized_) return;
context_->makeCurrent(this);
overlay_renderer_.setHighlightTriangles(world_xyz, r, g, b, a);
requestUpdate();
}
void ViewportWindow::setHudText(const QString& text) {
overlay_renderer_.setHudText(text);
requestUpdate();
}
+24
View File
@@ -45,6 +45,7 @@ QT_END_NAMESPACE
#include "BvhAccel.h"
#include "InstancedGeometry.h"
#include "OverlayRenderer.h"
#include "SidecarCache.h"
// Matches GL_DRAW_INDIRECT_BUFFER layout for glMultiDrawElementsIndirect.
@@ -221,6 +222,11 @@ public:
float mesh_local[3] = {0, 0, 0};
float world_pos[3] = {0, 0, 0};
float world_normal[3]= {0, 0, 0};
// The instance's composed (FederatedFalseOrigin · ModelTransformation
// · CoordinateOperation · placement_transformation) matrix in
// column-major form. Mesh-local positions × this = world. Caching
// by callers becomes stale if any federation matrix is later edited.
float composed_transform[16] = {1,0,0,0, 0,1,0,0, 0,0,1,0, 0,0,0,1};
};
bool pickMeshLocalAt(int x, int y, MeshLocalPick& out);
@@ -231,6 +237,19 @@ public:
void toggleAreaTool();
bool areaToolActive() const { return area_tool_active_; }
// Replace the overlay highlight-triangle list rendered after the main
// pass. `world_xyz` is 3 floats per vertex, 3 verts per triangle, in
// world space. Empty disables the overlay. Triggers a viewport
// update so the change becomes visible immediately.
void setHighlightTriangles(const std::vector<float>& world_xyz,
float r, float g, float b, float a);
// Top-left HUD text drawn via QPainter on top of the GL surface at
// the end of each frame. Empty hides the HUD. Used today by the
// area-measurement tool for the running total; later tools can pile
// additional readouts in by extending this with a multi-line API.
void setHudText(const QString& text);
// Federation pipeline: composed instance transform =
// FederatedFalseOrigin · ModelTransformation · CoordinateOperation
// · placement_transformation
@@ -635,6 +654,11 @@ private:
// Area-measurement tool: see toggleAreaTool / surfacePickedInTool.
bool area_tool_active_ = false;
// Renders any client-supplied overlay primitives (highlight triangles
// today; lines/points/labels later) in their own pass after the main
// geometry, with depth-test on / depth-write off.
OverlayRenderer overlay_renderer_;
// Active section planes. Uploaded as uniform array each frame to the
// main + pick programs; capped at MaxSectionPlanes.
std::vector<SectionPlane> section_planes_;