#35: interface scale, safe area, and the mobile test kit

MobilePort: ui_scale() (clampf(4.3 / the screen's shorter side in inches, 1, 1.8) times the
Interface size; 1 on desktop), a size-class fallback (below 500 pt = phone, 1.6) when the
density is 0 or implausible, safe_rect(ci) (the display's safe area mapped into ci's canvas
through the final transform), minimum_target() (44 pt in canvas pixels), and the `forced`
override for tests. The desktop preview (-- --mobile) plays the phone in the window:
--safe-area=l,t,r,b insets it, --dpi=N sets its density, and without --dpi a 16:9-or-wider
window is a 2.7 in phone (about 1.6x) and a squarer one a 6 in iPad (1x).

GameSettings: interface_size (0.8-1.3, saved under [touch]) and apply_scale(), which sets the
window's content_scale_factor (always 1 on desktop). PerfTest shows the screen, density, safe
area, and resulting scale, to check the density on a device.

Test kit: test_mobile (last in SUITES) runs game/tests/mobile/*_test.gd in name order and puts
the root window back between files; mobile/touch.gd sends touches through
Input.parse_input_event; scale_test covers phones, iPads, desktop, the safe rect, and the target;
sticks_test is the 8c81d81 driver's 24 checks. game/tools/capture_mobile.gd takes the phone
screenshots.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
Forrest 2026-10-14 14:40:06 -04:00
parent f0291133fd
commit aee60b0ba2
14 changed files with 874 additions and 3 deletions

View file

@ -11,6 +11,8 @@ extends RefCounted
## resolution scale, used when the pixel size is 1 (the HUD stays sharp either way). ## resolution scale, used when the pixel size is 1 (the HUD stays sharp either way).
## * Gameplay: whether the tips show on the first day and night (Tutorial). ## * Gameplay: whether the tips show on the first day and night (Tutorial).
## * Co-op: your player name, and whether your microphone is sent in voice chat. ## * Co-op: your player name, and whether your microphone is sent in voice chat.
## * Touch (phones): the interface size, times the scale the screen's size calls for
## (MobilePort.ui_scale; it doesn't change desktop).
## Values missing from the file or out of range fall back to the defaults, so an old or ## Values missing from the file or out of range fall back to the defaults, so an old or
## hand-edited file never breaks the game. ## hand-edited file never breaks the game.
@ -33,6 +35,8 @@ var show_tips := true
## Co-op: your name for the lobby and the name tag, and whether your microphone is sent. ## Co-op: your name for the lobby and the name tag, and whether your microphone is sent.
var player_name := "" var player_name := ""
var microphone := true var microphone := true
## Phones: the Interface size, 0.8-1.3 times the scale the screen calls for (MobilePort.ui_scale).
var interface_size := 1.0
static func load_from(path: String = PATH) -> GameSettings: static func load_from(path: String = PATH) -> GameSettings:
@ -52,6 +56,7 @@ static func load_from(path: String = PATH) -> GameSettings:
var n: Variant = f.get_value("coop", "player_name", "") var n: Variant = f.get_value("coop", "player_name", "")
g.player_name = String(n).strip_edges().left(20) if n is String else "" g.player_name = String(n).strip_edges().left(20) if n is String else ""
g.microphone = _flag(f.get_value("coop", "microphone", g.microphone), g.microphone) g.microphone = _flag(f.get_value("coop", "microphone", g.microphone), g.microphone)
g.interface_size = _number(f.get_value("touch", "interface_size", g.interface_size), 0.8, 1.3, g.interface_size)
return g return g
@ -68,11 +73,12 @@ func save_to(path: String = PATH) -> Error:
f.set_value("gameplay", "show_tips", show_tips) f.set_value("gameplay", "show_tips", show_tips)
f.set_value("coop", "player_name", player_name) f.set_value("coop", "player_name", player_name)
f.set_value("coop", "microphone", microphone) f.set_value("coop", "microphone", microphone)
f.set_value("touch", "interface_size", interface_size)
return f.save(path) return f.save(path)
## Applies everything: bus volumes, dead zones (into config too, when given), and the display ## Applies everything: bus volumes, dead zones (into config too, when given), the interface
## (skipped without a real display, e.g. headless). ## scale, and the display (skipped without a real display, e.g. headless).
func apply(viewport: Viewport, config: GameConfig = null) -> void: func apply(viewport: Viewport, config: GameConfig = null) -> void:
for bus in BUSES: for bus in BUSES:
var i := AudioServer.get_bus_index(bus) var i := AudioServer.get_bus_index(bus)
@ -88,6 +94,7 @@ func apply(viewport: Viewport, config: GameConfig = null) -> void:
config.aim_dead_zone = aim_dead_zone config.aim_dead_zone = aim_dead_zone
if viewport != null: if viewport != null:
apply_pixels(viewport) apply_pixels(viewport)
apply_scale(viewport)
if DisplayServer.get_name() == "headless": if DisplayServer.get_name() == "headless":
return return
var mode := DisplayServer.window_get_mode() var mode := DisplayServer.window_get_mode()
@ -112,6 +119,15 @@ func apply_pixels(viewport: Viewport) -> void:
viewport.msaa_3d = ProjectSettings.get_setting("rendering/anti_aliasing/quality/msaa_3d", Viewport.MSAA_DISABLED) viewport.msaa_3d = ProjectSettings.get_setting("rendering/anti_aliasing/quality/msaa_3d", Viewport.MSAA_DISABLED)
## The interface scale (MobilePort.ui_scale: on a phone, the screen's size times
## interface_size; always 1 on desktop) as the window's content_scale_factor, which scales every
## CanvasLayer (the HUD, the menus, the sticks) and leaves the 3D view alone.
func apply_scale(viewport: Viewport) -> void:
var window := viewport.get_window()
if window != null:
window.content_scale_factor = MobilePort.ui_scale(interface_size)
static func _number(v: Variant, lo: float, hi: float, fallback: float) -> float: static func _number(v: Variant, lo: float, hi: float, fallback: float) -> float:
if not (v is float or v is int): if not (v is float or v is int):
return fallback return fallback

View file

@ -7,15 +7,233 @@ extends RefCounted
## main menu's button and the settings' Co-op section), two thumbsticks move and attack ## main menu's button and the settings' Co-op section), two thumbsticks move and attack
## (TouchSticks), and leaving the app pauses the game. ## (TouchSticks), and leaving the app pauses the game.
## The microphone is never opened (audio/driver/enable_input.mobile in project.godot). ## The microphone is never opened (audio/driver/enable_input.mobile in project.godot).
## The interface is scaled for the screen's physical size (ui_scale) and kept inside its safe
## area (safe_rect), with touch targets of at least minimum_target(); see below.
## * perf_test(): the iOS preset's "perf_test" feature. Main adds PerfTest (the frame-time ## * perf_test(): the iOS preset's "perf_test" feature. Main adds PerfTest (the frame-time
## readout and test buttons), and CampaignDebug's jumps work in that release build. ## readout and test buttons), and CampaignDebug's jumps work in that release build.
## On desktop, `-- --mobile` and `-- --perf-test` after the usual arguments turn the same switches ## On desktop, `-- --mobile` and `-- --perf-test` after the usual arguments turn the same switches
## on, to see the phone build without a phone (add --rendering-method mobile for its renderer). ## on, to see the phone build without a phone (add --rendering-method mobile for its renderer).
## Tests: -1 detects the platform, 0 forces desktop, 1 forces a phone.
static var forced := -1
static func active() -> bool: static func active() -> bool:
if forced >= 0:
return forced == 1
return OS.has_feature("mobile") or "--mobile" in OS.get_cmdline_user_args() return OS.has_feature("mobile") or "--mobile" in OS.get_cmdline_user_args()
static func perf_test() -> bool: static func perf_test() -> bool:
return OS.has_feature("perf_test") or "--perf-test" in OS.get_cmdline_user_args() return OS.has_feature("perf_test") or "--perf-test" in OS.get_cmdline_user_args()
## --- The interface on a phone: its scale, the safe area, and the touch target ---
## ui_scale() is the root window's content_scale_factor on a phone (GameSettings.apply). It
## scales every CanvasLayer (the HUD, the menus, the sticks) and leaves the 3D view alone. It's
## worked out from the screen's physical size: clampf(4.3 / the shorter side in inches, 1, 1.8),
## about 1.6 on a phone and 1 on an iPad, times the Interface size setting (0.8-1.3). At 1.6 a
## 19.5:9 phone's canvas is about 1460x675 instead of 2340x1080. Desktop is always 1.
## The density (screen_get_dpi) isn't trusted blindly: when it's 0 or impossible for a phone or a
## tablet (DPI_RANGE, INCH_RANGE), the size class decides: a shorter side below 500 points is a
## phone (1.6), anything bigger a tablet (1). PerfTest shows what a device reports (describe()).
## The desktop preview (-- --mobile, or tests' forced = 1) plays the phone in the window:
## * --dpi=N (or preview_dpi) gives the window that density. Without it, a window at least
## 1.7:1 (16:9 and wider) is a phone whose shorter side is 2.7 in (about 1.6x), a squarer one
## an iPad's 6 in (1x).
## * --safe-area=left,top,right,bottom (or preview_insets) insets the safe area by that many
## window pixels on each side, to stand in for a notch and the home indicator.
## Apple's minimum touch target, in points (an iPhone's pixels over its screen scale).
const TARGET_PT := 44.0
## The scale from the screen's size: this many inches across the shorter side is 1x.
const REFERENCE_INCHES := 4.3
const MIN_SCALE := 1.0
const MAX_SCALE := 1.8
## The size class, when the density can't be trusted: a phone's shorter side is below this many
## points, and gets PHONE_SCALE; anything bigger is a tablet (TABLET_SCALE).
const PHONE_POINTS := 500.0
const PHONE_SCALE := 1.6
const TABLET_SCALE := 1.0
## The densities (dots per inch) and shorter sides (inches) a phone or a tablet can have. Outside
## them the reported density is wrong.
const DPI_RANGE := Vector2(120.0, 800.0)
const INCH_RANGE := Vector2(1.5, 13.0)
## An original iPhone's density: one point per pixel. Pixels per point are the density over it
## where the screen doesn't say (the desktop preview).
const POINT_DPI := 163.0
## The desktop preview without --dpi: a window at least this wide for its height is a phone with
## PREVIEW_PHONE_INCHES across its shorter side, a squarer one an iPad with PREVIEW_TABLET_INCHES.
const PREVIEW_PHONE_ASPECT := 1.7
const PREVIEW_PHONE_INCHES := 2.7
const PREVIEW_TABLET_INCHES := 6.0
## The desktop preview's density (dots per inch). 0: the --dpi=N user argument, or by the
## window's shape (see above).
static var preview_dpi := 0.0
## The desktop preview's safe-area insets in window pixels: [left, top, right, bottom]. Empty:
## the --safe-area=l,t,r,b user argument, or none.
static var preview_insets: Array = []
## A phone in the desktop preview (active() without the "mobile" feature: -- --mobile, or a test).
static func previewing() -> bool:
return active() and not OS.has_feature("mobile")
## The interface scale (the window's content_scale_factor): screen_scale() times interface_size
## (the Interface size setting, 0.8-1.3) on a phone; 1 on desktop.
static func ui_scale(interface_size: float = 1.0) -> float:
if not active():
return 1.0
return screen_scale() * clampf(interface_size, 0.8, 1.3)
## The scale this screen's physical size calls for (scale_for), before the Interface size.
static func screen_scale() -> float:
return scale_for(screen_pixels(), screen_dpi(), pixels_per_point())
## The scale for a screen this many pixels across, at this density (dots per inch), with this
## many pixels per point: clampf(4.3 / the shorter side in inches, 1, 1.8). When the density
## can't be right (dpi_plausible), the size class: below PHONE_POINTS points across the shorter
## side is a phone (1.6), else a tablet (1).
static func scale_for(pixels: Vector2, dpi: float, per_point: float) -> float:
var short := minf(pixels.x, pixels.y)
if dpi_plausible(pixels, dpi):
return clampf(REFERENCE_INCHES / (short / dpi), MIN_SCALE, MAX_SCALE)
return PHONE_SCALE if short / maxf(per_point, 0.001) < PHONE_POINTS else TABLET_SCALE
## Whether a screen this many pixels across could have this density: one inside DPI_RANGE, which
## makes the shorter side a length inside INCH_RANGE.
static func dpi_plausible(pixels: Vector2, dpi: float) -> bool:
if dpi < DPI_RANGE.x or dpi > DPI_RANGE.y:
return false
var inches := minf(pixels.x, pixels.y) / dpi
return inches >= INCH_RANGE.x and inches <= INCH_RANGE.y
## The phone's screen in pixels: the screen on a phone, the window in the desktop preview.
static func screen_pixels() -> Vector2:
if previewing():
var root := _root()
return Vector2(root.size) if root != null else Vector2.ZERO
return Vector2(DisplayServer.screen_get_size())
## The screen's density (dots per inch): the screen's own on a phone; in the desktop preview
## preview_dpi, --dpi=N, or the phone's or the iPad's by the window's shape.
static func screen_dpi() -> float:
if not previewing():
return float(DisplayServer.screen_get_dpi())
if preview_dpi > 0.0:
return preview_dpi
var arg := _arg("--dpi=")
if arg.is_valid_float() and float(arg) > 0.0:
return float(arg)
var px := screen_pixels()
var short := minf(px.x, px.y)
var phone := maxf(px.x, px.y) >= PREVIEW_PHONE_ASPECT * short
return short / (PREVIEW_PHONE_INCHES if phone else PREVIEW_TABLET_INCHES)
## Pixels per point: the screen's scale on a phone (2 or 3 on an iPhone; Android's density
## over 160), else the density over POINT_DPI (the desktop preview, or a phone that says 1 and
## has a plausible density), else 1.
static func pixels_per_point() -> float:
var dpi := screen_dpi()
if previewing():
return maxf(dpi / POINT_DPI, 0.001)
var s := DisplayServer.screen_get_scale()
if s > 1.0:
return s
return dpi / POINT_DPI if dpi_plausible(screen_pixels(), dpi) else 1.0
## The safe area in window pixels: the display's (DisplayServer.get_display_safe_area: clear of
## the notch, the rounded corners and the home indicator) on a phone; the window less the
## preview's insets in the desktop preview. The whole window when there's none.
static func safe_area_pixels(window: Window) -> Rect2:
var full := Rect2(Vector2.ZERO, Vector2(window.size))
var safe := full
if previewing():
var inset := insets()
safe = Rect2(full.position + Vector2(inset[0], inset[1]),
(full.size - Vector2(inset[0] + inset[2], inset[1] + inset[3])).max(Vector2.ZERO))
elif active():
safe = Rect2(DisplayServer.get_display_safe_area()).abs()
safe.position -= Vector2(DisplayServer.window_get_position()) # screen to window (0 when full screen)
safe = safe.intersection(full)
return safe if safe.has_area() else full
## The preview's safe-area insets in window pixels, [left, top, right, bottom]: preview_insets,
## or --safe-area=l,t,r,b, or none.
static func insets() -> Array:
var from: Array = preview_insets
if from.size() != 4:
from = Array(_arg("--safe-area=").split(","))
var out: Array = []
for v: Variant in from:
var x := float(v) if v is float or v is int or (v is String and (v as String).is_valid_float()) else NAN
if is_nan(x):
return [0.0, 0.0, 0.0, 0.0]
out.append(maxf(x, 0.0))
return out if out.size() == 4 else [0.0, 0.0, 0.0, 0.0]
## The safe area in ci's canvas coordinates (the window's pixels through the viewport's final
## transform and ci's canvas layer, so with the interface scale): where the HUD's widgets and
## the menus go on a phone. On desktop, the whole visible rect.
static func safe_rect(ci: CanvasItem) -> Rect2:
if not active():
return ci.get_viewport_rect()
return _to_window(ci).affine_inverse() * safe_area_pixels(ci.get_window())
## Apple's minimum touch target (44 points) in canvas pixels at the current scale, for ci's
## canvas (the root window's without one): about 70 on a phone or an iPad. 44 on desktop.
static func minimum_target(ci: CanvasItem = null) -> float:
if not active():
return TARGET_PT
var s := absf(_to_window(ci).get_scale().y)
return TARGET_PT * pixels_per_point() / s if s > 0.0 else TARGET_PT
## Two lines for PerfTest's overlay, to check on a device what it reports: the screen (pixels,
## density, pixels per point) and the display's safe area as reported (the simulated one in the
## desktop preview); then the scale and how it was worked out, the window's factor, and the
## canvas and the touch target that gives.
static func describe() -> String:
var px := screen_pixels()
var dpi := screen_dpi()
var root := _root()
var safe := Rect2i(safe_area_pixels(root)) if previewing() and root != null else DisplayServer.get_display_safe_area()
var canvas := root.get_visible_rect().size if root != null else Vector2.ZERO
return "Screen %d×%d · %d dpi · %.2f px/pt · safe area %d,%d %d×%d\nScale ×%.2f (%s) · window ×%.2f · canvas %d×%d · 44 pt = %d px" % [
roundi(px.x), roundi(px.y), roundi(dpi), pixels_per_point(), safe.position.x, safe.position.y, safe.size.x, safe.size.y,
screen_scale(), "dpi" if dpi_plausible(px, dpi) else "size class", root.content_scale_factor if root != null else 1.0,
roundi(canvas.x), roundi(canvas.y), roundi(minimum_target())]
## ci's canvas coordinates to window pixels (the root window's canvas without ci).
static func _to_window(ci: CanvasItem) -> Transform2D:
if ci != null:
return ci.get_viewport().get_final_transform() * ci.get_canvas_transform()
var root := _root()
return root.get_final_transform() if root != null else Transform2D.IDENTITY
static func _root() -> Window:
var tree := Engine.get_main_loop() as SceneTree
return tree.root if tree != null else null
## The value of a `--name=value` user argument ("" without one).
static func _arg(prefix: String) -> String:
for a: String in OS.get_cmdline_user_args():
if a.begins_with(prefix):
return a.trim_prefix(prefix)
return ""

View file

@ -4,7 +4,9 @@ extends CanvasLayer
## late night on a phone (docs/ios-test-port.md). Over everything, top centre: ## late night on a phone (docs/ios-test-port.md). Over everything, top centre:
## * Now, over the last second: FPS, the frame time (average and worst), the CPU time in ## * Now, over the last second: FPS, the frame time (average and worst), the CPU time in
## physics (the farm's tick, FarmSim.step, runs there) and in rendering, the GPU time to draw ## physics (the farm's tick, FarmSim.step, runs there) and in rendering, the GPU time to draw
## the view, the enemies alive, the 3D view's render size, and the renderer and device. ## the view, the enemies alive, the 3D view's render size, and the renderer and device. And
## the screen as the device reports it (size, density, safe area) with the interface scale
## that gives (MobilePort.describe), to check the density on a phone.
## * This night, from its start to its end (then held until the next night): the frame time's ## * This night, from its start to its end (then held until the next night): the frame time's
## average, 99th percentile, and worst, the share of frames slower than 30 FPS, the peak ## average, 99th percentile, and worst, the share of frames slower than 30 FPS, the peak
## enemies alive, and how long it ran. Frames while paused aren't counted. Printed as one ## enemies alive, and how long it ran. Frames while paused aren't counted. Printed as one
@ -145,6 +147,7 @@ func _refresh(now: int) -> void:
roundi(_second_frames * 1000.0 / span), span / n, _second_worst, _second_physics / n, _second_physics_worst, roundi(_second_frames * 1000.0 / span), span / n, _second_worst, _second_physics / n, _second_physics_worst,
_second_render_cpu / n, "%.1f ms" % gpu if gpu > 0.0 else "n/a", enemies, roundi(size_3d.x), roundi(size_3d.y), _second_render_cpu / n, "%.1f ms" % gpu if gpu > 0.0 else "n/a", enemies, roundi(size_3d.x), roundi(size_3d.y),
RenderingServer.get_current_rendering_method(), RenderingServer.get_current_rendering_driver_name(), OS.get_model_name()] RenderingServer.get_current_rendering_method(), RenderingServer.get_current_rendering_driver_name(), OS.get_model_name()]
_now.text += "\n" + MobilePort.describe() # the screen as the phone reports it, and the interface scale it gives
if _in_night: if _in_night:
_night.text = _describe_night("so far") _night.text = _describe_night("so far")
_second_usec = now _second_usec = now

View file

@ -0,0 +1,244 @@
extends RefCounted
## The interface scale and the safe area (MobilePort, GameSettings, #35):
## * scale_for: phones about 1.6 (clamped to 1.8 for the smallest), iPads and desktop 1, the
## same in portrait; a missing or impossible density falls back to the size class.
## * ui_scale: 1 on desktop whatever the Interface size; on a phone, the screen's scale times
## the Interface size (clamped to 0.8-1.3). The desktop preview plays a phone or an iPad by
## the window's shape, or at preview_dpi.
## * GameSettings: interface_size saves, loads, and falls back; apply() sets the window's
## content_scale_factor on a phone (the canvas shrinks by it) and leaves desktop at 1 with the
## same canvas.
## * safe_rect: the whole visible rect on desktop (insets ignored), the window less the
## simulated insets on a phone, mapped into the canvas with the scale; the insets parse.
## * minimum_target: 44 on desktop; on a phone 44 points (about 70 canvas pixels), whatever the
## window's size, and smaller in canvas pixels as the Interface size grows.
const SETTINGS := "user://test_mobile_scale_settings.cfg"
const PHONE := Vector2i(2340, 1080) # 19.5:9
const IPAD := Vector2i(1600, 1200) # 4:3
var t: GameTestRunner
var _layer: CanvasLayer
var _probe: Control
func run(p_t: GameTestRunner) -> void:
t = p_t
var root := t.root
var size := root.size
var factor := root.content_scale_factor
var pixels := [root.scaling_3d_mode, root.scaling_3d_scale, root.msaa_3d]
_layer = CanvasLayer.new()
_probe = Control.new()
_layer.add_child(_probe)
root.add_child(_layer)
_probe.set_anchors_and_offsets_preset(Control.PRESET_FULL_RECT)
_devices()
_settings_file()
await _desktop()
await _phone()
await _ipad()
await _min_target()
_insets()
MobilePort.forced = -1
MobilePort.preview_dpi = 0.0
MobilePort.preview_insets = []
GameSettings.new().apply(null) # the defaults for the audio and dead zones, as test_save does
root.size = size
root.content_scale_factor = factor
root.scaling_3d_mode = pixels[0]
root.scaling_3d_scale = pixels[1]
root.msaa_3d = pixels[2]
_layer.queue_free()
await t.process_frame
if FileAccess.file_exists(SETTINGS):
DirAccess.remove_absolute(ProjectSettings.globalize_path(SETTINGS))
## scale_for: real screens (pixels, density, pixels per point).
func _devices() -> void:
var cases := [
# name, pixels, dpi, px/pt, low, high
["iPhone 15", Vector2(2556, 1179), 460.0, 3.0, 1.6, 1.75],
["iPhone 15 Pro Max", Vector2(2796, 1290), 460.0, 3.0, 1.5, 1.6],
["iPhone 13 mini", Vector2(2340, 1080), 476.0, 3.0, 1.8, 1.8],
["iPhone SE", Vector2(1334, 750), 326.0, 2.0, 1.8, 1.8],
["iPad (10th)", Vector2(2360, 1640), 264.0, 2.0, 1.0, 1.0],
["iPad mini", Vector2(2266, 1488), 326.0, 2.0, 1.0, 1.0],
["iPad Pro 13\"", Vector2(2752, 2064), 264.0, 2.0, 1.0, 1.0],
["a 1080p desktop monitor", Vector2(1920, 1080), 96.0, 1.0, 1.0, 1.0],
]
for c: Array in cases:
var s := MobilePort.scale_for(c[1], c[2], c[3])
t.check(s >= c[4] - 0.005 and s <= c[5] + 0.005, "%s: scale %.2f (want %.2f-%.2f)" % [c[0], s, c[4], c[5]])
var portrait := MobilePort.scale_for(Vector2(c[1].y, c[1].x), c[2], c[3])
t.check(is_equal_approx(portrait, s), "%s: the same in portrait (%.2f)" % [c[0], portrait])
t.check(is_equal_approx(MobilePort.scale_for(Vector2(2556, 1179), 460.0, 3.0), 4.3 / (1179.0 / 460.0)),
"the scale is 4.3 inches over the shorter side's")
# The size class, for a density of 0 or one that can't be right.
t.check(MobilePort.scale_for(Vector2(2556, 1179), 0.0, 3.0) == MobilePort.PHONE_SCALE, "no density: a phone (393 pt) gets 1.6")
t.check(MobilePort.scale_for(Vector2(2556, 1179), 72.0, 3.0) == MobilePort.PHONE_SCALE, "72 dpi on a phone's pixels: the size class (1.6)")
t.check(MobilePort.scale_for(Vector2(2556, 1179), 2000.0, 3.0) == MobilePort.PHONE_SCALE, "2000 dpi: the size class (1.6)")
t.check(MobilePort.scale_for(Vector2(2360, 1640), 0.0, 2.0) == MobilePort.TABLET_SCALE, "no density: an iPad (820 pt) gets 1")
t.check(MobilePort.scale_for(Vector2(1334, 750), 0.0, 2.0) == MobilePort.PHONE_SCALE, "no density: an iPhone SE (375 pt) gets 1.6")
t.check(not MobilePort.dpi_plausible(Vector2(1179, 2556), 0.0) and MobilePort.dpi_plausible(Vector2(1179, 2556), 460.0),
"0 dpi is never trusted; an iPhone's 460 is")
## interface_size in the settings file: saved, loaded, clamped, and a default when it's wrong.
func _settings_file() -> void:
var g := GameSettings.new()
t.check(g.interface_size == 1.0, "Interface size defaults to 100%")
g.interface_size = 1.25
g.save_to(SETTINGS)
t.check(is_equal_approx(GameSettings.load_from(SETTINGS).interface_size, 1.25), "Interface size saves and loads")
var f := ConfigFile.new()
f.load(SETTINGS)
f.set_value("touch", "interface_size", 5.0)
f.save(SETTINGS)
t.check(GameSettings.load_from(SETTINGS).interface_size == 1.3, "a size above 130% loads as 130%")
f.set_value("touch", "interface_size", "big")
f.save(SETTINGS)
t.check(GameSettings.load_from(SETTINGS).interface_size == 1.0, "a size that isn't a number loads as 100%")
## Desktop: factor 1, the same canvas, whatever the Interface size, and insets don't apply.
func _desktop() -> void:
MobilePort.forced = 0
MobilePort.preview_insets = [140, 0, 140, 60]
var root := t.root
for size: Vector2i in [Vector2i(1920, 1080), PHONE]:
root.size = size
var g := GameSettings.new()
g.interface_size = 1.3
g.apply(root)
await t.process_frame
t.check(root.content_scale_factor == 1.0 and MobilePort.ui_scale(1.3) == 1.0 and MobilePort.ui_scale(0.8) == 1.0,
"desktop %s: the factor stays 1 (%.2f)" % [size, root.content_scale_factor])
var want := Vector2(size) * (1080.0 / size.y) # the 1080-tall canvas, as before
t.check(root.get_visible_rect().size.is_equal_approx(want), "desktop %s: the canvas is %s (%s)" % [size, want, root.get_visible_rect().size])
t.check(MobilePort.safe_rect(_probe) == _probe.get_viewport_rect(), "desktop %s: the safe rect is the visible rect" % size)
t.check(MobilePort.minimum_target() == 44.0 and MobilePort.minimum_target(_probe) == 44.0, "desktop: the minimum target is 44")
t.check(Vector2(root.get_final_transform().get_scale()).is_equal_approx(Vector2.ONE), "desktop 2340x1080: no extra scale")
MobilePort.preview_insets = []
## A 19.5:9 phone in the preview: about 1.6, applied as the window's factor, and the safe rect
## inside the notch and home indicator insets.
func _phone() -> void:
MobilePort.forced = 1
var root := t.root
root.size = PHONE
t.check(MobilePort.previewing(), "forced to a phone on desktop: the preview")
var s := MobilePort.screen_scale()
t.check(s > 1.55 and s < 1.65, "a 19.5:9 window plays a phone: scale %.2f (about 1.6)" % s)
t.check(is_equal_approx(MobilePort.ui_scale(), s) and is_equal_approx(MobilePort.ui_scale(1.25), s * 1.25)
and is_equal_approx(MobilePort.ui_scale(5.0), s * 1.3) and is_equal_approx(MobilePort.ui_scale(0.1), s * 0.8),
"ui_scale is that times the Interface size, clamped to 0.8-1.3")
MobilePort.preview_dpi = 460.0
root.size = Vector2i(2556, 1179)
t.check(is_equal_approx(MobilePort.screen_scale(), 4.3 / (1179.0 / 460.0)), "preview_dpi 460 at 2556x1179: an iPhone 15's %.2f" % MobilePort.screen_scale())
MobilePort.preview_dpi = 0.0
root.size = PHONE
var g := GameSettings.new()
g.apply(root)
await t.process_frame
t.check(is_equal_approx(root.content_scale_factor, s), "GameSettings.apply sets the factor to the scale (%.2f)" % root.content_scale_factor)
var canvas := root.get_visible_rect().size
t.check(canvas.is_equal_approx(Vector2(PHONE) / s), "the canvas shrinks by it: %s" % canvas)
t.check(canvas.x > 1400.0 and canvas.x < 1520.0 and canvas.y > 650.0 and canvas.y < 700.0, "about 1460x675 (%s)" % canvas)
t.check(_probe.size.is_equal_approx(canvas), "a full-rect HUD Control gets that canvas (%s)" % _probe.size)
g.interface_size = 1.25
g.apply_scale(root)
await t.process_frame
t.check(is_equal_approx(root.content_scale_factor, s * 1.25), "Interface size 125%%: factor %.2f" % root.content_scale_factor)
g.interface_size = 1.0
g.apply_scale(root)
await t.process_frame
# The safe rect, no inset: the whole canvas.
var full := MobilePort.safe_rect(_probe)
t.check(full.position.is_zero_approx() and full.size.is_equal_approx(canvas), "no inset: the safe rect is the canvas (%s)" % full)
# A notch on both sides (the phone may turn either way) and the home indicator.
MobilePort.preview_insets = [140, 0, 140, 60]
var safe := MobilePort.safe_rect(_probe)
var want := Rect2(Vector2(140.0, 0.0) / s, Vector2(PHONE.x - 280.0, PHONE.y - 60.0) / s)
t.check(safe.position.is_equal_approx(want.position) and safe.size.is_equal_approx(want.size),
"inset 140,0,140,60 px: the safe rect %s (want %s)" % [safe, want])
t.check(Rect2(Vector2.ZERO, canvas).encloses(safe), "it's inside the canvas")
var corner := Vector2(root.get_final_transform() * safe.end)
t.check(corner.is_equal_approx(Vector2(PHONE.x - 140.0, PHONE.y - 60.0)), "its far corner is %s window pixels (2200, 1020)" % corner)
var line := MobilePort.describe() # PerfTest's readout
t.check(line.contains("Screen 2340×1080 · 400 dpi") and line.contains("safe area 140,0 2060×1020") and line.contains("(dpi)")
and line.contains("canvas 1469×678"), "describe(): %s" % line.replace("\n", " / "))
# A layer that's moved and scaled gets the same area in its own coordinates.
var moved := CanvasLayer.new()
moved.offset = Vector2(100.0, 50.0)
moved.scale = Vector2(2.0, 2.0)
var c := Control.new()
moved.add_child(c)
root.add_child(moved)
var there := MobilePort.safe_rect(c)
t.check(there.position.is_equal_approx((want.position - moved.offset) / 2.0) and there.size.is_equal_approx(want.size / 2.0),
"in a moved, scaled layer: %s" % there)
moved.free()
# Too much inset: the whole window rather than nothing.
MobilePort.preview_insets = [2000, 0, 2000, 0]
t.check(MobilePort.safe_rect(_probe).size.is_equal_approx(canvas), "insets wider than the window: the whole canvas")
MobilePort.preview_insets = []
## A 4:3 window plays an iPad: 1x, the canvas 1920x1440 as before.
func _ipad() -> void:
MobilePort.forced = 1
var root := t.root
root.size = IPAD
var s := MobilePort.screen_scale()
t.check(s == 1.0, "a 4:3 window plays an iPad: scale %.2f" % s)
GameSettings.new().apply_scale(root)
await t.process_frame
t.check(root.content_scale_factor == 1.0 and root.get_visible_rect().size.is_equal_approx(Vector2(1920.0, 1440.0)),
"4:3 at 1x: the canvas is 1920x1440 (%s)" % root.get_visible_rect().size)
MobilePort.preview_insets = [0, 40, 0, 40]
var safe := MobilePort.safe_rect(_probe)
var k := 1920.0 / IPAD.x # canvas pixels per window pixel
t.check(safe.position.is_equal_approx(Vector2(0.0, 40.0 * k)) and safe.size.is_equal_approx(Vector2(1920.0, (IPAD.y - 80.0) * k)),
"4:3 inset 0,40,0,40: %s" % safe)
MobilePort.preview_insets = []
## The minimum touch target: 44 points, about 70 canvas pixels on a phone and on an iPad, the
## same at any window size, and smaller in canvas pixels as the Interface size grows.
func _min_target() -> void:
MobilePort.forced = 1
var root := t.root
var targets := {}
for size: Vector2i in [PHONE, Vector2i(1170, 540), IPAD]:
root.size = size
GameSettings.new().apply_scale(root)
await t.process_frame
var m := MobilePort.minimum_target(_probe)
targets[size] = m
t.check(m > 60.0 and m < 80.0, "%s: the minimum target is %.1f canvas px (about 70)" % [size, m])
t.check(is_equal_approx(m, MobilePort.minimum_target()), "%s: the same without a canvas item" % size)
var points := m * root.get_final_transform().get_scale().y / MobilePort.pixels_per_point()
t.check(is_equal_approx(points, 44.0), "%s: that's 44 points (%.2f)" % [size, points])
t.check(is_equal_approx(targets[PHONE], targets[Vector2i(1170, 540)]), "the phone's target doesn't depend on the window's pixels")
root.size = PHONE
var g := GameSettings.new()
g.interface_size = 1.3
g.apply_scale(root)
await t.process_frame
t.check(is_equal_approx(MobilePort.minimum_target(_probe), targets[PHONE] / 1.3), "at 130%% it's 1.3 times fewer canvas pixels (%.1f)" % MobilePort.minimum_target(_probe))
## The insets parse from numbers or text (as --safe-area=l,t,r,b), and anything else is none.
func _insets() -> void:
MobilePort.forced = 1
MobilePort.preview_insets = ["140", "0", "140.5", "60"]
t.check(MobilePort.insets() == [140.0, 0.0, 140.5, 60.0], "text insets parse: %s" % [MobilePort.insets()])
MobilePort.preview_insets = [10, -5, 0, 0]
t.check(MobilePort.insets() == [10.0, 0.0, 0.0, 0.0], "a negative inset is none")
MobilePort.preview_insets = ["a", "0", "0", "0"]
t.check(MobilePort.insets() == [0.0, 0.0, 0.0, 0.0], "a bad inset: none at all")
MobilePort.preview_insets = []
t.check(MobilePort.insets() == [0.0, 0.0, 0.0, 0.0], "no --safe-area: no inset")

View file

@ -0,0 +1 @@
uid://cmrhytpkiqesd

View file

@ -0,0 +1,187 @@
extends RefCounted
## The thumbsticks (TouchSticks) by touch, through the game's entry scene (main.tscn, with test
## save and settings paths) on a 19.5:9 phone at its interface scale: the 24 checks of the
## driver that came with them (8c81d81).
## * On a phone Main adds them, fire loses its mouse button, and combat aims by stick.
## * A finger on the right half is the move stick (it walks; its emulated click doesn't fire),
## one on the left half the attack stick (it aims screen-up and attacks while held, without
## switching combat to mouse aim); both work at once, and lifting a finger stops it. A tilt
## inside the aim dead zone doesn't fire.
## * A pause lets go of the sticks, and nothing walks on after it.
## * A button gets its touch first: no stick starts.
## * In the intro the sticks are off, and a held finger skips it.
## The InputMap's mouse buttons for fire and offhand (TouchSticks erases them) are put back.
const Touch := preload("res://game/tests/mobile/touch.gd")
const SAVE := "user://test_sticks_save.json"
const SETTINGS := "user://test_sticks_settings.cfg"
const PHONE := Vector2i(2340, 1080)
var t: GameTestRunner
var main: Main
var attacks: Array[int] = []
func run(p_t: GameTestRunner) -> void:
t = p_t
_clean()
var bindings := {}
for action: StringName in [&"fire", &"offhand"]:
bindings[action] = InputMap.action_get_events(action)
var size := t.root.size
var factor := t.root.content_scale_factor
MobilePort.forced = 1
t.root.size = PHONE
main = (load("res://game/scenes/main.tscn") as PackedScene).instantiate() as Main
main.save_path = SAVE
main.settings_path = SETTINGS
t.root.add_child(main)
await t.process_frame
await t.process_frame
await _sticks()
main.queue_free()
t.paused = false
await t.process_frame
for action: StringName in bindings:
InputMap.action_erase_events(action)
for e: InputEvent in bindings[action]:
InputMap.action_add_event(action, e)
for action in [&"fire", &"offhand", &"move_left", &"move_right", &"move_forward", &"move_back",
&"aim_left", &"aim_right", &"aim_up", &"aim_down"]:
Input.action_release(action)
MobilePort.forced = -1
t.root.size = size
t.root.content_scale_factor = factor
_clean()
func _clean() -> void:
for p in [SAVE, SAVE + ".tmp", SETTINGS]:
if FileAccess.file_exists(p):
DirAccess.remove_absolute(ProjectSettings.globalize_path(p))
func _physics(n: int) -> void:
for k in n:
await t.physics_frame
## Skips the first day's conversation, which pauses the farm.
func _skip_talk() -> void:
for k in 20:
await t.process_frame
if t.paused and main.screen == Main.Screen.PLAYING and main.sim.dialogue != null:
main.sim.dialogue.box.skip()
func _move() -> Vector2:
return Input.get_vector("move_left", "move_right", "move_forward", "move_back")
func _sticks() -> void:
var sticks := main.farm.get_node_or_null("Hud/TouchSticks") as TouchSticks
t.check(sticks != null, "TouchSticks added on a phone")
if sticks == null:
return
t.check(t.root.content_scale_factor > 1.5, "at the phone's interface scale (%.2f)" % t.root.content_scale_factor)
var mouse_fire := InputMap.action_get_events("fire").filter(func(e: InputEvent) -> bool: return e is InputEventMouseButton)
t.check(mouse_fire.is_empty(), "fire has no mouse button")
t.check(main.sim.combat.device == ScarecrowCombat.Device.GAMEPAD, "combat aims by stick")
main.sim.combat.attacked.connect(func(_w: int) -> void: attacks.append(0))
main.new_vacation(false)
await t.process_frame
main.sim.campaign.advance_phase() # morning -> day
await _skip_talk()
t.check(sticks.can_act(), "sticks can act in the day (phase %d)" % main.sim.campaign.state.phase)
var w := sticks.size
var right := Vector2(w.x * 0.75, w.y * 0.6)
var left := Vector2(w.x * 0.25, w.y * 0.6)
var player := main.sim.scarecrow.player
# Move: finger 0 on the right half, dragged to the rim, rightward.
var p0 := player.global_position
Touch.touch(0, right, true)
Touch.drag(0, right, right + Vector2(TouchSticks.RADIUS, 0.0))
await _physics(40)
t.check(_move().x > 0.9 and absf(_move().y) < 0.1, "move stick tilted right reads (1, 0): %s" % _move())
t.check(sticks.finger[TouchSticks.Stick.MOVE] == 0, "right half started the move stick")
t.check(player.global_position.distance_to(p0) > 1.0, "the scarecrow walked %.1f m" % player.global_position.distance_to(p0))
t.check(not Input.is_action_pressed("fire"), "moving doesn't fire (the tap's emulated click)")
# Attack: finger 1 on the left half, dragged up (forward on screen).
var a0 := attacks.size()
Touch.touch(1, left, true)
Touch.drag(1, left, left + Vector2(0.0, -TouchSticks.RADIUS))
await _physics(60)
t.check(Input.is_action_pressed("fire"), "attack stick holds fire")
t.check(attacks.size() - a0 >= 2, "attacks repeat while held (%d)" % (attacks.size() - a0))
var cam := t.root.get_camera_3d()
var fwd := Vector2(-cam.global_basis.z.x, -cam.global_basis.z.z).normalized()
t.check(main.sim.combat.aim.dot(fwd) > 0.9, "aim is screen-up (dot %.2f)" % main.sim.combat.aim.dot(fwd))
t.check(main.sim.combat.device == ScarecrowCombat.Device.GAMEPAD, "taps didn't switch combat to mouse aim")
t.check(_move().x > 0.9, "move holds while attacking")
# Let go of the attack stick.
Touch.touch(1, left + Vector2(0.0, -TouchSticks.RADIUS), false)
await _physics(5)
var a1 := attacks.size()
await _physics(40)
t.check(not Input.is_action_pressed("fire") and attacks.size() == a1, "releasing stops the attacks")
# Let go of the move stick.
Touch.touch(0, right + Vector2(TouchSticks.RADIUS, 0.0), false)
await _physics(5)
var p1 := player.global_position
await _physics(30)
t.check(_move() == Vector2.ZERO and player.global_position.distance_to(p1) < 0.2, "releasing stops the walk")
# A small tilt (inside the aim dead zone) aims nowhere and doesn't fire.
Touch.touch(1, left, true)
Touch.drag(1, left, left + Vector2(TouchSticks.RADIUS * 0.15, 0.0))
await _physics(10)
t.check(not Input.is_action_pressed("fire"), "a tilt inside the dead zone doesn't fire")
Touch.touch(1, left, false)
await _physics(3)
# A pause mid-walk lets go.
Touch.touch(0, right, true)
Touch.drag(0, right, right + Vector2(0.0, -TouchSticks.RADIUS))
await _physics(10)
t.check(_move().y < -0.9, "walking forward")
main.pause()
await t.process_frame
t.check(_move() == Vector2.ZERO and sticks.finger[TouchSticks.Stick.MOVE] == -1, "pause lets the sticks go")
main.resume()
await _physics(5)
var p2 := player.global_position
await _physics(30)
t.check(player.global_position.distance_to(p2) < 0.2, "no walking on after the pause")
Touch.touch(0, right, false) # the finger lifted after the pause: ignored
await t.process_frame
await _button(sticks, right)
# The intro: a held finger skips it; the sticks stay out of it.
main.new_vacation()
await t.process_frame
t.check(main.sim.intro.running and not sticks.can_act(), "intro running, sticks off")
Touch.touch(0, right, true)
await t.create_timer(OpeningIntro.SKIP_HOLD + 0.6).timeout
t.check(sticks.finger[TouchSticks.Stick.MOVE] == -1, "no stick during the intro")
t.check(main.sim.intro._skipping or not main.sim.intro.running, "holding a finger skips the intro")
Touch.touch(0, right, false)
await t.process_frame
## A button over the move half (as PerfTest's were, in the driver) takes its tap: no stick starts.
func _button(sticks: TouchSticks, at: Vector2) -> void:
var layer := CanvasLayer.new()
layer.layer = 20
var b := Button.new()
b.focus_mode = Control.FOCUS_NONE
b.size = Vector2(200.0, 100.0)
b.position = at - b.size * 0.5
layer.add_child(b)
main.add_child(layer)
await t.process_frame
var pressed: Array[int] = []
b.pressed.connect(func() -> void: pressed.append(0))
Touch.touch(0, at, true)
await t.process_frame
t.check(sticks.finger[TouchSticks.Stick.MOVE] == -1 and sticks.finger[TouchSticks.Stick.ATTACK] == -1, "a touch on a button starts no stick")
Touch.touch(0, at, false)
await t.process_frame
t.check(pressed.size() == 1, "the button got the tap")
layer.free()

View file

@ -0,0 +1 @@
uid://ccpmbww2ehqxx

View file

@ -0,0 +1,49 @@
extends RefCounted
## Fingers for the phone tests (game/tests/mobile/), sent the way a phone sends them: through
## Input.parse_input_event, so Godot's touch-to-click emulation runs too (finger 0 is also the
## left mouse button), and delivered at once (Input.flush_buffered_events), so a check right
## after a call sees its effect on the GUI and on _unhandled_input.
## Points are canvas coordinates of the root viewport (what a full-rect HUD Control sees, at any
## interface scale); they're turned into window pixels through the root's final transform, as
## a phone's touches arrive.
## const Touch := preload("res://game/tests/mobile/touch.gd")
## Touch.touch(0, at, true) # finger 0 down at `at`
## Touch.drag(0, at, at + Vector2(150, 0)) # it moves (one drag event; the finger stays down)
## Touch.touch(0, at + Vector2(150, 0), false) # and lifts
## Touch.tap(1, at) # finger 1 down and up at once
## Finger i goes down (pressed) or lifts at this canvas point.
static func touch(i: int, canvas_pos: Vector2, pressed: bool) -> void:
var e := InputEventScreenTouch.new()
e.index = i
e.pressed = pressed
e.position = window_pos(canvas_pos)
_send(e)
## Finger i, already down, moves from one canvas point to another (one drag event).
static func drag(i: int, from: Vector2, to: Vector2) -> void:
var e := InputEventScreenDrag.new()
e.index = i
e.position = window_pos(to)
e.relative = window_pos(to) - window_pos(from)
e.screen_relative = e.relative
_send(e)
## Finger i taps this canvas point: down, then up.
static func tap(i: int, canvas_pos: Vector2) -> void:
touch(i, canvas_pos, true)
touch(i, canvas_pos, false)
## A canvas point of the root viewport in window pixels (where a phone reports a touch there).
static func window_pos(canvas_pos: Vector2) -> Vector2:
var tree := Engine.get_main_loop() as SceneTree
return tree.root.get_final_transform() * canvas_pos
static func _send(e: InputEvent) -> void:
Input.parse_input_event(e)
Input.flush_buffered_events()

View file

@ -0,0 +1 @@
uid://33srlb8fgmxj

View file

@ -27,6 +27,7 @@ const SUITES := [
"res://game/tests/test_dialogue.gd", "res://game/tests/test_dialogue.gd",
"res://game/tests/test_loading.gd", "res://game/tests/test_loading.gd",
"res://game/tests/test_intro.gd", "res://game/tests/test_intro.gd",
"res://game/tests/test_mobile.gd",
] ]
const TICK := 1.0 / 60.0 const TICK := 1.0 / 60.0
## Points on the farm's edge (FarmZones.edge) for tests that send an enemy in from a known side: ## Points on the farm's edge (FarmZones.edge) for tests that send an enemy in from a known side:

38
game/tests/test_mobile.gd Normal file
View file

@ -0,0 +1,38 @@
extends RefCounted
## The phone tests: every game/tests/mobile/*_test.gd (one file per task), in name order, each
## with the runner's check(). A test file extends RefCounted and has `func run(t) -> void` (it
## may await); it forces a phone or desktop with MobilePort.forced = 1 or 0, sends fingers with
## mobile/touch.gd, and before it returns sets MobilePort.forced back to -1 and frees what it
## added (checked here). Between files this puts the root window back as it was (its size and
## content_scale_factor, which a phone's GameSettings.apply changes), along with the desktop
## preview's density and insets (MobilePort.preview_dpi, preview_insets) and the pause.
## Run just these: -- --suite=test_mobile
const DIR := "res://game/tests/mobile/"
func run(t: GameTestRunner) -> void:
var files: Array[String] = []
for f in DirAccess.get_files_at(DIR):
if f.ends_with("_test.gd"):
files.append(f)
files.sort()
t.check(not files.is_empty(), "%s has tests" % DIR)
var suite := t.current
var size := t.root.size
var factor := t.root.content_scale_factor
for f in files:
var name := f.get_basename()
print("-- ", name)
t.current = "%s/%s" % [suite, name]
var test: Object = (load(DIR + f) as GDScript).new()
await test.call("run", t)
t.check(MobilePort.forced == -1, "it set MobilePort.forced back to -1")
MobilePort.forced = -1
MobilePort.preview_dpi = 0.0
MobilePort.preview_insets = []
t.root.size = size
t.root.content_scale_factor = factor
t.paused = false
await t.process_frame
t.current = suite

View file

@ -0,0 +1 @@
uid://dwd5iel01flrd

View file

@ -0,0 +1,110 @@
extends SceneTree
## Captures the phone build's day HUD for review: runs the real game (main.tscn) in a window as a
## phone (MobilePort's preview: pass -- --mobile, so Main sets the farm up as on a phone and
## GameSettings.apply scales the interface), starts a New vacation without its intro, begins day
## 1, skips the day's conversation, and saves the screen; then the same with the safe area
## marked (MobilePort.safe_rect outlined, outside it shaded), and quits. It prints what the scale
## came to (MobilePort.describe). It needs a window (not --headless) that isn't fullscreen (the
## project's default), so pass --windowed and a resolution; keep it visible and pass
## --disable-vsync (a hidden window with VSync on crawls on some desktops). The desktop may
## resize a big window (one desktop here maximized a 2340x1080 one), so --size=WxH makes it
## borderless at exactly that size once it's up, and applies the scale for it again:
## godot --path . --rendering-method mobile --windowed --resolution 2340x1080 --screen 2 \
## --disable-vsync --script res://game/tools/capture_mobile.gd -- --mobile \
## --size=2340x1080 --safe-area=140,0,140,60 --out=/tmp/hs-mobile --prefix=phone
## Options (after --): --out=dir (default /tmp/hs-mobile/), --prefix=text (default "day"),
## --size=WxH, and MobilePort's own --safe-area=l,t,r,b and --dpi=N. It saves to its own
## user://capture_mobile_* files, so the player's save and settings are never touched.
const SAVE := "user://capture_mobile_save.json"
const SETTINGS := "user://capture_mobile_settings.cfg"
const SHADE := Color(1.0, 0.0, 0.6, 0.3)
const EDGE := Color(1.0, 0.0, 0.6, 0.9)
var _out := "/tmp/hs-mobile/"
var _prefix := "day"
var _size := Vector2i.ZERO
func _initialize() -> void:
for a in OS.get_cmdline_user_args():
var arg := String(a)
if arg.begins_with("--out="):
_out = arg.trim_prefix("--out=")
elif arg.begins_with("--prefix="):
_prefix = arg.trim_prefix("--prefix=")
elif arg.begins_with("--size="):
var wh := arg.trim_prefix("--size=").split("x")
if wh.size() == 2:
_size = Vector2i(int(wh[0]), int(wh[1]))
if not _out.ends_with("/"):
_out += "/"
_run.call_deferred()
func _run() -> void:
_clean()
DirAccess.make_dir_recursive_absolute(_out)
if not MobilePort.active():
push_warning("capture_mobile: not a phone; pass -- --mobile to see the phone build")
var main := (load("res://game/scenes/main.tscn") as PackedScene).instantiate() as Main
main.save_path = SAVE
main.settings_path = SETTINGS
root.add_child(main)
for i in 5:
await process_frame
if _size != Vector2i.ZERO and root.size != _size:
root.borderless = true # the desktop won't shrink or tile it then
root.size = _size
root.position = DisplayServer.screen_get_position(root.current_screen)
for i in 20:
await process_frame
main.settings.apply_scale(root) # the scale for the window's new shape
main.new_vacation(false)
await process_frame
main.sim.campaign.advance_phase() # the first morning's sign -> day 1
for i in 30:
await process_frame
if paused and main.screen == Main.Screen.PLAYING and main.sim.dialogue != null:
main.sim.dialogue.box.skip() # the day's conversation pauses the farm
await create_timer(1.5).timeout # the HUD settles (tips fade in, the camera arrives)
print("capture_mobile: window %s, canvas %s" % [root.size, root.get_visible_rect().size])
print("capture_mobile: ", MobilePort.describe())
await _shot("")
var marks := CanvasLayer.new()
marks.layer = 100
var c := Control.new()
c.mouse_filter = Control.MOUSE_FILTER_IGNORE
marks.add_child(c)
root.add_child(marks)
c.set_anchors_and_offsets_preset(Control.PRESET_FULL_RECT)
c.draw.connect(func() -> void:
var all := c.get_viewport_rect()
var safe := MobilePort.safe_rect(c)
c.draw_rect(Rect2(all.position, Vector2(all.size.x, safe.position.y - all.position.y)), SHADE)
c.draw_rect(Rect2(Vector2(all.position.x, safe.end.y), Vector2(all.size.x, all.end.y - safe.end.y)), SHADE)
c.draw_rect(Rect2(Vector2(all.position.x, safe.position.y), Vector2(safe.position.x - all.position.x, safe.size.y)), SHADE)
c.draw_rect(Rect2(Vector2(safe.end.x, safe.position.y), Vector2(all.end.x - safe.end.x, safe.size.y)), SHADE)
c.draw_rect(safe, EDGE, false, 3.0)
var t := MobilePort.minimum_target(c)
c.draw_rect(Rect2(safe.get_center() - Vector2(t, t) * 0.5, Vector2(t, t)), EDGE, false, 2.0)) # the minimum touch target
await _shot("_safe")
main.queue_free()
await process_frame
await create_timer(0.3).timeout
_clean()
quit()
func _shot(suffix: String) -> void:
await process_frame
await process_frame
var path := "%s%s%s.png" % [_out, _prefix, suffix]
var err := root.get_texture().get_image().save_png(path)
print("capture_mobile: %s (%s)" % [path, error_string(err)])
func _clean() -> void:
for p in [SAVE, SAVE + ".tmp", SETTINGS]:
if FileAccess.file_exists(p):
DirAccess.remove_absolute(ProjectSettings.globalize_path(p))

View file

@ -0,0 +1 @@
uid://c82qfl7ugukef