A fast 2D and 3D game engine — TypeScript SDK, C++/WebAssembly core, visual editor. Ship one project to web, desktop, WeChat MiniGames, playable ads, and native Android / iOS.
TypeScript 2d-game-engine3d3d-game-engineandroidcppecsgame-editorgame-enginegamedeviostypescriptwebassemblywebglwebgpuwechat-minigame
fix(native): every native host draws from one pacer, its present's own block and the game's cap, so an Android frame near its budget holds 60 fps instead of dropping to 30
yhh8210bd0c0d2c
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex e4d8684ec..1be797fdb 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -22,6 +22,7 @@ published separately; it ships inside the editor.### Fixed+- **Android frames no longer drop to 30 fps when they come close to the frame budget** (#105). The Android host drew each frame from a Choreographer callback and asked for the next one after the frame, whose present had already blocked until the display took it: two clocks, and a frame that ran past one vsync waited for a second. A 15 ms frame on a 60 fps cap ran at 30 fps on a Snapdragon 8 Elite, every interval 33 ms; a shooter in the issue saw 33/50/66 ms. The host now runs its own loop, as the desktop one does: the present paces it, input is served while it waits, and a frame is drawn when one is due even while a fast touch panel keeps the queue full. The same 15 ms frame holds 60 fps (p99 18.5 ms), and a 20 ms one runs at 46 fps instead of halving. A backgrounded app still draws nothing and uses no CPU. The cap App.setTargetFrameRate sets is now held by one pacer every native host shares (the web loop's rule: a cadence, restarted after a stall), so the desktop and iOS hosts, which ignored it, keep it too.- **A native build reports its GPU frame time.** The desktop and Android hosts never asked the GPU for timestamps, so the engine's GPU frame timer and the profiler's GPU track read -1 on every device. They ask for them now where the GPU has them.- **Voxel GI costs less on mobile GPUs.** The gather, which only reads the cache, reads it as a plain array, and the per-frame ageing reads and writes each slot plainly (each invocation owns one) and leaves empty slots alone; both had gone through atomics. On a Snapdragon 8 Elite phone at 2670x1200 a frame with one ray per point went from 134 to 83 ms, and with a 4-voxel range from 32 to 17 ms. Voxel GI is still too heavy for a phone at its defaults (about 0.8 s a frame).- **Baked lighting shows on built-in meshes.** A `builtin:` cube, sphere or plane baked with `bake-scene` or the editor drew as if nothing had been baked: the bake unwrapped a lightmap UV set for its own use, but the mesh the game loaded had none, so the atlas was never read. The built-in meshes now carry that UV set, the bake lays out its charts by it, and existing bakes stay valid.diff --git a/native/host/FramePacer.hpp b/native/host/FramePacer.hppnew file mode 100644index 000000000..cc4603c13--- /dev/null+++ b/native/host/FramePacer.hpp@@ -0,0 +1,103 @@+// SPDX-License-Identifier: Apache-2.0+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team+/**+ * @file FramePacer.hpp+ * @brief When a native host's next frame is due: the game's frame-rate cap,+ * held as a cadence, and the floor that keeps a loop from spinning.+ *+ * @details One clock paces a frame, never two. The swapchain's Fifo present is+ * that clock on every native host: it blocks until the display takes+ * the frame, so a loop that calls frame() back to back runs at the+ * panel's rate and no faster, and a frame that costs more than a vsync+ * shows on the next one rather than waiting for a second clock to come+ * round again. (Android drove frames from Choreographer callbacks on+ * top of that present: a callback, a frame whose present blocked past+ * the next vsync, then a callback asked for after it. A 15 ms frame on+ * a 60 Hz cadence ran at 30 fps on a Snapdragon 8 Elite, every interval+ * 33 ms; issue #105 measured 33/50/66 ms in a real game.)+ *+ * What this adds on top of the present is only what the present cannot+ * know:+ *+ * - The cap App.setTargetFrameRate asked for, with the web loop's rule+ * (App.mainLoop): a cadence, not a minimum gap, since a gap measured+ * frame to frame loses to jitter half the time and waits a third; and+ * after a stall the cadence restarts from the frame that ran late.+ * - A floor on how often a frame may start. A present stops blocking+ * while a surface is torn down ("GetCurrentTexture was not called"),+ * and a loop with nothing else to stop it once ran 11.5 million frames+ * in a backgrounded app. No display needs more than kFloorFps here;+ * a bench that asked for an uncapped present lifts it.+ *+ * The host loop asks untilDue(), serves input while it waits, and calls+ * frameStarted() as it begins a frame. Plain data and steady_clock only:+ * the same rule on every platform, testable without one.+ */+#pragma once++#include <chrono>++namespace eshost {++class FramePacer {+public:+ using Clock = std::chrono::steady_clock;++ /// The fastest any loop is let start frames when nothing else holds it back.+ static constexpr double kFloorFps = 240.0;+ /// A frame this close to its due time is due: the wait is in whole milliseconds on most platforms.+ static constexpr Clock::duration kJitter = std::chrono::milliseconds(1);++ /// The game's cap in frames per second; 0 (or less) is the display's own rate.+ void setTarget(float fps) {+ const float next = fps > 0.0f ? fps : 0.0f;+ if (next == target_) return;+ target_ = next;+ interval_ = target_ > 0.0f+ ? std::chrono::duration_cast<Clock::duration>(std::chrono::duration<double>(1.0 / target_))+ : Clock::duration::zero();+ nextAt_ = Clock::time_point{}; // the cadence restarts at the next frame+ }+ float target() const { return target_; }++ /// True while a bench measures uncapped frames: the floor would be what it measured.+ void setUnbounded(bool on) { unbounded_ = on; }++ /// How long from @p now until a frame is due; zero when one is. A host stepped by a display callback, which cannot spin,+ /// passes @p floor false: it needs the cap and nothing else.+ Clock::duration untilDue(Clock::time_point now, bool floor = true) const {+ Clock::time_point due = Clock::time_point{};+ if (interval_ > Clock::duration::zero() && nextAt_ != Clock::time_point{}) due = nextAt_;+ if (floor && !unbounded_ && lastStart_ != Clock::time_point{}) {+ const auto floorAt = lastStart_ + kFloor;+ if (floorAt > due) due = floorAt;+ }+ const auto wait = due - now;+ return wait > kJitter ? wait : Clock::duration::zero();+ }++ /// A frame begins at @p now: advances the cadence.+ void frameStarted(Clock::time_point now) {+ lastStart_ = now;+ if (interval_ <= Clock::duration::zero()) return;+ // More than a frame behind (a stall, a pause): the cadence restarts here.+ nextAt_ = (nextAt_ == Clock::time_point{} || now - nextAt_ > interval_) ? now + interval_ : nextAt_ + interval_;+ }++ /// The frame budget: the cap's interval, or one 60 Hz refresh when the display sets the rate.+ Clock::duration budget() const {+ return interval_ > Clock::duration::zero() ? interval_ : std::chrono::duration_cast<Clock::duration>(+ std::chrono::duration<double>(1.0 / 60.0));+ }++private:+ static constexpr Clock::duration kFloor =+ std::chrono::duration_cast<Clock::duration>(std::chrono::duration<double>(1.0 / kFloorFps));+ float target_ = 0.0f;+ Clock::duration interval_ = Clock::duration::zero();+ Clock::time_point nextAt_{};+ Clock::time_point lastStart_{};+ bool unbounded_ = false;+};++} // namespace eshostdiff --git a/native/host/Host.cpp b/native/host/Host.cppindex 5fb970cbe..2e80ccc9a 100644--- a/native/host/Host.cpp+++ b/native/host/Host.cpp@@ -192,6 +192,7 @@ bool bindSurface() {h.gfx->setSurfaceReadback(shotWanted());// A benched frame must not be quantised to the panel's refresh — see Bench.hpp.h.gfx->setPresentUncapped(benchWanted());+ framePacer().setUnbounded(benchWanted()); // nor held to the pacer's floorif (!h.gfx->configureSurface(h.platform->surface(), w, hh)) {ESHOST_LOGE("configureSurface failed");return false;@@ -211,6 +212,15 @@ void surfaceLost() {bool booted() { return hostAlive() && host().ready; }+FramePacer& framePacer() {+ static FramePacer pacer;+ return pacer;+}++std::chrono::steady_clock::duration untilFrameDue(bool floor) {+ return framePacer().untilDue(std::chrono::steady_clock::now(), floor);+}+bool surfaceBound() { return hostAlive() && host().surfaceReady; }bool boot(Platform& platform) {@@ -300,8 +310,9 @@ void frame(long long vsyncNanos) {ESHOST_LOGI("surface bound again — drawing resumes");}// Past the point where a frame can be skipped, so what is timed below is a- // frame that actually happened (see Bench.hpp).+ // frame that actually happened (see Bench.hpp), and what the pacer counts too.benchFrameBegin();+ framePacer().frameStarted(std::chrono::steady_clock::now());// A window can change size without being recreated: a rotation, an insets// change (the system bars leaving on the frame after launch), a layout on@@ -316,7 +327,7 @@ void frame(long long vsyncNanos) {}// How much time actually passed, not how much we wish had. A host is stepped- // by the display — CADisplayLink on iOS, the Choreographer on Android — so the+ // by the display — CADisplayLink on iOS, its own present elsewhere — so the// rate is the panel's, and a fixed 1/60 is only right on a 60 Hz one. A 120 Hz// phone ran this game at 2.02x real speed for exactly that reason, which reads// as "the animations are too fast" rather than as a clock bug.@@ -328,7 +339,7 @@ void frame(long long vsyncNanos) {constexpr double kMaxDelta = 0.25;constexpr double kFirstFrameDelta = 1.0 / 60.0;// The vsync being drawn for when the display supplied one — the web loop's rule too (rAF's timestamp, not callback- // entry). Android's Choreographer stamps on CLOCK_MONOTONIC, which is the steady clock there.+ // entry); otherwise the steady clock as the frame starts.const auto nowAt = vsyncNanos > 0? std::chrono::steady_clock::time_point(std::chrono::nanoseconds(vsyncNanos)): std::chrono::steady_clock::now();diff --git a/native/host/Host.hpp b/native/host/Host.hppindex cb213f837..23c628c1d 100644--- a/native/host/Host.hpp+++ b/native/host/Host.hpp@@ -28,12 +28,14 @@*/#pragma once+#include <chrono>#include <string>#include <utility>#include <vector>#include "esengine/core/Types.hpp"#include "esengine/renderer/webgpu/WebGPUDevice.hpp"+#include "FramePacer.hpp"namespace eshost {@@ -112,8 +114,8 @@ struct Platform {virtual bool pollMotion(MotionState&) { return false; }virtual bool vibrate(int, int) { return false; }virtual bool keepScreenOn(bool) { return false; }- /** The game's target frame rate, as App.setTargetFrameRate set it (0 = as fast as the display goes). A host stepped by- * the display paces itself to it; one that is not (desktop's own loop) ignores it. */+ /** The game's target frame rate, as App.setTargetFrameRate set it (0 = as fast as the display goes). The loop already+ * holds it through framePacer(); this is for telling the OS (Android's frame-rate hint), which only a platform can. */virtual void setTargetFrameRate(float /*fps*/) {}virtual ~Platform() = default;@@ -311,12 +313,22 @@ void surfaceLost();/** @brief Runs the game's update + one rendered, presented frame. No-op until* boot() has succeeded and a surface is bound.*- * @param vsyncNanos The vsync this frame is for, on the steady clock's timeline- * (Android's Choreographer hands one over), or 0 to measure the wall clock.- * Frame to frame it is the display's cadence; the wall clock at callback- * entry carries the scheduler's jitter, which reads as uneven motion. */+ * @param vsyncNanos The vsync this frame is for, on the steady clock's timeline,+ * when a display callback hands one over, or 0 to measure the wall clock.+ * A host whose loop is paced by its present (FramePacer.hpp) passes 0. */void frame(long long vsyncNanos = 0);+/** @brief The pacer every native host's loop shares (FramePacer.hpp): the cap+ * App.setTargetFrameRate set, and the floor that keeps a loop from+ * spinning. Exists before boot, so a host can set its default cap. */+FramePacer& framePacer();++/** @brief How long until the next frame is due (zero: now). A looping host waits+ * this long, serving input meanwhile, before it calls frame(); one stepped+ * by a display callback passes @p floor false and skips the vsyncs the+ * cap falls between. */+std::chrono::steady_clock::duration untilFrameDue(bool floor = true);+/** @brief Feeds one touch to the game. @p type: 0 start / 1 move / 2 end / 3 cancel.* Coordinates are in surface pixels, top-left origin (as on the web). */void touch(int type, int id, float x, float y);diff --git a/native/host/bindings/DeviceBindings.cpp b/native/host/bindings/DeviceBindings.cppindex c8bb4eb68..ca3930f6f 100644--- a/native/host/bindings/DeviceBindings.cpp+++ b/native/host/bindings/DeviceBindings.cpp@@ -97,7 +97,10 @@ esjs::Val js_keepScreenOn(const esjs::Args& a) {}esjs::Val js_setTargetFrameRate(const esjs::Args& a) {const double fps = a.size() > 0 ? esjs::toNumber(a[0]) : 0;- if (hostAlive() && host().platform) host().platform->setTargetFrameRate(fps > 0 ? (float)fps : 0.0f);+ const float target = fps > 0 ? (float)fps : 0.0f;+ // The loop holds the cap (FramePacer, the same on every host); the platform only tells its OS, where it has a say.+ framePacer().setTarget(target);+ if (hostAlive() && host().platform) host().platform->setTargetFrameRate(target);return esjs::undefined();}diff --git a/native/host/platform/android.cpp b/native/host/platform/android.cppindex 3c26f01c8..813af5450 100644--- a/native/host/platform/android.cpp+++ b/native/host/platform/android.cpp@@ -22,7 +22,6 @@#include <android/font.h>#include <android/font_matcher.h>#include <android/native_window.h>-#include <android/choreographer.h>#include <jni.h>#include <unistd.h>@@ -513,10 +512,9 @@ int32_t onInput(android_app*, AInputEvent* ev) {void framesSurface(bool has);void framesResumed(bool is);-// Tells the system what rate the game is meant to run at, so the panel and the Choreographer settle on a cadence the game can-// hold. Without it a 120 Hz panel calls the frame every 8.3 ms, a frame that costs 10 ms plus a blocked present misses by a-// vsync, and the period lands on 16.6 / 25 / 33 ms at random — 45 to 55 fps and uneven motion. 60 Hz is an exact fraction of-// 120 Hz and of 60 Hz, so the system can hold it on either. ANativeWindow_setFrameRate is API 30; the manifest floor is 29,+// Tells the system what rate the game is meant to run at, so the panel settles on a refresh the game can hold: a 120 Hz panel+// left at 120 holds every present to an 8.3 ms grid, and a frame the cap spaces 16.7 ms apart then lands a vsync early or late+// at random. 60 Hz is an exact fraction of 120 Hz and of 60 Hz, so the system can hold it on either. ANativeWindow_setFrameRate is API 30; the manifest floor is 29,// so it is looked up like PerformanceHints' symbols rather than made a load-time requirement.void hintFrameRate(ANativeWindow* window, float fps) {constexpr int8_t kCompatibilityDefault = 0; // ANATIVEWINDOW_FRAME_RATE_COMPATIBILITY_DEFAULT@@ -537,10 +535,11 @@ void hintFrameRate(ANativeWindow* window, float fps) {"frame rate hint: %.0f fps (%s)", fps, result == 0 ? "accepted" : "refused");}-// What the game wants until it says otherwise (App.setTargetFrameRate -> es_setTargetFrameRate).+// What the game wants until it says otherwise (App.setTargetFrameRate -> es_setTargetFrameRate): a phone holds 60 by default,+// where the web and the desktop take the display's rate, since a phone's panel is often 120 Hz and its battery and heat pay+// for every frame past what the game was made for.constexpr float kDefaultFps = 60.0f;float g_targetFps = kDefaultFps;-bool g_targetSet = false;void onAppCmd(android_app* app, int32_t cmd) {// NativeActivity supplies a content rectangle in window pixels; the glue@@ -611,8 +610,8 @@ void onAppCmd(android_app* app, int32_t cmd) {struct PerformanceHints {void* session = nullptr;- // One display refresh. The Choreographer is what calls the frame, so the- // deadline is the panel's cadence, whatever it happens to be.+ // The deadline a session opens with: one 60 Hz refresh, the default cap.+ // updateTarget() moves it with the cap.static constexpr int64_t kFrameBudgetNanos = 16'666'667;// Opaque on purpose: the header's typedefs come with the same availability@@ -623,7 +622,9 @@ struct PerformanceHints {using CloseFn = void (*)(void*);ReportFn reportFn = nullptr;+ ReportFn updateTargetFn = nullptr; // APerformanceHint_updateTargetWorkDuration: the same shape as reportCloseFn closeFn = nullptr;+ int64_t targetNanos = kFrameBudgetNanos;void open() {// RTLD_DEFAULT: libandroid is already loaded — this asks whether THIS@@ -636,6 +637,8 @@ struct PerformanceHints {dlsym(RTLD_DEFAULT, "APerformanceHint_reportActualWorkDuration"));closeFn = reinterpret_cast<CloseFn>(dlsym(RTLD_DEFAULT, "APerformanceHint_closeSession"));+ updateTargetFn = reinterpret_cast<ReportFn>(+ dlsym(RTLD_DEFAULT, "APerformanceHint_updateTargetWorkDuration"));if (getManager && createSession && reportFn && closeFn) {if (void* manager = getManager()) {@@ -650,6 +653,14 @@ struct PerformanceHints {"perf hints: %s", session ? "session up (ADPF)" : "unavailable");}+ /// The deadline is the frame budget the pacer holds, so it follows the cap.+ void updateTarget(std::chrono::steady_clock::duration budget) {+ const int64_t nanos = std::chrono::duration_cast<std::chrono::nanoseconds>(budget).count();+ if (!session || !updateTargetFn || nanos <= 0 || nanos == targetNanos) return;+ targetNanos = nanos;+ updateTargetFn(session, nanos);+ }+void report(std::chrono::steady_clock::duration frame) {if (!session) return;const auto nanos = std::chrono::duration_cast<std::chrono::nanoseconds>(frame).count();@@ -666,32 +677,27 @@ struct PerformanceHints {// The frame source// =============================================================================//-// The display drives the frame, and nothing else does. That is what iOS already-// says with a CADisplayLink and what the web says with requestAnimationFrame;-// this is the Android third of the same sentence, and it is a Choreographer.+// One clock paces a frame: the swapchain's Fifo present, which blocks until the+// display takes the frame. The loop in android_main serves input, waits until+// eshost::untilFrameDue() says a frame is due (the game's cap, held as a cadence,+// and a floor against a present that stops blocking — FramePacer.hpp), and+// otherwise calls frame() back to back. The desktop loop is the same loop.//-// It replaces a loop that polled with a zero timeout and called frame()-// immediately, forever, trusting the swapchain's FIFO present to be the thing-// that blocked. That holds right up until a present does NOT block — a surface-// mid-teardown answers "GetCurrentTexture was not called this frame prior to-// Present" and returns — and then the only brake is gone and the loop runs as-// fast as the CPU allows. One backgrounded app was measured 11.5 million frames-// in, holding a quarter of a core to render about one frame a second. A vsync-// source cannot fail that way: no callback, no frame.+// It used to be a Choreographer callback, posted again after each frame. With a+// present that also blocks that is two clocks: a frame whose present waited past+// the next vsync asked for a callback only after it, which then came a vsync+// later again. A 15 ms frame on a 60 Hz cadence ran at 30 fps, every interval+// 33 ms, on a Snapdragon 8 Elite; issue #105 measured 33/50/66 ms in a real game.//// Two conditions, both required, exactly the pair iOS pauses its display link on:// there has to be a surface to present to, and the activity has to be the one the// user is looking at. Either alone is not enough — pressing HOME leaves the-// surface alive, so a driver gated on the surface only goes on rendering the game+// surface alive, so a loop gated on the surface only goes on rendering the game// at the full panel rate onto a window nobody can see. (Measured: 121 fps from the// home screen.) The host already treats PAUSE as "not visible" by suspending audio-// and the game clock; this makes rendering agree with the other two.-struct FrameDriver {- AChoreographer* choreographer = nullptr;- PerformanceHints* hints = nullptr;- /// A callback is in flight. Guards against posting twice for one vsync, which- /// would double the frame rate for as long as both chains lived.- bool posted = false;+// and the game clock; this makes rendering agree with the other two. While either+// is missing the loop blocks in the poll: no frames, and no spinning.+struct FrameGate {bool hasSurface = false;/// Starts true, and only APP_CMD_PAUSE clears it. Waiting for a RESUME to/// arrive first is what broke this once: a launch that never delivered one@@ -700,26 +706,12 @@ struct FrameDriver {/// nothing, where a missed PAUSE is the thing actually being guarded against,/// and PAUSE always arrives because the OS is what sends it.bool resumed = true;- /// Derived from the two above; kept so a callback already in flight can tell- /// it was cancelled.+ /// Derived from the two above: whether the loop draws.bool running = false;- /// Must be called on the thread that will receive callbacks (the glue's own,- /// which has a prepared looper).- void attach() {- choreographer = AChoreographer_getInstance();- if (!choreographer) {- __android_log_print(ANDROID_LOG_ERROR, LOG_TAG,- "no Choreographer on this thread — nothing will drive frames");- }- }-void setSurface(bool has) { hasSurface = has; sync(); }void setResumed(bool is) { resumed = is; sync(); }- /// Start or stop asking for frames, to match the two conditions. An already- /// posted callback still arrives and is ignored — there is no API to cancel- /// one, and dropping it is what pausing means anyway.void sync() {const bool want = hasSurface && resumed;if (want == running) return;@@ -728,57 +720,16 @@ struct FrameDriver {// one place that can explain a black screen, which is otherwise silent.__android_log_print(ANDROID_LOG_INFO, LOG_TAG, "frames: %s (surface=%d resumed=%d)",running ? "running" : "paused", (int)hasSurface, (int)resumed);- if (running) post();- }-- void post() {- if (!choreographer || posted || !running) return;- posted = true;- // The 64-bit callback is API 29, which is the floor (see the manifest- // template for why the floor cannot go lower).- AChoreographer_postFrameCallback64(choreographer, &FrameDriver::onVsync64, this);- }-- /// When the next frame is due, on the vsync clock; 0 restarts the cadence.- int64_t nextRunNanos = 0;--private:- /// The cap the game asked for, held as a cadence and not as a minimum gap — the web loop's rule (App.mainLoop): a gap- /// measured frame to frame loses to jitter half the time and waits a third. Only an explicit cap paces here; the default- /// 60 is the system's to hold, through the hint. Returns false for a vsync this frame is skipped on.- bool due(int64_t vsyncNanos) {- if (!g_targetSet || g_targetFps <= 0.0f || vsyncNanos <= 0) return true;- const int64_t interval = (int64_t)(1e9 / g_targetFps);- constexpr int64_t kJitter = 2'000'000; // 2 ms- if (vsyncNanos < nextRunNanos - kJitter) return false;- nextRunNanos = (nextRunNanos == 0 || vsyncNanos - nextRunNanos > interval)- ? vsyncNanos + interval : nextRunNanos + interval;- return true;}-- void tick(int64_t vsyncNanos) {- posted = false;- if (!running) return;- if (!due(vsyncNanos)) { post(); return; }- // Timed around the frame alone, and re-posted after it: asking for the- // next vsync first would let a frame that overran queue behind itself.- const auto begin = std::chrono::steady_clock::now();- eshost::frame(vsyncNanos);- if (hints) hints->report(std::chrono::steady_clock::now() - begin);- post();- }-- // The vsync's own timestamp is the game clock's tick (Host::frame), not the moment this callback happened to run.- static void onVsync64(int64_t frameTimeNanos, void* data) { static_cast<FrameDriver*>(data)->tick(frameTimeNanos); }};-FrameDriver g_frames;+FrameGate g_frames;+/// The cap itself is the pacer's (es_setTargetFrameRate set it before calling this); the OS is told here, the one part only+/// the platform can do.void framesTargetRate(float fps) {- if (g_targetSet && fps == g_targetFps) return;- g_targetSet = true;+ if (fps == g_targetFps) return;g_targetFps = fps;- g_frames.nextRunNanos = 0;hintFrameRate(g_platform.window, fps);}void framesSurface(bool has) { g_frames.setSurface(has); }@@ -1018,26 +969,46 @@ void android_main(android_app* app) {app->activity->callbacks->onWindowFocusChanged = onWindowFocusChanged;PerformanceHints hints;hints.open();- g_frames.hints = &hints;- g_frames.attach();-- // Nothing but waiting. Frames arrive as Choreographer callbacks and input as- // looper events, both dispatched from inside the poll — so there is no state- // this loop has to sample, and therefore no reason for it to ever spin.+ eshost::framePacer().setTarget(kDefaultFps);++ // The frame loop (see FrameGate). Each turn waits for input or for the next+ // frame to fall due, whichever comes first, serves every event already queued,+ // and then draws if a frame is due. Drawing does not wait for the queue to run+ // dry: a touch panel reporting at 240-480 Hz keeps it non-empty, and a loop+ // that drew only on a timed-out poll starved frames for up to a second while a+ // finger was down.+ using Clock = std::chrono::steady_clock;while (true) {- int events;- android_poll_source* source;- const int id = ALooper_pollOnce(-1, nullptr, &events, (void**)&source);- if (id == ALOOPER_POLL_ERROR) {- __android_log_print(ANDROID_LOG_ERROR, LOG_TAG, "looper error — leaving the frame loop");- return;+ int timeoutMs = -1; // not drawing: sleep until the OS has something+ if (g_frames.running) {+ const auto wait = eshost::untilFrameDue();+ // Rounded up: waking early only goes round the loop again.+ timeoutMs = wait > Clock::duration::zero()+ ? (int)std::chrono::duration_cast<std::chrono::milliseconds>(wait + std::chrono::microseconds(999)).count()+ : 0;}- if (id >= 0 && source) source->process(app, source);- if (app->destroyRequested) {- g_platform.device.stop();- g_platform.device.activity = nullptr;- framesResumed(false);- return;+ for (;;) {+ int events;+ android_poll_source* source;+ const int id = ALooper_pollOnce(timeoutMs, nullptr, &events, (void**)&source);+ if (id == ALOOPER_POLL_TIMEOUT) break;+ if (id == ALOOPER_POLL_ERROR) {+ __android_log_print(ANDROID_LOG_ERROR, LOG_TAG, "looper error — leaving the frame loop");+ return;+ }+ if (id >= 0 && source) source->process(app, source);+ if (app->destroyRequested) {+ g_platform.device.stop();+ g_platform.device.activity = nullptr;+ framesResumed(false);+ return;+ }+ timeoutMs = 0; // the rest of what is queued, without waiting for more}+ if (!g_frames.running || eshost::untilFrameDue() > Clock::duration::zero()) continue;+ hints.updateTarget(eshost::framePacer().budget());+ const auto begin = Clock::now();+ eshost::frame();+ hints.report(Clock::now() - begin);}}diff --git a/native/host/platform/desktop.cpp b/native/host/platform/desktop.cppindex 54c80fff7..21ad6717b 100644--- a/native/host/platform/desktop.cpp+++ b/native/host/platform/desktop.cpp@@ -25,6 +25,7 @@#include <SDL3/SDL.h>#include <SDL3/SDL_main.h>+#include <chrono>#include <cstdio>#include <cstring>#include <string>@@ -656,9 +657,16 @@ int main(int argc, char** argv) {SDL_Event e;// A hidden or minimized window has no surface to present to, so the loop// blocks for an event rather than spinning at the display's refresh rate.- if (!eshost::surfaceBound() && SDL_WaitEvent(&e)) handleEvent(e);+ if (!eshost::surfaceBound()) {+ if (SDL_WaitEvent(&e)) handleEvent(e);+ } else if (const auto wait = eshost::untilFrameDue(); wait > std::chrono::steady_clock::duration::zero()) {+ // The game's cap holds the next frame back (FramePacer.hpp): wait for it, serving input meanwhile. Rounded up,+ // since waking early only goes round the loop again. Otherwise the present's own block is the pace.+ const auto ms = std::chrono::duration_cast<std::chrono::milliseconds>(wait + std::chrono::microseconds(999)).count();+ if (SDL_WaitEventTimeout(&e, (Sint32)ms)) handleEvent(e);+ }while (SDL_PollEvent(&e)) handleEvent(e);- if (running && eshost::surfaceBound()) {+ if (running && eshost::surfaceBound() && eshost::untilFrameDue() == std::chrono::steady_clock::duration::zero()) {eshost::frame();// Shown once something has been drawn on it: sizing happens during// boot, and a window shown before that is a default-sized emptydiff --git a/native/host/platform/ios.mm b/native/host/platform/ios.mmindex e2c13e417..d9dfb3ff4 100644--- a/native/host/platform/ios.mm+++ b/native/host/platform/ios.mm@@ -249,7 +249,12 @@ IOSPlatform g_platform;}}-- (void)step:(CADisplayLink*)link { eshost::frame(); }+// The display link is the clock here; the pacer only holds the game's cap (FramePacer.hpp), skipping the vsyncs it falls+// between, as every host does.+- (void)step:(CADisplayLink*)link {+ if (eshost::untilFrameDue(/*floor=*/false) > std::chrono::steady_clock::duration::zero()) return;+ eshost::frame();+}- (void)viewSafeAreaInsetsDidChange {[super viewSafeAreaInsetsDidChange];diff --git a/tests/CMakeLists.txt b/tests/CMakeLists.txtindex b1d172bfa..9c3a64cbc 100644--- a/tests/CMakeLists.txt+++ b/tests/CMakeLists.txt@@ -106,6 +106,14 @@ add_executable(test_touch_streamtarget_include_directories(test_touch_stream PRIVATE ${CMAKE_SOURCE_DIR}/native/host)add_test(NAME test_touch_stream COMMAND test_touch_stream)+# The native hosts' frame pacer: header-only, the cap and the floor every looping+# host draws by (native/host/FramePacer.hpp).+add_executable(test_frame_pacer+ input/test_frame_pacer.cpp+)+target_include_directories(test_frame_pacer PRIVATE ${CMAKE_SOURCE_DIR}/native/host)+add_test(NAME test_frame_pacer COMMAND test_frame_pacer)+# Tilemap system testsadd_executable(test_tilemaptilemap/test_tilemap.cppdiff --git a/tests/input/test_frame_pacer.cpp b/tests/input/test_frame_pacer.cppnew file mode 100644index 000000000..b06170999--- /dev/null+++ b/tests/input/test_frame_pacer.cpp@@ -0,0 +1,87 @@+// SPDX-License-Identifier: Apache-2.0+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team+/**+ * @file The native hosts' frame pacer (native/host/FramePacer.hpp): the game's+ * cap held as a cadence, the web loop's rule, and the floor that keeps a+ * loop whose present stopped blocking from spinning. Header-only and+ * clock-free in its inputs, so the rule is tested here rather than on a+ * device.+ */+#define DOCTEST_CONFIG_IMPLEMENT_WITH_MAIN+#include "doctest.h"++#include "FramePacer.hpp"++using eshost::FramePacer;+using Clock = FramePacer::Clock;+using std::chrono::microseconds;+using std::chrono::milliseconds;++namespace {+const Clock::time_point T0 = Clock::time_point{} + std::chrono::hours(1);+Clock::time_point at(double ms) { return T0 + std::chrono::duration_cast<Clock::duration>(std::chrono::duration<double, std::milli>(ms)); }+double ms(Clock::duration d) { return std::chrono::duration<double, std::milli>(d).count(); }+} // namespace++TEST_CASE("with no cap the present paces, and only the floor holds a frame back") {+ FramePacer p;+ CHECK(p.untilDue(at(0)) == Clock::duration::zero());+ p.frameStarted(at(0));+ // A present that blocked: the next frame is due at once.+ CHECK(p.untilDue(at(16.7)) == Clock::duration::zero());+ // One that did not (a surface going away): held to the floor, 1/240 s after the last start.+ CHECK(ms(p.untilDue(at(0.5))) == doctest::Approx(1000.0 / FramePacer::kFloorFps - 0.5).epsilon(0.01));+}++TEST_CASE("a display-stepped host asks for the cap alone") {+ FramePacer p;+ p.frameStarted(at(0));+ CHECK(p.untilDue(at(2.0), /*floor=*/false) == Clock::duration::zero());+ p.setTarget(30.0f);+ p.frameStarted(at(10));+ CHECK(ms(p.untilDue(at(26.7), false)) == doctest::Approx(16.67).epsilon(0.01));+}++TEST_CASE("a bench lifts the floor") {+ FramePacer p;+ p.setUnbounded(true);+ p.frameStarted(at(0));+ CHECK(p.untilDue(at(0.1)) == Clock::duration::zero());+}++TEST_CASE("a cap is a cadence, not a gap") {+ FramePacer p;+ p.setTarget(30.0f);+ p.frameStarted(at(0));+ // Due 33.3 ms after the first start, whenever the frame itself ended.+ CHECK(ms(p.untilDue(at(20))) == doctest::Approx(13.33).epsilon(0.01));+ // A frame that starts a little late does not push the next one late: the cadence is kept.+ p.frameStarted(at(35));+ CHECK(ms(p.untilDue(at(40))) == doctest::Approx(26.67).epsilon(0.01));+ // Within the jitter of due counts as due (a millisecond-granular wait wakes a little early).+ CHECK(p.untilDue(at(66.0)) == Clock::duration::zero());+}++TEST_CASE("after a stall the cadence restarts from the late frame") {+ FramePacer p;+ p.setTarget(60.0f);+ p.frameStarted(at(0));+ p.frameStarted(at(200)); // a stall: far more than one interval behind+ // Not a burst of catch-up frames: the next is one interval after the late one.+ CHECK(ms(p.untilDue(at(201))) == doctest::Approx(15.67).epsilon(0.01));+}++TEST_CASE("changing the cap restarts the cadence") {+ FramePacer p;+ p.setTarget(30.0f);+ p.frameStarted(at(0));+ p.setTarget(60.0f);+ CHECK(p.target() == 60.0f);+ // No stale 33 ms deadline: only the floor applies until the next frame starts the new cadence.+ CHECK(p.untilDue(at(10)) == Clock::duration::zero());+ p.frameStarted(at(10));+ CHECK(ms(p.untilDue(at(11))) == doctest::Approx(15.67).epsilon(0.01));+ CHECK(ms(p.budget()) == doctest::Approx(16.67).epsilon(0.01));+ p.setTarget(0.0f);+ CHECK(ms(p.budget()) == doctest::Approx(16.67).epsilon(0.01));+}diff --git a/tools/releaseNotes.mjs b/tools/releaseNotes.mjsindex 0c2f37a82..5ea0ce967 100644--- a/tools/releaseNotes.mjs+++ b/tools/releaseNotes.mjs@@ -3830,4 +3830,6 @@ export const NOTED = {{"note":"A native build reports its GPU frame time."},"perf(render): Voxel GI reads its cache plainly where nothing else writes it, and skips empty slots when it ages them, so a phone spends far less on its upkeep and its rays":{"note":"Voxel GI costs less on mobile GPUs."},+ "fix(native): every native host draws from one pacer, its present's own block and the game's cap, so an Android frame near its budget holds 60 fps instead of dropping to 30":+ {"note":"Android frames no longer drop to 30 fps when they come close to the frame budget."},};