Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion dm/gfx/nvn/nvn_mtl.m
Original file line number Diff line number Diff line change
Expand Up @@ -16645,7 +16645,7 @@ - (void)metalDisplayLink:(CAMetalDisplayLink *)link needsUpdate:(CAMetalDisplayL
// 55 Hz, and a game paced by the link runs at 55 fps (27.5 at 30). There the link runs at the screen's rate and only the refreshes nearest a steady clock of the wanted rate count as
// ticks (g_link_vperiod, NvMetalDisplayLinkDelegate): 60 a second on average, each frame shown on the refreshes nearest its 1/60 s slot. DM_LINK_VTICK=0 keeps the system's choice.
// In fullscreen the Mac front end switches such a screen to a rate that is a multiple where it has one (front_screen_match), and the range is set again for it (link_sync)
__attribute__((weak)) int front_screen_max_fps(void) { return 0; } // front_mac.m; graphics unit tests and iOS have none
__attribute__((weak)) int front_screen_max_fps(void) { return 0; } // front_mac.m, front_ios.m; graphics unit tests have none
__attribute__((weak)) void front_screen_match(int fps) { (void)fps; } // front_mac.m; graphics unit tests and iOS have none
__attribute__((weak)) void front_picture_shape(int w, int h) { (void)w; (void)h; } // front_mac.m, front_ios.m; graphics unit tests have none
static CAFrameRateRange link_range(int mode) {
Expand Down
2 changes: 1 addition & 1 deletion dm/host/front.h
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@ static inline void front_hud_env(void) {
void front_run(void (*guest)(void));
// The CAMetalLayer the graphics backend presents frames to (NULL when there is no window)
void *front_metal_layer(void);
// The highest refresh rate of the window's screen in Hz, 0 = not known (Mac front_mac.m; none on iOS, whose screens run at multiples of 60 Hz). Any thread
// The highest refresh rate of the window's screen in Hz, 0 = not known (front_mac.m; front_ios.m: the screen the game's view is on, a TV's while the picture is there). Any thread
int front_screen_max_fps(void);
// The pixel size of the display the game is shown on: on the Mac the window's screen in its current mode (the main display before the window is up) (a scaled Retina mode's pixels), an iPhone's or iPad's screen (nativeBounds).
// Returns 0 and leaves w, h alone when not known (no front end: graphics unit tests). Any thread
Expand Down
16 changes: 15 additions & 1 deletion dm/ios/Sources/front_ios.m
Original file line number Diff line number Diff line change
Expand Up @@ -32,8 +32,14 @@
static void front_ios_audio_watch(void);
static UILabel *front_ios_fps_label(void);

// The highest refresh rate of the screen the game's view is on (front.h front_screen_max_fps): the phone's or iPad's own, a TV's while the picture is there (tv_attach), the screen an
// iPad's window was moved to. Written on the main thread ([DmGameView screenChanged]) and read by the game's and the present thread; 0 until the view is in a window
static _Atomic int g_screen_fps;
int front_screen_max_fps(void) { return g_screen_fps; }

@interface DmGameView : UIView
@property (nonatomic) CGFloat maxPixelWidth; // 0: the screen's own pixels; a TV caps the drawable at 1920 across (tv_attach)
- (void)screenChanged;
@end
@implementation DmGameView
+ (Class)layerClass { return CAMetalLayer.class; }
Expand All @@ -49,7 +55,12 @@ - (instancetype)initWithFrame:(CGRect)f {
}
return self;
}
- (void)didMoveToWindow { [super didMoveToWindow]; [self setNeedsLayout]; } // the phone's screen or a TV's (DmTVSceneDelegate)
- (void)didMoveToWindow { [super didMoveToWindow]; [self screenChanged]; [self setNeedsLayout]; } // the phone's screen or a TV's (DmTVSceneDelegate)
- (void)screenChanged { // the view joined a window, or its window's scene went to another screen (front_ios_scene_changed)
UIScreen *screen = self.window.windowScene.screen; if (!screen) return; // off every window: the last screen's rate stays
int hz = (int)screen.maximumFramesPerSecond, was = g_screen_fps;
g_screen_fps = hz; if (hz != was) LOG("front end: the game's screen shows up to %d Hz", hz);
}
- (void)layoutSubviews { // render at the pixels of the screen the view is on (an iPad window can move to another), at most maxPixelWidth across
[super layoutSubviews];
CAMetalLayer *l = (CAMetalLayer *)self.layer;
Expand Down Expand Up @@ -232,6 +243,9 @@ - (BOOL)prefersStatusBarHidden { return YES; }
- (UIInterfaceOrientationMask)supportedInterfaceOrientations { return UIInterfaceOrientationMaskAll; }
@end
UIViewController *front_ios_root(void) { return [DmRootVC new]; }
void front_ios_scene_changed(UIWindowScene *scene) { // main.m: the app's scene changed its geometry, which UIKit also reports when the scene moves to another screen
if (g_root.game.window.windowScene == scene) [g_root.game screenChanged];
}

// A TV (cable or AirPlay): iOS gives the app the TV as a scene of its own instead of mirroring the phone. The game's view moves there, 16:9 fills the TV, and the game is
// docked as a Switch on its dock (1080p, the operation mode change notification); the phone keeps the pad. Unplugging puts the view back and the mode the game had before
Expand Down
2 changes: 2 additions & 0 deletions dm/ios/Sources/main.m
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,7 @@
int dm_main(int argc, char **argv); // dm/host/main.c compiled in with -Dmain=dm_main
UIViewController *front_ios_root(void);
void front_ios_focus_event(int ev);
void front_ios_scene_changed(UIWindowScene *scene);

static char *g_argv[4]; static int g_argc;

Expand Down Expand Up @@ -262,6 +263,7 @@ - (void)sceneWillResignActive:(UIScene *)s { front_ios_focus_event(0); }
- (void)sceneDidEnterBackground:(UIScene *)s { front_ios_focus_event(1); }
- (void)sceneWillEnterForeground:(UIScene *)s { front_ios_focus_event(2); }
- (void)sceneDidBecomeActive:(UIScene *)s { front_ios_focus_event(3); }
- (void)windowScene:(UIWindowScene *)s didUpdateEffectiveGeometry:(UIWindowSceneGeometry *)was { (void)was; front_ios_scene_changed(s); } // also when the scene moves to another screen
@end

int main(int argc, char **argv) {
Expand Down
84 changes: 84 additions & 0 deletions dm/ios/tests/screen_rate_check.m
Original file line number Diff line number Diff line change
@@ -0,0 +1,84 @@
// A small iOS app that checks the screen rate the front end reports (front.h front_screen_max_fps) on the production game view and scene delegate
// (front_ios.m and main.m, included below). The host's entry points they call are empty here: no game files, no host, no controllers.
// tools/build_screen_rate_check.py builds it; it writes its lines to Documents/screen_rate.log and shows the count on screen.
#import <UIKit/UIKit.h>
#import <GameController/GameController.h>
#include <time.h>
#include "../Sources/front_ios.m"
#define main production_main
#include "../Sources/main.m"
#undef main

uint64_t g_t0_ns;
uint64_t now_ns(void) { struct timespec t; clock_gettime(CLOCK_MONOTONIC, &t); return (uint64_t)t.tv_sec * 1000000000ull + (uint64_t)t.tv_nsec; }
int dm_main(int argc, char **argv) { (void)argc; (void)argv; return 0; }
void dm_host_preload_start(int argc, char **argv) { (void)argc; (void)argv; }
void dm_haptics_apple_init(void) {}
UIView *dm_gamepad_view(CGRect frame) { return [[UIView alloc] initWithFrame:frame]; }
void dm_gamepad_reset(void) {}
void dm_gamepad_active(void) {}
bool dm_show_launcher(void *view, void (*done)(void)) { (void)view; (void)done; return false; }
uint64_t mtl_present_count(void) { return 0; }
void dm_audio_suspend(int on) { (void)on; }
void dm_audio_reset(void) {}
void dm_focus_set(int state) { (void)state; }
void guest_clock_freeze_for(int reason, int on) { (void)reason; (void)on; }
void dm_gfx_suspend(int on) { (void)on; }
void dm_cloud_saves_env(void) {}
void dm_gamepad_arrange(UIView *view, DmLayout layout) { (void)view; (void)layout; }
void dm_gamepad_opmode_changed(void) {}
void dm_gamepad_touch_feedback(bool on) { (void)on; }
void dm_haptics_set_enabled(int on) { (void)on; }
int dm_opmode(void) { return 0; }
void dm_set_opmode(int m) { (void)m; }
int save_sync_flush(int timeout_ms) { (void)timeout_ms; return 1; }

static int g_checks, g_failed;
static void check(const char *name, BOOL ok) { g_checks++; g_failed += !ok; fprintf(stderr, "%s: %s\n", ok ? "ok" : "FAILED", name); }

@interface RateScene : SceneDelegate
@end
@implementation RateScene
- (void)scene:(UIScene *)scene willConnectToSession:(UISceneSession *)session options:(UISceneConnectionOptions *)options {
g_boot_ok = 0; // the root view controller then starts no host (DmRootVC viewDidLoad)
[super scene:scene willConnectToSession:session options:options];
DmRootVC *root = (DmRootVC *)self.window.rootViewController;
for (UIView *v in root.view.subviews.copy) [v removeFromSuperview]; // the "Game files not found" hint
UILabel *text = [[UILabel alloc] initWithFrame:root.view.bounds];
text.autoresizingMask = UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight;
text.numberOfLines = 0; text.textAlignment = NSTextAlignmentCenter; text.textColor = UIColor.whiteColor;
text.text = @"Screen rate check\nrunning";
[root.view addSubview:text];
dispatch_after(dispatch_time(DISPATCH_TIME_NOW, NSEC_PER_SEC), dispatch_get_main_queue(), ^{
UIWindowScene *ws = (UIWindowScene *)scene; int hz = (int)ws.screen.maximumFramesPerSecond;
check("no rate before the game's view is in a window", front_screen_max_fps() == 0);
root.game = [[DmGameView alloc] initWithFrame:root.view.bounds]; g_root = root;
[root.view insertSubview:root.game atIndex:0];
check("the view in the window: the rate of its scene's screen", hz > 0 && front_screen_max_fps() == hz);
g_screen_fps = 1; [root.game removeFromSuperview];
check("the view off every window: the last rate stays", front_screen_max_fps() == 1);
[root.view insertSubview:root.game atIndex:0]; // as the view's move to a TV's window and back (tv_attach, tv_detach)
check("the view in a window again: the rate is read again", front_screen_max_fps() == hz);
g_screen_fps = 1; [self windowScene:ws didUpdateEffectiveGeometry:ws.effectiveGeometry];
check("the scene's geometry changed: the rate is read again", front_screen_max_fps() == hz);
dispatch_async(dispatch_get_global_queue(QOS_CLASS_USER_INITIATED, 0), ^{
int there = front_screen_max_fps();
dispatch_async(dispatch_get_main_queue(), ^{
check("another thread reads the same rate", there == hz);
fprintf(stderr, "screen rate %d Hz: %d checks, %d failed\n", hz, g_checks, g_failed);
text.text = [NSString stringWithFormat:@"Screen rate check\n%d Hz: %d checks, %d failed", hz, g_checks, g_failed];
[root.view bringSubviewToFront:text];
});
});
});
}
@end

int main(int argc, char **argv) {
@autoreleasepool {
NSURL *docs = [NSFileManager.defaultManager URLsForDirectory:NSDocumentDirectory inDomains:NSUserDomainMask][0];
freopen([docs URLByAppendingPathComponent:@"screen_rate.log"].fileSystemRepresentation, "w", stderr);
setvbuf(stderr, NULL, _IOLBF, 0);
return UIApplicationMain(argc, argv, nil, NSStringFromClass(App.class));
}
}
61 changes: 61 additions & 0 deletions dm/ios/tools/build_screen_rate_check.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,61 @@
#!/usr/bin/env python3
"""Build the screen rate check (dm/ios/tests/screen_rate_check.m) as an unsigned iOS app.

Requires Xcode and XcodeGen; GAME (or DM_GAME) selects the profile whose constants the
front end's sources compile with. No game files, keys or signing are used. --output must
name a new directory; every product stays under it. Prints the app's path: install and
open it on a simulator (--simulator) or, once signed, on a device, then read
Documents/screen_rate.log in its container.
"""
import argparse
import json
import os
from pathlib import Path
import subprocess
import sys

REPO = Path(__file__).resolve().parents[3]
LANDSCAPE = ['UIInterfaceOrientationLandscapeLeft', 'UIInterfaceOrientationLandscapeRight']


def main():
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument('--output', required=True, type=Path, help='new scratch directory for the project and build products')
parser.add_argument('--simulator', action='store_true', help='build for the iOS Simulator instead of a device')
args = parser.parse_args()
game = os.environ.get('GAME') or os.environ.get('DM_GAME')
if not game:
parser.error('set GAME (or DM_GAME) to a base game title ID')
root = args.output.resolve()
root.mkdir(parents=True) # Never overwrite an existing project or build.
include = root / 'Include'
include.mkdir()
subprocess.run([sys.executable, '-B', str(REPO / 'dm/games/game.py'), 'header', game, str(include / 'game_profile.h')], check=True)
scene = {'UISceneConfigurationName': 'Default', 'UISceneDelegateClassName': 'RateScene'}
target = {
'type': 'application', 'platform': 'iOS',
'sources': [{'path': str(REPO / 'dm/ios/tests/screen_rate_check.m')}],
'dependencies': [{'sdk': name + '.framework'} for name in ('UIKit', 'QuartzCore', 'Metal', 'AVFAudio', 'GameController')],
'settings': {'base': {
'PRODUCT_BUNDLE_IDENTIFIER': 'dev.nxnative.screen-rate-check', 'ENABLE_DEBUG_DYLIB': 'NO',
'HEADER_SEARCH_PATHS': [str(REPO / 'dm/host'), str(include)],
}},
'info': {'path': 'Info.plist', 'properties': {
'CFBundleDisplayName': 'Screen rate', 'UILaunchScreen': {}, 'UIFileSharingEnabled': True,
'CADisableMinimumFrameDurationOnPhone': True, 'UISupportedInterfaceOrientations': LANDSCAPE,
'UIApplicationSceneManifest': {'UISceneConfigurations': {'UIWindowSceneSessionRoleApplication': [scene]}},
}},
}
project = {'name': 'ScreenRateCheck', 'options': {'deploymentTarget': {'iOS': '26.0'}}, 'targets': {'ScreenRateCheck': target}}
spec = root / 'project.yml'
spec.write_text(json.dumps(project, indent=2) + '\n')
subprocess.run(['xcodegen', 'generate', '--spec', str(spec)], check=True)
sdk = 'iphonesimulator' if args.simulator else 'iphoneos'
subprocess.run(['xcodebuild', '-project', str(root / 'ScreenRateCheck.xcodeproj'), '-scheme', 'ScreenRateCheck', '-configuration', 'Debug',
'-destination', 'generic/platform=iOS Simulator' if args.simulator else 'generic/platform=iOS',
'-derivedDataPath', str(root / 'DerivedData'), '-jobs', '3', 'CODE_SIGNING_ALLOWED=NO', 'build'], check=True)
print(root / f'DerivedData/Build/Products/Debug-{sdk}/ScreenRateCheck.app')


if __name__ == '__main__':
main()
1 change: 1 addition & 0 deletions docs/agents/symptoms.md
Original file line number Diff line number Diff line change
Expand Up @@ -544,6 +544,7 @@ One line per symptom in the [subsystem references](../reference/): what you see
- a steady game whose frame-rate counter wanders between 50 and 60 on the iPhone only; the `display link up to tick` lines show about as many empty ticks as frames dropped by merging: frames arrive two in one tick and none in the next. → [Vulkan acquire and vsync event follow the display link](../reference/frame-rate.md#vulkan-acquire-and-vsync-event-follow-the-display-link)
- a `regress.py` run of an NVN game stays at 20 fps from the start (`frame N not reached`, a NEW-FAIL) in some runs only: `frame step: hold 1 → 2` and `2 → 3 vsyncs` in the first 15 presents, then `display link recovered: stalled 1017 ms` about once a second to the end, and no trial back to a shorter hold. → [A game window another process starts opens behind other windows](../reference/frame-rate.md#a-game-window-another-process-starts-opens-behind-other-windows)
- asked for 60 Hz, the system fires the display link on every third refresh of a 165 Hz screen, 55 Hz, so games paced by it ran at 55 fps (27.5 at 30). → [Virtual 60 Hz ticks on screens that are not a multiple of 60](../reference/frame-rate.md#virtual-60-hz-ticks-on-screens-that-are-not-a-multiple-of-60)
- on an iPhone or iPad the host does not know how fast the screen refreshes. With `DM_FPS_TARGET=120` in a game whose profile has `fps_max 120`, the log reads `120 fps: cap 0 → 60 fps (the screen is below 120 Hz)` on a 120 Hz screen too and the game stays at 60. The display link never counts virtual ticks either, whatever screen the picture is on. → [An iPhone or iPad tells the host its screen's rate](../reference/frame-rate.md#an-iphone-or-ipad-tells-the-host-its-screens-rate)
- virtual ticks keep the average, but a frame still stays up two or three refreshes in turn (13.9 / 20.8 ms at 144 Hz), and Apple's HUD showed the frame interval jumping between them. → [Fullscreen switches the screen to a rate the frame rate divides](../reference/frame-rate.md#fullscreen-switches-the-screen-to-a-rate-the-frame-rate-divides)
- a Mac game in fullscreen holds 60 fps for 45 s to 3 minutes, then the same work takes about twice the GPU time (Tears of the Kingdom 10.5 → 19.7 ms) and the frame step falls to 30 fps. `powermetrics` shows the GPU at its lowest clock (338 MHz on an M4 Pro) while it is 72–98% busy, with thermal pressure nominal. Probes back to 60 fail, because the clock does not rise within a probe. `gamepolicyd` logs `Game mode enabled` and `Set DPS to 2`. → [macOS Game Mode holds the GPU at its lowest clock](../reference/frame-rate.md#macos-game-mode-holds-the-gpu-at-its-lowest-clock)
- a Mac game started with `DM_FULLSCREEN=1` from an app that is itself in fullscreen (the launcher's console mode) came up as a window. → [A game opened from a fullscreen app stays a window](../reference/frame-rate.md#a-game-opened-from-a-fullscreen-app-stays-a-window)
Expand Down
Loading
Loading