diff --git a/CMakeLists.txt b/CMakeLists.txt index d6853508..35515373 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -226,6 +226,8 @@ set(SOURCES ) set(HEADERS + include/framepacer.h + include/timingstats.h include/mainwindow.h include/glwidget.h include/graphics.h @@ -343,6 +345,13 @@ if(BUILD_TESTING) set_property(TARGET grSim_rendering_test APPEND_STRING PROPERTY LINK_FLAGS " -Wl,--wrap=glBegin") endif() + add_test(NAME render_capture_measurements_regression COMMAND grSim_rendering_test --profile-captures) + set_tests_properties(render_capture_measurements_regression PROPERTIES + TIMEOUT 15 LABELS "opengl" ENVIRONMENT "GRSIM_PROFILE_RENDERING=1") + if(UNIX AND NOT APPLE) + set_tests_properties(render_capture_measurements_regression PROPERTIES + ENVIRONMENT "QT_QPA_PLATFORM=xcb;LIBGL_ALWAYS_SOFTWARE=1;GRSIM_PROFILE_RENDERING=1") + endif() add_test(NAME rendering_regression COMMAND grSim_rendering_test) set_tests_properties(rendering_regression PROPERTIES TIMEOUT 30 LABELS "opengl") if(UNIX AND NOT APPLE) @@ -353,6 +362,21 @@ if(BUILD_TESTING) ENVIRONMENT "QT_QPA_PLATFORM=xcb;LIBGL_ALWAYS_SOFTWARE=1;QT_SCALE_FACTOR=2" TIMEOUT 30 LABELS "opengl") endif() + add_test(NAME frame_schedule_regression COMMAND grSim_timing_test --schedule) + set_tests_properties(frame_schedule_regression PROPERTIES TIMEOUT 5) + add_test(NAME render_cadence_regression COMMAND grSim_timing_test --cadence) + set_tests_properties(render_cadence_regression PROPERTIES TIMEOUT 15 LABELS "opengl") + if(UNIX AND NOT APPLE) + set_tests_properties(render_cadence_regression PROPERTIES + ENVIRONMENT "QT_QPA_PLATFORM=xcb;LIBGL_ALWAYS_SOFTWARE=1") + endif() + add_test(NAME render_measurements_regression COMMAND grSim_timing_test --cadence) + set_tests_properties(render_measurements_regression PROPERTIES + TIMEOUT 15 LABELS "opengl" ENVIRONMENT "GRSIM_PROFILE_RENDERING=1") + if(UNIX AND NOT APPLE) + set_tests_properties(render_measurements_regression PROPERTIES + ENVIRONMENT "QT_QPA_PLATFORM=xcb;LIBGL_ALWAYS_SOFTWARE=1;GRSIM_PROFILE_RENDERING=1") + endif() add_test(NAME timing_rendering_regression COMMAND grSim_timing_test --rendering) set_tests_properties(timing_rendering_regression PROPERTIES TIMEOUT 30 LABELS "opengl") if(UNIX AND NOT APPLE) diff --git a/README.md b/README.md index f2a1ccf8..45701c42 100644 --- a/README.md +++ b/README.md @@ -146,6 +146,17 @@ Kazunori Kimura and Jeremy Feltracco and Kenta Sato and Atousa Ahsani}, ``` +Hover over the Render/Sim status to inspect recent frame intervals, drawing and +swap times, simulation tick times and physics backlog. FPS counts submitted +window frames, excluding screenshots; the display compositor controls presentation. +The 60 FPS cap uses fixed deadlines and keeps showing the latest completed scene +during physics lag. + +For optional GPU timing, launch with `GRSIM_PROFILE_RENDERING=1`. Results are +collected asynchronously when the graphics context supports timer queries; the +default leaves GPU queries disabled. CPU timings and bounded recent histories +remain available in either mode. + The `grSim_replay` developer executable records a fresh physics world's complete settings, initial body states, random seed and accepted protocol commands by simulation tick. Replay runs without rendering or wall-clock command scheduling: diff --git a/include/framepacer.h b/include/framepacer.h new file mode 100644 index 00000000..5934cc6c --- /dev/null +++ b/include/framepacer.h @@ -0,0 +1,31 @@ +#ifndef FRAMEPACER_H +#define FRAMEPACER_H + +#include +#include +#include + +// Deadlines stay on the original time line. Late frames are skipped rather +// than queued, and integer-millisecond timer rounding never accumulates. +class FramePacer { +public: + void reset(qint64 now, double fps) + { + if (!std::isfinite(fps) || fps <= 0) fps = 60; + period = 1e9 / std::max(1.0, std::min(1000.0, fps)); + next = double(now) + period; + } + bool due(qint64 now) const { return double(now) >= next; } + void advance(qint64 now) + { + if (due(now)) next += (std::floor((double(now) - next) / period) + 1) * period; + } + int delayMilliseconds(qint64 now) const + { + return std::max(1, std::min(1000, int(std::ceil((next - double(now)) / 1e6)))); + } +private: + double period = 1e9 / 60.0, next = 0; +}; + +#endif diff --git a/include/glwidget.h b/include/glwidget.h index 2432b3cc..9649d9c8 100644 --- a/include/glwidget.h +++ b/include/glwidget.h @@ -22,6 +22,11 @@ Copyright (C) 2011, Parsian Robotic Center (eew.aut.ac.ir/~parsian/grsim) #define GL_SILENCE_DEPRECATION #include #include +#include +#include +#include +#include +#include "timingstats.h" #include #include #include "simulation.h" @@ -84,6 +89,7 @@ class GLWidget : public QGLWidget { QMenu *cameraMenu; int Current_robot,Current_team; int lockedIndex; + FrameTimings frameTimings() const; bool ctrl,alt,kickingball,altTrigger; bool chiping; double kickpower, chipAngle; @@ -107,11 +113,13 @@ public slots: void lockCameraToBall(); signals: void frameRendered(); + void frameSubmitted(); void clicked(); void selectedRobot(); void closeSignal(bool); void robotTurnedOnOff(int,bool); protected: + void paintEvent(QPaintEvent* event) override; virtual bool hasFramebufferObjects() const; virtual bool hasFramebufferBlit() const; void resizeEvent(QResizeEvent* event) override; @@ -134,6 +142,22 @@ public slots: SceneRenderer renderer; QString graphicsRenderer, graphicsVendor, graphicsVersion; bool softwareRendering = false; + TimingWindow intervalTimings, sceneTimings, labelTimings, paintTimings, gpuTimings; + QElapsedTimer frameClock; + qint64 previousFrame = -1; + quint64 submittedFrames = 0; + bool gpuTimingRequested = false, gpuTimingSupported = false; + bool gpuTimingInitialized = false, paintingWindow = false; + QPointer gpuContext; + QPointer gpuSurfaceOwner; + QSurface* gpuSurface = nullptr; + QMetaObject::Connection gpuCleanupConnection; + void initializeGpuTiming(); + void cleanupGpuTiming(); + std::array, 4> gpuQueries; + std::array gpuPending{{false, false, false, false}}; + int activeGpuQuery = -1; + QWidget* lagWarning; bool showCursor = false; double cursorRadius = 0; diff --git a/include/mainwindow.h b/include/mainwindow.h index e7934cdc..c867dc27 100644 --- a/include/mainwindow.h +++ b/include/mainwindow.h @@ -21,6 +21,7 @@ Copyright (C) 2011, Parsian Robotic Center (eew.aut.ac.ir/~parsian/grsim) #include #include +#include "framepacer.h" #include @@ -74,10 +75,11 @@ public slots: int robotIndex(int robot,int team); private: - int getRenderInterval(); void updateGraphicsDeviceStatus(); SimulationController* simulation; QTimer *renderTimer; + QElapsedTimer renderClock; + FramePacer framePacer; QTimer *uiTimer; GLWidget *glwidget; diff --git a/include/scenesnapshot.h b/include/scenesnapshot.h index d6a88767..39c164e6 100644 --- a/include/scenesnapshot.h +++ b/include/scenesnapshot.h @@ -7,6 +7,7 @@ #include #include #include "simulationsettings.h" +#include "timingstats.h" enum class PrimitiveKind { None, Sphere, Box, Cylinder, Ground }; @@ -42,6 +43,8 @@ struct SceneSnapshot { std::vector robots; std::array ballPosition{{0, 0, 0}}; unsigned odeHelpers = 0; + TimingSummary stepTimings; + double snapshotMs = 0; }; using SceneSnapshotPtr = std::shared_ptr; diff --git a/include/simulation.h b/include/simulation.h index ef8b5afc..25d7394b 100644 --- a/include/simulation.h +++ b/include/simulation.h @@ -67,6 +67,8 @@ private slots: int stepsThisSecond = 0; bool initialized = false; LagMonitor lag; + TimingWindow stepTimings; + TimingSummary recentStepTimings; }; // GUI-facing interface. All operations are queued; only snapshots cross back. diff --git a/include/timingstats.h b/include/timingstats.h new file mode 100644 index 00000000..690ff5aa --- /dev/null +++ b/include/timingstats.h @@ -0,0 +1,49 @@ +#ifndef TIMINGSTATS_H +#define TIMINGSTATS_H + +#include +#include +#include +#include + +struct TimingSummary { + unsigned samples = 0; + double medianMs = 0, p95Ms = 0, p99Ms = 0, maximumMs = 0; +}; + +// Bounded recent history; recording never allocates or sorts. Summarize only +// when a consumer needs diagnostics, outside the drawing/stepping hot paths. +class TimingWindow { +public: + void add(double milliseconds) + { + if (!std::isfinite(milliseconds) || milliseconds < 0) return; + values[next] = milliseconds; + next = (next + 1) % values.size(); + count = std::min(count + 1, unsigned(values.size())); + } + TimingSummary summary() const + { + TimingSummary result; + result.samples = count; + if (!count) return result; + auto sorted = values; + std::sort(sorted.begin(), sorted.begin() + count); + result.medianMs = sorted[(count - 1) / 2]; + result.p95Ms = sorted[unsigned(std::ceil(count * 0.95)) - 1]; + result.p99Ms = sorted[unsigned(std::ceil(count * 0.99)) - 1]; + result.maximumMs = sorted[count - 1]; + return result; + } +private: + std::array values{}; + unsigned count = 0, next = 0; +}; + +struct FrameTimings { + TimingSummary interval, scene, labels, paintAndSwap, gpu; + bool gpuRequested = false, gpuSupported = false; + std::uint64_t frames = 0; +}; + +#endif diff --git a/src/glwidget.cpp b/src/glwidget.cpp index a099d60b..77dcf63c 100644 --- a/src/glwidget.cpp +++ b/src/glwidget.cpp @@ -31,11 +31,16 @@ Copyright (C) 2011, Parsian Robotic Center (eew.aut.ac.ir/~parsian/grsim) #include #include #include +#include +#include +#include GLWidget::GLWidget(QWidget *parent, ConfigWidget* _cfg, SimulationController* controller) : QGLWidget(parent), cfg(_cfg), simulation(controller), renderer(this) { Q_INIT_RESOURCE(textures); + frameClock.start(); + gpuTimingRequested = qEnvironmentVariableIntValue("GRSIM_PROFILE_RENDERING") == 1; state = CursorMode::STEADY; m_fbo = nullptr; selected = -1; @@ -149,6 +154,7 @@ GLWidget::GLWidget(QWidget *parent, ConfigWidget* _cfg, SimulationController* co GLWidget::~GLWidget() { makeCurrent(); + cleanupGpuTiming(); delete m_fbo; renderer.graphics.clearTextures(); doneCurrent(); @@ -407,11 +413,106 @@ void GLWidget::resizeGL(int width, int height) { glViewport(0, 0, width, height) bool GLWidget::hasFramebufferObjects() const { return QGLFramebufferObject::hasOpenGLFramebufferObjects(); } bool GLWidget::hasFramebufferBlit() const { return QGLFramebufferObject::hasOpenGLFramebufferBlit(); } +void GLWidget::initializeGpuTiming() +{ + if (!paintingWindow || !gpuTimingRequested || gpuTimingInitialized) return; + gpuContext = QOpenGLContext::currentContext(); + if (!gpuContext) return; + gpuSurface = gpuContext->surface(); + if (gpuSurface && gpuSurface->surfaceClass() == QSurface::Window) + gpuSurfaceOwner = static_cast(gpuSurface); + else if (gpuSurface) + gpuSurfaceOwner = static_cast(gpuSurface); + gpuTimingInitialized = true; + gpuTimingSupported = true; + for (auto& query : gpuQueries) { + query.reset(new QOpenGLTimerQuery()); + if (!query->create()) { gpuTimingSupported = false; break; } + } + if (!gpuTimingSupported) + for (auto& query : gpuQueries) query.reset(); + gpuCleanupConnection = connect(gpuContext, &QOpenGLContext::aboutToBeDestroyed, + this, &GLWidget::cleanupGpuTiming, Qt::DirectConnection); +} + +void GLWidget::cleanupGpuTiming() +{ + if (!gpuTimingInitialized) return; + disconnect(gpuCleanupConnection); + auto* previous = QOpenGLContext::currentContext(); + auto* previousSurface = previous ? previous->surface() : nullptr; + auto* owner = gpuContext.data(); + const bool switched = owner && previous != owner; + if (switched && gpuSurfaceOwner) owner->makeCurrent(gpuSurface); + // Never delete query IDs in another context: IDs are not shared. A lost + // context frees its native resources; with no current context deletion is + // harmless, whereas a different context could have unrelated matching IDs. + if (owner != QOpenGLContext::currentContext()) { + if (QOpenGLContext::currentContext()) QOpenGLContext::currentContext()->doneCurrent(); + } + for (auto& query : gpuQueries) query.reset(); + gpuPending.fill(false); + activeGpuQuery = -1; + gpuContext.clear(); + gpuSurfaceOwner.clear(); + gpuSurface = nullptr; + gpuTimingInitialized = gpuTimingSupported = false; + gpuTimings = TimingWindow(); + if (switched) { + if (owner) owner->doneCurrent(); + if (previous && previousSurface) previous->makeCurrent(previousSurface); + } +} + +FrameTimings GLWidget::frameTimings() const +{ + FrameTimings result; + result.interval = intervalTimings.summary(); + result.scene = sceneTimings.summary(); + result.labels = labelTimings.summary(); + result.paintAndSwap = paintTimings.summary(); + result.gpu = gpuTimings.summary(); + result.gpuRequested = gpuTimingRequested; + result.gpuSupported = gpuTimingSupported; + result.frames = submittedFrames; + return result; +} + +void GLWidget::paintEvent(QPaintEvent* event) +{ + QElapsedTimer elapsed; + elapsed.start(); + QScopedValueRollback painting(paintingWindow, true); + QGLWidget::paintEvent(event); // Includes Qt's automatic buffer swap. + if (!graphicsEnabled || !snapshot || !isValid()) return; + paintTimings.add(elapsed.nsecsElapsed() / 1e6); + const qint64 now = frameClock.nsecsElapsed(); + if (previousFrame >= 0) intervalTimings.add((now - previousFrame) / 1e6); + previousFrame = now; + ++submittedFrames; + // Swap completion on the CPU is not proof of compositor presentation. + emit frameSubmitted(); +} + void GLWidget::paintGL() { if (!graphicsEnabled) return; refreshSnapshot(); if (!snapshot) return; + QElapsedTimer elapsed; + elapsed.start(); + initializeGpuTiming(); + activeGpuQuery = -1; + if (paintingWindow && gpuTimingSupported && gpuContext == QOpenGLContext::currentContext()) { + for (unsigned i = 0; i < gpuQueries.size(); ++i) { + if (gpuPending[i] && gpuQueries[i]->isResultAvailable()) { + gpuTimings.add(gpuQueries[i]->waitForResult() / 1e6); + gpuPending[i] = false; + } + if (!gpuPending[i] && activeGpuQuery < 0) activeGpuQuery = int(i); + } + if (activeGpuQuery >= 0) gpuQueries[activeGpuQuery]->begin(); + } auto& graphics = renderer.graphics; if (cammode == CameraMode::CURRENT_ROBOT_VIEW) { const auto* robot = robotSnapshot(robotIndex(Current_robot, Current_team)); @@ -452,6 +553,8 @@ void GLWidget::paintGL() if (fboSupported) QOpenGLContext::currentContext()->functions()->glBindFramebuffer(GL_FRAMEBUFFER, target); renderer.draw(*snapshot, fullW, fullH, quality, selected, showCursor, cursor, cursorRadius); } + sceneTimings.add(elapsed.nsecsElapsed() / 1e6); + elapsed.restart(); if (quality.showRobotLabels) { QFont font; for (const auto& robot : snapshot->robots) { @@ -470,6 +573,12 @@ void GLWidget::paintGL() if (blitSupported) functions->glBindFramebuffer(GL_READ_FRAMEBUFFER, readTarget); } glViewport(viewport[0], viewport[1], viewport[2], viewport[3]); + labelTimings.add(elapsed.nsecsElapsed() / 1e6); + if (activeGpuQuery >= 0) { + gpuQueries[activeGpuQuery]->end(); + gpuPending[activeGpuQuery] = true; + activeGpuQuery = -1; + } hasRendered = true; emit frameRendered(); } diff --git a/src/mainwindow.cpp b/src/mainwindow.cpp index 8438eac9..bb84f389 100644 --- a/src/mainwindow.cpp +++ b/src/mainwindow.cpp @@ -41,14 +41,6 @@ Copyright (C) 2011, Parsian Robotic Center (eew.aut.ac.ir/~parsian/grsim) #include "config.h" #include "logger.h" -int MainWindow::getRenderInterval() -{ - const double fps = configwidget->DesiredFPS(); - return std::isfinite(fps) && fps > 0 ? qMax(1, qCeil(1000.0 / qMax(1.0, fps))) : 17; -} - - - void MainWindow::customFPS(int fps) { Q_UNUSED(fps); @@ -181,7 +173,9 @@ MainWindow::MainWindow(QWidget *parent, ConfigWidget *config) renderTimer = new QTimer(this); renderTimer->setTimerType(Qt::PreciseTimer); - renderTimer->setInterval(getRenderInterval()); + renderTimer->setSingleShot(true); + renderClock.start(); + framePacer.reset(renderClock.nsecsElapsed(), configwidget->DesiredFPS()); uiTimer = new QTimer(this); uiTimer->setInterval(33); @@ -192,7 +186,7 @@ MainWindow::MainWindow(QWidget *parent, ConfigWidget *config) m_rateTimer.start(); QObject::connect(renderTimer, SIGNAL(timeout()), this, SLOT(renderTick())); - QObject::connect(glwidget, SIGNAL(frameRendered()), this, SLOT(recordRenderedFrame())); + QObject::connect(glwidget, SIGNAL(frameSubmitted()), this, SLOT(recordRenderedFrame())); QObject::connect(uiTimer, SIGNAL(timeout()), this, SLOT(updateUI())); QObject::connect(takeSnapshotAct, SIGNAL(triggered(bool)), this, SLOT(takeSnapshot())); QObject::connect(takeSnapshotToClipboardAct, SIGNAL(triggered(bool)), this, SLOT(takeSnapshotToClipboard())); @@ -215,7 +209,7 @@ MainWindow::MainWindow(QWidget *parent, ConfigWidget *config) if (configwidget->Robots_Count() != robotwidget->robotCombo->count()) changeRobotCount(); else simulation->configure(configwidget->simulationSettings()); }); - renderTimer->start(); + renderTimer->start(framePacer.delayMilliseconds(renderClock.nsecsElapsed())); uiTimer->start(); @@ -290,7 +284,8 @@ int MainWindow::robotIndex(int robot, int team) void MainWindow::changeTimer() { - renderTimer->setInterval(getRenderInterval()); + framePacer.reset(renderClock.nsecsElapsed(), configwidget->DesiredFPS()); + renderTimer->start(framePacer.delayMilliseconds(renderClock.nsecsElapsed())); } void MainWindow::changePhysicsTimer() @@ -310,10 +305,15 @@ QString dRealToStr(dReal a) void MainWindow::renderTick() { - if (!glwidget->graphicsEnabled || !glwidget->isVisible()) return; - const auto snapshot = simulation->latest(); - if (!snapshot || snapshot->pendingTime >= snapshot->settings.DeltaTime() * 2) return; - glwidget->update(); + const qint64 now = renderClock.nsecsElapsed(); + if (framePacer.due(now)) { + framePacer.advance(now); + // The mailbox contains completed immutable states. Physics backlog + // changes their age, not their safety to draw. + if (glwidget->graphicsEnabled && glwidget->isVisible() && simulation->latest()) + glwidget->update(); + } + renderTimer->start(framePacer.delayMilliseconds(renderClock.nsecsElapsed())); } void MainWindow::recordRenderedFrame() @@ -376,6 +376,29 @@ void MainWindow::updateUI() m_renderFps = m_renderFramesThisSecond / elapsed; m_renderFramesThisSecond = 0; m_rateTimer.restart(); + const auto timings = glwidget->frameTimings(); + const auto gpu = timings.gpu.samples + ? tr("%1 ms").arg(timings.gpu.p95Ms, 0, 'f', 2) + : (timings.gpuRequested ? tr("unavailable or pending") : tr("profiling disabled")); + fpslabel->setToolTip(tr( + "Submitted frames; display presentation is controlled by the compositor.\n" + "Frame interval p50 / p95 / p99: %1 / %2 / %3 ms\n" + "Scene / labels / paint + swap p95: %4 / %5 / %6 ms\n" + "GPU drawing p95: %7\n" + "Simulation tick p95 / p99: %8 / %9 ms; snapshot: %10 ms\n" + "Physics backlog: %11 ms; ODE helpers: %12") + .arg(timings.interval.medianMs, 0, 'f', 2) + .arg(timings.interval.p95Ms, 0, 'f', 2) + .arg(timings.interval.p99Ms, 0, 'f', 2) + .arg(timings.scene.p95Ms, 0, 'f', 2) + .arg(timings.labels.p95Ms, 0, 'f', 2) + .arg(timings.paintAndSwap.p95Ms, 0, 'f', 2) + .arg(gpu) + .arg(snapshot->stepTimings.p95Ms, 0, 'f', 2) + .arg(snapshot->stepTimings.p99Ms, 0, 'f', 2) + .arg(snapshot->snapshotMs, 0, 'f', 2) + .arg(snapshot->pendingTime * 1000, 0, 'f', 2) + .arg(snapshot->odeHelpers)); } fpslabel->setText(QString("Render: %1 fps | Sim: %2 Hz") .arg(QString::asprintf("%06.2f", m_renderFps)) diff --git a/src/simulation.cpp b/src/simulation.cpp index c0dc9843..b0daf503 100644 --- a/src/simulation.cpp +++ b/src/simulation.cpp @@ -134,6 +134,8 @@ void SimulationWorker::connectSockets(const SimulationSettings* previous) void SimulationWorker::rebuildWorld() { delete world; + stepTimings = TimingWindow(); + recentStepTimings = TimingSummary(); RobotsFormation form(FORMATION_INSIDE_1, &settings); world = new SSLWorld(this, &settings, &form, &form); const QByteArray requestedThreads = qgetenv("GRSIM_ODE_THREADS"); @@ -225,7 +227,10 @@ void SimulationWorker::tick() int steps = 0; while (accumulator >= step && steps < 4 && (steps == 0 || budget.nsecsElapsed() < 4000000)) { + QElapsedTimer stepClock; + stepClock.start(); world->stepSimulation(step); + stepTimings.add(stepClock.nsecsElapsed() / 1e6); accumulator -= step; ++steps; ++stepsThisSecond; @@ -233,6 +238,7 @@ void SimulationWorker::tick() const qint64 rate = rateClock.nsecsElapsed(); if (rate >= 1000000000) { physicsHz = stepsThisSecond / (rate / 1e9); + recentStepTimings = stepTimings.summary(); stepsThisSecond = 0; rateClock.restart(); } @@ -243,7 +249,11 @@ void SimulationWorker::tick() void SimulationWorker::publish() { + QElapsedTimer buildClock; + buildClock.start(); auto snapshot = world->snapshot(generation); + snapshot->snapshotMs = buildClock.nsecsElapsed() / 1e6; + snapshot->stepTimings = recentStepTimings; snapshot->physicsHz = physicsHz; snapshot->pendingTime = accumulator + (clock.nsecsElapsed() - lastTick) / 1e9; snapshot->lagging = lag.update(snapshot->pendingTime, settings.DeltaTime(), clock.nsecsElapsed()); diff --git a/tests/rendering_regression.cpp b/tests/rendering_regression.cpp index dab03a5c..9a58fdbb 100644 --- a/tests/rendering_regression.cpp +++ b/tests/rendering_regression.cpp @@ -202,6 +202,47 @@ static bool checkNoBlitUpdates(TestView& view) return passed; } +static bool checkProfiledCaptures(MainWindow& window, GLWidget& view) +{ + window.resize(800, 600); + window.showNormal(); + auto drawWindowFrame = [&]() { + const auto before = view.frameTimings().frames; + view.update(); + QElapsedTimer wait; + wait.start(); + while (view.frameTimings().frames == before && wait.elapsed() < 3000) { + QCoreApplication::processEvents(); + QThread::msleep(1); + } + return view.frameTimings().frames > before; + }; + bool passed = drawWindowFrame(); + const auto firstFrames = view.frameTimings().frames; + for (int i = 0; i < 3; ++i) { + view.makeCurrent(); + while (glGetError() != GL_NO_ERROR) {} + const auto captured = view.renderPixmap(320 + i * 10, 240, false).toImage(); + passed = !captured.isNull() && passed; + // Qt's legacy capture may leave GL_FRONT errors in its temporary + // framebuffer context. Drain those before testing the normal window. + view.makeCurrent(); + while (glGetError() != GL_NO_ERROR) {} + passed = drawWindowFrame() && passed; + view.makeCurrent(); + const GLenum error = glGetError(); + std::printf("%s profiled window resumes after temporary capture context (GL error 0x%x)\n", + error == GL_NO_ERROR ? "PASS" : "FAIL", unsigned(error)); + passed = error == GL_NO_ERROR && passed; + } + const auto timings = view.frameTimings(); + const bool measured = timings.gpuRequested && timings.frames > firstFrames && + (!timings.gpuSupported || timings.gpu.samples > 0); + std::printf("%s GPU timing survives screenshot context changes (supported=%d samples=%u)\n", + measured ? "PASS" : "FAIL", timings.gpuSupported, timings.gpu.samples); + return passed && measured; +} + int main(int argc, char** argv) { QCoreApplication::setAttribute(Qt::AA_EnableHighDpiScaling); @@ -225,6 +266,11 @@ int main(int argc, char** argv) view->makeCurrent(); std::printf("OpenGL renderer: %s; display scale: %.1f\n", glGetString(GL_RENDERER), view->devicePixelRatioF()); if (qgetenv("QT_SCALE_FACTOR") == "2" && view->devicePixelRatioF() < 1.9) return 2; + if (argc > 1 && QByteArray(argv[1]) == "--profile-captures") { + const bool passed = checkProfiledCaptures(*window, *view); + delete window; + return passed ? 0 : 1; + } bool passed = true; passed = checkTexturedCylinderDetail(*view) && passed; for (const QSize size : {QSize(512, 512), QSize(320, 240)}) { diff --git a/tests/timing_regression.cpp b/tests/timing_regression.cpp index c98bd364..0e113c7e 100644 --- a/tests/timing_regression.cpp +++ b/tests/timing_regression.cpp @@ -12,6 +12,9 @@ #include #include #include "mainwindow.h" +#include "framepacer.h" +#include "timingstats.h" +#include #include "ssl_vision_wrapper.pb.h" #include "ssl_simulation_robot_control.pb.h" #include "ssl_simulation_robot_feedback.pb.h" @@ -230,11 +233,99 @@ static bool scenario(MainWindow& window, GLWidget& view, quint16 controlPort, do return passed; } +static bool checkSchedule() +{ + bool passed = true; + for (double fps : {1.0, 5.0, 59.94, 60.0, 120.0, 1000.0}) { + FramePacer schedule; + schedule.reset(0, fps); + qint64 now = 0; + unsigned frames = 0; + // Drive the same deadlines used by MainWindow with a synthetic clock. + while (now < 60000000000LL) { + const int delay = schedule.delayMilliseconds(now); + passed = delay >= 1 && delay <= 1000 && passed; + now += qint64(delay) * 1000000; + if (schedule.due(now)) { ++frames; schedule.advance(now); } + } + const bool count = std::abs(double(frames) - 60 * fps) <= 1; + passed = count && passed; + std::printf("%s deadline count %.2f FPS over 60 seconds: %u\n", + count ? "PASS" : "FAIL", fps, frames); + // A blocked GUI drops missed render deadlines without a catch-up burst. + schedule.advance(now + 5000000000LL); + passed = !schedule.due(now + 5000000000LL) && passed; + } + for (double invalid : {0.0, -1.0, std::numeric_limits::infinity(), + std::numeric_limits::quiet_NaN()}) { + FramePacer schedule; + schedule.reset(0, invalid); + passed = schedule.delayMilliseconds(0) == 17 && passed; + } + TimingWindow samples; + for (unsigned i = 1; i <= 240; ++i) samples.add(i); + samples.add(-1); samples.add(std::numeric_limits::quiet_NaN()); + const auto full = samples.summary(); + passed = full.samples == 240 && full.medianMs == 120 && full.p95Ms == 228 && + full.p99Ms == 238 && full.maximumMs == 240 && passed; + for (unsigned i = 0; i < 240; ++i) samples.add(2); + const auto wrapped = samples.summary(); + passed = wrapped.samples == 240 && wrapped.p99Ms == 2 && passed; + std::printf("%s bounded timing histories, invalid FPS and stalled deadlines\n", + passed ? "PASS" : "FAIL"); + return passed; +} + +// Stop the producer before deliberately ageing its last completed snapshot. +// This exercises the real renderTick policy without racing a running worker. +static bool checkCadence(MainWindow& window, GLWidget& view) +{ + view.simulation->stop(); + auto frozen = std::const_pointer_cast(view.scene()); + if (!frozen) return false; + frozen->pendingTime = 0.5; + view.refreshSnapshot(); + view.updateGL(); + QCoreApplication::processEvents(); + const auto tick = frozen->tick; + int frames = 0; + bool fractionalInterval = false, boundedTimer = true; + const auto frameConnection = QObject::connect(&view, &GLWidget::frameRendered, + [&]() { ++frames; }); + QTimer* render = nullptr; + for (auto* timer : window.findChildren(QString(), Qt::FindDirectChildrenOnly)) + if (timer->timerType() == Qt::PreciseTimer) render = timer; + if (!render) return false; + const auto timerConnection = QObject::connect(render, &QTimer::timeout, [&]() { + fractionalInterval = fractionalInterval || render->interval() < 17; + boundedTimer = boundedTimer && render->interval() > 0; + }); + QEventLoop loop; + QTimer::singleShot(600, &loop, &QEventLoop::quit); + loop.exec(); + QObject::disconnect(frameConnection); + QObject::disconnect(timerConnection); + const bool drawing = frames >= 5 && view.scene()->tick == tick; + std::printf("%s 60 FPS uses fractional deadlines without a zero-timer spin\n", + fractionalInterval && boundedTimer ? "PASS" : "FAIL"); + std::printf("%s drawing continues from completed snapshots during physics lag (%d frames)\n", + drawing ? "PASS" : "FAIL", frames); + const auto timings = view.frameTimings(); + const bool measured = timings.frames >= unsigned(frames) && timings.interval.samples > 0 && + timings.scene.samples > 0 && timings.labels.samples > 0 && timings.paintAndSwap.samples > 0 && + (!timings.gpuRequested || !timings.gpuSupported || timings.gpu.samples > 0); + std::printf("%s frame measurements; GPU requested=%d supported=%d samples=%u\n", + measured ? "PASS" : "FAIL", timings.gpuRequested, timings.gpuSupported, timings.gpu.samples); + return fractionalInterval && boundedTimer && drawing && measured; +} + int main(int argc, char** argv) { + if (argc > 1 && QByteArray(argv[1]) == "--schedule") return checkSchedule() ? 0 : 1; if (argc > 2 && QByteArray(argv[1]) == "--observe") return observe(argc, argv); if (argc > 1 && QByteArray(argv[1]) == "--check-observer") return checkObserver(argc, argv); - const bool rendering = argc > 1 && QByteArray(argv[1]) == "--rendering"; + const bool cadence = argc > 1 && QByteArray(argv[1]) == "--cadence"; + const bool rendering = cadence || (argc > 1 && QByteArray(argv[1]) == "--rendering"); QApplication app(argc, argv); QUdpSocket reserve; if (!reserve.bind(QHostAddress(QHostAddress::LocalHost), 0)) return 2; @@ -257,6 +348,11 @@ int main(int argc, char** argv) auto* view = window->findChild(); if (!view) return 2; if (rendering && !view->isValid()) return 2; + if (cadence) { + const bool passed = checkCadence(*window, *view); + delete window; + return passed ? 0 : 1; + } bool passed = scenario(*window, *view, controlPort, 60, 0, rendering); passed = scenario(*window, *view, controlPort, 5, 0, rendering) && passed; passed = scenario(*window, *view, controlPort, 1, 0, rendering) && passed;