Free, open-source 3D sculpting for Linux, macOS and Windows: dense meshes, remeshing, painting, built-in AI (image/text to 3D), Send to Unreal, game-ready LODs, Gaussian splats and OpenUSD.
C++ 3d3d-sculptingcppdear-imguidigital-sculptingfbxgame-developmentgaussian-splattinggltfimage-to-3dmcpopenglopenusdsculptingtext-to-3dunreal-engine
Benchmark takes: --benchmark-script take.sfui plays a UI test take in real time with the HUD, video and a per-frame CSV
islandmed564e12f22e02
diff --git a/CMakeLists.txt b/CMakeLists.txtindex e6de73ea..44211abb 100644--- a/CMakeLists.txt+++ b/CMakeLists.txt@@ -446,6 +446,8 @@ if(SCULPTFORGE_BUILD_APP)src/app/PanelExtract.cppsrc/app/PanelTimeline.cppsrc/app/ProofMode.cpp+ src/app/BenchVideo.cpp+ src/app/BenchTake.cppsrc/app/Tablet.cppsrc/app/Wintab.cppsrc/app/SpaceMouse.cpp@@ -465,14 +467,14 @@ if(SCULPTFORGE_BUILD_APP)target_compile_definitions(sculptforge PRIVATE SCULPTFORGE_VERSION="${PROJECT_VERSION}"SCULPTFORGE_PRERELEASE="${SCULPTFORGE_PRERELEASE}"SF_UPDATE_CHECK=$<BOOL:${SCULPTFORGE_UPDATE_CHECK}>)- # The commit a build came from, for proof mode's results (src/app/ProofMode.cpp); taken when CMake configures.+ # The commit a build came from, for proof mode's results and HUD (src/app/ProofMode.cpp, BenchTake.cpp); taken when CMake configures.find_package(Git QUIET)if(GIT_FOUND AND EXISTS ${CMAKE_CURRENT_SOURCE_DIR}/.git)execute_process(COMMAND ${GIT_EXECUTABLE} rev-parse --short HEAD WORKING_DIRECTORY ${CMAKE_CURRENT_SOURCE_DIR}OUTPUT_VARIABLE SF_GIT_COMMIT OUTPUT_STRIP_TRAILING_WHITESPACE ERROR_QUIET)endif()if(SF_GIT_COMMIT)- set_source_files_properties(src/app/ProofMode.cpp PROPERTIES COMPILE_DEFINITIONS "SF_GIT_COMMIT=\"${SF_GIT_COMMIT}\"")+ set_source_files_properties(src/app/ProofMode.cpp src/app/BenchTake.cpp PROPERTIES COMPILE_DEFINITIONS "SF_GIT_COMMIT=\"${SF_GIT_COMMIT}\"")endif()if(MSVC)target_compile_options(sculptforge PRIVATE /W4 /utf-8 /permissive-)@@ -941,6 +943,14 @@ if(SCULPTFORGE_BUILD_TESTS)# pointer's circle (#19).add_test(NAME ui_stroke_path COMMAND sculptforge --run "new_sphere" --measure-stroke 1.5)set_tests_properties(ui_stroke_path PROPERTIES LABELS ui TIMEOUT 60 ENVIRONMENT "SF_NO_UPDATE_CHECK=1")+ # A benchmark take (--benchmark-script, src/app/BenchTake.cpp) on a sphere: played in real time, a CSV row per+ # frame with the strokes' lag, and a video as long as the take (within 5%).+ if(Python3_Interpreter_FOUND)+ add_test(NAME bench_take_sphere COMMAND ${Python3_EXECUTABLE} ${CMAKE_CURRENT_SOURCE_DIR}/tests/takes/check_take.py+ $<TARGET_FILE:sculptforge> ${CMAKE_CURRENT_SOURCE_DIR}/tests/takes/sphere.sfui+ ${CMAKE_CURRENT_BINARY_DIR}/bench-take --min-seconds 5)+ set_tests_properties(bench_take_sphere PROPERTIES LABELS ui TIMEOUT 240 RUN_SERIAL TRUE)+ endif()# Background dabs (a heavy mesh's stroke on the solver thread, no preview), forced on a light sphere: replaying# the stroke in the frame loop gives the same mesh, bit for bit, and its undo the mesh it started from.add_test(NAME ui_stroke_background COMMAND sculptforge --run "new_sphere" --measure-stroke 1.5)diff --git a/changes/feat-benchmark-script.md b/changes/feat-benchmark-script.mdnew file mode 100644index 00000000..ce0dbbde--- /dev/null+++ b/changes/feat-benchmark-script.md@@ -0,0 +1,10 @@+---+added: **Benchmark takes** (`sculptforge --benchmark-script take.sfui [project]`): a UI test script's strokes, orbits,+ keys and waits played in real time (wall-clock pacing, 240 Hz stroke samples) in the interactive loop, with the+ benchmark HUD, the benchmark video path and a per-frame CSV (frame ms, stroke lag) beside it. Steps a take can't+ play in real time (shots, expectations) are skipped; steps that run commands or read other files are refused.+ docs/benchmark.md.+---+Dev tooling (creator-kit performance clips), so no What's New. The benchmark video's encoder and pixel-buffer ring+moved from ProofMode.cpp to BenchVideo.cpp unchanged, except that finishing now flushes the last frames still in the+ring (the clip runs to the last frame shown). Test: bench_take_sphere.diff --git a/docs/benchmark.md b/docs/benchmark.mdindex f8f56c43..7837db7c 100644--- a/docs/benchmark.md+++ b/docs/benchmark.md@@ -124,3 +124,43 @@ Field notes:The benchmarks page (`website/benchmarks/index.html`) reads `results.json` and shows one row per mesh size andsubmission: frame time and lag percentiles per phase, hardware, version.++## Benchmark takes (`--benchmark-script`)++Proof mode's strokes are fixed; for clips of real sculpting at real speed (b-roll with its numbers), a **take** plays a+UI test script's input instead:++```+sculptforge --benchmark-script take.sfui [project.sfproj] --benchmark-video take.mp4 [--benchmark-out take.csv]+```++- The take is a `.sfui` script (the UI test format, `src/app/UiTest.cpp`): `stroke`, `pen_stroke`, `orbit`, `camera`,+ `zoom`, `key`, `click`, `brush_size`, `wait` and the other input steps, plus the scene's set-up commands+ (`run new_sphere`, `run ui_look`, `run subdivide`...). The project after it, if any, is opened first; with none the+ take sets up its own scene. `tests/takes/sphere.sfui` is a short example.+- It plays in **real time** in the app's own interactive loop (the one you sculpt in, `App::run`): each frame the+ script moves on by the wall clock's time since the last frame, never by a fixed step, so a slow frame is a jump+ in the clip as it is for a person. `stroke` sends its pointer samples at 240 a second (each frame, the samples+ since the last one), like proof mode; `pen_stroke` sends 4 a frame. A step's own end is checked once a frame, so+ waits are at least as long as written.+- The proof mode HUD (version, commit, frame times over the last second, stroke lag, GPU) and the script's pointer+ are drawn on top, and the frames go to the MP4 the same way as proof mode's: read back through pixel buffers,+ encoded by ffmpeg on its own thread at a constant 30 fps (a frame repeats while the app is slower), so the video+ is as long as the take. `--benchmark-no-video` records none; `--benchmark-vsync` keeps vertical sync on.+- The CSV has one row per frame: `frame`, `t_s` (since the take started), `frame_ms`, `stroking` (1 while a stroke+ is held), and `lag_ms` / `lag_px` as defined above (blank when no dab is on screen to measure). Its default name+ is the video's with `.csv`; with neither given both go in the current folder as `sculptforge-take-<name>-<time>`.+ A summary is printed at the end (frame percentiles, the slowest frame, stroke lag).+- It waits for the start-up to settle (a second, and no background job running) before the clock starts, and keeps+ half a second after the script's last step so the clip ends on the result. Esc stops it early.++Local only: no ports, no IPC, no update check, and no files read but the take and the project. Steps a take can't+play in real time or that reach outside it are handled when it loads: `shot`, `snapshot`, `remember`, `print`,+`dump_shortcuts` and every `expect*` are skipped with a warning; `run` with anything but a scene set-up command,+`env`, `drop`, `choose_file`, `answer_dialog`, `restart`, the phone and AI client steps and the rest are refused+and the take doesn't start (exit code 1). Settings are isolated as for any benchmark. Exit code 0 when the take+played through and the video and CSV were written.++`ctest -R bench_take_sphere` plays `tests/takes/sphere.sfui` and checks the CSV (a row per frame, the strokes'+lag, frame times adding up to the wall clock within 5%, at least the script's length) and, with ffprobe, that the+video is as long as the take within 5%.diff --git a/src/app/App.cpp b/src/app/App.cppindex d07cbc89..ffd9e13e 100644--- a/src/app/App.cpp+++ b/src/app/App.cpp@@ -274,7 +274,7 @@ bool App::init(const AppOptions& options) {uiScale_ = targetUiScale(); // the style follows in applyLook belowbuildUiFonts(uiScale_);timer.step("ImGui, settings, fonts");- if (recording) {+ if (recording || !options.benchmarkScript.empty()) { // (a benchmark take: the same scripts)ImGui::GetCurrentContext()->TestEngineHookItems = true; // lets the demo find buttons by labelio.IniFilename = nullptr; // fixed, reproducible layout}@@ -818,7 +818,7 @@ bool App::focusKeepsDrawing(double now) const {bool App::wantsFrames(double now) const {return now < activeUntil_ || focusKeepsDrawing(now) || drag_ != Drag::None || ui::HoverAnimating() || // a hover ring easing in or outdoc_.sculptor.strokeActive() ||- proofRunning() || // (not a keep-alive from the last frame: building a scene takes longer than any timeout)+ proofRunning() || takeRunning() || // (not a keep-alive from the last frame: building a scene takes longer than any timeout)!dabQueue_.empty() || // a stroke's dabs still waiting (drainStrokeDabs) are placed a few each framestrokeFinishing_ || solverBusy() || // the solver thread is placing a stroke's dabs (AsyncStroke.cpp)backgroundBusy() || playingLayer_ >= 0 || faceTakePlaying_ ||@@ -841,7 +841,9 @@ int App::run() {if (!options_.renderPath.empty()) return renderHeadless();if (!options_.recordPath.empty() || !options_.uiTest.empty()) return runRecording();if (!options_.timelapsePath.empty()) return runTimelapseCli(); // (PanelTimeline.cpp)- if (options_.benchmark) startProofMode(); // runs in this loop (ProofMode.cpp)+ if (!options_.benchmarkScript.empty()) { // a take, in real time in this loop (BenchTake.cpp)+ if (!startTake()) return 1;+ } else if (options_.benchmark) startProofMode(); // runs in this loop (ProofMode.cpp)if (g_wakeEvent == 0) g_wakeEvent = SDL_RegisterEvents(1);// Dabs are queued and placed within a time budget each frame (strokeTo). SF_STROKE_IMMEDIATE=1 places them all// as each pointer sample arrives, as before 0.9.6 (for comparison).@@ -945,9 +947,9 @@ int App::run() {// Input keeps the frames coming a little while (hover highlights, tooltips after their delay); other// events (the window shown, moved, focused) need a frame or two.const auto onEvent = [&](const SDL_Event& ev) {- if (strokeProbe_ && ((ev.type >= SDL_EVENT_MOUSE_MOTION && ev.type <= SDL_EVENT_MOUSE_WHEEL) ||- (ev.type >= SDL_EVENT_PEN_PROXIMITY_IN && ev.type <= SDL_EVENT_PEN_AXIS)))- return; // --measure-stroke: the real pointer stays out of the scripted stroke+ if ((strokeProbe_ || takeRunning()) && ((ev.type >= SDL_EVENT_MOUSE_MOTION && ev.type <= SDL_EVENT_MOUSE_WHEEL) ||+ (ev.type >= SDL_EVENT_PEN_PROXIMITY_IN && ev.type <= SDL_EVENT_PEN_AXIS)))+ return; // --measure-stroke, a take: the real pointer stays out of the scripted strokehandleEvent(ev);if (ev.type == SDL_EVENT_KEYMAP_CHANGED || ev.type == SDL_EVENT_KEYBOARD_ADDED ||ev.type == SDL_EVENT_KEYBOARD_REMOVED || ev.type == SDL_EVENT_MOUSE_ADDED ||@@ -991,6 +993,7 @@ int App::run() {phases = 0;mark();while (SDL_PollEvent(&e)) onEvent(e);+ if (take_) takeBeforeFrame(); // a take's input since the last frame, at the wall clock's pacemark();// (The window must have settled too: a window manager that maximises it late, on a busy machine, changes// the canvas and with it the brush's size in the world mid-stroke.)@@ -1225,6 +1228,7 @@ int App::run() {ImGui_ImplOpenGL3_RenderDrawData(ImGui::GetDrawData());hardwareProfileFrameEnd();if (proof_) proofBeforeSwap(fbW, fbH); // Help > Benchmark: timing, video capture, the scripted pointer+ if (take_) takeBeforeSwap(fbW, fbH); // --benchmark-script: the same for a takeSDL_GL_SwapWindow(window_);mark();if (phases == 7) // (Help > Benchmark splits each phase's frames by these)@@ -1277,6 +1281,7 @@ int App::run() {int(drag_ != Drag::None), int(backgroundBusy()), int(perf_.framesStill < 10));}finishProject();+ if (take_) return takeExitCode_;return options_.benchmark && proofSkippedScenes() ? 2 : 0; // (--benchmark: a scene skipped for memory)}diff --git a/src/app/App.h b/src/app/App.hindex f4c643c6..9ad3694c 100644--- a/src/app/App.h+++ b/src/app/App.h@@ -116,6 +116,9 @@ struct AppOptions {std::string benchmarkSizes, benchmarkOut, benchmarkVideo;bool benchmarkNoVideo = false, benchmarkVsync = false;float benchmarkStrokeSeconds = 6.0f;+ // --benchmark-script take.sfui: the take (a UI test script's input) played in real time with the benchmark HUD,+ // video and a per-frame CSV (BenchTake.cpp); benchmark is set too (isolated settings, --size 1920x1080).+ std::string benchmarkScript;};class Demo;@@ -2461,6 +2464,14 @@ private:bool proofRunning() const; // a benchmark is measuring (not its intro or results): every frame is wantedvoid proofBeforeSwap(int fbW, int fbH); // the interactive loop, after drawing a frame, before showing itvoid drawProofUi();+ // sculptforge --benchmark-script (BenchTake.cpp): a .sfui take played in real time, timed, filmed.+ std::shared_ptr<struct TakeState> take_;+ int takeExitCode_ = 0;+ bool startTake(); // false: the take didn't load (refused steps); the reason is logged+ bool takeRunning() const; // the take is playing: every frame is wanted, the real pointer kept out+ void takeBeforeFrame(); // before the UI is built: the script's next input, at the wall clock's pace+ void takeBeforeSwap(int fbW, int fbH); // after drawing, before showing: timing, lag, video; the end+ void drawTakeHud(); // from drawUi: the HUD and the script's pointer// ---- end Sculpt Timeline ----};diff --git a/src/app/BenchTake.cpp b/src/app/BenchTake.cppnew file mode 100644index 00000000..5bd43619--- /dev/null+++ b/src/app/BenchTake.cpp@@ -0,0 +1,285 @@+// SculptForge - open source digital sculpting+// SPDX-License-Identifier: GPL-3.0-or-later+//+// Benchmark takes (sculptforge --benchmark-script take.sfui; docs/benchmark.md): a UI test script's input (strokes,+// orbits, keys, clicks, waits) played in REAL time in the app's own interactive loop, so a clip shows the speed a+// person gets. Each frame the script is advanced by the wall-clock time since the last one (never a fixed step: a+// slow frame is a jump, as it is for a person); `stroke` sends its pointer samples at 240 a second. The proof mode+// HUD is drawn on top and the frames go to the same MP4 path (BenchVideo.h), and a CSV gets every frame's time and+// how far the stroke on screen trails the pointer, so every clip comes with its numbers.+//+// Local only: the take and the project it opens (a positional argument) are the only files read; steps that run+// commands, read files or change other settings are refused when the take loads, and shots and expectations are+// skipped (Demo::loadTake).+#include "app/App.h"+#include "app/BenchVideo.h"+#include "app/Demo.h"+#include "app/Theme.h"++#include "render/GL.h"++#include <algorithm>+#include <chrono>+#include <cmath>+#include <cstdio>+#include <ctime>+#include <filesystem>+#include <fstream>++#ifndef SF_GIT_COMMIT+#define SF_GIT_COMMIT "unknown"+#endif++namespace sf {++namespace {++double nowSeconds() { return std::chrono::duration<double>(std::chrono::steady_clock::now().time_since_epoch()).count(); }++constexpr double kSettleSeconds = 1.0; // the window and the first upload settle before the take starts+constexpr double kSettleGiveUp = 60.0; // ... but a job that never finishes doesn't hold it up for ever+constexpr double kEndSeconds = 0.5; // the last frames after the script, so the clip ends on the result++double percentile(std::vector<double> v, double q) {+ if (v.empty()) return 0.0;+ std::sort(v.begin(), v.end());+ return v[std::min(v.size() - 1, size_t(q * double(v.size())))];+}++std::string fileStamp() {+ const std::time_t t = std::time(nullptr);+ char buf[32];+ std::strftime(buf, sizeof buf, "%Y%m%d-%H%M%S", std::localtime(&t));+ return buf;+}++} // namespace++struct TakeState {+ enum class Stage { Settle, Play, Ending, Done };+ Stage stage = Stage::Settle;+ std::string name, csvPath, videoPath, gpu, error;+ bool video = true, vsync = false;+ double settleStart = 0, playStart = 0, lastUpdate = 0, lastFrame = 0, endAt = 0;+ struct Frame {+ double t, ms;+ bool stroking;+ double lagMs = -1, lagPx = -1; // -1: no dab on screen to measure+ };+ std::vector<Frame> frames;+ // The stroke under way: the script's pointer samples, and the dabs placed (strokeProbe_).+ struct Sample {+ double t;+ glm::vec2 p;+ double s; // path length so far+ };+ std::vector<Sample> samples;+ std::vector<glm::vec2> dabs;+ size_t dabFrom = 0; // the sample the newest dab was last matched to (the stroke only moves forward)+ bool inStroke = false;+ std::string hud[3];+ BenchVideo writer;+};++bool App::startTake() {+ auto t = std::make_shared<TakeState>();+ demo_ = std::make_unique<Demo>(*this);+ std::string error;+ if (!demo_->loadTake(options_.benchmarkScript, error)) {+ std::fprintf(stderr, "%s\n", error.c_str());+ demo_.reset();+ return false;+ }+ const std::filesystem::path script(std::u8string(options_.benchmarkScript.begin(), options_.benchmarkScript.end()));+ t->name = script.filename().string();+ t->video = !options_.benchmarkNoVideo;+ t->vsync = options_.benchmarkVsync;+ // The video where --benchmark-video says, the CSV where --benchmark-out says or beside the video; else both in+ // the current folder, named after the take.+ auto u8 = [](const std::filesystem::path& x) {+ const auto s = x.u8string();+ return std::string(s.begin(), s.end());+ };+ const std::string base = u8(std::filesystem::current_path() / ("sculptforge-take-" + script.stem().string() + "-" + fileStamp()));+ t->videoPath = !options_.benchmarkVideo.empty() ? options_.benchmarkVideo : base + ".mp4";+ if (!options_.benchmarkOut.empty()) t->csvPath = options_.benchmarkOut;+ else if (!options_.benchmarkVideo.empty())+ t->csvPath = u8(std::filesystem::path(std::u8string(t->videoPath.begin(), t->videoPath.end())).replace_extension(".csv"));+ else t->csvPath = base + ".csv";+ t->settleStart = nowSeconds();+ demo_->pointerHook = [this](float x, float y) {+ TakeState& s = *take_;+ if (s.stage != TakeState::Stage::Play || drag_ != Drag::Stroke) return;+ if (!s.inStroke) { // a new stroke: measured from its own first sample+ s.inStroke = true;+ s.samples.clear();+ s.dabs.clear();+ s.dabFrom = 0;+ }+ const glm::vec2 q(x, y);+ s.samples.push_back({nowSeconds(), q, s.samples.empty() ? 0.0 : s.samples.back().s + double(glm::length(q - s.samples.back().p))});+ };+ take_ = t;+ SDL_Log("Benchmark take %s: video %s, CSV %s", t->name.c_str(), t->video ? t->videoPath.c_str() : "(none)", t->csvPath.c_str());+ return true;+}++bool App::takeRunning() const { return take_ && take_->stage != TakeState::Stage::Done; }++void App::takeBeforeFrame() {+ TakeState& t = *take_;+ const double now = nowSeconds();+ if (t.stage == TakeState::Stage::Settle) {+ if (t.gpu.empty()) {+ if (libraryBrowser_.open()) libraryBrowser_.toggle(); // the canvas clear (it opens at start-up)+ if (!t.vsync) SDL_GL_SetSwapInterval(0);+ t.gpu = reinterpret_cast<const char*>(gl::GetString(GL_RENDERER));+ }+ t.hud[0] = t.name + " - getting ready";+ const bool settled = now - t.settleStart > kSettleSeconds && !backgroundBusy() && !hardwareCalibrating();+ if (!settled && now - t.settleStart < kSettleGiveUp) return;+ if (!settled) SDL_Log("Benchmark take: still busy after %.0f s; starting anyway", kSettleGiveUp);+ t.stage = TakeState::Stage::Play;+ t.playStart = t.lastUpdate = t.lastFrame = now;+ strokeProbe_ = &t.dabs;+ }+ if (t.stage == TakeState::Stage::Play) {+ demo_->update(float(now - t.lastUpdate)); // the wall clock's time since the last frame, however long+ t.lastUpdate = now;+ if (demo_->finished() && !doc_.sculptor.strokeActive() && dabQueue_.empty()) {+ t.stage = TakeState::Stage::Ending;+ t.endAt = now + kEndSeconds;+ }+ }+ Demo::beginFrame(); // (the items the script finds are this frame's)+}++void App::takeBeforeSwap(int fbW, int fbH) {+ TakeState& t = *take_;+ using Stage = TakeState::Stage;+ if (t.stage == Stage::Settle || t.stage == Stage::Done) return;+ const double now = nowSeconds();+ if (const bool* keys = SDL_GetKeyboardState(nullptr); keys && keys[SDL_SCANCODE_ESCAPE] && t.stage == Stage::Play) {+ t.error = "Stopped with Esc: the take is partial";+ t.stage = Stage::Ending;+ t.endAt = now;+ }+ if (t.video) { // the frame about to be shown, HUD included+ const int w = fbW & ~1, h = fbH & ~1;+ if (!t.writer.running() && !t.writer.start(t.videoPath, w, h)) {+ t.error = "The video couldn't be recorded (ffmpeg missing?)";+ t.video = false;+ }+ t.writer.grab(now, w, h);+ }++ TakeState::Frame f{now - t.playStart, (now - t.lastFrame) * 1000.0, drag_ == Drag::Stroke};+ t.lastFrame = now;+ if (!f.stroking && !doc_.sculptor.strokeActive()) t.inStroke = false;+ // How far the stroke on screen (the newest dab) trails the pointer (the newest sample): the sample nearest the+ // dab, searched forward from the last match (a path that crosses itself never matches an older pass).+ if (t.inStroke && !t.dabs.empty() && !t.samples.empty()) {+ const glm::vec2 d = t.dabs.back();+ size_t best = t.samples.size() - 1;+ float bestDist = 1e30f;+ for (size_t i = t.samples.size(); i-- > t.dabFrom && t.samples.size() - i < 2000;) {+ const float dist = glm::length(t.samples[i].p - d);+ if (dist < bestDist) bestDist = dist, best = i;+ }+ t.dabFrom = best;+ f.lagMs = (now - t.samples[best].t) * 1000.0;+ f.lagPx = t.samples.back().s - t.samples[best].s;+ }+ t.frames.push_back(f);++ // The HUD: the last second's frames.+ std::vector<double> ms, lag;+ double span = 0;+ for (size_t i = t.frames.size(); i-- > 0 && span < 1000.0;) {+ span += t.frames[i].ms;+ ms.push_back(t.frames[i].ms);+ if (t.frames[i].lagMs >= 0) lag.push_back(t.frames[i].lagMs);+ }+ char buf[256];+ std::snprintf(buf, sizeof buf, "%s - %.1f s, real time", t.name.c_str(), f.t);+ t.hud[0] = buf;+ std::snprintf(buf, sizeof buf, "frame %.1f ms (p95 %.1f, slowest %.1f over the last second) %s", percentile(ms, 0.5),+ percentile(ms, 0.95), percentile(ms, 1.0), t.vsync ? "vsync on" : "vsync off");+ t.hud[1] = buf;+ if (!lag.empty()) std::snprintf(buf, sizeof buf, "stroke trails pointer %.0f ms / %.0f px %s", percentile(lag, 0.5), f.lagPx < 0 ? 0.0 : f.lagPx, t.gpu.c_str());+ else std::snprintf(buf, sizeof buf, "%s", t.gpu.c_str());+ t.hud[2] = buf;++ if (t.stage != Stage::Ending || now < t.endAt) return;+ // The end: the video closed, the CSV written, a summary, and the app quits.+ t.stage = Stage::Done;+ strokeProbe_ = nullptr;+ if (!t.vsync) SDL_GL_SetSwapInterval(1);+ if (t.writer.running() && !t.writer.finish()) t.error += (t.error.empty() ? "" : "; ") + std::string("the video couldn't be written");+ {+ std::ofstream csv(std::filesystem::path(std::u8string(t.csvPath.begin(), t.csvPath.end())));+ csv << "frame,t_s,frame_ms,stroking,lag_ms,lag_px\n";+ char line[160];+ for (size_t i = 0; i < t.frames.size(); ++i) {+ const TakeState::Frame& r = t.frames[i];+ std::snprintf(line, sizeof line, "%zu,%.4f,%.3f,%d,", i, r.t, r.ms, r.stroking ? 1 : 0);+ csv << line;+ if (r.lagMs >= 0) {+ std::snprintf(line, sizeof line, "%.2f,%.1f", r.lagMs, r.lagPx);+ csv << line;+ } else csv << ",";+ csv << "\n";+ }+ if (!csv) t.error += (t.error.empty() ? "" : "; ") + ("the CSV couldn't be written to " + t.csvPath);+ }+ ms.clear(), lag.clear(); // (the whole take now)+ double sum = 0;+ for (const TakeState::Frame& r : t.frames) {+ ms.push_back(r.ms);+ sum += r.ms;+ if (r.lagMs >= 0) lag.push_back(r.lagMs);+ }+ const double wall = now - t.playStart;+ std::printf("Take %s: %zu frames in %.2f s (script clock %.2f s; frame times add up to %.1f%% of the wall clock)\n",+ t.name.c_str(), t.frames.size(), wall, double(demo_->clock()), wall > 0 ? 100.0 * sum / 1000.0 / wall : 0.0);+ std::printf(" frame p50 %.1f ms, p95 %.1f, p99 %.1f, slowest %.1f\n", percentile(ms, 0.5), percentile(ms, 0.95),+ percentile(ms, 0.99), percentile(ms, 1.0));+ if (!lag.empty())+ std::printf(" stroke trails pointer p50 %.0f ms, p95 %.0f ms (%zu frames)\n", percentile(lag, 0.5), percentile(lag, 0.95), lag.size());+ std::printf("CSV: %s%s%s\n", t.csvPath.c_str(), t.video ? "\nVideo: " : "", t.video ? t.videoPath.c_str() : "");+ for (const std::string& failure : demo_->failures()) std::fprintf(stderr, "FAIL %s\n", failure.c_str());+ if (!t.error.empty()) std::fprintf(stderr, "Take: %s\n", t.error.c_str());+ std::fflush(stdout);+ takeExitCode_ = t.error.empty() && demo_->failures().empty() ? 0 : 1;+ running_ = false;+}++void App::drawTakeHud() {+ TakeState& t = *take_;+ if (t.stage == TakeState::Stage::Done) return;+ // Top left of the canvas, as proof mode's (burned into the video: it is part of the frame).+ const float sc = uiScale_;+ const CanvasRect c = canvasRect();+ ImDrawList* dl = ImGui::GetForegroundDrawList();+ ImFont* font = ImGui::GetFont();+ const float bigSize = ImGui::GetFontSize() * 1.35f, smallSize = ImGui::GetFontSize() * 1.05f;+ const ImVec2 at(c.x + 14 * sc, c.y + 14 * sc);+ const std::string brand = std::string("SculptForge ") + SCULPTFORGE_VERSION + " (" + SF_GIT_COMMIT + ") - benchmark take";+ const char* lines[] = {brand.c_str(), t.hud[0].c_str(), t.hud[1].c_str(), t.hud[2].c_str()};+ float w = 0, h = 0;+ for (int i = 0; i < 4; ++i) {+ const ImVec2 s = font->CalcTextSizeA(i == 1 ? bigSize : smallSize, 1e9f, 0.0f, lines[i]);+ w = std::max(w, s.x);+ h += s.y + 3 * sc;+ }+ dl->AddRectFilled(ImVec2(at.x - 10 * sc, at.y - 8 * sc), ImVec2(at.x + w + 10 * sc, at.y + h + 6 * sc), IM_COL32(12, 12, 14, 215), 6 * sc);+ float y = at.y;+ for (int i = 0; i < 4; ++i) {+ const float size = i == 1 ? bigSize : smallSize;+ dl->AddText(font, size, ImVec2(at.x, y), i == 0 ? theme::u32(theme::textDim) : i == 1 ? theme::u32(theme::textBright) : theme::u32(theme::text), lines[i]);+ y += font->CalcTextSizeA(size, 1e9f, 0.0f, lines[i]).y + 3 * sc;+ }+ if (t.stage != TakeState::Stage::Settle) demo_->drawOverlay(); // the script's pointer, as a demo video shows it+}++} // namespace sfdiff --git a/src/app/BenchVideo.cpp b/src/app/BenchVideo.cppnew file mode 100644index 00000000..d6e371c8--- /dev/null+++ b/src/app/BenchVideo.cpp@@ -0,0 +1,149 @@+// SculptForge - open source digital sculpting+// SPDX-License-Identifier: GPL-3.0-or-later+#include "app/BenchVideo.h"++#include "app/ShellQuote.h"++#include <algorithm>+#include <cstring>++namespace sf {++namespace {+constexpr GLenum kPixelPackBuffer = 0x88EB, kStreamRead = 0x88E1, kMapReadBit = 0x0001;+}++bool BenchVideo::start(const std::string& path, int w, int h) {+ w_ = w, h_ = h;+ // Bottom-up rows from glReadPixels: flipped; scaled to at most 1920 wide to keep the encoder light.+ const std::string quoted = shellQuote(path); // (never a shell-active file name)+ if (quoted.empty()) return false;+ const std::string cmd = "ffmpeg -loglevel error -y -f rawvideo -pix_fmt rgba -s " + std::to_string(w) + "x" ++ std::to_string(h) + " -r " + std::to_string(kFps) ++ " -i - -vf \"vflip,scale='min(1920,iw)':-2\" -c:v libx264 -preset veryfast -crf 20 "+ "-pix_fmt yuv420p -movflags +faststart " + quoted;+#if defined(_WIN32)+ ff_ = _popen(cmd.c_str(), "wb");+#else+ ff_ = popen(cmd.c_str(), "w");+#endif+ if (!ff_) return false;+ thread_ = std::thread([this] { loop(); });+ gl::GenBuffers(3, pbo_);+ for (GLuint b : pbo_) {+ gl::BindBuffer(kPixelPackBuffer, b);+ gl::BufferData(kPixelPackBuffer, GLsizeiptr(size_t(w) * size_t(h) * 4), nullptr, kStreamRead);+ }+ gl::BindBuffer(kPixelPackBuffer, 0);+ return true;+}++void BenchVideo::grab(double t, int w, int h) {+ if (!ff_ || w != w_ || h != h_) return;+ const int slot = pboNext_;+ if (pboFilled_ >= 3) { // the oldest read is done by now: hand it to the encoder+ gl::BindBuffer(kPixelPackBuffer, pbo_[slot]);+ if (const void* data = gl::MapBufferRange(kPixelPackBuffer, 0, GLsizeiptr(size_t(w) * size_t(h) * 4), kMapReadBit)) {+ std::vector<uint8_t> rgba(size_t(w) * size_t(h) * 4);+ std::memcpy(rgba.data(), data, rgba.size());+ gl::UnmapBuffer(kPixelPackBuffer);+ push(pboTime_[slot], std::move(rgba));+ }+ }+ gl::BindFramebuffer(GL_READ_FRAMEBUFFER, 0);+ gl::BindBuffer(kPixelPackBuffer, pbo_[slot]);+ gl::PixelStorei(GL_PACK_ALIGNMENT, 1);+ gl::ReadPixels(0, 0, w, h, GL_RGBA, GL_UNSIGNED_BYTE, nullptr);+ gl::BindBuffer(kPixelPackBuffer, 0);+ pboTime_[slot] = t;+ pboNext_ = (slot + 1) % 3;+ pboFilled_ = std::min(pboFilled_ + 1, 3);+}++// Takes the frame shown at `t` (seconds); drops it when the encoder is behind (or, `wait`, waits for it).+void BenchVideo::push(double t, std::vector<uint8_t>&& rgba, bool wait) {+ std::unique_lock<std::mutex> lock(m_);+ if (wait) cv_.wait(lock, [&] { return queue_.size() < 4; });+ else if (queue_.size() >= 4) return;+ queue_.push_back({t, std::move(rgba)});+ cv_.notify_all();+}++bool BenchVideo::finish() {+ if (!ff_) return false;+ // The frames still in the ring, oldest first: the video runs to the last frame shown.+ const size_t bytes = size_t(w_) * size_t(h_) * 4;+ for (int k = 0; k < pboFilled_; ++k) {+ const int slot = (pboNext_ - pboFilled_ + k + 3) % 3;+ gl::BindBuffer(kPixelPackBuffer, pbo_[slot]);+ if (const void* data = gl::MapBufferRange(kPixelPackBuffer, 0, GLsizeiptr(bytes), kMapReadBit)) {+ std::vector<uint8_t> rgba(bytes);+ std::memcpy(rgba.data(), data, bytes);+ gl::UnmapBuffer(kPixelPackBuffer);+ push(pboTime_[slot], std::move(rgba), true);+ }+ }+ gl::BindBuffer(kPixelPackBuffer, 0);+ pboFilled_ = 0;+ {+ std::lock_guard<std::mutex> lock(m_);+ stop_ = true;+ cv_.notify_all();+ }+ thread_.join();+#if defined(_WIN32)+ const int status = _pclose(ff_);+#else+ const int status = pclose(ff_);+#endif+ ff_ = nullptr;+ gl::DeleteBuffers(3, pbo_);+ return status == 0 && written_ > 0;+}++BenchVideo::~BenchVideo() {+ if (!ff_) return;+ { // (no GL here: the context may be gone; the buffers go with it)+ std::lock_guard<std::mutex> lock(m_);+ stop_ = true;+ cv_.notify_all();+ }+ thread_.join();+#if defined(_WIN32)+ _pclose(ff_);+#else+ pclose(ff_);+#endif+}++// Frames to ffmpeg at a constant rate (frames repeat while the app is slower).+void BenchVideo::loop() {+ std::vector<uint8_t> last;+ double next = -1.0;+ for (;;) {+ std::pair<double, std::vector<uint8_t>> f;+ {+ std::unique_lock<std::mutex> lock(m_);+ cv_.wait(lock, [&] { return stop_ || !queue_.empty(); });+ if (queue_.empty()) break;+ f = std::move(queue_.front());+ queue_.pop_front();+ cv_.notify_all(); // (a waiting push)+ }+ if (next < 0) next = f.first;+ // Slots up to this frame's time show the previous frame; then this one.+ while (!last.empty() && next + 1.0 / kFps <= f.first) {+ std::fwrite(last.data(), 1, last.size(), ff_);+ ++written_;+ next += 1.0 / kFps;+ }+ if (next <= f.first + 1e-9 || last.empty()) {+ std::fwrite(f.second.data(), 1, f.second.size(), ff_);+ ++written_;+ next += 1.0 / kFps;+ }+ last = std::move(f.second);+ }+}++} // namespace sfdiff --git a/src/app/BenchVideo.h b/src/app/BenchVideo.hnew file mode 100644index 00000000..8114cd32--- /dev/null+++ b/src/app/BenchVideo.h@@ -0,0 +1,52 @@+// SculptForge - open source digital sculpting+// SPDX-License-Identifier: GPL-3.0-or-later+//+// The benchmark video (proof mode, ProofMode.cpp; benchmark takes, BenchTake.cpp): each frame about to be shown is+// read back asynchronously through a ring of pixel buffers and handed to ffmpeg on a thread of its own, which+// writes a constant 30 fps in real time (a frame repeats while the app is slower; frames drop when the encoder is+// behind). The HUD is part of the frame, so it is in the video.+#pragma once++#include "render/GL.h"++#include <condition_variable>+#include <cstdint>+#include <cstdio>+#include <deque>+#include <mutex>+#include <string>+#include <thread>+#include <utility>+#include <vector>++namespace sf {++class BenchVideo {+public:+ static constexpr int kFps = 30;+ // Starts ffmpeg for frames of w x h (even sizes); false when it can't (ffmpeg missing, a shell-active name).+ bool start(const std::string& path, int w, int h);+ // The default framebuffer, about to be shown at `t` (seconds): read into the ring; the oldest read goes to the+ // encoder. A frame of another size than start's is skipped.+ void grab(double t, int w, int h);+ bool finish(); // the frames still being read included; false when nothing was written or ffmpeg failed+ bool running() const { return ff_ != nullptr; }+ ~BenchVideo();++private:+ void push(double t, std::vector<uint8_t>&& rgba, bool wait = false);+ void loop();+ FILE* ff_ = nullptr;+ int w_ = 0, h_ = 0;+ std::thread thread_;+ std::mutex m_;+ std::condition_variable cv_;+ std::deque<std::pair<double, std::vector<uint8_t>>> queue_;+ bool stop_ = false;+ long written_ = 0;+ GLuint pbo_[3] = {0, 0, 0};+ double pboTime_[3] = {0, 0, 0};+ int pboNext_ = 0, pboFilled_ = 0;+};++} // namespace sfdiff --git a/src/app/Demo.cpp b/src/app/Demo.cppindex ef20df7c..8a206939 100644--- a/src/app/Demo.cpp+++ b/src/app/Demo.cpp@@ -258,6 +258,7 @@ void Demo::mouseMotion(float x, float y, SDL_MouseID which) {e.motion.state = buttonDown_ ? SDL_BUTTON_LMASK : 0;mouse_ = ImVec2(x, y);app_.handleEvent(e);+ if (pointerHook) pointerHook(x, y);}void Demo::mouseButton(bool down, int button, SDL_MouseID which, int clicks) {@@ -441,6 +442,7 @@ void Demo::click(const std::string& label) {void Demo::stroke(std::function<ImVec2(float u)> path, float seconds, bool invert, bool hold) {// Glide to the start, press, follow the path, release.auto started = std::make_shared<bool>(false);+ auto sent = std::make_shared<float>(0.0f); // a take: the stroke's time its last pointer sample was sent atauto from = std::make_shared<ImVec2>();steps_.push_back([this, path, from](float t) {const ImVec2 p = path(0.0f);@@ -449,11 +451,20 @@ void Demo::stroke(std::function<ImVec2(float u)> path, float seconds, bool invermouseMotion(from->x + (p.x - from->x) * u, from->y + (p.y - from->y) * u);return t >= 0.35f;});- steps_.push_back([this, path, seconds, invert, hold, started](float t) {+ steps_.push_back([this, path, seconds, invert, hold, started, sent](float t) {if (!*started) {app_.invertToggle_ = invert;mouseButton(true, SDL_BUTTON_LEFT);*started = true;+ *sent = 0.0f;+ }+ if (take_) { // a take (real time): the samples since the last frame, 240 a second, as a tablet sends them+ constexpr float kHz = 240.0f;+ for (float s = (std::floor(*sent * kHz) + 1.0f) / kHz; s < std::min(t, seconds); s += 1.0f / kHz) {+ const ImVec2 q = path(s / seconds);+ mouseMotion(q.x, q.y);+ }+ *sent = t;}const ImVec2 p = path(std::min(t / seconds, 1.0f));mouseMotion(p.x, p.y);diff --git a/src/app/Demo.h b/src/app/Demo.hindex fee846b3..0c8667b3 100644--- a/src/app/Demo.h+++ b/src/app/Demo.h@@ -60,6 +60,13 @@ public:// UI tests (UiTest.cpp). Steps that fail stop the run; failures() lists why.bool loadScript(const std::string& path, std::string& error);+ // A benchmark take (sculptforge --benchmark-script, BenchTake.cpp): the script played in real time in the+ // interactive loop. Only the steps a person could do in real time load: shots and expectations are skipped with a+ // warning, steps that run commands or read other files (run, env, drop, choose_file, restart...) are refused.+ // `stroke` sends its pointer samples at 240 a second (each frame: those since the last), as a tablet does.+ bool loadTake(const std::string& path, std::string& error);+ // Called with every pointer position the script sends (after the app has handled it): the take's stroke lag.+ std::function<void(float x, float y)> pointerHook;bool testing() const { return testing_; }const std::vector<std::string>& failures() const { return failures_; }int stepsRun() const { return int(step_); }@@ -171,6 +178,7 @@ private:ImVec2 viewCenter(const View& v) const;bool testing_ = false;+ bool take_ = false; // loadTake: real-time pointer samples, no shots or expectationsstd::vector<std::string> failures_;std::string frameText_, shotRequest_, shotDir_, scriptName_, lineText_;std::vector<uint8_t> lastShot_;diff --git a/src/app/PanelProject.cpp b/src/app/PanelProject.cppindex edd2ad41..4e920946 100644--- a/src/app/PanelProject.cpp+++ b/src/app/PanelProject.cpp@@ -165,7 +165,8 @@ void App::initProject() {#if SF_UPDATE_CHECKconst int64_t now = std::chrono::duration_cast<std::chrono::seconds>(std::chrono::system_clock::now().time_since_epoch()).count();applyUpdatePolicy();- if (checkUpdates_ && options_.uiTest.empty() && !std::getenv("SF_NO_UPDATE_CHECK") && updateCheckDue(updateCheckedAt_, now))+ if (checkUpdates_ && options_.uiTest.empty() && options_.benchmarkScript.empty() && // (a take: local only)+ !std::getenv("SF_NO_UPDATE_CHECK") && updateCheckDue(updateCheckedAt_, now))startUpdateCheck(false);#endifdiff --git a/src/app/PanelTimeline.cpp b/src/app/PanelTimeline.cppindex ff937aac..c16c911d 100644--- a/src/app/PanelTimeline.cpp+++ b/src/app/PanelTimeline.cpp@@ -325,6 +325,7 @@ void App::drawTimelineUi() {Timeline::historyDocument = &doc_;}if (proof_) drawProofUi();+ if (take_) drawTakeHud(); // (BenchTake.cpp)// Keep a timeline on the active Part's history (each Part's travels with its undo stack).Timeline* t = Timeline::of(doc_.undo);if (!t && s.record) t = Timeline::attach(doc_).get();diff --git a/src/app/ProofMode.cpp b/src/app/ProofMode.cppindex 9f889f5d..c4e6bcf3 100644--- a/src/app/ProofMode.cpp+++ b/src/app/ProofMode.cpp@@ -11,7 +11,7 @@// in milliseconds from the pointer sample the newest drawn dab belongs to until the frame showing it is handed// to the display (SwapWindow; the display's own scan-out and the compositor come on top). A HUD shows the// numbers live; the frames go, HUD included, to an MP4 (read back through pixel buffers, encoded by ffmpeg on-// its own thread), and a JSON result with the hardware and version is written at the end.+// its own thread: BenchVideo.h), and a JSON result with the hardware and version is written at the end.#include "app/ProofMode.h"#include "core/Precision.h"@@ -20,7 +20,7 @@#include "core/Micro.h"#include "app/App.h"-#include "app/ShellQuote.h"+#include "app/BenchVideo.h"#include "app/Theme.h"#include "core/Benchmark.h"@@ -35,15 +35,12 @@#include <algorithm>#include <chrono>#include <cmath>-#include <condition_variable>#include <cstdio>#include <cstdlib>#include <cstring>#include <ctime>-#include <deque>#include <filesystem>#include <fstream>-#include <mutex>#include <sstream>#include <thread>@@ -226,9 +223,7 @@ namespace {using Clock = std::chrono::steady_clock;double nowSeconds() { return std::chrono::duration<double>(Clock::now().time_since_epoch()).count(); }-constexpr GLenum kPixelPackBuffer = 0x88EB, kStreamRead = 0x88E1, kMapReadBit = 0x0001;constexpr double kPointerHz = 240.0;-constexpr int kVideoFps = 30;struct Percentiles {double p50 = 0, p95 = 0, p99 = 0, max = 0, mean = 0;@@ -260,95 +255,6 @@ Json percentilesJson(const Percentiles& p) {return j;}-// Frames to ffmpeg on a thread of its own, at a constant rate (frames repeat while the app is slower).-class VideoWriter {-public:- bool start(const std::string& path, int w, int h) {- w_ = w, h_ = h;- // Bottom-up rows from glReadPixels: flipped; scaled to at most 1920 wide to keep the encoder light.- const std::string quoted = shellQuote(path); // (never a shell-active file name)- if (quoted.empty()) return false;- const std::string cmd = "ffmpeg -loglevel error -y -f rawvideo -pix_fmt rgba -s " + std::to_string(w) + "x" +- std::to_string(h) + " -r " + std::to_string(kVideoFps) +- " -i - -vf \"vflip,scale='min(1920,iw)':-2\" -c:v libx264 -preset veryfast -crf 20 "- "-pix_fmt yuv420p -movflags +faststart " + quoted;-#if defined(_WIN32)- ff_ = _popen(cmd.c_str(), "wb");-#else- ff_ = popen(cmd.c_str(), "w");-#endif- if (!ff_) return false;- thread_ = std::thread([this] { loop(); });- return true;- }- // Takes the frame shown at `t` (seconds); drops it when the encoder is behind.- void push(double t, std::vector<uint8_t>&& rgba) {- std::lock_guard<std::mutex> lock(m_);- if (queue_.size() >= 4) return;- queue_.push_back({t, std::move(rgba)});- cv_.notify_one();- }- bool finish() {- if (!ff_) return false;- {- std::lock_guard<std::mutex> lock(m_);- stop_ = true;- cv_.notify_one();- }- thread_.join();-#if defined(_WIN32)- const int status = _pclose(ff_);-#else- const int status = pclose(ff_);-#endif- ff_ = nullptr;- return status == 0 && written_ > 0;- }- int width() const { return w_; }- int height() const { return h_; }- bool running() const { return ff_ != nullptr; }- ~VideoWriter() {- if (ff_) finish();- }--private:- void loop() {- std::vector<uint8_t> last;- double next = -1.0;- for (;;) {- std::pair<double, std::vector<uint8_t>> f;- {- std::unique_lock<std::mutex> lock(m_);- cv_.wait(lock, [&] { return stop_ || !queue_.empty(); });- if (queue_.empty()) break;- f = std::move(queue_.front());- queue_.pop_front();- }- if (next < 0) next = f.first;- // Slots up to this frame's time show the previous frame; then this one.- while (!last.empty() && next + 1.0 / kVideoFps <= f.first) {- std::fwrite(last.data(), 1, last.size(), ff_);- ++written_;- next += 1.0 / kVideoFps;- }- if (next <= f.first + 1e-9 || last.empty()) {- std::fwrite(f.second.data(), 1, f.second.size(), ff_);- ++written_;- next += 1.0 / kVideoFps;- }- last = std::move(f.second);- }- }- FILE* ff_ = nullptr;- int w_ = 0, h_ = 0;- std::thread thread_;- std::mutex m_;- std::condition_variable cv_;- std::deque<std::pair<double, std::vector<uint8_t>>> queue_;- bool stop_ = false;- long written_ = 0;-};-struct PhaseSpec {const char* name;float radiusPx; // 0 = an orbit, no stroke@@ -463,10 +369,7 @@ struct ProofState {std::string hudTitle, hudLine2, hudLine3;std::string error;// Video- VideoWriter writer;- GLuint pbo[3] = {0, 0, 0};- double pboTime[3] = {0, 0, 0};- int pboW = 0, pboH = 0, pboNext = 0, pboFilled = 0;+ BenchVideo writer;Json hardware;std::string gpu;bool written = false;@@ -740,40 +643,11 @@ void App::proofBeforeSwap(int fbW, int fbH) {// The frame about to be shown: into the video (asynchronously, through a ring of pixel buffers).if (p.video && p.stage != Stage::Announce && p.stage != Stage::Build) {const int w = fbW & ~1, h = fbH & ~1;- if (!p.writer.running() && p.error.find("video") == std::string::npos) {- if (p.writer.start(p.videoPath, w, h)) {- p.pboW = w, p.pboH = h;- gl::GenBuffers(3, p.pbo);- for (GLuint b : p.pbo) {- gl::BindBuffer(kPixelPackBuffer, b);- gl::BufferData(kPixelPackBuffer, GLsizeiptr(size_t(w) * size_t(h) * 4), nullptr, kStreamRead);- }- gl::BindBuffer(kPixelPackBuffer, 0);- } else {- p.error = "The video couldn't be recorded (ffmpeg missing?)";- p.video = false;- }- }- if (p.writer.running() && w == p.pboW && h == p.pboH) {- const int slot = p.pboNext;- if (p.pboFilled >= 3) { // the oldest read is done by now: hand it to the encoder- gl::BindBuffer(kPixelPackBuffer, p.pbo[slot]);- if (const void* data = gl::MapBufferRange(kPixelPackBuffer, 0, GLsizeiptr(size_t(w) * size_t(h) * 4), kMapReadBit)) {- std::vector<uint8_t> rgba(size_t(w) * size_t(h) * 4);- std::memcpy(rgba.data(), data, rgba.size());- gl::UnmapBuffer(kPixelPackBuffer);- p.writer.push(p.pboTime[slot], std::move(rgba));- }- }- gl::BindFramebuffer(GL_READ_FRAMEBUFFER, 0);- gl::BindBuffer(kPixelPackBuffer, p.pbo[slot]);- gl::PixelStorei(GL_PACK_ALIGNMENT, 1);- gl::ReadPixels(0, 0, w, h, GL_RGBA, GL_UNSIGNED_BYTE, nullptr);- gl::BindBuffer(kPixelPackBuffer, 0);- p.pboTime[slot] = now;- p.pboNext = (slot + 1) % 3;- p.pboFilled = std::min(p.pboFilled + 1, 3);+ if (!p.writer.running() && p.error.find("video") == std::string::npos && !p.writer.start(p.videoPath, w, h)) {+ p.error = "The video couldn't be recorded (ffmpeg missing?)";+ p.video = false;}+ p.writer.grab(now, w, h);}const double frameMs = (now - p.lastFrame) * 1000.0;@@ -1047,7 +921,6 @@ void App::proofBeforeSwap(int fbW, int fbH) {if (!p.vsync) SDL_GL_SetSwapInterval(1);if (p.writer.running()) {if (!p.writer.finish()) p.error += (p.error.empty() ? "" : "; ") + std::string("the video couldn't be written");- gl::DeleteBuffers(3, p.pbo);}Json root = Json::object();root.set("schema", "sculptforge-benchmark/1");diff --git a/src/app/UiTest.cpp b/src/app/UiTest.cppindex c1bc0541..340094b2 100644--- a/src/app/UiTest.cpp+++ b/src/app/UiTest.cpp@@ -2141,6 +2141,17 @@ bool Demo::parseStep(int line, const std::vector<std::string>& w, std::string& eat += scriptDir_.size();}if (!parseScript(text, statements, error)) return false;+ if (take_) { // a take: only commands that set up the scene (no files, no jobs that aren't the take's own)+ static const std::set<std::string> setup = {+ "new_sphere", "new_plane", "new_head", "new_bench_sphere", "new_starter_mesh", "ui_look", "subdivide",+ "subdiv_divide", "subdiv_level", "dyntopo", "set_color", "set_material", "set_shading", "viewport_shading",+ "mask_clear", "mask_rect", "part_select", "part_visibility", "transform", "layer_set_weight", "undo", "redo"};+ for (const auto& st : statements)+ if (!setup.count(st.command)) {+ error = "'run " + st.command + "' can't be used in a benchmark take (only the scene's set-up commands)";+ return false;+ }+ }// A command that works on a worker (uv_auto: App::commandRunning) holds the script, frames still drawing,// until its result is in, like the console and an AI tool wait for it.auto next = std::make_shared<size_t>(0);@@ -2977,6 +2988,11 @@ void Demo::testKeyNow(SDL_Keycode key, SDL_Keymod mods) {app_.handleEvent(e);}+bool Demo::loadTake(const std::string& path, std::string& error) {+ take_ = true;+ return loadScript(path, error);+}+bool Demo::loadScript(const std::string& path, std::string& error) {std::ifstream f(std::filesystem::path(std::u8string(path.begin(), path.end())));if (!f) {@@ -3008,6 +3024,27 @@ bool Demo::loadScript(const std::string& path, std::string& error) {auto words = splitWords(line);if (words.empty()) continue;lineText_ = line;+ if (take_) { // a benchmark take: only what a person does in real time+ const std::string& verb = words[0];+ static const std::set<std::string> skipped = {"shot", "snapshot", "remember", "print", "dump_shortcuts"};+ if (skipped.count(verb) || verb.rfind("expect", 0) == 0) {+ SDL_Log("%s:%d: '%s' skipped (a take checks and shoots nothing)", scriptName_.c_str(), n, verb.c_str());+ continue;+ }+ static const std::set<std::string> allowed = {+ "click", "double_click", "right_click", "hover", "hover_model", "hover_window", "type", "key", "key_down",+ "key_up", "hold", "stroke", "view_drag", "axis_click", "axis_hover", "axis_drag", "view_figure_click",+ "click_part", "drag", "button_drag", "drag_landmark", "gizmo_hover", "gizmo_drag", "stroke_popup_item",+ "drag_item", "drag_path", "release", "orbit", "camera", "zoom", "camera_distance", "brush_size", "look",+ "run", "wait", "wait_idle", "wait_for", "wait_value", "pen_stroke", "pen_drag_item", "pen_button", "pen_hover",+ "pen_enter", "pen_drag", "pen_pressure", "pen_new", "pen_out", "pen_rest", "wheel", "mouse_move",+ "touch_stroke", "touch_pinch", "classic_keys", "input_style"};+ if (!allowed.count(verb)) {+ error = scriptName_ + ":" + std::to_string(n) + ": '" + verb ++ "' can't be used in a benchmark take (only input, the camera and waits play in real time)";+ return false;+ }+ }std::string err;if (!parseStep(n, words, err)) {error = scriptName_ + ":" + std::to_string(n) + ": " + err;diff --git a/src/app/main.cpp b/src/app/main.cppindex 9da645d8..3781eae5 100644--- a/src/app/main.cpp+++ b/src/app/main.cpp@@ -88,6 +88,9 @@ void usage() {" --benchmark core-200m Research: a 200 million micro triangle head in memory (open, strokes, orbit)\n"" --benchmark core-100m The same at 100 million micro triangles\n"" --benchmark-file PATH Open the project PATH, then the same strokes and orbit\n"+ " --benchmark-script T.sfui Play a take (a UI test script's strokes, orbits, keys and waits) in real time\n"+ " with the HUD; writes an MP4 and a per-frame CSV (frame ms, stroke lag) and exits.\n"+ " A project to open goes after it: --benchmark-script take.sfui head.sfproj\n"" --focus-detail FILE Experimental: open a Focus Detail file (.sfdetail)\n"" --benchmark-sizes 5,20 Proof mode mesh sizes in millions of triangles\n"" --benchmark-out FILE Where the JSON result goes (default: sculptforge-benchmark-<time>.json here)\n"@@ -243,6 +246,10 @@ static int runMain(int argc, char** argv) {options.benchmark = true;options.benchmarkScene = "file:" + next();}+ else if (a == "--benchmark-script") { // a take in real time (BenchTake.cpp)+ options.benchmark = true;+ options.benchmarkScript = next();+ }else if (a == "--benchmark-sizes") options.benchmarkSizes = next();else if (a == "--benchmark-out") options.benchmarkOut = next();else if (a == "--benchmark-video") options.benchmarkVideo = next();diff --git a/tests/takes/check_take.py b/tests/takes/check_take.pynew file mode 100755index 00000000..2aff86d8--- /dev/null+++ b/tests/takes/check_take.py@@ -0,0 +1,73 @@+#!/usr/bin/env python3+# bench_take_sphere: plays tests/takes/sphere.sfui with sculptforge --benchmark-script and checks what comes out. The+# CSV has a row per frame, strokes with their lag; the take ran in real time (at least as long as its script, and its+# frame times add up to its wall clock within 5%); the video is as long as the take within 5% (ffprobe, when there).+# check_take.py APP TAKE OUT_DIR [--min-seconds S]+import argparse, csv, os, shutil, subprocess, sys, time++ap = argparse.ArgumentParser()+ap.add_argument("app")+ap.add_argument("take")+ap.add_argument("out")+ap.add_argument("--min-seconds", type=float, default=4.5)+a = ap.parse_args()+os.makedirs(a.out, exist_ok=True)+video, table = os.path.join(a.out, "take.mp4"), os.path.join(a.out, "take.csv")+for f in (video, table):+ if os.path.exists(f):+ os.remove(f)+ffmpeg = shutil.which("ffmpeg") is not None+cmd = [a.app, "--benchmark-script", a.take, "--size", "1280x720", "--benchmark-out", table]+cmd += ["--benchmark-video", video] if ffmpeg else ["--benchmark-no-video"]+env = dict(os.environ, SF_NO_UPDATE_CHECK="1")+start = time.monotonic()+run = subprocess.run(cmd, env=env, capture_output=True, text=True, timeout=240)+elapsed = time.monotonic() - start+print(run.stdout, end="")+fails = []+if run.returncode != 0:+ fails.append(f"exit code {run.returncode}:\n{run.stderr[-3000:]}")+if "skipped (a take checks and shoots nothing)" not in run.stderr + run.stdout:+ fails.append("the shot and expectation weren't reported as skipped")+rows = []+if os.path.exists(table):+ with open(table, newline="") as f:+ r = csv.DictReader(f)+ if r.fieldnames != ["frame", "t_s", "frame_ms", "stroking", "lag_ms", "lag_px"]:+ fails.append(f"CSV columns {r.fieldnames}")+ rows = list(r)+else:+ fails.append("no CSV")+if rows:+ wall = float(rows[-1]["t_s"])+ total = sum(float(x["frame_ms"]) for x in rows) / 1000.0+ lagged = [float(x["lag_ms"]) for x in rows if x["lag_ms"]]+ stroking = sum(1 for x in rows if x["stroking"] == "1")+ print(f"{len(rows)} frames, {wall:.2f} s (process {elapsed:.1f} s), frame times {total:.2f} s, "+ f"{stroking} stroking, {len(lagged)} with lag")+ if wall < a.min_seconds:+ fails.append(f"the take took {wall:.2f} s, under its script's {a.min_seconds} s: not real time")+ if wall > elapsed:+ fails.append(f"the take's clock ({wall:.2f} s) ran past the process's ({elapsed:.2f} s)")+ if abs(total - wall) > 0.05 * wall:+ fails.append(f"frame times add up to {total:.2f} s, the wall clock {wall:.2f} s (more than 5% apart)")+ if stroking < 5 or len(lagged) < 3:+ fails.append(f"too few stroke frames ({stroking}) or lag samples ({len(lagged)})")+ if any(l < 0 or l > 60000 for l in lagged):+ fails.append("a lag out of range")+ if ffmpeg:+ if not os.path.exists(video) or os.path.getsize(video) == 0:+ fails.append("no video")+ elif shutil.which("ffprobe"):+ probe = subprocess.run(["ffprobe", "-v", "error", "-show_entries", "format=duration", "-of", "csv=p=0", video],+ capture_output=True, text=True)+ try:+ length = float(probe.stdout.strip())+ print(f"video {length:.2f} s")+ if abs(length - wall) > 0.05 * wall:+ fails.append(f"the video is {length:.2f} s, the take {wall:.2f} s (more than 5% apart)")+ except ValueError:+ fails.append(f"ffprobe: {probe.stderr.strip()}")+for f in fails:+ print("FAIL", f)+sys.exit(1 if fails else 0)diff --git a/tests/takes/sphere.sfui b/tests/takes/sphere.sfuinew file mode 100644index 00000000..d1dfc33b--- /dev/null+++ b/tests/takes/sphere.sfui@@ -0,0 +1,12 @@+# A short benchmark take on a sphere (sculptforge --benchmark-script; test bench_take_sphere): two strokes and an+# orbit, played in real time. The shot and the expectation are skipped (a take checks and shoots nothing).+run new_sphere subdivisions=5+camera 0 0+wait 0.3+stroke 0.3 0.4 0.7 0.6 1.5+wait 0.3+orbit 300 0+stroke 0.3 0.6 0.7 0.4 1.0+shot skipped_in_a_take+expect_value moved > 0+wait 0.3