diff --git a/psprecomp/ARCHITECTURE.md b/psprecomp/ARCHITECTURE.md
index a828b37..a69043b 100644
--- a/psprecomp/ARCHITECTURE.md
+++ b/psprecomp/ARCHITECTURE.md
@@ -163,6 +163,7 @@ All under `runtime/` (headers in `runtime/include/`, sources in `runtime/src/`):
| HLE | `src/hle/psp_hle_*.cpp` | Firmware NID implementations: io, kernel (thread/sema/mutex/lwmutex/eventflag/memory), display, ge, ctrl, power, utility, adhoc (own row below); `sceUtilitySavedata` is PPSSPP-compatible: `psp_savedata_crypto.{h,cpp}` (sceChnnlsv/KIRK CMD4/7 AES scheme, per-file MAC in `SAVEDATA_FILE_LIST`, `SAVEDATA_PARAMS` signing) and `psp_savedata_dialog.{h,cpp}` (LISTLOAD/LISTSAVE list state machine + software-rendered overlay laid out in 480x272 design units but rasterised at an integer scale (1..4, `set_output_scale` set by `present_blit` from the output size) with FreeType text from OFL fonts embedded at build time (`assets/fonts`, `assets/embed_fonts.cmake`; Cinzel + Crimson Text) as the generic look, or, when a game module installs an `SdTheme` (`set_theme` / `set_theme_provider`: background image, 9-slice/mirrored-cap sprites for tab, selection bar, normal bar, corner ornaments, cursor, button glyphs, colours, optional TTF for body text; sprite pixels map 1:1 to design units and are bilinear-scaled by the canvas scale), the same layout drawn from that game's own UI textures — the Dissidia module builds one lazily from `menu/en/menu_lpk_label_gim_0.bin` + `menu/menu_pk_label_gim_0.bin` (`games/dissidia/runtime/savedata_theme.cpp`, `gim_decode.{h,cpp}`, read through `read_asset` so loose-file mods restyle it; `PSPRECOMP_SDTHEME=0` disables), ICON0.PNG/PARAM.SFO/size shown per row, blitted by `present_dialog_overlay` in `psp_ge_draw.cpp`; `PSPRECOMP_SAVEDATA_AUTO=1` keeps the headless auto-select); the list has a Triangle key opening **Manage saves** (`psp_savemgr_ui.{h,cpp}`: import / export of PSP save folders from PPSSPP, memory sticks or a typed path, with region retargeting + re-signing and `.bak` backups outside `SAVEDATA`; the copy logic is `psp_savemgr.{h,cpp}`, shared with `tools/savemgr`; `PSPRECOMP_SAVEMGR=0` disables; see games/dissidia/docs/savedata.md); host tests `runtime/tests/run_savedata_*.sh`, `test_savedata_hle`, `test_savemgr`; name-based registration wired to the generated `syscall_table.cpp` stub addresses via dispatch overrides (issue #40 — no per-game stub addresses in the runtime; unbound stubs get a loud per-NID unimplemented no-op that returns a deterministic `v0 = 0`; NID→stub lookup for runtime code via `psp_hle_stub_addr_for_nid`) |
| GE list processor | `psp_ge.cpp` | Display-list interpretation, including SIGNAL flow-control behaviors 0x10–0x12 (JUMP/CALL/RET) |
| Renderer | `psp_ge_draw.cpp`, `psp_ge_vertex.cpp`, `psp_ge_texture.cpp`, `psp_ge_shader.cpp` | Vertex decode/transform (column-major PSP matrices), CLUT/texture decode, shaders, GL draw — deep-dive in [docs/GRAPHICS.md](docs/GRAPHICS.md). Default draw path is the batched GPU-skinning one (state-keyed batches, ring VBO synchronised by orphaning, GL 3.3 core only); `PSPRECOMP_GE_FAST=0` selects the per-PRIM CPU-skinning path. `psp_gl_stats.cpp` wraps glad's function pointers for `PSPRECOMP_GL_STATS` (call counters / per-call `glGetError`); `PSPRECOMP_GE_AB` renders every PRIM on both paths into twin targets and diffs them per present (see DEBUGGING.md) |
+| Present sync | `psp_present_sync.cpp` | Vertical sync (setting / `PSPRECOMP_VSYNC`: swap interval or Vulkan present mode, switched live at the next swap), the Android display refresh request (`ANativeWindow_setFrameRate` with the game's frame rate) and `[PRESENT_STATS]` present timing; called around every swap by `psp_gl_swap` (issue #67) |
| Render queue | `psp_render_queue.cpp` | Condvar request queue — the only path by which GL work reaches the main thread |
| Event loop | `psp_event_loop.cpp` | SDL2 event pump, quit handling, render-queue drain; routes events to the settings menu first and gates the game's input through it. Controllers are read in the background (`SDL_HINT_JOYSTICK_ALLOW_BACKGROUND_EVENTS`) but `publish_input()` mutes their buttons and sticks while no window of this process has the keyboard focus, so several instances on one machine do not share a pad (`PSPRECOMP_PAD_BACKGROUND=1` restores the old behaviour); pad state is still tracked, so held buttons are right on refocus |
| Settings menu | `psp_settings.{h,cpp}`, `src/hle/psp_settings_render.inc` (via `psp_savedata_dialog.cpp`), `include/psp_touch.h` | In-game menu (Esc / F1, Guide, L3+R3, the touch menu button, or `psp_settings_request_open()` from a game module's own menu entry). A category sidebar (Display, Graphics, Image, Effects, Controls (only with a touch screen), Network, Cloud, System, Drivers (only where `psp_gpu::supported`), Debug), a scrolling list of captioned rows (toggles, choices, sliders, actions, text fields, sub-menus: Image > HDR, Effects > Ray Tracing) and a description panel whose text scrolls by itself when long. `psp_settings.cpp` owns the state, applies and persists choices (`settings.ini`, exported as `PSPRECOMP_*` at the top of `main()`), and turns the page's `Row`s into a `psp_sddialog::SetScene`; `SettingsView` (`psp_settings_render.inc`, same painter, fonts and `SdTheme` as the save dialog) draws it at ~60 fps with animation (iris open / close, staggered panel slide, gliding selection and sliders, value pulses, drifting crystal motes) into the second overlay slot that `overlay_fetch` prefers, and remembers the geometry it drew (`SetGeom`) so pad, keyboard, mouse (hover, click, wheel, scroll-bar and slider drags, right click = Back) and touch (tap, drag-scroll with fling, sliders) hit-test the exact same rectangles; pointer positions are mapped through the picture rectangle (`ge_draw_overlay_rect`). While the menu is open the on-screen touch controls are hidden and let go (`psp_touch.cpp`), so fingers drive the menu directly. The frosted panels are drawn once per canvas scale into cached premultiplied layers and composited per frame, and the canvas scale drops automatically when a frame takes over 20 ms. Text entry (server, room, peers, sync folder, WebDAV) is an on-screen keyboard modal (pad, mouse, touch, or the host keyboard typing directly). While open the game is paused (guest threads wait in the vblank HLE, `psp_settings_guest_wait`), sees no input (and none until released after closing; the close animation keeps the game paused until it ends), and the main thread presents the last frame plus the menu (`ge_draw_present_overlay_now`). Render-scale changes resize every pool target in place, keeping its picture (`ge_draw_set_render_scale`), once a guest thread has parked, so no display list is mid-way. Frame rate is a game capability: a module registers `PspFrameRateHook` (Dissidia: `games/dissidia/runtime/framerate.cpp`); without one the row is hidden. Host test: `runtime/tests/run_settings_ui.sh` (`DUMP_SETTINGS=
` writes PPM frames). Game modules open it from the game's own menus (Dissidia: `games/dissidia/runtime/menu_settings.cpp`, which adds rows to the title, start and pause menus); elements they add to the game's screens are drawn on the game layer (`ge_draw_set_game_layer`, `psp_ge_draw.h`), a translucent image over the PSP picture under dialogs and touch controls that expires 0.15 s after the module stops sending it, with optional copies of parts of the game's own picture under it (`ge_draw_set_game_layer_copies`); `psp_texpack_watch` hands a module the HD image (either pack kind) the game got for a texture so added elements match the active texture pack |
diff --git a/psprecomp/docs/ENV_FLAGS.md b/psprecomp/docs/ENV_FLAGS.md
index 03c4d59..e5515ee 100644
--- a/psprecomp/docs/ENV_FLAGS.md
+++ b/psprecomp/docs/ENV_FLAGS.md
@@ -119,6 +119,15 @@ backend is not built in or no device is usable the runtime stops at start-up (se
`PSPRECOMP_VK_SUBMIT_EVERY=` (early GPU submits; 0 = only at sync points), `PSPRECOMP_VK_NO_PRESENT=1` (benchmark: never present),
`PSPRECOMP_VK_NO_MULTIDRAW=1`, `PSPRECOMP_VK_TRACE=1` (log every draw). `[VKGL]` lines in the log give draws, pipelines, GPU time and CPU cost per frame.
+### `PSPRECOMP_VSYNC`
+`0` (default on desktops) or `1` (default on Android). Vertical sync: with `1` each frame waits for the display (Vulkan FIFO present mode, GL
+swap interval -1 where the driver offers adaptive sync, else 1), so the picture never tears, and on a variable refresh rate display
+(FreeSync, G-Sync, HDMI VRR) the refresh follows the game's frame rate. With `0` frames are shown at once (Vulkan IMMEDIATE / MAILBOX, GL
+swap interval 0). Also Settings > Display > Vertical Sync (saved as `vsync=0|1`, changes at the next frame, wins over this variable).
+`runtime/src/psp_present_sync.cpp`, issue #67. `PSPRECOMP_PRESENT_STATS=1` logs present-to-present timing every 5 s (`[PRESENT_STATS]`:
+mean, standard deviation, median, p99, max and the frames shown for more than 1.5x the median). Android also asks the display for a
+refresh rate that matches the game's frame rate (`ANativeWindow_setFrameRate`, Android 11+; `[PRESENT] asked the display for ...`).
+
### `PSPRECOMP_DISC0`
- **Read in:** `runtime/src/main.cpp`
- **Type:** env (path string).
diff --git a/psprecomp/docs/GRAPHICS.md b/psprecomp/docs/GRAPHICS.md
index 455cef9..8cb4420 100644
--- a/psprecomp/docs/GRAPHICS.md
+++ b/psprecomp/docs/GRAPHICS.md
@@ -361,8 +361,12 @@ Two consequences of how this is implemented:
framebuffer (software rendering, `sceGeEdram` writes) is invisible; only GE-rendered FBO
content is shown. Double-buffer flips via `sceDisplaySetFrameBuf` all present the same FBO.
- Frame pacing is driven by the *guest*, not the renderer: `sceDisplayWaitVblankStart` sleeps
- 16.667 ms on the game thread to simulate the 60 Hz vblank. No `SDL_GL_SetSwapInterval` is
- called, so vsync is whatever the platform defaults to.
+ on the game thread to the next simulated vblank (60 Hz, or the battle frame rate above 60).
+ Whether the swap then waits for the display is the Vertical Sync setting
+ (`runtime/src/psp_present_sync.cpp`, `PSPRECOMP_VSYNC`): off = Vulkan IMMEDIATE / MAILBOX or
+ GL swap interval 0, on = FIFO / swap interval -1 or 1, which on a VRR display lets the refresh
+ follow the game. It can change while running: the Vulkan layer rebuilds its swapchain at the
+ next swap (the same path as the HDR switch), GL changes the swap interval on the presenting thread.
### Present-time post-processing
diff --git a/psprecomp/games/dissidia/docs/steamdeck.md b/psprecomp/games/dissidia/docs/steamdeck.md
index 6bb9fab..0917ab8 100644
--- a/psprecomp/games/dissidia/docs/steamdeck.md
+++ b/psprecomp/games/dissidia/docs/steamdeck.md
@@ -471,9 +471,9 @@ ghidra-allegrex v21.3, see the top-level README), or `--skip-analyze` to reuse e
* Music is ATRAC3/3+ decoded via libavcodec; a build without `libavcodec-dev` has no music.
* The European PSN image (`ULES01505`) is the one tested in depth; the US UMD (`ULUS10566`) has been tried
briefly (it works).
-* No driver vsync: the guest's 60 Hz vblank is simulated and the window is swapped without waiting, so tearing is
- possible outside gamescope (gamescope composites whole frames). `PSPRECOMP_VSYNC=1` turns the driver's vsync on at
- the risk of stalling the render thread.
+* Vertical sync is off by default: the guest's vblank is simulated and the window is swapped without waiting, so tearing
+ is possible outside gamescope (gamescope composites whole frames). Settings > Display > Vertical Sync (or
+ `PSPRECOMP_VSYNC=1`) makes each frame wait for the display; with an external VRR monitor the refresh then follows the game.
## Tested on a Deck
diff --git a/psprecomp/games/dissidia/docs/testing.md b/psprecomp/games/dissidia/docs/testing.md
index fa143b4..7629818 100644
--- a/psprecomp/games/dissidia/docs/testing.md
+++ b/psprecomp/games/dissidia/docs/testing.md
@@ -306,3 +306,15 @@ Added with `psp_settings_add_debug_toggle` (runtime/include/psp_settings.h: a ga
- The game's own pressed test (`FUN_08AB399C`, the press latch's hook) returned no edges for the scripted Jecht chain presses at 30 or 120 Hz in test runs (`press latch: ... 0 edges` in the `[FPS]` line), so the press latch may not be doing anything for these inputs; not investigated.
- Jecht's Circle / Square are handed to the game on a 30 Hz grid above 30 fps (`jecht_grid_filter`, `PSPRECOMP_JECHT_GRID=0` to turn it off): the Jecht Combo Timing helper above therefore sees each press on a grid update, and a press can reach the game up to one 30 Hz frame after you pressed it. Details and measurements: docs/frame-rate.md "Jecht timed windows on the 30 Hz grid".
+
+## Frame pacing and vertical sync (issue #67)
+
+`PSPRECOMP_PRESENT_STATS=1` logs `[PRESENT_STATS]` every 5 s: present-to-present mean, standard deviation, median, p99, max and
+"uneven" (frames shown for more than 1.5x the median). The test-script command `vsync <0|1>` switches vertical sync in the middle of a
+run (A/B of the same fight); `BT_DISPLAY_MODE=fullscreen` makes `battle_test.py` run fullscreen, the way players do. Measure on a real,
+lit display: with the screen locked or powered off the compositor throttles a waiting (FIFO) swap to 60 Hz, which looks like a pacing
+bug and is not. Measured on a 3440x1440 175 Hz VRR monitor (GNOME 50 Wayland, VRR mode on, AMD, Vulkan), 150 fps fight
+(`~/dissidia/vrr_run.sh` on the desktop), per 5 s window: vertical sync off (MAILBOX) 6.67 ms, standard deviation 0.14-0.75; on
+(FIFO) 6.67 ms, standard deviation 0.14-0.63, at most 2 uneven frames. On a fixed 175 Hz refresh FIFO would put 150 fps frames on a
+5.71 ms grid (5.7 / 11.4 ms); even 6.67 ms frames mean the refresh followed the game. Both modes show a single 20-26 ms frame every
+few seconds: that comes from the game side, not from presenting.
diff --git a/psprecomp/games/dissidia/runtime/framerate.cpp b/psprecomp/games/dissidia/runtime/framerate.cpp
index 0d3a528..57d0c54 100644
--- a/psprecomp/games/dissidia/runtime/framerate.cpp
+++ b/psprecomp/games/dissidia/runtime/framerate.cpp
@@ -43,6 +43,7 @@
#include "hle/psp_hle_adhoc.h"
#include "psp_ge_draw.h"
#include "psp_screenfx.h"
+#include "psp_present_sync.h"
#include
#ifdef __linux__
#include
@@ -271,6 +272,9 @@ void parse_script(std::istream& in, std::vector& ev) {
} else if (cmd == "fxlights") { // fxlights <0|1>: lights from glowing effects off / on (psp_fx_lights_set), for an A/B of the same trial in one run
int v = 1; ss >> v;
ev.push_back({t, 16, static_cast(v), 0, "", rel});
+ } else if (cmd == "vsync") { // vsync <0|1>: vertical sync off / on while running (psp_vsync_set), for pacing A/B in one run
+ int v = 1; ss >> v;
+ ev.push_back({t, 30, static_cast(v), 0, "", rel});
} else if (cmd == "poke") { // poke : write one word of a fighter (finding which stat a number on the HUD comes from)
std::string who = "player", off; long v = 0; ss >> who >> off >> v;
ev.push_back({t, 15, static_cast(std::strtoul(off.c_str(), nullptr, 16)), static_cast(v), who, rel});
@@ -568,6 +572,7 @@ void testdrive_frame(uint8_t* rdram, recomp_context* ctx) {
g_injected_ranalog_deadline_ms.store(e.b == 0x8080u ? 0 : INT64_MAX, std::memory_order_relaxed);
continue;
}
+ if (e.kind == 30) { psp_vsync_set(e.a != 0); continue; }
if (e.kind == 15) {
const uint32_t a = test_fighter(e.text == "cpu" ? 1u : 0u);
if (a) { w32(a + e.a, e.b); std::fprintf(stderr, "[TEST] gt=%.0f poke %s +%X = %d\n", g_gt_ms, e.text.c_str(), e.a, static_cast(e.b)); }
@@ -1947,6 +1952,7 @@ void fps_set(int fps) {
fps = fps < 30 ? 30 : fps > 240 ? 240 : (fps + 15) / 30 * 30; // a multiple of 30
if (g_target.exchange(fps) != fps) std::fprintf(stderr, "[FPS] target frame rate %d\n", fps);
psp_adhoc_set_local_fps(fps); // told to the other players
+ psp_present_set_target_fps(fps); // Android: ask the display for a matching refresh rate
}
const int k_rates[] = {30, 60, 90, 120, 150, 180, 210, 240};
@@ -2111,5 +2117,6 @@ void dissidia_framerate_install(uint8_t* rdram) {
fx_install();
psp_settings_set_frame_rate_hook({k_rates, static_cast(std::size(k_rates)), fps_get, fps_set});
psp_adhoc_set_local_fps(g_target.load());
+ psp_present_set_target_fps(g_target.load());
std::fprintf(stderr, "[FPS] frame rate %d (battle logic; scope %s)\n", g_target.load(), g_scope_all ? "all" : "battle");
}
diff --git a/psprecomp/games/dissidia/tools/battle_test.py b/psprecomp/games/dissidia/tools/battle_test.py
index 6556bbc..4d725e6 100755
--- a/psprecomp/games/dissidia/tools/battle_test.py
+++ b/psprecomp/games/dissidia/tools/battle_test.py
@@ -66,7 +66,9 @@ def start(self):
shutil.copytree(os.path.join(self.work, 'ms0'), ms0)
ini = os.path.join(self.out, 'settings_%d.ini' % self.fps)
with open(ini, 'w') as f:
- f.write('display=window\nfps=%d\nrender_scale=%d\nwidescreen=%d\nvoice=en\ncheck_updates=0\nhd_textures=%d\n' % (self.fps, self.render_scale, self.widescreen, 1 if os.environ.get('PSPRECOMP_TEXPACK') else 0))
+ f.write('display=%s\nfps=%d\nrender_scale=%d\nwidescreen=%d\nvoice=en\ncheck_updates=0\nhd_textures=%d\n' % (
+ os.environ.get('BT_DISPLAY_MODE', 'window'), # BT_DISPLAY_MODE=fullscreen: a real-display test the way players run (VRR, pacing)
+ self.fps, self.render_scale, self.widescreen, 1 if os.environ.get('PSPRECOMP_TEXPACK') else 0))
env = dict(os.environ, DISPLAY=self.display, PSPRECOMP_SETTINGS=ini, PSPRECOMP_MS0=ms0, PSPRECOMP_FIGHTER_LOG='1',
PSPRECOMP_DEBUG_PORT=str(self.port), PSPRECOMP_SAVEDATA_AUTO='0', PSPRECOMP_TEST_FREEZE_CPU='1')
env.pop('PSPRECOMP_FPS', None)
diff --git a/psprecomp/runtime/CMakeLists.txt b/psprecomp/runtime/CMakeLists.txt
index be90d4e..3b70a21 100644
--- a/psprecomp/runtime/CMakeLists.txt
+++ b/psprecomp/runtime/CMakeLists.txt
@@ -211,6 +211,7 @@ set(RUNTIME_SOURCES
src/psp_scheduler.cpp
src/psp_render_queue.cpp
src/psp_event_loop.cpp
+ src/psp_present_sync.cpp
src/psp_settings.cpp
src/psp_ge.cpp
src/psp_ge_vertex.cpp
diff --git a/psprecomp/runtime/include/psp_gl_window.h b/psprecomp/runtime/include/psp_gl_window.h
index 9361aa6..2ca0318 100644
--- a/psprecomp/runtime/include/psp_gl_window.h
+++ b/psprecomp/runtime/include/psp_gl_window.h
@@ -2,6 +2,7 @@
// (PSPRECOMP_RENDERER=vulkan, src/vk/) the window has no GL context, so these go through the Vulkan layer.
#pragma once
#include
+#include "psp_present_sync.h"
#ifdef __ANDROID__
#include "psp_android.h"
#endif
@@ -19,8 +20,10 @@ inline void psp_gl_swap(SDL_Window* w) {
#ifdef __ANDROID__
psp_android_frame_hint();
#endif
+ psp_present_before_swap(w); // vertical sync changed in the settings, display refresh hint (psp_present_sync.cpp)
#if defined(PSPRECOMP_HAVE_VKGL)
- if (vkgl::active()) { vkgl::swap(); return; }
+ if (vkgl::active()) { vkgl::swap(); psp_present_after_swap(); return; }
#endif
SDL_GL_SwapWindow(w);
+ psp_present_after_swap();
}
diff --git a/psprecomp/runtime/include/psp_present_sync.h b/psprecomp/runtime/include/psp_present_sync.h
new file mode 100644
index 0000000..3003c39
--- /dev/null
+++ b/psprecomp/runtime/include/psp_present_sync.h
@@ -0,0 +1,24 @@
+// Vertical sync, variable refresh rate and display refresh hints (issue #67).
+//
+// The game paces itself (the simulated vblank in psp_hle_display.cpp); this decides how a finished frame reaches the
+// screen. Off: present at once (lowest latency, may tear outside a compositor). On: wait for the display (Vulkan FIFO,
+// GL swap interval -1 / 1); on a FreeSync / G-Sync / HDMI VRR display that is what lets the refresh follow the game.
+//
+// PSPRECOMP_VSYNC=0|1 (unset = off on desktops; Android sets 1), saved as `vsync` by the settings menu.
+// PSPRECOMP_PRESENT_STATS=1 logs present-to-present timing every 5 s ([PRESENT_STATS]).
+#pragma once
+#include
+
+/// 1 when vertical sync is wanted (the setting / PSPRECOMP_VSYNC), 0 when not.
+int psp_vsync_wanted();
+/// Change it while running (settings menu): applied by the presenting thread at the next swap.
+void psp_vsync_set(int on);
+/// Apply the current choice to a GL context (call on the GL thread; the Vulkan backend reads psp_vsync_wanted()).
+void psp_vsync_apply_gl();
+
+/// The frame rate the game is set to (battles; menus run at 30). Android asks the display for a matching refresh rate.
+void psp_present_set_target_fps(int fps);
+
+/// Called by psp_gl_swap on the presenting thread, right before / after the swap.
+void psp_present_before_swap(SDL_Window* w);
+void psp_present_after_swap();
diff --git a/psprecomp/runtime/src/psp_event_loop.cpp b/psprecomp/runtime/src/psp_event_loop.cpp
index 451f0f7..1d2ceb6 100644
--- a/psprecomp/runtime/src/psp_event_loop.cpp
+++ b/psprecomp/runtime/src/psp_event_loop.cpp
@@ -678,7 +678,7 @@ int psp_runtime_init_sdl() {
#endif
if (use_vk) {
std::string verr;
- if (!vkgl::init(g_window, std::getenv("PSPRECOMP_VSYNC") != nullptr, &verr)) {
+ if (!vkgl::init(g_window, psp_vsync_wanted() != 0, &verr)) {
std::fprintf(stderr, "[RT] Vulkan backend unavailable: %s\n", verr.c_str());
SDL_DestroyWindow(g_window);
SDL_Quit();
@@ -700,9 +700,9 @@ int psp_runtime_init_sdl() {
gl_stats_install(); // PSPRECOMP_GL_STATS=1 call counters (psp_gl_stats.cpp)
- // No driver-side vsync: the guest's vblank is simulated (hle display) and
- // a blocking swap would stall the render thread for up to a refresh.
- if (!use_vk) SDL_GL_SetSwapInterval(std::getenv("PSPRECOMP_VSYNC") ? 1 : 0);
+ // Vertical sync is a setting (off by default on desktops): the guest's vblank is simulated (hle display), so
+ // without it the swap never waits; with it the swap waits for the display, which on a VRR display follows the game.
+ if (!use_vk) psp_vsync_apply_gl();
// 6. Print GL info for diagnostics
std::fprintf(stderr, "[RT] GL: %s\n",
diff --git a/psprecomp/runtime/src/psp_present_sync.cpp b/psprecomp/runtime/src/psp_present_sync.cpp
new file mode 100644
index 0000000..beb1ead
--- /dev/null
+++ b/psprecomp/runtime/src/psp_present_sync.cpp
@@ -0,0 +1,160 @@
+// Vertical sync, VRR and display refresh hints (issue #67). See include/psp_present_sync.h.
+#include "psp_present_sync.h"
+
+#include
+#include
+
+#include
+#include
+#include
+#include
+#include
+#include
+#include
+#include
+
+#if defined(PSPRECOMP_HAVE_VKGL)
+#include "vk/vkgl.h"
+#endif
+#ifdef __ANDROID__
+#include
+#include
+#endif
+
+namespace {
+
+int env_vsync() {
+ const char* e = std::getenv("PSPRECOMP_VSYNC");
+ return (e && *e && std::strcmp(e, "0") != 0) ? 1 : 0; // unset or "0": off
+}
+
+std::atomic g_vsync{-1}; // -1: not read from the environment yet
+std::atomic g_vsync_applied{-1};// what the presenting thread last applied (GL swap interval / Vulkan swapchain)
+std::atomic g_target_fps{0};
+
+// ---- present timing statistics (PSPRECOMP_PRESENT_STATS=1)
+using Clock = std::chrono::steady_clock;
+bool g_stats = false, g_stats_init = false;
+Clock::time_point g_last{}, g_window_t0{};
+std::vector g_iv; // present-to-present intervals of the current window, ms
+
+void stats_report(Clock::time_point now) {
+ if (g_iv.size() < 10) return;
+ std::vector s = g_iv;
+ std::sort(s.begin(), s.end());
+ double sum = 0, sq = 0;
+ for (float v : s) { sum += v; sq += double(v) * v; }
+ const double mean = sum / s.size(), sd = std::sqrt(std::max(0.0, sq / s.size() - mean * mean));
+ const float med = s[s.size() / 2], p99 = s[std::min(s.size() - 1, size_t(s.size() * 0.99))];
+ int uneven = 0; // a frame shown for more than 1.5x the typical frame time: a visible hitch
+ for (float v : s) if (v > med * 1.5f) uneven++;
+ const int tf = g_target_fps.load();
+ std::fprintf(stderr, "[PRESENT_STATS] %zu presents in %.1f s: mean %.2f ms, sd %.2f, median %.2f, p99 %.2f, max %.2f, "
+ "uneven %d; vsync %s, target %d fps\n",
+ s.size(), std::chrono::duration(now - g_window_t0).count(), mean, sd, med, p99, s.back(), uneven,
+ g_vsync_applied.load() == 1 ? "on" : "off", tf);
+ g_iv.clear();
+ g_window_t0 = now;
+}
+
+#ifdef __ANDROID__
+// ANativeWindow_setFrameRate is API 30; the APK's minSdk is lower, so look it up at run time.
+using SetFrameRateFn = int32_t (*)(ANativeWindow*, float, int8_t);
+SetFrameRateFn set_frame_rate_fn() {
+ // The NDK puts it in libnativewindow (libandroid only re-exports it on some builds); RTLD_DEFAULT does not search either
+ // from the app's linker namespace (both found on the Android 15 emulator).
+ static SetFrameRateFn fn = [] {
+ for (const char* lib : {"libnativewindow.so", "libandroid.so"}) {
+ void* h = dlopen(lib, RTLD_NOW | RTLD_LOCAL);
+ if (void* f = h ? dlsym(h, "ANativeWindow_setFrameRate") : nullptr) return reinterpret_cast(f);
+ const char* e = dlerror();
+ std::fprintf(stderr, "[PRESENT] %s: %s\n", lib, e ? e : "no ANativeWindow_setFrameRate");
+ }
+ return static_cast(nullptr);
+ }();
+ return fn;
+}
+void android_frame_rate(SDL_Window* w) {
+ static ANativeWindow* s_win = nullptr;
+ static int s_fps = -1;
+ const int fps = g_target_fps.load();
+ if (fps <= 0 || !w) return;
+ SDL_SysWMinfo info;
+ SDL_VERSION(&info.version);
+ if (!SDL_GetWindowWMInfo(w, &info) || info.subsystem != SDL_SYSWM_ANDROID) return;
+ ANativeWindow* nw = info.info.android.window;
+ if (!nw || (nw == s_win && fps == s_fps)) return; // the surface is recreated after a resume: vote again then
+ s_win = nw; s_fps = fps;
+ if (SetFrameRateFn fn = set_frame_rate_fn()) {
+ const int32_t r = fn(nw, float(fps), 0 /* ANATIVEWINDOW_FRAME_RATE_COMPATIBILITY_DEFAULT */);
+ std::fprintf(stderr, "[PRESENT] asked the display for %d Hz (ANativeWindow_setFrameRate -> %d)\n", fps, r);
+ } else {
+ std::fprintf(stderr, "[PRESENT] ANativeWindow_setFrameRate not found (it needs Android 11): display refresh left to the system\n");
+ }
+}
+#endif
+
+} // namespace
+
+int psp_vsync_wanted() {
+ int v = g_vsync.load();
+ if (v < 0) { v = env_vsync(); g_vsync.store(v); }
+ return v;
+}
+
+void psp_vsync_set(int on) {
+ on = on ? 1 : 0;
+ if (g_vsync.exchange(on) != on) std::fprintf(stderr, "[PRESENT] vertical sync %s (applied at the next frame)\n", on ? "on" : "off");
+}
+
+void psp_vsync_apply_gl() {
+ const int on = psp_vsync_wanted();
+ int got = 0;
+ if (on) {
+ // Adaptive (late swaps tear instead of waiting a whole refresh) where the driver has it, else plain vsync.
+ if (SDL_GL_SetSwapInterval(-1) == 0) got = -1;
+ else if (SDL_GL_SetSwapInterval(1) == 0) got = 1;
+ } else {
+ SDL_GL_SetSwapInterval(0);
+ }
+ g_vsync_applied.store(on);
+ std::fprintf(stderr, "[PRESENT] GL swap interval %d (vertical sync %s)\n", got, on ? "on" : "off");
+}
+
+void psp_present_set_target_fps(int fps) { g_target_fps.store(fps); }
+
+void psp_present_before_swap(SDL_Window* w) {
+ const int want = psp_vsync_wanted();
+ if (g_vsync_applied.load() != want) {
+#if defined(PSPRECOMP_HAVE_VKGL)
+ if (vkgl::active()) {
+ vkgl::set_swap_interval(want != 0); // new swapchain (present mode) at this swap
+ g_vsync_applied.store(want);
+ } else
+#endif
+ psp_vsync_apply_gl();
+ }
+#ifdef __ANDROID__
+ android_frame_rate(w);
+#else
+ (void)w;
+#endif
+}
+
+void psp_present_after_swap() {
+ if (!g_stats_init) {
+ const char* e = std::getenv("PSPRECOMP_PRESENT_STATS");
+ g_stats = e && *e && std::strcmp(e, "0") != 0;
+ g_stats_init = true;
+ }
+ if (!g_stats) return;
+ const auto now = Clock::now();
+ if (g_last.time_since_epoch().count()) {
+ const float ms = std::chrono::duration(now - g_last).count();
+ if (ms < 1000.f) g_iv.push_back(ms); // a loading pause is not a hitch
+ } else {
+ g_window_t0 = now;
+ }
+ g_last = now;
+ if (now - g_window_t0 > std::chrono::seconds(5)) stats_report(now);
+}
diff --git a/psprecomp/runtime/src/psp_settings.cpp b/psprecomp/runtime/src/psp_settings.cpp
index 2eb3732..9471a13 100644
--- a/psprecomp/runtime/src/psp_settings.cpp
+++ b/psprecomp/runtime/src/psp_settings.cpp
@@ -156,7 +156,7 @@ bool updates_choice();
bool texpack_choice();
bool texpack_at_start();
-enum Row { ROW_DISPLAY, ROW_RES, ROW_SCALE, ROW_FPS, ROW_FPSCOUNT, ROW_WIDE, ROW_TALL, ROW_SOFT, ROW_RENDERER, ROW_AA, ROW_SHARP, ROW_BRIGHT, ROW_CONTRAST, ROW_SAT, ROW_HDR, ROW_HDR_BOOST, ROW_HDR_GAMUT, ROW_HDR_PEAK, ROW_HDR_PAPER, ROW_HDR_SCENE, ROW_SSAO, ROW_CONTACT, ROW_RT, ROW_RT_SOFT, ROW_RT_REFL, ROW_RT_REFL_FX, ROW_SSR, ROW_ANISO, ROW_UPSCALE, ROW_VOICE, ROW_TEXPACK, ROW_TOUCH, ROW_TOUCH_EDIT, ROW_UPDATES, ROW_QUIT,
+enum Row { ROW_DISPLAY, ROW_RES, ROW_SCALE, ROW_FPS, ROW_FPSCOUNT, ROW_VSYNC, ROW_WIDE, ROW_TALL, ROW_SOFT, ROW_RENDERER, ROW_AA, ROW_SHARP, ROW_BRIGHT, ROW_CONTRAST, ROW_SAT, ROW_HDR, ROW_HDR_BOOST, ROW_HDR_GAMUT, ROW_HDR_PEAK, ROW_HDR_PAPER, ROW_HDR_SCENE, ROW_SSAO, ROW_CONTACT, ROW_RT, ROW_RT_SOFT, ROW_RT_REFL, ROW_RT_REFL_FX, ROW_SSR, ROW_ANISO, ROW_UPSCALE, ROW_VOICE, ROW_TEXPACK, ROW_TOUCH, ROW_TOUCH_EDIT, ROW_UPDATES, ROW_QUIT,
ROW_NET_MODE, ROW_NET_SERVER, ROW_NET_ROOM, ROW_NET_PEERS, ROW_NET_STATUS, // Network page
ROW_CLOUD_PROVIDER, ROW_CLOUD_FOLDER, ROW_CLOUD_URL, ROW_CLOUD_USER, ROW_CLOUD_PASS, ROW_CLOUD_GOOGLE,
ROW_CLOUD_AUTO, ROW_CLOUD_REPLAYS, ROW_CLOUD_NOW, ROW_CLOUD_STATUS, // Cloud page
@@ -967,6 +967,17 @@ std::vector make_rows() {
m.help = g_quit_armed ? "Quit\nUnsaved progress is lost. Press again to quit, or move away to cancel."
: "Quit\nClose the game and return to the desktop / Steam.";
break;
+ case ROW_VSYNC: {
+ const bool on = psp_vsync_wanted() != 0;
+ m.label = "Vertical Sync";
+ m.value = on ? "On" : "Off";
+ m.can_dec = on; m.can_inc = !on;
+ m.help = "Vertical sync\nOn: each frame waits for the screen, so the picture never tears. With a variable refresh rate "
+ "screen (FreeSync, G-Sync, HDMI VRR) the screen then follows the game's frame rate: smooth at any rate, "
+ "no tearing. Off: frames are shown at once, the lowest delay, but the picture can tear (not inside "
+ "Steam's Game Mode, which never tears). Saved.";
+ break;
+ }
case ROW_FPSCOUNT: {
const bool on = ge_draw_fps_counter();
m.label = "FPS Counter";
@@ -1271,7 +1282,7 @@ psp_sddialog::SetKind row_kind(Row r) {
if (const EnvOpt* o = env_row_opt(r)) return o->type == 'c' ? K::Choice : K::Toggle;
switch (r) {
case ROW_RT_REFL_FX:
- case ROW_FPSCOUNT: case ROW_WIDE: case ROW_TALL: case ROW_SOFT: case ROW_TEXPACK: case ROW_UPDATES: case ROW_HDR: case ROW_HDR_SCENE: case ROW_CLOUD_AUTO:
+ case ROW_FPSCOUNT: case ROW_VSYNC: case ROW_WIDE: case ROW_TALL: case ROW_SOFT: case ROW_TEXPACK: case ROW_UPDATES: case ROW_HDR: case ROW_HDR_SCENE: case ROW_CLOUD_AUTO:
case ROW_CLOUD_REPLAYS: case ROW_PERF: case ROW_FX: case ROW_GLOWSOFT: case ROW_GLOWPASS:
case ROW_DBG0: case ROW_DBG1: case ROW_DBG2: case ROW_DBG3: case ROW_DBG4: case ROW_DBG5:
return K::Toggle;
@@ -1572,6 +1583,12 @@ void change(int d) { // left / right on the selected row
case ROW_CLOUD_REPLAYS: if (g_cloud.replays != (d > 0)) { g_cloud.replays = d > 0; cloud_apply(); } break;
case ROW_CLOUD_FOLDER: case ROW_CLOUD_URL: case ROW_CLOUD_USER: case ROW_CLOUD_PASS: case ROW_CLOUD_GOOGLE:
case ROW_CLOUD_NOW: case ROW_CLOUD_STATUS: break;
+ case ROW_VSYNC:
+ if ((d > 0) != (psp_vsync_wanted() != 0)) {
+ psp_vsync_set(d > 0);
+ save("vsync", d > 0 ? "1" : "0");
+ }
+ break;
case ROW_FPSCOUNT:
if ((d > 0) != ge_draw_fps_counter()) {
ge_draw_set_fps_counter(d > 0);
@@ -1764,6 +1781,7 @@ void build_rows() {
add(ROW_SEC_WINDOW); add(ROW_DISPLAY); if (!is_fullscreen()) add(ROW_RES); add(ROW_WIDE); if (window_is_tall()) add(ROW_TALL); add(ROW_UPSCALE);
add(ROW_SEC_PERF);
if (g_fps.get && g_fps.count > 1) add(ROW_FPS);
+ add(ROW_VSYNC);
add(ROW_FPSCOUNT);
break;
case PAGE_GRAPHICS:
@@ -2102,6 +2120,7 @@ void confirm_row() {
break;
case ROW_CLOUD_STATUS: break;
case ROW_FPSCOUNT: change(ge_draw_fps_counter() ? -1 : 1); return;
+ case ROW_VSYNC: change(psp_vsync_wanted() ? -1 : 1); return;
case ROW_PERF: change(ge_draw_perf_overlay() ? -1 : 1); return;
case ROW_FX: change(ge_draw_fx_shaders() ? -1 : 1); return;
case ROW_SYNC: ge_draw_set_sync_mode((ge_draw_sync_mode() + 1) % 5); break;
@@ -2445,6 +2464,7 @@ void psp_settings_load_early() {
if ((it = g_saved.find("net_room")) != g_saved.end()) put("PSPRECOMP_ADHOC_ROOM", it->second);
if ((it = g_saved.find("net_peers")) != g_saved.end()) put("PSPRECOMP_ADHOC_PEERS", it->second);
if ((it = g_saved.find("fps_counter")) != g_saved.end()) put("PSPRECOMP_FPS_COUNTER", it->second == "1" ? "1" : "0");
+ if ((it = g_saved.find("vsync")) != g_saved.end() && (it->second == "0" || it->second == "1")) put("PSPRECOMP_VSYNC", it->second);
if ((it = g_saved.find("perf_overlay")) != g_saved.end()) put("PSPRECOMP_PERF_HUD", it->second == "1" ? "1" : "0");
if ((it = g_saved.find("ge_ring")) != g_saved.end() && (it->second == "map" || it->second == "sub"))
put("PSPRECOMP_GE_RING", it->second);
diff --git a/psprecomp/runtime/src/vk/vkgl_core.cpp b/psprecomp/runtime/src/vk/vkgl_core.cpp
index 9696fa7..dc43066 100644
--- a/psprecomp/runtime/src/vk/vkgl_core.cpp
+++ b/psprecomp/runtime/src/vk/vkgl_core.cpp
@@ -1689,7 +1689,6 @@ void core_shutdown() {
G = nullptr;
}
-void core_set_vsync(bool v) { if (G) G->vsync = v; }
void core_drawable(int* w, int* h) { if (G) { *w = G->fb0_w; *h = G->fb0_h; } }
void core_drawable_query(SDL_Window* window, int* w, int* h) {
@@ -1735,6 +1734,8 @@ static void log_stats() {
}
static bool g_hdr_dirty = false;
+static bool g_vsync_dirty = false; // vertical sync switched in the settings: new present mode (psp_present_sync.cpp)
+void core_set_vsync(bool v) { if (G && G->vsync != v) { G->vsync = v; g_vsync_dirty = true; } }
void core_set_hdr(bool on) { if (!G) return; G->ctx.set_hdr_wanted(on); g_hdr_dirty = true; }
bool core_hdr_supported() { return G && G->ctx.hdr_supported(); }
void core_set_profile(bool on) { if (G) G->want_prof.store(on); }
@@ -1783,12 +1784,12 @@ void core_swap() {
int dw = 0, dh = 0;
SDL_Vulkan_GetDrawableSize(gl.window, &dw, &dh);
Frame& f = fr();
- if (g_hdr_dirty && !gl.no_present && dw > 0 && dh > 0) { // HDR switched in the settings: new swapchain format, new default framebuffer
- g_hdr_dirty = false;
+ if ((g_hdr_dirty || g_vsync_dirty) && !gl.no_present && dw > 0 && dh > 0) { // HDR or vertical sync switched in the settings: new swapchain (format / present mode), new default framebuffer
+ g_hdr_dirty = false; g_vsync_dirty = false;
vkDeviceWaitIdle(gl.dev);
std::string herr;
if (c.create_swapchain(dw, dh, gl.vsync, &herr)) create_fb0(dw, dh);
- else std::fprintf(stderr, "[VKGL] HDR swapchain switch failed: %s\n", herr.c_str());
+ else std::fprintf(stderr, "[VKGL] swapchain switch (HDR / vertical sync) failed: %s\n", herr.c_str());
vkDestroySemaphore(gl.dev, f.acquire_sem, nullptr);
VkSemaphoreCreateInfo hsi{VK_STRUCTURE_TYPE_SEMAPHORE_CREATE_INFO}; vkCreateSemaphore(gl.dev, &hsi, nullptr, &f.acquire_sem);
}