Files
plotter/adapters/qt6/qt_plot_widget.hpp
T
Martino Ferrari 3c0e7763ab fix(render): one fence per frame for the vertex ring; two qt6 adapter fixes
The persistent-mapped instance ring had three slots and recorded a fence per
upload, so a frame recycled a slot whose fence was recorded a few draws earlier
*in that same frame*: from the fourth of the demos' nine uploads on, each one
waited on the frame's own work. It is free on a driver that retires draws
promptly (the GLFW host, 1.07 ms/frame) and ~4 ms of the Qt widget's 7.11 ms
under llvmpipe, and it grows with the trace and cursor counts this library
exists for.

* The ring grows to cover a frame's upload count, the frame's write cursor is
  the ring index (so a frame writes 0, 1, 2, ... and never a slot twice), one
  fence is recorded after the frame's last draw, and the only wait is at the
  start of the next frame. A wait that times out, or a slot written with no
  fence ever recorded behind it, drops the store to the orphan path -- the
  treatment a refused fence already had -- so nothing is ever written into
  storage the GPU may still be reading.
* New test-only counters (PLOT_RING_STATS, the PLOT_PYRAMID_COUNT_* pattern:
  free functions, no member, so no consumer's layout changes) pin a frame's
  upload and wait counts. The new tests assert the frame's slot offsets are
  distinct, that the ring grew past its floor to cover the frame, and that a
  frame waits at most once per store -- read from the counters and from
  glClientWaitSync itself.
* qt6: print the unresolved entry-point names before the load-failure branch,
  which used to return first and leave the one failure this widget can have
  reporting nothing but a generic message.
* qt6: the cached pointer anchor is now in logical pixels and a move's delta is
  the logical difference scaled by the DPR in effect, so a scale change between
  two move events (the window dragged onto another monitor mid-drag) is no
  longer a cross-scale jump applied as a pan. The anchor moved into a
  toolkit-free unit (adapters/qt6/qt_pointer.hpp) with its own test.

GLFW demo headless: 1.07 -> 0.73 ms/frame. Qt widget under xvfb/llvmpipe:
7.1 -> 3.8 ms at dpr 1.0, 6.7 -> 3.6 ms at 1.25, with both upload paths still
rendering and the demo's scripted pan/box-zoom checks passing at both scales.
2026-09-28 01:38:09 +02:00

217 lines
10 KiB
C++

#pragma once
// The plot headers come first, and must. Qt's <QOpenGLWidget> reaches
// <QtGui/qopengl.h>, which on a desktop platform includes the system <GL/gl.h>;
// that header defines GL_TRUE, GL_COLOR_BUFFER_BIT, GL_TEXTURE_2D and the rest as
// preprocessor macros, and those are exactly the names plot/gl/api.hpp declares as
// enumerators -- a macro rewrite turns each definition into nonsense. Parsing
// api.hpp before the macros exist is what lets the two coexist (the GLFW adapter
// sidesteps the same clash with GLFW_INCLUDE_NONE, which Qt offers no equivalent
// of). A translation unit that uses this widget must keep the same order for
// anything it includes itself, and must not name a `plot::gl::GL_*` enumerator
// after a Qt header that reaches GL has been included: the macro rewrites that
// token wherever it appears, namespace and all.
#include <plot/core/rect.hpp>
#include <plot/core/status.hpp>
#include <plot/core/types.hpp>
#include <plot/input/controller.hpp>
#include <plot/math/vec2.hpp>
#include <plot/plot/plot.hpp>
#include <plot/render/renderer.hpp>
#include <qt6/qt_pointer.hpp>
#include <QOpenGLFunctions>
#include <QOpenGLWidget>
#include <functional>
#include <optional>
#include <utility>
class QKeyEvent;
class QMouseEvent;
class QPointF;
class QWheelEvent;
namespace plot::qt {
/// Embeds a `Plot` in a Qt widget: a `QOpenGLWidget` whose framebuffer the plot
/// is rendered into, with Qt's own input events translated into `plot::input`
/// ones.
///
/// `QOpenGLWidget` renders into an FBO of its own, which it binds before calling
/// `paintGL()` -- exactly the "currently bound framebuffer" `Renderer` documents
/// it draws into. The widget therefore never creates a target of its own, and the
/// renderer's scissor-cleared viewport is the widget's whole rectangle. Nothing is
/// rendered to a texture or through a second pass: the plot is what Qt composes,
/// and the widget's other content (Qt draws none; a `QOpenGLWidget` is opaque)
/// would be drawn around it.
///
/// ## The surface format is a precondition, not a setting
///
/// This widget cannot ask for a context version: Qt hands a widget the
/// *application default* `QSurfaceFormat` at the moment its context is created,
/// and a context cannot be renegotiated afterwards. An embedding application must
/// therefore have done this before the widget exists:
///
/// QSurfaceFormat fmt;
/// fmt.setVersion(3, 3);
/// fmt.setProfile(QSurfaceFormat::CoreProfile);
/// fmt.setSwapBehavior(QSurfaceFormat::DoubleBuffer);
/// fmt.setDepthBufferSize(0);
/// fmt.setStencilBufferSize(0);
/// QSurfaceFormat::setDefaultFormat(fmt);
/// QCoreApplication::setAttribute(Qt::AA_UseDesktopOpenGL); // before QApplication
///
/// The last line matters as much as the rest: an ES or ANGLE backend has no 3.3
/// core profile to give, and this library's loader resolves desktop entry points.
/// `initializeGL()` reports the failure through `init_status()` rather than
/// asserting, but it cannot repair a format that was already decided.
///
/// ## The coordinate convention: device pixels, both sides
///
/// Two pixel spaces meet here, exactly as they do in the GLFW and ImGui adapters.
/// Qt reports widget geometry and mouse positions in **logical** pixels
/// (`width()`, `QMouseEvent::position()`), while the widget's framebuffer -- what
/// `Renderer::begin_frame()` takes and what every `Rect` in this library speaks --
/// is in **device** pixels, `devicePixelRatioF()` times as large on a scaled
/// display.
///
/// This widget converts everything into device pixels and keeps it there:
///
/// * the viewport handed to the plot is `round(width() * dpr)` x
/// `round(height() * dpr)` (rounded, not truncated, so the last column of the
/// FBO is inside the plot), and
/// * every pointer and wheel position is multiplied by the same
/// `devicePixelRatioF()` before it reaches the controller.
///
/// `device_viewport()` and `to_device()` are the only two places that mapping
/// exists, so the viewport and the input cannot disagree -- and they must not: a
/// mismatch renders correctly but pans by the wrong amount, which is invisible on
/// an unscaled display and wrong on every other one.
///
/// The *anchor* a move's delta is measured from is the one thing kept in logical
/// pixels: `devicePixelRatioF()` can change between two move events, and the delta
/// is then a logical difference scaled by the ratio in effect now, never the
/// difference of two device positions taken at different ratios (see
/// `PointerAnchor`). A drag that crosses onto a display with another scale factor
/// therefore pans by the distance the pointer moved, not by a cross-scale jump.
///
/// ## Input
///
/// Qt reports levels and edges directly (`QMouseEvent` press/release are edges,
/// `buttons()` is the state after the event), so the translation is a
/// reinterpretation rather than the edge synthesis the ImGui adapter needs.
/// Wheel input is the one unit conversion: Qt's `angleDelta()` is in eighths of a
/// degree, 120 to a notch, while `Controller::on_wheel()` takes notches, positive
/// = zoom in -- which is Qt's positive `angleDelta().y()` too. A wheel event with
/// no vertical component is refused before it reaches the controller, because a
/// zero-notch zoom changes no range but still runs the range setters, which clear
/// auto scale: a horizontal scroll must not silently stop a live axis following.
///
/// ## Threading
///
/// Qt widgets live on the GUI thread, and so does everything here: `initializeGL`,
/// `paintGL` and the event handlers all run there, which is the thread that owns
/// the context. A host that feeds the plot from a producer thread acquires its
/// data on this thread (see the frame callback).
class PlotWidget : public QOpenGLWidget, protected QOpenGLFunctions {
Q_OBJECT
public:
/// One frame of host code, run by `paintGL()` after the viewport is set and
/// before the frame is staged. It is where data is refreshed -- acquiring a
/// `data::StreamSeries`, re-fitting a live axis, moving cursors -- and `dt` is
/// the wall time since the previous call, in seconds. Optional; a widget with
/// no callback just re-draws the plot as it stands.
using FrameFn = std::function<void(Plot&, f64)>;
/// Renders and drives `plot`, which must outlive this widget.
explicit PlotWidget(Plot& plot, QWidget* parent = nullptr);
~PlotWidget() override;
PlotWidget(const PlotWidget&) = delete;
PlotWidget& operator=(const PlotWidget&) = delete;
void set_frame_callback(FrameFn frame) { frame_ = std::move(frame); }
/// The plot this widget renders. Valid for the widget's whole life.
Plot& plot() noexcept { return *plot_; }
const Plot& plot() const noexcept { return *plot_; }
/// The controller the widget feeds, bound to `plot()`.
input::Controller& controller() noexcept { return controller_; }
const input::Controller& controller() const noexcept { return controller_; }
/// The renderer, or null until a successful `initializeGL()`. Valid from the
/// corresponding `paintGL()` onwards, and after the widget's context exists.
Renderer* renderer() noexcept { return renderer_ ? &*renderer_ : nullptr; }
const Renderer* renderer() const noexcept { return renderer_ ? &*renderer_ : nullptr; }
/// What `initializeGL()` made of the context: `Ok`, or the failure that left
/// the widget drawing nothing. A `QOpenGLWidget` virtual cannot return a
/// `Status`, and a widget must not throw across Qt's callback, so the outcome
/// is recorded here instead.
const Status& init_status() const noexcept { return init_status_; }
/// Frames actually staged, and the frame time of the last one (ms). The mean is
/// an exponential moving average seeded by the first frame, of the same
/// render-only span: the frame callback, `begin_frame`, `draw` and `end_frame`.
u64 frames_painted() const noexcept { return frames_; }
f32 last_frame_ms() const noexcept { return last_frame_ms_; }
f32 mean_frame_ms() const noexcept { return mean_frame_ms_; }
/// The region the last frame was drawn into, in device pixels -- the rect
/// `begin_frame()` was handed. Zero-sized before the first frame.
Rect last_device_viewport() const noexcept { return last_viewport_; }
protected:
void initializeGL() override;
void resizeGL(int w, int h) override;
void paintGL() override;
void mousePressEvent(QMouseEvent* event) override;
void mouseMoveEvent(QMouseEvent* event) override;
void mouseReleaseEvent(QMouseEvent* event) override;
/// Qt reports the second press of a double click as this event and not as a
/// press, so without it a drag that began with a double click would have no
/// press to start from. Forwarded as one.
void mouseDoubleClickEvent(QMouseEvent* event) override;
void wheelEvent(QWheelEvent* event) override;
void keyPressEvent(QKeyEvent* event) override;
private:
/// The widget's rectangle in device pixels: the plot's viewport, and the size
/// of the framebuffer the frame is drawn into.
Rect device_viewport() const noexcept;
/// A Qt position (logical widget pixels) in device pixels. The one place a
/// pointer position is mapped, so everything the controller sees is scaled by
/// the same factor the viewport is -- a move's *delta*, whose ratio can change
/// between two events, is scaled by `PointerAnchor` instead.
Vec2 to_device(const QPointF& p) const noexcept;
/// Translates one mouse event and hands it to the controller. `pressed` and
/// `released` are the transitions Qt reports on the event itself.
void forward_pointer(QMouseEvent* event, bool pressed, bool released);
/// Sets the plot's viewport to the current device rect (through the controller,
/// which refreshes the layout with it).
void refresh_viewport();
Plot* plot_ = nullptr; ///< declared first: the controller is built over it
input::Controller controller_;
std::optional<Renderer> renderer_;
FrameFn frame_;
Status init_status_;
/// The position a move's delta is measured from, in **logical** pixels: Qt
/// reports no delta of its own, and the ratio can change between two events
/// (see `PointerAnchor` for why the anchor must not be device pixels).
PointerAnchor anchor_;
u64 frames_ = 0;
f32 last_frame_ms_ = 0.0f;
f32 mean_frame_ms_ = 0.0f;
/// Wall clock at the last `paintGL()` start, or negative before the first one.
f64 last_paint_s_ = -1.0;
Rect last_viewport_{};
};
} // namespace plot::qt