From c504551b28df29d04316152a2d0369982b19dd39 Mon Sep 17 00:00:00 2001 From: Claude Date: Fri, 13 Nov 2026 11:30:09 -0500 Subject: [PATCH] A10: Menus and settings The game now opens on a main menu when it has a window: practice against bots (count and skill), join a server (by address, or from a LAN search list), settings, and quit. In a match, Escape brings up a pause menu (the match goes on) with settings and leave; when a match the player was in ends, a results screen shows their place, eliminations and the last of the feed. - KeyBindings: every action rebindable to a key or mouse button. bind() refuses an input another action uses and names it; Escape is reserved. ClientInput reads keys through the bindings. - GameSettings: bindings, mouse, graphics (quality preset and the print pass), audio (master, music and effects buses), display (window mode, vsync, frame cap), name, last server and practice choices, saved in user://settings.cfg. Missing, unreadable or corrupt files and bad values fall back to defaults, value by value; hand-edited key clashes are repaired on load. - Menus (src/ui): paper-and-ink panels, brass focus edge, keyboard navigable; a drawn sea-and-tide-post backdrop, or an ink wash over a match. AppShell runs menus and the session. - LocalServer takes a bot difficulty. - make menu-captures renders every screen. Closes #50 Co-Authored-By: Claude Opus 5.5 --- CLAUDE.md | 5 +- Makefile | 6 +- docs/STYLE.md | 1 + src/app/app_shell.gd | 189 ++++++++ src/app/app_shell.gd.uid | 1 + src/app/client_config.gd | 8 +- src/app/client_session.gd | 48 ++- src/app/main.gd | 21 +- src/client/client_input.gd | 59 +-- src/client/game_settings.gd | 169 ++++++++ src/client/game_settings.gd.uid | 1 + src/client/input_settings.gd | 4 +- src/client/key_bindings.gd | 195 +++++++++ src/client/key_bindings.gd.uid | 1 + src/client/match_view.gd | 14 +- src/client/style/palette.gd | 6 +- src/server/local_server.gd | 7 +- src/ui/menu_backdrop.gd | 64 +++ src/ui/menu_backdrop.gd.uid | 1 + src/ui/menu_theme.gd | 91 ++++ src/ui/menu_theme.gd.uid | 1 + src/ui/menus.gd | 594 ++++++++++++++++++++++++++ src/ui/menus.gd.uid | 1 + test/capture/menu_join.tscn | 9 + test/capture/menu_main.tscn | 9 + test/capture/menu_pause.tscn | 9 + test/capture/menu_practice.tscn | 9 + test/capture/menu_results.tscn | 9 + test/capture/menu_scene.gd | 37 ++ test/capture/menu_scene.gd.uid | 1 + test/capture/menu_settings.tscn | 9 + test/capture/menu_settings_mouse.tscn | 9 + test/client/test_game_settings.gd | 130 ++++++ test/client/test_game_settings.gd.uid | 1 + test/client/test_key_bindings.gd | 85 ++++ test/client/test_key_bindings.gd.uid | 1 + test/project/test_palette.gd | 1 + test/ui/test_menus.gd | 265 ++++++++++++ test/ui/test_menus.gd.uid | 1 + 39 files changed, 2022 insertions(+), 50 deletions(-) create mode 100644 src/app/app_shell.gd create mode 100644 src/app/app_shell.gd.uid create mode 100644 src/client/game_settings.gd create mode 100644 src/client/game_settings.gd.uid create mode 100644 src/client/key_bindings.gd create mode 100644 src/client/key_bindings.gd.uid create mode 100644 src/ui/menu_backdrop.gd create mode 100644 src/ui/menu_backdrop.gd.uid create mode 100644 src/ui/menu_theme.gd create mode 100644 src/ui/menu_theme.gd.uid create mode 100644 src/ui/menus.gd create mode 100644 src/ui/menus.gd.uid create mode 100644 test/capture/menu_join.tscn create mode 100644 test/capture/menu_main.tscn create mode 100644 test/capture/menu_pause.tscn create mode 100644 test/capture/menu_practice.tscn create mode 100644 test/capture/menu_results.tscn create mode 100644 test/capture/menu_scene.gd create mode 100644 test/capture/menu_scene.gd.uid create mode 100644 test/capture/menu_settings.tscn create mode 100644 test/capture/menu_settings_mouse.tscn create mode 100644 test/client/test_game_settings.gd create mode 100644 test/client/test_game_settings.gd.uid create mode 100644 test/client/test_key_bindings.gd create mode 100644 test/client/test_key_bindings.gd.uid create mode 100644 test/ui/test_menus.gd create mode 100644 test/ui/test_menus.gd.uid diff --git a/CLAUDE.md b/CLAUDE.md index ec9e3b0..0f65650 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -31,14 +31,15 @@ continuity. | `make match` | Plays one whole offline match, lobby to results: a scripted player and 23 bots on a local server (about 25 s). Saves the command log to `build/match/match.tclog`, replays it and checks the replay ends on the same state hash. `MATCH_SEED=N` changes the seed; the default, 2, is one where the scripted player also builds. | | `make match-captures` | Renders eight stages of that match from its command log (`captures/match_.png`), about 3 minutes. Needs Docker. Look at them. | | `make terrain-capture` | Renders the terrain crack check and a skirtless control in the capture container. The control must crack and the real terrain must not. Needs Docker. | -| `tools/godot.sh -- --connect=HOST:PORT --autoplay --client-seconds=N` | Runs the client headless against a server for N seconds, played by its script, and prints one JSON line saying how far it got. `--offline` plays a server in the same process instead. On a real display, with no options, the game starts an offline match; see `src/app/client_config.gd`. | +| `tools/godot.sh -- --connect=HOST:PORT --autoplay --client-seconds=N` | Runs the client headless against a server for N seconds, played by its script, and prints one JSON line saying how far it got. `--offline` plays a server in the same process instead. On a real display, with no options, the game opens on its main menu (`AppShell`); see `src/app/client_config.gd`. | | `make client-check` | Starts a server and a client as two processes, joins them over loopback UDP and checks the client plays (about a minute, real time). | | `tools/godot.sh -- --list-server [--port=N]` | Runs a list server (default UDP port 24660). Game servers started with `--listen --list=HOST[:PORT] --name=NAME` register with it; see `src/server/list_server.gd`. | -| `tools/godot.sh -- --browse [--list=HOST[:PORT]] [--lan-target=IP] [--lan-port=N]` | Looks for servers on the LAN and in list servers and prints them as one JSON line. Menus (A10) will show the same list. | +| `tools/godot.sh -- --browse [--list=HOST[:PORT]] [--lan-target=IP] [--lan-port=N]` | Looks for servers on the LAN and in list servers and prints them as one JSON line. The join menu (A10) shows the same list. | | `make discovery-check` | Starts a list server and a game server as processes and checks `--browse` finds the game both on the LAN (loopback) and through the list (about 15 s). | | `make fuzz` | Feeds 1,000,000 malformed messages (`FUZZ_MESSAGES=N`, `FUZZ_SEED=N`) to every network parser and fails on any engine error or memory growth (about 40 s). | | `make client-captures` | Renders what a network client sees on the barge, gliding and landed, the build ghost allowed and refused, and a breakwater basin kept dry by the tide (`captures/client_.png`, about 4 min). Needs Docker. Look at them. | | `make hud-captures` | Renders the HUD over a staged moment of play (three bots out, carried items, a wound) at 1280x720, in build mode, and at 3840x2160 (`captures/hud_*.png`, about 5 min). Needs Docker. Look at them. | +| `make menu-captures` | Renders every menu screen: main, practice, join (with a made-up server list), settings (controls and mouse tabs), pause and results over a match (`captures/menu_*.png`, about 5 min). Needs Docker. Look at them. | | `make style-captures` | Renders a hamlet and a dock with and without the woodcut print pass (`captures/style_*.png`). Needs Docker. | | `make soak` | The 24-client network soak (N8): a real server and 24 headless `SoakPlayer` clients in three processes, each behind a `UdpRelay` adding 60 ms, +/-20 ms jitter and 2% loss each way, for two whole matches in real time (about 30 min, under `nice`). Fails on a world-hash mismatch, errors, unreadable packets, a client that didn't play every match, memory growth between matches, or a p99 tick over budget. `SOAK_MATCHES`, `SOAK_CLIENTS`, `SOAK_PROCS`, `SOAK_LATENCY`, `SOAK_JITTER`, `SOAK_LOSS` scale it. Results in `build/soak/report.txt`. | | `make soak-selfcheck` | About a minute: tampers with one client's world and checks the soak's comparison catches it and only it. | diff --git a/Makefile b/Makefile index 763f4f3..53f4351 100644 --- a/Makefile +++ b/Makefile @@ -1,7 +1,7 @@ # Tidewall build entry points. Everything runs headless with the repo-local engine. GODOT := tools/godot.sh -.PHONY: check import parse test test-selfcheck smoke capture-test terrain-capture binaries verify-engine bot-matches match match-captures client-check client-captures hud-captures style-captures discovery-check fuzz soak soak-selfcheck server-package-check +.PHONY: check import parse test test-selfcheck smoke capture-test terrain-capture binaries verify-engine bot-matches match match-captures client-check client-captures hud-captures style-captures menu-captures discovery-check fuzz soak soak-selfcheck server-package-check ## Everything that must pass before a push. check: verify-engine binaries parse test test-selfcheck smoke @@ -71,6 +71,10 @@ hud-captures: import @CAPTURE_SIZE=1280x720 tools/capture.sh client_hud_build captures/hud_build_720.png @CAPTURE_SIZE=3840x2160 tools/capture.sh client_hud captures/hud_2160.png +## A10: every menu screen (captures/menu_*.png, about 5 min). Needs Docker. Look at them. +menu-captures: import + @for scene in menu_main menu_practice menu_join menu_settings menu_settings_mouse menu_pause menu_results; do tools/capture.sh $$scene captures/$$scene.png; done + ## A1: the woodcut print pass on and off, side by side scenes (captures/style_*.png). Needs Docker. style-captures: import @for scene in style_hamlet style_hamlet_plain style_dock style_dock_plain; do tools/capture.sh $$scene captures/$$scene.png; done diff --git a/docs/STYLE.md b/docs/STYLE.md index 74b53a4..d7cad76 100644 --- a/docs/STYLE.md +++ b/docs/STYLE.md @@ -68,6 +68,7 @@ or `src/app`, and on any palette colour this table doesn't list. Values are sRGB | `INK` | 0.16, 0.13, 0.11 | Printer's ink: outlines, hatching | | `PAPER` | 0.91, 0.87, 0.78 | Unbleached paper: HUD panels and text | | `PAPER_DIM` | 0.66, 0.62, 0.54 | Paper in shadow: panel edges, dimmed text | +| `GILT_DEEP` | 0.62, 0.45, 0.12 | Brass on paper: the menu control with focus | | `OUTLINE` | 0.08, 0.08, 0.08 | Text outline on the HUD | | `GHOST_OK` | 0.46, 0.80, 0.70, 38% | Build ghost: allowed | | `GHOST_REFUSED` | 0.86, 0.32, 0.22, 38% | Build ghost: refused | diff --git a/src/app/app_shell.gd b/src/app/app_shell.gd new file mode 100644 index 0000000..5a39943 --- /dev/null +++ b/src/app/app_shell.gd @@ -0,0 +1,189 @@ +## The game program on a display: the menus, and a ClientSession while a match is +## played. Practice and Join start a session; Escape in a match brings up the pause +## menu (the match goes on: it's a live server, even offline); Leave ends the session +## and goes back to the main menu; when a match the player was in ends, the results +## screen shows where they placed. +## +## Main makes one when the game starts with a window. Tests drive it headless through +## the same methods the menus' signals call. +class_name AppShell +extends Node + +signal quit_requested + +var settings: GameSettings +var settings_path: String +var menus: Menus +var session: ClientSession = null +## Keeps the mouse free and skips the window when false (tests, headless). +var grab_mouse: bool = true + +## Results of the match being played: feed entries already counted, by victim handle, +## and how many fell to this player. +var _counted: Dictionary = {} +var eliminations: int = 0 +## The phase last seen, and whether this player took part in the current match. +var _phase: int = -1 +var _took_part: bool = false + + +func _init(with: GameSettings = null, path: String = GameSettings.DEFAULT_PATH) -> void: + name = "AppShell" + settings_path = path + settings = with if with != null else GameSettings.load_from(path) + var layer: CanvasLayer = CanvasLayer.new() + layer.name = "MenuLayer" + layer.layer = 10 + add_child(layer) + menus = Menus.new() + menus.use_settings(settings, path) + layer.add_child(menus) + menus.practice_requested.connect(start_practice) + menus.join_requested.connect(join) + menus.resume_requested.connect(resume) + menus.leave_requested.connect(leave) + menus.quit_requested.connect(func() -> void: quit_requested.emit()) + menus.settings_changed.connect(_settings_changed) + + +func _ready() -> void: + settings.apply_to_program(get_tree()) + if session == null: + menus.show_screen("main", false) + + +## Starts an offline match against bots. +func start_practice(bots: int, difficulty: int) -> void: + var match_seed: int = int(Time.get_unix_time_from_system() * 1000.0) & 0x7FFFFFFF + var practice: ClientSession = ClientSession.new() + practice.play_offline(match_seed, bots, null, difficulty) + _begin(practice) + + +## Joins a server. Says so on the join screen if the connection can't be opened. +func join(host: String, port: int, player_name: String) -> Error: + var joining: ClientSession = ClientSession.new() + var error: Error = joining.connect_to(host, port, player_name) + if error != OK: + joining.free() + menus.show_screen("join") + return error + _begin(joining) + return OK + + +## Takes over a session started elsewhere (Main, for --offline or --connect). +func adopt(started: ClientSession) -> void: + _begin(started) + + +## The pause menu over the match. +func pause() -> void: + if session == null: + return + session.paused = true + menus.show_screen("pause", false) + _free_mouse() + + +## Back to the match. +func resume() -> void: + if session == null: + return + session.paused = false + menus.close() + _take_mouse() + + +## Leaves the match and goes back to the main menu. +func leave() -> void: + if session != null: + session.leave() + remove_child(session) + session.queue_free() + session = null + menus.over_match = false + _free_mouse() + menus.show_screen("main", false) + + +func _begin(started: ClientSession) -> void: + if session != null: + leave() + session = started + menus.over_match = true + session.use_settings(settings) + session.pause_requested.connect(pause) + add_child(session) + move_child(session, 0) + menus.close() + _counted.clear() + eliminations = 0 + _phase = -1 + _took_part = false + _take_mouse() + + +func _process(_delta: float) -> void: + if session != null: + watch_match() + + +## Counts this player's eliminations from the feed, and shows the results when a match +## they took part in ends. Called every frame. +func watch_match() -> void: + var game: ClientGame = session.game + var own: int = session.own_handle() + var changed: bool = game.match_phase != _phase + if changed and (game.match_phase == Match.LOBBY or game.match_phase == Match.COUNTDOWN): + _counted.clear() + eliminations = 0 + _took_part = false + _phase = game.match_phase + if game.playing(): + _took_part = true + for entry: Dictionary in game.feed: + var victim: int = int(entry.get("victim", 0)) + if _counted.has(victim): + continue + _counted[victim] = true + if own != 0 and int(entry.get("by", 0)) == own and victim != own: + eliminations += 1 + if changed and _phase == Match.RESULTS and _took_part: + var result: Dictionary = results() + session.paused = true + menus.show_results(int(result["place"]), int(result["total"]), eliminations, result["lines"]) + _free_mouse() + + +## Where this player placed, out of how many, and the last lines of the feed. +func results() -> Dictionary: + var game: ClientGame = session.game + var own: int = session.own_handle() + var place: int = 0 + for entry: Dictionary in game.feed: + if int(entry.get("victim", 0)) == own: + place = int(entry.get("place", 0)) + if place == 0 and _took_part: + # Never placed by a fall: still standing at the end. + place = 1 + var lines: Array[String] = [] + for line: Dictionary in HudState.feed_lines(game.feed, own): + lines.append(String(line["text"])) + return {"place": place, "total": game.match_size, "lines": lines} + + +func _settings_changed() -> void: + settings.apply_to_program(get_tree() if is_inside_tree() else null) + if session != null: + session.use_settings(settings) + + +func _take_mouse() -> void: + if grab_mouse and DisplayServer.get_name() != "headless": + Input.mouse_mode = Input.MOUSE_MODE_CAPTURED + + +func _free_mouse() -> void: + if grab_mouse and DisplayServer.get_name() != "headless": + Input.mouse_mode = Input.MOUSE_MODE_VISIBLE diff --git a/src/app/app_shell.gd.uid b/src/app/app_shell.gd.uid new file mode 100644 index 0000000..5cf3913 --- /dev/null +++ b/src/app/app_shell.gd.uid @@ -0,0 +1 @@ +uid://gqxi72yc7yjn diff --git a/src/app/client_config.gd b/src/app/client_config.gd index 43a3e60..98bc157 100644 --- a/src/app/client_config.gd +++ b/src/app/client_config.gd @@ -1,6 +1,7 @@ ## What the client was asked to do on the command line. ## -## tidewall an offline match against bots +## tidewall the main menu (with a window) +## tidewall --offline an offline match against bots ## tidewall --connect=HOST[:PORT] join a server ## options: --name=NAME --seed=N --bots=N (offline) --autoplay ## --client-seconds=N quit after N seconds, saying what happened @@ -8,8 +9,9 @@ ## print the servers found on the LAN and in list ## servers as one JSON line, then quit ## -## Menus replace most of this later. Under tools/godot.sh, which has no window, a mode -## has to be asked for: --offline or --connect. +## With a window and none of these, the game opens on its menus (AppShell). Under +## tools/godot.sh, which has no window, a mode has to be asked for: --offline or +## --connect. class_name ClientConfig extends RefCounted diff --git a/src/app/client_session.gd b/src/app/client_session.gd index 3ad6e72..b4717ce 100644 --- a/src/app/client_session.gd +++ b/src/app/client_session.gd @@ -26,6 +26,13 @@ var frames: int = 0 ## The in-game HUD, once the session is in a scene tree. var hud: Hud = null +## The player's settings (see use_settings()). +var settings: GameSettings = GameSettings.new() +## Escape asks for the pause menu: whoever runs the session shows it (AppShell). With +## nobody listening, Escape only lets go of the mouse. +signal pause_requested +## True while a menu is over the match: the keys and mouse don't play. +var paused: bool = false var _viewed: Simulation = null var _status: Label = null @@ -45,8 +52,23 @@ func connect_to(host: String, port: int, player_name: String) -> Error: ## Starts an offline match of this player and `bots` bots on a server in this process. -func play_offline(match_seed: int, bots: int, rules: MatchRules = null) -> void: - local = LocalServer.new(match_seed, bots, rules) +func play_offline(match_seed: int, bots: int, rules: MatchRules = null, difficulty: int = -1) -> void: + local = LocalServer.new(match_seed, bots, rules, difficulty) + + +## Takes the player's settings: their keys and mouse now, and graphics for each +## match's view. +func use_settings(with: GameSettings) -> void: + settings = with + input.settings = with.mouse + input.bindings = with.bindings + if view != null: + view.apply_settings(with) + + +## The handle this client plays as: the server's name for it in the feed. +func own_handle() -> int: + return LocalServer.HANDLE if local != null else (link.handle if link != null else 0) ## Leaves the server, if there is one across the network. @@ -72,7 +94,12 @@ func status_text() -> String: ## One frame: packets in, commands out, and the picture brought up to date. func pump(delta: float) -> void: frames += 1 - input.poll() + if paused: + # Nothing held while a menu is up, so the player stops rather than runs on. + input.move = Vector2.ZERO + input.buttons = 0 + else: + input.poll() if link != null: game.poll() if local != null: @@ -109,20 +136,22 @@ func _process(delta: float) -> void: ## What the HUD should show now. func hud_state() -> HudState: - var handle: int = LocalServer.HANDLE if local != null else (link.handle if link != null else 0) - return HudState.from_client(game, input, handle) + return HudState.from_client(game, input, own_handle()) func _unhandled_input(event: InputEvent) -> void: var captured: bool = Input.mouse_mode == Input.MOUSE_MODE_CAPTURED var key: InputEventKey = event as InputEventKey var click: InputEventMouseButton = event as InputEventMouseButton - if key != null and key.pressed and key.physical_keycode == KEY_ESCAPE: - # Escape lets go of the mouse; a click takes it back. + if key != null and key.pressed and not key.echo and key.physical_keycode == KEY_ESCAPE: + # Escape lets go of the mouse and asks for the pause menu; a click takes the + # mouse back when there is no menu. Input.mouse_mode = Input.MOUSE_MODE_VISIBLE - elif click != null and click.pressed and not captured and not input.autoplay: + pause_requested.emit() + get_viewport().set_input_as_handled() + elif click != null and click.pressed and not captured and not input.autoplay and not paused: Input.mouse_mode = Input.MOUSE_MODE_CAPTURED - else: + elif not paused: input.handle(event, captured) @@ -149,6 +178,7 @@ func _show(delta: float) -> void: if _viewed != null: view = MatchView.new() view.setup(_viewed, 0) + view.apply_settings(settings) add_child(view) move_child(view, 0) ghost = BuildGhost.new() diff --git a/src/app/main.gd b/src/app/main.gd index b2026b6..be3d78d 100644 --- a/src/app/main.gd +++ b/src/app/main.gd @@ -6,6 +6,7 @@ ## tidewall --browse list the servers it can find ## tools/godot.sh -- --list-server a list server (see ListServerRunner) ## +## With a window and no mode asked for, the game opens on the main menu (AppShell). ## Without a window (tools/godot.sh is always headless) the game only starts when ## --offline or --connect asks for it, so a bare run prints a line and stops. extends Node @@ -42,6 +43,11 @@ func _ready() -> void: if _config.browse: _start_browsing() return + var windowed: bool = DisplayServer.get_name() != "headless" and not _config.autoplay + if windowed and not _config.asked: + # The game as a player starts it: the main menu. + _open_shell() + return _session = ClientSession.new() _session.input.autoplay = _config.autoplay if _config.host.is_empty(): @@ -53,10 +59,23 @@ func _ready() -> void: printerr("tidewall: couldn't open a connection: %s" % error_string(error)) get_tree().quit(1) return - add_child(_session) + if windowed: + # Asked for a match on the command line: straight in, with the menus for pause. + _open_shell().adopt(_session) + else: + add_child(_session) _left = _config.seconds +func _open_shell() -> AppShell: + var shell: AppShell = AppShell.new() + shell.quit_requested.connect(func() -> void: + shell.leave() + get_tree().quit(0)) + add_child(shell) + return shell + + func _start_browsing() -> void: _browser = ServerBrowser.new() if _browser.open() != OK: diff --git a/src/client/client_input.gd b/src/client/client_input.gd index 760e819..cb35540 100644 --- a/src/client/client_input.gd +++ b/src/client/client_input.gd @@ -1,12 +1,12 @@ ## Turns the keyboard and mouse into the local player's commands, one per tick. ## -## Keys (physical positions, so they sit the same on any layout): +## Keys come from `bindings` (KeyBindings, set in the settings menu). By default: ## W A S D move · Space jump · Ctrl crouch · Shift sprint · left mouse use or fire · ## right mouse aim · R reload · E pick up or open · G drop the held item · ## 1 the boathook, 2 to 6 the five slots · B build mode on and off · ## in build mode 1 to 5 pick wall, floor, ramp, roof or breakwater, Tab the material, ## and left mouse places. -## Rebinding and gamepads come with the settings menu. +## Gamepads come with A13. ## ## With `autoplay` on, a simple script plays instead: it leaps from the barge over ## land, glides, and walks about. That is for tests and for checking a connection with @@ -15,6 +15,7 @@ class_name ClientInput extends RefCounted var settings: InputSettings = InputSettings.new() +var bindings: KeyBindings = KeyBindings.new() ## The look direction, in radians, in the simulation's convention. var yaw: float = 0.0 var pitch: float = 0.0 @@ -29,6 +30,14 @@ var build_kind: int = StructureSet.WALL var material: int = Materials.DRIFTWOOD var autoplay: bool = false +## Actions held down, and the command buttons they hold. +const HELD: Dictionary = { + "jump": PlayerCommand.BUTTON_JUMP, "crouch": PlayerCommand.BUTTON_CROUCH, + "sprint": PlayerCommand.BUTTON_SPRINT, "reload": PlayerCommand.BUTTON_RELOAD, + "interact": PlayerCommand.BUTTON_INTERACT, "drop": PlayerCommand.BUTTON_DROP, + "fire": PlayerCommand.BUTTON_FIRE, "aim": PlayerCommand.BUTTON_AIM, +} + func aiming() -> bool: return buttons & PlayerCommand.BUTTON_AIM != 0 and not build_mode @@ -39,22 +48,13 @@ func poll() -> void: if autoplay: return move = Vector2( - _axis(KEY_D, KEY_A), - _axis(KEY_W, KEY_S), + _axis("right", "left"), + _axis("forward", "back"), ) buttons = 0 - var keys: Dictionary = { - KEY_SPACE: PlayerCommand.BUTTON_JUMP, KEY_CTRL: PlayerCommand.BUTTON_CROUCH, - KEY_SHIFT: PlayerCommand.BUTTON_SPRINT, KEY_R: PlayerCommand.BUTTON_RELOAD, - KEY_E: PlayerCommand.BUTTON_INTERACT, KEY_G: PlayerCommand.BUTTON_DROP, - } - for key: Key in keys: - if Input.is_physical_key_pressed(key): - buttons |= int(keys[key]) - if Input.is_mouse_button_pressed(MOUSE_BUTTON_LEFT): - buttons |= PlayerCommand.BUTTON_FIRE - if Input.is_mouse_button_pressed(MOUSE_BUTTON_RIGHT): - buttons |= PlayerCommand.BUTTON_AIM + for action: String in HELD: + if bindings.is_held(action): + buttons |= int(HELD[action]) ## Takes one input event: mouse motion turns the look, and keys that act once per @@ -66,9 +66,9 @@ func handle(event: InputEvent, captured: bool) -> void: if motion != null and captured: turn(motion.relative) return - var key: InputEventKey = event as InputEventKey - if key != null and key.pressed and not key.echo: - press(key.physical_keycode) + var action: String = bindings.action_for_event(event) + if not action.is_empty(): + act(action) ## Turns the look by a mouse motion, in pixels. @@ -78,14 +78,21 @@ func turn(relative: Vector2) -> void: pitch = look.y -## A key that acts once per press: the number row, build mode and the material. +## A key that acts once per press, by its default binding (for tests and scripts). func press(keycode: Key) -> void: - if keycode == KEY_B: + var action: String = bindings.action_using(int(keycode)) + if not action.is_empty(): + act(action) + + +## An action that happens once per press: build mode, the material, the number row. +func act(action: String) -> void: + if action == "build": build_mode = not build_mode - elif keycode == KEY_TAB and build_mode: + elif action == "material" and build_mode: material = (material + 1) % Materials.NAMES.size() - elif keycode >= KEY_1 and keycode <= KEY_9: - var number: int = keycode - KEY_1 + elif action.begins_with("slot_"): + var number: int = action.substr(5).to_int() if build_mode: if number < StructureSet.KINDS.size(): build_kind = number @@ -127,5 +134,5 @@ func autoplay_command(tick: int, me: SimEntity, ground: SimGround) -> PlayerComm return command(tick) -func _axis(positive: Key, negative: Key) -> float: - return (1.0 if Input.is_physical_key_pressed(positive) else 0.0) - (1.0 if Input.is_physical_key_pressed(negative) else 0.0) +func _axis(positive: String, negative: String) -> float: + return (1.0 if bindings.is_held(positive) else 0.0) - (1.0 if bindings.is_held(negative) else 0.0) diff --git a/src/client/game_settings.gd b/src/client/game_settings.gd new file mode 100644 index 0000000..ac014ba --- /dev/null +++ b/src/client/game_settings.gd @@ -0,0 +1,169 @@ +## Everything the player can set, saved in the user's config file between launches: +## key bindings, the mouse (InputSettings), graphics, audio and the display. +## +## load_from() never fails: a missing, unreadable or corrupt file, or any value of the +## wrong type or out of range, gives the default for what it spoils. +class_name GameSettings +extends RefCounted + +const DEFAULT_PATH: String = InputSettings.DEFAULT_PATH + +## Graphics quality presets (H2 tunes what each does). +const QUALITY_NAMES: Array[String] = ["Low", "Medium", "High"] +const QUALITY_LOW: int = 0 +const QUALITY_MEDIUM: int = 1 +const QUALITY_HIGH: int = 2 +## Per preset: sun shadow distance in metres (0 = no shadows) and 3D render scale. +const QUALITY: Array[Dictionary] = [ + {"shadow_distance": 0.0, "render_scale": 0.75}, + {"shadow_distance": 200.0, "render_scale": 1.0}, + {"shadow_distance": 400.0, "render_scale": 1.0}, +] +const WINDOW_MODES: Array[String] = ["Windowed", "Fullscreen", "Exclusive fullscreen"] +## Frame caps offered, 0 for none. +const FRAME_CAPS: Array[int] = [0, 30, 60, 90, 120, 144, 165, 240] +const MAX_NAME_LENGTH: int = 24 + +var bindings: KeyBindings = KeyBindings.new() +var mouse: InputSettings = InputSettings.new() + +var quality: int = QUALITY_HIGH: + set(value): + quality = clampi(value, 0, QUALITY_NAMES.size() - 1) +## The woodcut print pass (docs/STYLE.md). +var print_pass: bool = true +## Volumes from 0 to 1. +var master_volume: float = 0.8: + set(value): + master_volume = clampf(value, 0.0, 1.0) +var music_volume: float = 0.6: + set(value): + music_volume = clampf(value, 0.0, 1.0) +var effects_volume: float = 0.9: + set(value): + effects_volume = clampf(value, 0.0, 1.0) +var window_mode: int = 0: + set(value): + window_mode = clampi(value, 0, WINDOW_MODES.size() - 1) +var vsync: bool = true +var max_fps: int = 0: + set(value): + max_fps = value if FRAME_CAPS.has(value) else 0 +## The name others see, and the last server joined. +var player_name: String = ClientConfig.DEFAULT_NAME: + set(value): + var clean: String = value.strip_edges().left(MAX_NAME_LENGTH) + player_name = clean if not clean.is_empty() else ClientConfig.DEFAULT_NAME +var last_server: String = "" +## Practice: how many bots, and their difficulty (-1 mixed, else an index into +## Tuning.BOT_DIFFICULTIES). +var practice_bots: int = Tuning.SOLO_PLAYERS - 1: + set(value): + practice_bots = clampi(value, 1, Tuning.SOLO_PLAYERS - 1) +var practice_difficulty: int = -1: + set(value): + practice_difficulty = clampi(value, -1, Tuning.BOT_DIFFICULTIES.size() - 1) + + +func shadow_distance() -> float: + return float(QUALITY[quality]["shadow_distance"]) + + +func render_scale() -> float: + return float(QUALITY[quality]["render_scale"]) + + +func save(path: String = DEFAULT_PATH) -> Error: + var config: ConfigFile = ConfigFile.new() + # The mouse keeps its own section, as InputSettings has always saved it. + config.set_value(InputSettings.SECTION, "mouse_sensitivity", mouse.mouse_sensitivity) + config.set_value(InputSettings.SECTION, "aim_sensitivity_scale", mouse.aim_sensitivity_scale) + config.set_value(InputSettings.SECTION, "invert_y", mouse.invert_y) + bindings.write(config) + config.set_value("graphics", "quality", quality) + config.set_value("graphics", "print_pass", print_pass) + config.set_value("audio", "master", master_volume) + config.set_value("audio", "music", music_volume) + config.set_value("audio", "effects", effects_volume) + config.set_value("display", "window_mode", window_mode) + config.set_value("display", "vsync", vsync) + config.set_value("display", "max_fps", max_fps) + config.set_value("player", "name", player_name) + config.set_value("player", "last_server", last_server) + config.set_value("practice", "bots", practice_bots) + config.set_value("practice", "difficulty", practice_difficulty) + return config.save(path) + + +static func load_from(path: String = DEFAULT_PATH) -> GameSettings: + var settings: GameSettings = GameSettings.new() + var config: ConfigFile = ConfigFile.new() + if config.load(path) != OK: + return settings + settings.mouse = InputSettings.load_from(path) + settings.bindings = KeyBindings.read(config) + settings.quality = _int(config, "graphics", "quality", settings.quality) + settings.print_pass = _bool(config, "graphics", "print_pass", settings.print_pass) + settings.master_volume = _float(config, "audio", "master", settings.master_volume) + settings.music_volume = _float(config, "audio", "music", settings.music_volume) + settings.effects_volume = _float(config, "audio", "effects", settings.effects_volume) + settings.window_mode = _int(config, "display", "window_mode", settings.window_mode) + settings.vsync = _bool(config, "display", "vsync", settings.vsync) + settings.max_fps = _int(config, "display", "max_fps", settings.max_fps) + var name_value: Variant = config.get_value("player", "name", settings.player_name) + if name_value is String: + settings.player_name = name_value + var server_value: Variant = config.get_value("player", "last_server", "") + if server_value is String: + settings.last_server = String(server_value).strip_edges().left(255) + settings.practice_bots = _int(config, "practice", "bots", settings.practice_bots) + settings.practice_difficulty = _int(config, "practice", "difficulty", settings.practice_difficulty) + return settings + + +## Applies the display and audio settings to the running program. Graphics apply to +## each MatchView as it is made (MatchView.apply_settings). Does nothing to the window +## when there is none. +func apply_to_program(tree: SceneTree) -> void: + _apply_audio() + if DisplayServer.get_name() == "headless": + return + Engine.max_fps = max_fps + DisplayServer.window_set_vsync_mode(DisplayServer.VSYNC_ENABLED if vsync else DisplayServer.VSYNC_DISABLED) + var modes: Array[DisplayServer.WindowMode] = [DisplayServer.WINDOW_MODE_WINDOWED, DisplayServer.WINDOW_MODE_FULLSCREEN, DisplayServer.WINDOW_MODE_EXCLUSIVE_FULLSCREEN] + if DisplayServer.window_get_mode() != modes[window_mode]: + DisplayServer.window_set_mode(modes[window_mode]) + if tree != null and tree.root != null: + tree.root.scaling_3d_scale = render_scale() + + +## Sets the Master bus, and the Music and Effects buses, making them if they aren't +## there yet (A8's sounds play on them). +func _apply_audio() -> void: + for bus: Array in [["Master", master_volume], ["Music", music_volume], ["Effects", effects_volume]]: + var index: int = AudioServer.get_bus_index(bus[0]) + if index < 0: + AudioServer.add_bus() + index = AudioServer.bus_count - 1 + AudioServer.set_bus_name(index, bus[0]) + AudioServer.set_bus_send(index, "Master") + var volume: float = float(bus[1]) + AudioServer.set_bus_mute(index, volume <= 0.0) + AudioServer.set_bus_volume_db(index, linear_to_db(maxf(volume, 0.0001))) + + +static func _int(config: ConfigFile, section: String, key: String, fallback: int) -> int: + var value: Variant = config.get_value(section, key, fallback) + return int(value) if value is int else fallback + + +static func _float(config: ConfigFile, section: String, key: String, fallback: float) -> float: + var value: Variant = config.get_value(section, key, fallback) + if (value is float and is_finite(value)) or value is int: + return float(value) + return fallback + + +static func _bool(config: ConfigFile, section: String, key: String, fallback: bool) -> bool: + var value: Variant = config.get_value(section, key, fallback) + return bool(value) if value is bool else fallback diff --git a/src/client/game_settings.gd.uid b/src/client/game_settings.gd.uid new file mode 100644 index 0000000..3f2f6fd --- /dev/null +++ b/src/client/game_settings.gd.uid @@ -0,0 +1 @@ +uid://c7fawn3kb6yfm diff --git a/src/client/input_settings.gd b/src/client/input_settings.gd index fcafcec..16c0d08 100644 --- a/src/client/input_settings.gd +++ b/src/client/input_settings.gd @@ -49,10 +49,10 @@ static func load_from(path: String = DEFAULT_PATH) -> InputSettings: if config.load(path) != OK: return settings var sensitivity: Variant = config.get_value(SECTION, "mouse_sensitivity", 1.0) - if sensitivity is float or sensitivity is int: + if (sensitivity is float and is_finite(sensitivity)) or sensitivity is int: settings.mouse_sensitivity = float(sensitivity) var aim_scale: Variant = config.get_value(SECTION, "aim_sensitivity_scale", 0.6) - if aim_scale is float or aim_scale is int: + if (aim_scale is float and is_finite(aim_scale)) or aim_scale is int: settings.aim_sensitivity_scale = float(aim_scale) var invert: Variant = config.get_value(SECTION, "invert_y", false) if invert is bool: diff --git a/src/client/key_bindings.gd b/src/client/key_bindings.gd new file mode 100644 index 0000000..3f728ae --- /dev/null +++ b/src/client/key_bindings.gd @@ -0,0 +1,195 @@ +## Which key or mouse button does what. Each action has one input, held as a code: a +## physical keycode (positions, so they sit the same on any layout), or a mouse button +## as its negative index (-1 left, -2 right, ...). +## +## The number keys do double duty by design: slot N's key also picks build piece N in +## build mode, so the builds have no actions of their own. +## +## bind() refuses an input another action already uses and names that action, so the +## settings menu can say what clashes. Escape is kept for menus and can't be bound. +class_name KeyBindings +extends RefCounted + +## Every action, in the order the settings menu lists them, with its default input. +const ACTIONS: Array[Dictionary] = [ + {"id": "forward", "label": "Forward", "default": KEY_W}, + {"id": "back", "label": "Back", "default": KEY_S}, + {"id": "left", "label": "Left", "default": KEY_A}, + {"id": "right", "label": "Right", "default": KEY_D}, + {"id": "jump", "label": "Jump", "default": KEY_SPACE}, + {"id": "crouch", "label": "Crouch", "default": KEY_CTRL}, + {"id": "sprint", "label": "Sprint", "default": KEY_SHIFT}, + {"id": "fire", "label": "Use, fire or place", "default": -MOUSE_BUTTON_LEFT}, + {"id": "aim", "label": "Aim", "default": -MOUSE_BUTTON_RIGHT}, + {"id": "reload", "label": "Reload", "default": KEY_R}, + {"id": "interact", "label": "Pick up or open", "default": KEY_E}, + {"id": "drop", "label": "Drop held item", "default": KEY_G}, + {"id": "build", "label": "Build mode", "default": KEY_B}, + {"id": "material", "label": "Next material", "default": KEY_TAB}, + {"id": "slot_0", "label": "Boathook / wall", "default": KEY_1}, + {"id": "slot_1", "label": "Slot 1 / floor", "default": KEY_2}, + {"id": "slot_2", "label": "Slot 2 / ramp", "default": KEY_3}, + {"id": "slot_3", "label": "Slot 3 / roof", "default": KEY_4}, + {"id": "slot_4", "label": "Slot 4 / breakwater", "default": KEY_5}, + {"id": "slot_5", "label": "Slot 5", "default": KEY_6}, +] +## Kept for opening and closing menus. +const RESERVED: Array[int] = [KEY_ESCAPE] + +## Action id -> code. +var codes: Dictionary = {} + + +func _init() -> void: + reset() + + +## Every action back to its default. +func reset() -> void: + codes.clear() + for action: Dictionary in ACTIONS: + codes[action["id"]] = int(action["default"]) + + +static func has_action(action: String) -> bool: + return _index_of(action) >= 0 + + +static func default_of(action: String) -> int: + var index: int = _index_of(action) + return int(ACTIONS[index]["default"]) if index >= 0 else 0 + + +static func label_of(action: String) -> String: + var index: int = _index_of(action) + return String(ACTIONS[index]["label"]) if index >= 0 else action + + +func code_of(action: String) -> int: + return int(codes.get(action, 0)) + + +## The action using `code`, other than `except`, or "" if none. +func action_using(code: int, except: String = "") -> String: + for action: String in codes: + if action != except and int(codes[action]) == code: + return action + return "" + + +## Binds `action` to `code`. Returns "" when done, or why not: "unknown action", +## "reserved", "not an input", or the id of the action that already uses it (nothing +## changes then). +func bind(action: String, code: int) -> String: + if not has_action(action): + return "unknown action" + if RESERVED.has(code): + return "reserved" + if not is_valid_code(code): + return "not an input" + var other: String = action_using(code, action) + if not other.is_empty(): + return other + codes[action] = code + return "" + + +## Every action whose input another action also uses (only possible in a hand-edited +## settings file; load_from() repairs those). +func conflicts() -> Array[String]: + var found: Array[String] = [] + for action: String in codes: + if not action_using(int(codes[action]), action).is_empty(): + found.append(action) + found.sort() + return found + + +## True if the input for `action` is held now. +func is_held(action: String) -> bool: + var code: int = code_of(action) + if code < 0: + return Input.is_mouse_button_pressed(-code as MouseButton) + if code > 0: + return Input.is_physical_key_pressed(code as Key) + return false + + +## The action a press event is for, or "". +func action_for_event(event: InputEvent) -> String: + var code: int = code_of_event(event) + return action_using(code) if code != 0 else "" + + +## The code of a key or mouse button press, or 0 for anything else. +static func code_of_event(event: InputEvent) -> int: + var key: InputEventKey = event as InputEventKey + if key != null and key.pressed and not key.echo: + return int(key.physical_keycode) if key.physical_keycode != KEY_NONE else int(key.keycode) + var button: InputEventMouseButton = event as InputEventMouseButton + if button != null and button.pressed: + return -int(button.button_index) + return 0 + + +static func is_valid_code(code: int) -> bool: + if code < 0: + return -code >= MOUSE_BUTTON_LEFT and -code <= MOUSE_BUTTON_XBUTTON2 and -code != MOUSE_BUTTON_WHEEL_UP and -code != MOUSE_BUTTON_WHEEL_DOWN + return code > 0 and not OS.get_keycode_string(code as Key).is_empty() + + +## A name for a code, for the settings menu. +static func describe(code: int) -> String: + if code < 0: + match -code: + MOUSE_BUTTON_LEFT: + return "Left mouse" + MOUSE_BUTTON_RIGHT: + return "Right mouse" + MOUSE_BUTTON_MIDDLE: + return "Middle mouse" + _: + return "Mouse %d" % -code + if code == 0: + return "None" + return OS.get_keycode_string(code as Key) + + +## Writes every binding into `config`'s "keys" section. +func write(config: ConfigFile) -> void: + for action: String in codes: + config.set_value("keys", action, int(codes[action])) + + +## Reads bindings from `config`. Anything missing, malformed or clashing with an +## earlier action keeps its default, and a default taken by then is left unbound +## rather than doubled. +static func read(config: ConfigFile) -> KeyBindings: + var bindings: KeyBindings = KeyBindings.new() + for action: Dictionary in ACTIONS: + var id: String = action["id"] + if not config.has_section_key("keys", id): + continue + var value: Variant = config.get_value("keys", id) + if value is int and is_valid_code(value) and not RESERVED.has(value): + bindings.codes[id] = int(value) + # Repair clashes in list order: the first action keeps its input. + var taken: Dictionary = {} + for action: Dictionary in ACTIONS: + var id: String = action["id"] + var code: int = int(bindings.codes[id]) + if taken.has(code): + code = int(action["default"]) + if taken.has(code): + code = 0 + bindings.codes[id] = code + if code != 0: + taken[code] = true + return bindings + + +static func _index_of(action: String) -> int: + for index: int in ACTIONS.size(): + if ACTIONS[index]["id"] == action: + return index + return -1 diff --git a/src/client/key_bindings.gd.uid b/src/client/key_bindings.gd.uid new file mode 100644 index 0000000..a4ce343 --- /dev/null +++ b/src/client/key_bindings.gd.uid @@ -0,0 +1 @@ +uid://br7i81anq3yf4 diff --git a/src/client/match_view.gd b/src/client/match_view.gd index c45c788..ceb9b28 100644 --- a/src/client/match_view.gd +++ b/src/client/match_view.gd @@ -19,6 +19,17 @@ var camera: Camera3D var rig: CameraRig = CameraRig.new() ## The woodcut print pass over the camera (Look.add_print_pass). var print_pass: MeshInstance3D +var sun: DirectionalLight3D + + +## Applies the player's graphics settings: the sun's shadows and the print pass. +func apply_settings(settings: GameSettings) -> void: + var distance: float = settings.shadow_distance() + if sun != null: + sun.shadow_enabled = distance > 0.0 + sun.directional_shadow_max_distance = maxf(distance, 1.0) + if print_pass != null: + print_pass.visible = settings.print_pass ## Builds the scene for `simulation`. `local_id` is the player this client plays, or 0. @@ -27,7 +38,8 @@ func setup(simulation: Simulation, local_id: int = 0) -> void: var world: WorldEnvironment = WorldEnvironment.new() world.environment = Look.environment() add_child(world) - add_child(Look.sun()) + sun = Look.sun() + add_child(sun) camera = Camera3D.new() camera.near = CameraRig.NEAR diff --git a/src/client/style/palette.gd b/src/client/style/palette.gd index 6f910fe..adb451e 100644 --- a/src/client/style/palette.gd +++ b/src/client/style/palette.gd @@ -1,7 +1,7 @@ ## Tidewall's one table of colours: the drowned-coast palette from docs/STYLE.md. ## Every colour the client draws with comes from here, so the look stays one look; a -## test (test_palette.gd) fails on a colour literal anywhere else in src/client or -## src/app. All values are sRGB. Add a colour here, named for what it is in the world, +## test (test_palette.gd) fails on a colour literal anywhere else in src/client, +## src/app or src/ui. All values are sRGB. Add a colour here, named for what it is in the world, ## before using it, and add it to the table in docs/STYLE.md. class_name Palette extends RefCounted @@ -80,6 +80,8 @@ const INK: Color = Color(0.16, 0.13, 0.11) const PAPER: Color = Color(0.91, 0.87, 0.78) ## Paper in shadow, for panel edges and dimmed text. const PAPER_DIM: Color = Color(0.66, 0.62, 0.54) +## Brass seen on paper: the edge of the menu control that has focus. +const GILT_DEEP: Color = Color(0.62, 0.45, 0.12) ## Dark text outline on the HUD. const OUTLINE: Color = Color(0.08, 0.08, 0.08) diff --git a/src/server/local_server.gd b/src/server/local_server.gd index c47bcb1..f3e81bb 100644 --- a/src/server/local_server.gd +++ b/src/server/local_server.gd @@ -18,9 +18,10 @@ var _greeted: bool = false ## A match of one person and `bots` bots. With `rules` null it starts at once, and a -## new one starts after each one's results. -func _init(match_seed: int, bots: int, rules: MatchRules = null) -> void: - loop = ServerLoop.new(match_seed, 1, bots, rules) +## new one starts after each one's results. `difficulty` is every bot's, as an index +## into Tuning.BOT_DIFFICULTIES, or -1 to mix them. +func _init(match_seed: int, bots: int, rules: MatchRules = null, difficulty: int = -1) -> void: + loop = ServerLoop.new(match_seed, 1, bots, rules, difficulty) game = NetGame.new(loop, NetServer.new()) game.adopt(HANDLE) diff --git a/src/ui/menu_backdrop.gd b/src/ui/menu_backdrop.gd new file mode 100644 index 0000000..2da7925 --- /dev/null +++ b/src/ui/menu_backdrop.gd @@ -0,0 +1,64 @@ +## What the menus stand on when no match is showing: a hazy sky over a dark sea, a low +## island on the horizon, and a painted tide post in the shallows with its notches, +## the game's clock. Drawn, not loaded, from Palette colours. +class_name MenuBackdrop +extends Control + +## Notches on the post, from the bottom. +const NOTCHES: int = 6 + + +func _init() -> void: + mouse_filter = Control.MOUSE_FILTER_IGNORE + + +func _notification(what: int) -> void: + if what == NOTIFICATION_RESIZED: + queue_redraw() + + +func _draw() -> void: + var w: float = size.x + var h: float = size.y + var horizon: float = h * 0.62 + # Sky: haze at the horizon up to the high blue. + draw_polygon(PackedVector2Array([Vector2(0, 0), Vector2(w, 0), Vector2(w, horizon), Vector2(0, horizon)]), + PackedColorArray([Palette.SKY_TOP, Palette.SKY_TOP, Palette.SKY_HAZE, Palette.SKY_HAZE])) + # A low island far off, in fog. + var island: PackedVector2Array = PackedVector2Array() + var left: float = w * 0.08 + var right: float = w * 0.46 + island.append(Vector2(left, horizon)) + for index: int in 13: + var t: float = float(index) / 12.0 + var rise: float = sin(t * PI) * (0.6 + 0.4 * sin(t * 9.0)) * h * 0.05 + island.append(Vector2(lerpf(left, right, t), horizon - rise)) + island.append(Vector2(right, horizon)) + draw_colored_polygon(island, Palette.SEA_FOG.darkened(0.25)) + # Sea: the sea's ink fading darker towards the viewer. + draw_polygon(PackedVector2Array([Vector2(0, horizon), Vector2(w, horizon), Vector2(w, h), Vector2(0, h)]), + PackedColorArray([Palette.SEA_INK.lightened(0.15), Palette.SEA_INK.lightened(0.15), Palette.SEA_INK.darkened(0.35), Palette.SEA_INK.darkened(0.35)])) + draw_line(Vector2(0, horizon), Vector2(w, horizon), Palette.INK, 1.5) + # Wave strokes, in rows that widen towards the viewer. + for row: int in 9: + var y: float = horizon + pow(float(row + 1) / 9.0, 1.6) * (h - horizon) + var length: float = 14.0 + row * 7.0 + var x: float = fmod(row * 97.0, length * 3.0) + while x < w: + draw_line(Vector2(x, y), Vector2(x + length * 0.5, y - 2.0 - row * 0.3), Palette.PAPER_DIM, 1.0 + row * 0.15) + draw_line(Vector2(x + length * 0.5, y - 2.0 - row * 0.3), Vector2(x + length, y), Palette.PAPER_DIM, 1.0 + row * 0.15) + x += length * 3.0 + # The tide post, standing in the shallows to the right. + var post_x: float = w * 0.84 + var post_top: float = h * 0.30 + var post_foot: float = h * 0.92 + var post_width: float = maxf(w * 0.018, 10.0) + draw_rect(Rect2(post_x - post_width * 0.5, post_top, post_width, post_foot - post_top), Palette.TAR_WEATHERED) + draw_rect(Rect2(post_x - post_width * 0.5, post_top, post_width, post_foot - post_top), Palette.INK, false, 2.0) + for notch: int in NOTCHES: + var y: float = lerpf(post_foot, post_top + 12.0, float(notch + 1) / float(NOTCHES + 1)) + var reach: float = post_width * (1.2 if notch % 2 == 0 else 0.8) + draw_line(Vector2(post_x - post_width * 0.5, y), Vector2(post_x - post_width * 0.5 + reach, y), Palette.PAPER, 3.0) + # The water about its foot. + var sea_at_post: float = h * 0.80 + draw_line(Vector2(post_x - post_width * 3.0, sea_at_post), Vector2(post_x + post_width * 3.0, sea_at_post), Palette.PAPER, 2.0) diff --git a/src/ui/menu_backdrop.gd.uid b/src/ui/menu_backdrop.gd.uid new file mode 100644 index 0000000..f105cbd --- /dev/null +++ b/src/ui/menu_backdrop.gd.uid @@ -0,0 +1 @@ +uid://bkaw0wml6sqe8 diff --git a/src/ui/menu_theme.gd b/src/ui/menu_theme.gd new file mode 100644 index 0000000..c487b20 --- /dev/null +++ b/src/ui/menu_theme.gd @@ -0,0 +1,91 @@ +## The menus' look, from docs/STYLE.md: unbleached paper panels edged in ink, ink +## lettering, plain ink-edged buttons, and brass (GILT) with a thicker edge for the +## control that has focus, so the keyboard's place is told by shape as well as colour. +## Godot's bundled default font. +class_name MenuTheme +extends RefCounted + + +static func make() -> Theme: + var theme: Theme = Theme.new() + theme.default_font_size = Menus.FONT_BODY + theme.set_stylebox("panel", "PanelContainer", _box(Palette.PAPER, Palette.INK, 3, 26.0)) + for type: String in ["Label", "Button", "CheckButton", "OptionButton", "LineEdit", "ItemList", "TabBar", "SpinBox"]: + theme.set_color("font_color", type, Palette.INK) + for type: String in ["Button", "OptionButton", "CheckButton"]: + theme.set_color("font_hover_color", type, Palette.INK) + theme.set_color("font_focus_color", type, Palette.INK) + theme.set_color("font_pressed_color", type, Palette.INK) + theme.set_color("font_hover_pressed_color", type, Palette.INK) + theme.set_color("font_disabled_color", type, Palette.PAPER_DIM) + theme.set_stylebox("normal", type, _box(Palette.CANVAS, Palette.INK, 2, 8.0)) + theme.set_stylebox("hover", type, _box(Palette.SALT, Palette.INK, 2, 8.0)) + theme.set_stylebox("pressed", type, _box(Palette.PAPER_DIM, Palette.INK, 2, 8.0)) + theme.set_stylebox("disabled", type, _box(Palette.PAPER, Palette.PAPER_DIM, 2, 8.0)) + theme.set_stylebox("focus", type, _box(Color.TRANSPARENT, Palette.GILT_DEEP, 4, 8.0, false)) + theme.set_stylebox("normal", "LineEdit", _box(Palette.SALT, Palette.INK, 2, 8.0)) + theme.set_stylebox("focus", "LineEdit", _box(Color.TRANSPARENT, Palette.GILT_DEEP, 4, 8.0, false)) + theme.set_color("font_placeholder_color", "LineEdit", Palette.PAPER_DIM) + theme.set_color("caret_color", "LineEdit", Palette.INK) + theme.set_stylebox("panel", "ItemList", _box(Palette.SALT, Palette.INK, 2, 6.0)) + theme.set_stylebox("focus", "ItemList", _box(Color.TRANSPARENT, Palette.GILT_DEEP, 4, 6.0, false)) + theme.set_stylebox("selected", "ItemList", _box(Palette.CANVAS, Palette.INK, 1, 4.0)) + theme.set_stylebox("selected_focus", "ItemList", _box(Palette.CANVAS, Palette.GILT_DEEP, 2, 4.0)) + theme.set_color("font_selected_color", "ItemList", Palette.INK) + theme.set_color("font_hovered_color", "ItemList", Palette.INK) + theme.set_stylebox("panel", "TabContainer", _box(Palette.PAPER, Palette.INK, 2, 12.0)) + theme.set_stylebox("tab_selected", "TabContainer", _box(Palette.PAPER, Palette.INK, 2, 8.0)) + theme.set_stylebox("tab_unselected", "TabContainer", _box(Palette.PAPER_DIM, Palette.INK, 1, 8.0)) + theme.set_stylebox("tab_hovered", "TabContainer", _box(Palette.CANVAS, Palette.INK, 1, 8.0)) + theme.set_stylebox("tab_focus", "TabContainer", _box(Color.TRANSPARENT, Palette.GILT_DEEP, 4, 8.0, false)) + for state: String in ["font_selected_color", "font_unselected_color", "font_hovered_color"]: + theme.set_color(state, "TabContainer", Palette.INK) + theme.set_stylebox("slider", "HSlider", _track(Palette.PAPER_DIM)) + theme.set_stylebox("grabber_area", "HSlider", _track(Palette.SEA_INK)) + theme.set_stylebox("grabber_area_highlight", "HSlider", _track(Palette.SEA_INK)) + theme.set_stylebox("focus", "HSlider", _box(Color.TRANSPARENT, Palette.GILT_DEEP, 3, 4.0, false)) + return theme + + +## A length of rope under a heading: a twisted line drawn in ink. +static func rope() -> Control: + var line: RopeLine = RopeLine.new() + line.custom_minimum_size = Vector2(0.0, 10.0) + return line + + +static func _box(fill: Color, edge: Color, width: int, padding: float, filled: bool = true) -> StyleBoxFlat: + var box: StyleBoxFlat = StyleBoxFlat.new() + box.bg_color = fill + box.draw_center = filled + box.border_color = edge + box.set_border_width_all(width) + # Square, cut corners like a painted board; never rounded. + box.set_corner_radius_all(0) + box.content_margin_left = padding + box.content_margin_right = padding + box.content_margin_top = padding * 0.5 + box.content_margin_bottom = padding * 0.5 + return box + + +## A slider's track: a thin inked bar, filled up to the grabber in the sea's ink. +static func _track(fill: Color) -> StyleBoxFlat: + var box: StyleBoxFlat = _box(fill, Palette.INK, 1, 0.0) + box.content_margin_top = 4.0 + box.content_margin_bottom = 4.0 + return box + + +## A rope divider. +class RopeLine: + extends Control + + func _draw() -> void: + var middle: float = size.y * 0.5 + draw_line(Vector2(0.0, middle), Vector2(size.x, middle), Palette.INK, 1.0) + var step: float = 7.0 + var x: float = 0.0 + while x < size.x: + draw_line(Vector2(x, middle + 3.0), Vector2(minf(x + step, size.x), middle - 3.0), Palette.INK, 1.5) + x += step diff --git a/src/ui/menu_theme.gd.uid b/src/ui/menu_theme.gd.uid new file mode 100644 index 0000000..319328c --- /dev/null +++ b/src/ui/menu_theme.gd.uid @@ -0,0 +1 @@ +uid://dna1xthnwvjef diff --git a/src/ui/menus.gd b/src/ui/menus.gd new file mode 100644 index 0000000..b43aa82 --- /dev/null +++ b/src/ui/menus.gd @@ -0,0 +1,594 @@ +## The game's menus (A10), in the paper-and-ink motifs of docs/STYLE.md: the main menu, +## practice against bots, joining a server (with the LAN and list-server browser), +## settings (controls, mouse, graphics, audio, display), the pause menu and the results. +## +## Menus only edit `settings` and say what the player asked for through signals; the +## program (Main) starts and leaves matches. Every screen can be driven from the +## keyboard: each grabs focus on its first control when shown, and Escape goes back. +## show_screen() and the buttons' `pressed` signals are what the UI test drives. +class_name Menus +extends Control + +signal practice_requested(bots: int, difficulty: int) +signal join_requested(host: String, port: int, player_name: String) +signal resume_requested +signal leave_requested +signal quit_requested +signal settings_changed + +const SCREENS: Array[String] = ["main", "practice", "join", "settings", "pause", "results"] +const PANEL_WIDTH: float = 560.0 +const FONT_TITLE: int = 40 +const FONT_HEADING: int = 24 +const FONT_BODY: int = 17 +const FONT_SMALL: int = 14 +## Seconds a server search listens for answers. +const SEARCH_SECONDS: float = 2.0 + +var settings: GameSettings = GameSettings.new() +## Where settings are saved; tests point it somewhere harmless. +var settings_path: String = GameSettings.DEFAULT_PATH +## Screen name -> its panel. +var screens: Dictionary = {} +## The screen shown, and the ones Back returns through. +var current: String = "" +var _history: Array[String] = [] + +## Controls tab: the action waiting for a key, or "". +var listening_for: String = "" +var _binding_buttons: Dictionary = {} +var _binding_note: Label +## Practice. +var _bots: SpinBox +var _difficulty: OptionButton +## Join. +var _name: LineEdit +var _address: LineEdit +var _servers: ItemList +var _found: Array[Dictionary] = [] +var _join_note: Label +var _browser: ServerBrowser = null +var _search_left: float = 0.0 +## Settings. +var _tabs: TabContainer +var _sensitivity: HSlider +var _aim_scale: HSlider +var _invert: CheckButton +var _quality: OptionButton +var _print_pass: CheckButton +var _volumes: Dictionary = {} +var _window_mode: OptionButton +var _vsync: CheckButton +var _max_fps: OptionButton +## Results. +var _results_title: Label +var _results_body: Label +## The backdrop drawn behind the menus when no match is showing. +var backdrop: MenuBackdrop +## Over a match, a wash of ink instead, so the match shows through. +var shade: ColorRect +## True while a match is being played under the menus (AppShell sets it). +var over_match: bool = false: + set(value): + over_match = value + backdrop.visible = not value + shade.visible = value + + +func _init() -> void: + name = "Menus" + set_anchors_and_offsets_preset(Control.PRESET_FULL_RECT) + theme = MenuTheme.make() + backdrop = MenuBackdrop.new() + backdrop.set_anchors_and_offsets_preset(Control.PRESET_FULL_RECT) + add_child(backdrop) + shade = ColorRect.new() + shade.color = Color(Palette.INK, 0.45) + shade.set_anchors_and_offsets_preset(Control.PRESET_FULL_RECT) + shade.mouse_filter = Control.MOUSE_FILTER_IGNORE + shade.visible = false + add_child(shade) + _build_main() + _build_practice() + _build_join() + _build_settings() + _build_pause() + _build_results() + for screen: String in screens: + (screens[screen] as Control).visible = false + + +## Puts `with` in the menus and refreshes every control from it. +func use_settings(with: GameSettings, path: String = GameSettings.DEFAULT_PATH) -> void: + settings = with + settings_path = path + _refresh_controls() + + +## Shows `screen`, remembering the one before for Back. `remember` false replaces +## the history (the main, pause and results screens start afresh). +func show_screen(screen: String, remember: bool = true) -> void: + assert(screens.has(screen), "no screen called %s" % screen) + if remember and not current.is_empty() and current != screen: + _history.append(current) + elif not remember: + _history.clear() + if not current.is_empty(): + (screens[current] as Control).visible = false + current = screen + listening_for = "" + visible = true + var panel: Control = screens[screen] + panel.visible = true + if screen == "settings" or screen == "practice" or screen == "join": + _refresh_controls() + if is_inside_tree(): + first_focus(screen).grab_focus() + + +## Back a screen; from the first one, the pause menu resumes and others stay. +func back() -> void: + if not listening_for.is_empty(): + listening_for = "" + _binding_note.text = "Left as it was." + _refresh_bindings() + return + if current == "settings": + save_settings() + if _history.is_empty(): + if current == "pause": + resume_requested.emit() + return + var previous: String = _history.pop_back() + (screens[current] as Control).visible = false + current = "" + show_screen(previous) + + +## Hides every screen (a match is being played). +func close() -> void: + if not current.is_empty(): + (screens[current] as Control).visible = false + current = "" + _history.clear() + listening_for = "" + visible = false + + +## The control a screen focuses first. +func first_focus(screen: String) -> Control: + var panel: Control = screens[screen] + return panel.get_meta("first") as Control + + +## The buttons on a screen, by their text, for tests and for keyboard focus order. +func buttons_of(screen: String) -> Dictionary: + var found: Dictionary = {} + _collect_buttons(screens[screen] as Node, found) + return found + + +## Shows the results of a match: `place` (0 when unknown), out of `total`, with +## `eliminations`, and the last lines of the feed. +func show_results(place: int, total: int, eliminations: int, lines: Array[String]) -> void: + if place == 1: + _results_title.text = "Last on dry ground" + elif place > 0: + _results_title.text = "Placed %d of %d" % [place, total] + else: + _results_title.text = "The match is over" + var body: Array[String] = ["Eliminations: %d" % eliminations] + if not lines.is_empty(): + body.append("") + body.append_array(lines) + _results_body.text = "\n".join(body) + show_screen("results", false) + + +func save_settings() -> Error: + var error: Error = settings.save(settings_path) + settings_changed.emit() + return error + + +func _process(delta: float) -> void: + if _browser == null: + return + _browser.poll() + _search_left -= delta + if _search_left <= 0.0: + _finish_search() + + +func _unhandled_input(event: InputEvent) -> void: + if not visible or current.is_empty(): + return + if not listening_for.is_empty(): + var code: int = KeyBindings.code_of_event(event) + if code == KEY_ESCAPE: + back() + get_viewport().set_input_as_handled() + elif code != 0: + try_bind(listening_for, code) + get_viewport().set_input_as_handled() + return + if event.is_action_pressed("ui_cancel"): + back() + get_viewport().set_input_as_handled() + + +## Starts waiting for the next key or mouse button for `action`. +func listen_for(action: String) -> void: + listening_for = action + (_binding_buttons[action] as Button).text = "Press a key..." + _binding_note.text = "Press the new key or mouse button for %s, or Escape to leave it." % KeyBindings.label_of(action) + + +## Binds `action` to `code`, saying why not when it can't. Returns bind()'s answer. +func try_bind(action: String, code: int) -> String: + var answer: String = settings.bindings.bind(action, code) + listening_for = "" + if answer.is_empty(): + _binding_note.text = "%s: %s." % [KeyBindings.label_of(action), KeyBindings.describe(code)] + save_settings() + elif answer == "reserved": + _binding_note.text = "%s is kept for the menus." % KeyBindings.describe(code) + elif KeyBindings.has_action(answer): + _binding_note.text = "%s is already used for %s. Change that first." % [KeyBindings.describe(code), KeyBindings.label_of(answer)] + else: + _binding_note.text = "That can't be bound." + _refresh_bindings() + return answer + + +# --- Building the screens ------------------------------------------------------------ + +func _panel(screen: String, title: String) -> VBoxContainer: + var panel: PanelContainer = PanelContainer.new() + panel.name = screen.capitalize() + panel.set_anchors_and_offsets_preset(Control.PRESET_CENTER) + panel.custom_minimum_size = Vector2(PANEL_WIDTH, 0.0) + panel.grow_horizontal = Control.GROW_DIRECTION_BOTH + panel.grow_vertical = Control.GROW_DIRECTION_BOTH + add_child(panel) + var column: VBoxContainer = VBoxContainer.new() + column.add_theme_constant_override("separation", 10) + panel.add_child(column) + var heading: Label = Label.new() + heading.text = title + heading.horizontal_alignment = HORIZONTAL_ALIGNMENT_CENTER + heading.add_theme_font_size_override("font_size", FONT_TITLE if screen == "main" else FONT_HEADING) + column.add_child(heading) + column.add_child(MenuTheme.rope()) + screens[screen] = panel + return column + + +func _button(column: Container, text: String, action: Callable) -> Button: + var button: Button = Button.new() + button.text = text + button.pressed.connect(action) + column.add_child(button) + var panel: Control = column + while panel != null and not screens.values().has(panel): + panel = panel.get_parent() as Control + if panel != null and not panel.has_meta("first"): + panel.set_meta("first", button) + return button + + +func _row(column: Container, label_text: String, control: Control) -> void: + var row: HBoxContainer = HBoxContainer.new() + row.add_theme_constant_override("separation", 12) + var label: Label = Label.new() + label.text = label_text + label.custom_minimum_size = Vector2(200.0, 0.0) + row.add_child(label) + control.size_flags_horizontal = Control.SIZE_EXPAND_FILL + row.add_child(control) + column.add_child(row) + + +## A row with a slider and its value beside it, as `format` % value (or a percentage +## when `percent`). +func _slider_row(column: Container, label_text: String, slider: HSlider, percent: bool = false) -> void: + var holder: HBoxContainer = HBoxContainer.new() + holder.add_theme_constant_override("separation", 10) + slider.size_flags_horizontal = Control.SIZE_EXPAND_FILL + slider.size_flags_vertical = Control.SIZE_SHRINK_CENTER + holder.add_child(slider) + var readout: Label = Label.new() + readout.custom_minimum_size = Vector2(52.0, 0.0) + readout.horizontal_alignment = HORIZONTAL_ALIGNMENT_RIGHT + holder.add_child(readout) + var show: Callable = func(value: float) -> void: + readout.text = ("%d%%" % roundi(value * 100.0)) if percent else ("%.2f" % value) + slider.value_changed.connect(show) + slider.set_meta("readout", show) + _row(column, label_text, holder) + + +func _note(column: Container) -> Label: + var label: Label = Label.new() + label.autowrap_mode = TextServer.AUTOWRAP_WORD_SMART + label.add_theme_font_size_override("font_size", FONT_SMALL) + label.custom_minimum_size = Vector2(PANEL_WIDTH - 60.0, 0.0) + column.add_child(label) + return label + + +func _build_main() -> void: + var column: VBoxContainer = _panel("main", "TIDEWALL") + var motto: Label = Label.new() + motto.text = "The sea is rising. Build high, hold your ground." + motto.horizontal_alignment = HORIZONTAL_ALIGNMENT_CENTER + motto.add_theme_font_size_override("font_size", FONT_SMALL) + column.add_child(motto) + _button(column, "Practice against bots", func() -> void: show_screen("practice")) + _button(column, "Join a server", func() -> void: show_screen("join")) + _button(column, "Settings", func() -> void: show_screen("settings")) + _button(column, "Quit", func() -> void: quit_requested.emit()) + + +func _build_practice() -> void: + var column: VBoxContainer = _panel("practice", "Practice") + _bots = SpinBox.new() + _bots.min_value = 1 + _bots.max_value = Tuning.SOLO_PLAYERS - 1 + _bots.step = 1 + _row(column, "Bots", _bots) + _difficulty = OptionButton.new() + _difficulty.add_item("Mixed", 0) + for index: int in Tuning.BOT_DIFFICULTIES.size(): + _difficulty.add_item(String(Tuning.BOT_DIFFICULTIES[index]["name"]).capitalize(), index + 1) + _row(column, "Bot skill", _difficulty) + _button(column, "Set out", _start_practice) + _button(column, "Back", back) + + +func _start_practice() -> void: + settings.practice_bots = int(_bots.value) + settings.practice_difficulty = _difficulty.selected - 1 + save_settings() + practice_requested.emit(settings.practice_bots, settings.practice_difficulty) + + +func _build_join() -> void: + var column: VBoxContainer = _panel("join", "Join a server") + _name = LineEdit.new() + _name.max_length = GameSettings.MAX_NAME_LENGTH + _name.placeholder_text = ClientConfig.DEFAULT_NAME + _row(column, "Your name", _name) + _address = LineEdit.new() + _address.placeholder_text = "host or host:port" + _address.text_submitted.connect(func(_text: String) -> void: _join_address()) + _row(column, "Address", _address) + _button(column, "Join this address", _join_address) + screens["join"].set_meta("first", _address) + _servers = ItemList.new() + _servers.custom_minimum_size = Vector2(0.0, 150.0) + _servers.item_activated.connect(_join_listed) + column.add_child(_servers) + _button(column, "Search the LAN", _search) + _button(column, "Join the chosen server", func() -> void: + var chosen: PackedInt32Array = _servers.get_selected_items() + if chosen.is_empty(): + _join_note.text = "Choose a server from the list first." + else: + _join_listed(chosen[0])) + _join_note = _note(column) + _button(column, "Back", back) + + +## Looks for servers on the LAN for a moment, then lists them. +func _search() -> void: + if _browser != null: + return + _browser = ServerBrowser.new() + if _browser.open() != OK: + _browser = null + _join_note.text = "Couldn't open a network socket to search." + return + _browser.scan_lan() + _search_left = SEARCH_SECONDS + _join_note.text = "Searching..." + + +func _finish_search() -> void: + show_servers(_browser.sorted()) + _browser.close() + _browser = null + + +## Lists `found` (ServerBrowser.sorted()). +func show_servers(found: Array[Dictionary]) -> void: + _found = found + _servers.clear() + for server: Dictionary in found: + var line: String = "%s %d/%d %s" % [server.get("name", "?"), int(server.get("players", 0)), int(server.get("max_players", 0)), server.get("source", "")] + if not server.get("compatible", false): + line += " (another version)" + _servers.add_item(line) + _servers.set_item_disabled(_servers.item_count - 1, not server.get("compatible", false)) + _join_note.text = "%d found." % found.size() if not found.is_empty() else "No servers answered. Try an address." + + +func _join_listed(index: int) -> void: + if index < 0 or index >= _found.size() or not _found[index].get("compatible", false): + return + var server: Dictionary = _found[index] + _join(String(server["address"]), int(server["port"])) + + +func _join_address() -> void: + var text: String = _address.text.strip_edges() + if text.is_empty(): + _join_note.text = "Type an address first." + return + var target: Dictionary = ServerConfig.parse_host_port(text, ServerConfig.DEFAULT_PORT) + if target.is_empty(): + _join_note.text = "That isn't an address: use host or host:port." + return + settings.last_server = text + _join(String(target["host"]), int(target["port"])) + + +func _join(host: String, port: int) -> void: + settings.player_name = _name.text + save_settings() + join_requested.emit(host, port, settings.player_name) + + +func _build_settings() -> void: + var column: VBoxContainer = _panel("settings", "Settings") + _tabs = TabContainer.new() + _tabs.custom_minimum_size = Vector2(PANEL_WIDTH + 140.0, 420.0) + column.add_child(_tabs) + + var controls_scroll: ScrollContainer = ScrollContainer.new() + controls_scroll.name = "Controls" + controls_scroll.horizontal_scroll_mode = ScrollContainer.SCROLL_MODE_DISABLED + _tabs.add_child(controls_scroll) + var controls: VBoxContainer = VBoxContainer.new() + controls.size_flags_horizontal = Control.SIZE_EXPAND_FILL + controls_scroll.add_child(controls) + for action: Dictionary in KeyBindings.ACTIONS: + var id: String = action["id"] + var button: Button = Button.new() + button.pressed.connect(listen_for.bind(id)) + _binding_buttons[id] = button + _row(controls, String(action["label"]), button) + var reset: Button = Button.new() + reset.text = "Put every key back" + reset.pressed.connect(func() -> void: + settings.bindings.reset() + _binding_note.text = "Every key is back to its default." + _refresh_bindings() + save_settings()) + controls.add_child(reset) + + var mouse: VBoxContainer = _tab("Mouse") + _sensitivity = _slider(InputSettings.MIN_SENSITIVITY, 4.0, 0.05) + _sensitivity.value_changed.connect(func(value: float) -> void: settings.mouse.mouse_sensitivity = value) + _slider_row(mouse, "Look speed", _sensitivity) + _aim_scale = _slider(0.1, 2.0, 0.05) + _aim_scale.value_changed.connect(func(value: float) -> void: settings.mouse.aim_sensitivity_scale = value) + _slider_row(mouse, "Speed while aiming", _aim_scale) + _invert = CheckButton.new() + _invert.toggled.connect(func(on: bool) -> void: settings.mouse.invert_y = on) + _row(mouse, "Invert up and down", _invert) + + var graphics: VBoxContainer = _tab("Graphics") + _quality = OptionButton.new() + for index: int in GameSettings.QUALITY_NAMES.size(): + _quality.add_item(GameSettings.QUALITY_NAMES[index], index) + _quality.item_selected.connect(func(index: int) -> void: settings.quality = index) + _row(graphics, "Quality", _quality) + _print_pass = CheckButton.new() + _print_pass.toggled.connect(func(on: bool) -> void: settings.print_pass = on) + _row(graphics, "Woodcut ink lines", _print_pass) + + var audio: VBoxContainer = _tab("Audio") + for bus: Array in [["master", "Everything"], ["music", "Music"], ["effects", "Effects"]]: + var slider: HSlider = _slider(0.0, 1.0, 0.05) + var key: String = bus[0] + slider.value_changed.connect(func(value: float) -> void: settings.set(key + "_volume", value)) + _volumes[key] = slider + _slider_row(audio, bus[1], slider, true) + + var display: VBoxContainer = _tab("Display") + _window_mode = OptionButton.new() + for index: int in GameSettings.WINDOW_MODES.size(): + _window_mode.add_item(GameSettings.WINDOW_MODES[index], index) + _window_mode.item_selected.connect(func(index: int) -> void: settings.window_mode = index) + _row(display, "Window", _window_mode) + _vsync = CheckButton.new() + _vsync.toggled.connect(func(on: bool) -> void: settings.vsync = on) + _row(display, "Vertical sync", _vsync) + _max_fps = OptionButton.new() + for cap: int in GameSettings.FRAME_CAPS: + _max_fps.add_item("No limit" if cap == 0 else "%d" % cap, cap) + _max_fps.item_selected.connect(func(index: int) -> void: settings.max_fps = GameSettings.FRAME_CAPS[index]) + _row(display, "Frame limit", _max_fps) + + _binding_note = _note(column) + _binding_note.text = "Choose an action to change its key." + _tabs.tab_changed.connect(func(tab: int) -> void: _binding_note.visible = tab == 0) + var done: Button = _button(column, "Back", back) + screens["settings"].set_meta("first", _tabs.get_tab_bar()) + done.name = "Back" + + +func _tab(title: String) -> VBoxContainer: + var column: VBoxContainer = VBoxContainer.new() + column.name = title + column.add_theme_constant_override("separation", 10) + _tabs.add_child(column) + return column + + +func _slider(low: float, high: float, step: float) -> HSlider: + var slider: HSlider = HSlider.new() + slider.min_value = low + slider.max_value = high + slider.step = step + slider.custom_minimum_size = Vector2(220.0, 24.0) + return slider + + +func _build_pause() -> void: + var column: VBoxContainer = _panel("pause", "Paused") + var note: Label = _note(column) + note.text = "The match goes on while you're here." + note.horizontal_alignment = HORIZONTAL_ALIGNMENT_CENTER + _button(column, "Back to the match", func() -> void: resume_requested.emit()) + _button(column, "Settings", func() -> void: show_screen("settings")) + _button(column, "Leave the match", func() -> void: leave_requested.emit()) + + +func _build_results() -> void: + var column: VBoxContainer = _panel("results", "Results") + _results_title = Label.new() + _results_title.horizontal_alignment = HORIZONTAL_ALIGNMENT_CENTER + _results_title.add_theme_font_size_override("font_size", FONT_HEADING) + column.add_child(_results_title) + _results_body = _note(column) + _button(column, "Stay and watch", func() -> void: resume_requested.emit()) + _button(column, "Back to the main menu", func() -> void: leave_requested.emit()) + + +# --- Keeping controls in step with the settings ------------------------------------ + +func _refresh_controls() -> void: + _bots.value = settings.practice_bots + _difficulty.selected = settings.practice_difficulty + 1 + _name.text = settings.player_name + if _address.text.is_empty(): + _address.text = settings.last_server + _sensitivity.set_value_no_signal(settings.mouse.mouse_sensitivity) + _aim_scale.set_value_no_signal(settings.mouse.aim_sensitivity_scale) + _invert.set_pressed_no_signal(settings.mouse.invert_y) + _quality.selected = settings.quality + _print_pass.set_pressed_no_signal(settings.print_pass) + (_volumes["master"] as HSlider).set_value_no_signal(settings.master_volume) + (_volumes["music"] as HSlider).set_value_no_signal(settings.music_volume) + (_volumes["effects"] as HSlider).set_value_no_signal(settings.effects_volume) + _window_mode.selected = settings.window_mode + _vsync.set_pressed_no_signal(settings.vsync) + _max_fps.selected = maxi(GameSettings.FRAME_CAPS.find(settings.max_fps), 0) + for slider: HSlider in [_sensitivity, _aim_scale, _volumes["master"], _volumes["music"], _volumes["effects"]]: + (slider.get_meta("readout") as Callable).call(slider.value) + _refresh_bindings() + + +func _refresh_bindings() -> void: + for action: String in _binding_buttons: + (_binding_buttons[action] as Button).text = KeyBindings.describe(settings.bindings.code_of(action)) + + +func _collect_buttons(node: Node, found: Dictionary) -> void: + for child: Node in node.get_children(): + var button: Button = child as Button + if button != null and not (button is OptionButton) and not (button is CheckButton): + found[button.text] = button + _collect_buttons(child, found) diff --git a/src/ui/menus.gd.uid b/src/ui/menus.gd.uid new file mode 100644 index 0000000..58290de --- /dev/null +++ b/src/ui/menus.gd.uid @@ -0,0 +1 @@ +uid://bdg6y620nfln diff --git a/test/capture/menu_join.tscn b/test/capture/menu_join.tscn new file mode 100644 index 0000000..6dba946 --- /dev/null +++ b/test/capture/menu_join.tscn @@ -0,0 +1,9 @@ +[gd_scene load_steps=2 format=3] + +[ext_resource type="Script" path="res://test/capture/menu_scene.gd" id="1"] + +[node name="CaptureMenu" type="Control"] +script = ExtResource("1") +screen = "join" +over_match = false +settings_tab = 0 diff --git a/test/capture/menu_main.tscn b/test/capture/menu_main.tscn new file mode 100644 index 0000000..f541aa8 --- /dev/null +++ b/test/capture/menu_main.tscn @@ -0,0 +1,9 @@ +[gd_scene load_steps=2 format=3] + +[ext_resource type="Script" path="res://test/capture/menu_scene.gd" id="1"] + +[node name="CaptureMenu" type="Control"] +script = ExtResource("1") +screen = "main" +over_match = false +settings_tab = 0 diff --git a/test/capture/menu_pause.tscn b/test/capture/menu_pause.tscn new file mode 100644 index 0000000..7ba1354 --- /dev/null +++ b/test/capture/menu_pause.tscn @@ -0,0 +1,9 @@ +[gd_scene load_steps=2 format=3] + +[ext_resource type="Script" path="res://test/capture/menu_scene.gd" id="1"] + +[node name="CaptureMenu" type="Control"] +script = ExtResource("1") +screen = "pause" +over_match = true +settings_tab = 0 diff --git a/test/capture/menu_practice.tscn b/test/capture/menu_practice.tscn new file mode 100644 index 0000000..7299285 --- /dev/null +++ b/test/capture/menu_practice.tscn @@ -0,0 +1,9 @@ +[gd_scene load_steps=2 format=3] + +[ext_resource type="Script" path="res://test/capture/menu_scene.gd" id="1"] + +[node name="CaptureMenu" type="Control"] +script = ExtResource("1") +screen = "practice" +over_match = false +settings_tab = 0 diff --git a/test/capture/menu_results.tscn b/test/capture/menu_results.tscn new file mode 100644 index 0000000..000e88f --- /dev/null +++ b/test/capture/menu_results.tscn @@ -0,0 +1,9 @@ +[gd_scene load_steps=2 format=3] + +[ext_resource type="Script" path="res://test/capture/menu_scene.gd" id="1"] + +[node name="CaptureMenu" type="Control"] +script = ExtResource("1") +screen = "results" +over_match = true +settings_tab = 0 diff --git a/test/capture/menu_scene.gd b/test/capture/menu_scene.gd new file mode 100644 index 0000000..6e7b235 --- /dev/null +++ b/test/capture/menu_scene.gd @@ -0,0 +1,37 @@ +## Capture scenario for the menus (A10): one screen of Menus, as a player would first see +## it, with default settings and nothing saved. `screen` is one of Menus.SCREENS; the +## join screen lists two made-up servers, and the results screen a made-up finish. +## `over_match` puts the ink wash over a plain stand-in for a match instead of the +## backdrop. +extends Control + +@export var screen: String = "main" +@export var over_match: bool = false +@export var settings_tab: int = 0 + + +func _ready() -> void: + set_anchors_and_offsets_preset(Control.PRESET_FULL_RECT) + if over_match: + var stand_in: MenuBackdrop = MenuBackdrop.new() + stand_in.set_anchors_and_offsets_preset(Control.PRESET_FULL_RECT) + add_child(stand_in) + var menus: Menus = Menus.new() + menus.use_settings(GameSettings.new(), "user://capture_unsaved.cfg") + add_child(menus) + menus.over_match = over_match + match screen: + "join": + menus.show_screen("join", false) + menus.show_servers([ + {"name": "Harbour Lights", "players": 11, "max_players": 24, "address": "192.0.2.10", "port": 24650, "source": "lan", "compatible": true}, + {"name": "Saltmarsh", "players": 2, "max_players": 24, "address": "192.0.2.11", "port": 24650, "source": "list", "compatible": true}, + {"name": "Old Pier", "players": 0, "max_players": 24, "address": "192.0.2.12", "port": 24650, "source": "lan", "compatible": false}, + ] as Array[Dictionary]) + "results": + menus.show_results(3, 24, 4, ["Ada drowned", "You took Thole with a dock carbine", "Gannet fell"] as Array[String]) + "settings": + menus.show_screen("settings", false) + menus._tabs.current_tab = settings_tab + _: + menus.show_screen(screen, false) diff --git a/test/capture/menu_scene.gd.uid b/test/capture/menu_scene.gd.uid new file mode 100644 index 0000000..e594333 --- /dev/null +++ b/test/capture/menu_scene.gd.uid @@ -0,0 +1 @@ +uid://cxiu5n42retf7 diff --git a/test/capture/menu_settings.tscn b/test/capture/menu_settings.tscn new file mode 100644 index 0000000..32c774d --- /dev/null +++ b/test/capture/menu_settings.tscn @@ -0,0 +1,9 @@ +[gd_scene load_steps=2 format=3] + +[ext_resource type="Script" path="res://test/capture/menu_scene.gd" id="1"] + +[node name="CaptureMenu" type="Control"] +script = ExtResource("1") +screen = "settings" +over_match = false +settings_tab = 0 diff --git a/test/capture/menu_settings_mouse.tscn b/test/capture/menu_settings_mouse.tscn new file mode 100644 index 0000000..d180f34 --- /dev/null +++ b/test/capture/menu_settings_mouse.tscn @@ -0,0 +1,9 @@ +[gd_scene load_steps=2 format=3] + +[ext_resource type="Script" path="res://test/capture/menu_scene.gd" id="1"] + +[node name="CaptureMenu" type="Control"] +script = ExtResource("1") +screen = "settings" +over_match = false +settings_tab = 1 diff --git a/test/client/test_game_settings.gd b/test/client/test_game_settings.gd new file mode 100644 index 0000000..cbf6fd6 --- /dev/null +++ b/test/client/test_game_settings.gd @@ -0,0 +1,130 @@ +extends TestCase + +## A10: settings saved between launches, and corrupt files falling back to defaults. + +const PATH: String = "user://test_game_settings.cfg" + + +func after_each() -> void: + super.after_each() + DirAccess.remove_absolute(ProjectSettings.globalize_path(PATH)) + + +func test_everything_round_trips() -> void: + var settings: GameSettings = GameSettings.new() + settings.mouse.mouse_sensitivity = 2.5 + settings.mouse.invert_y = true + assert_eq(settings.bindings.bind("jump", KEY_F), "") + settings.quality = GameSettings.QUALITY_LOW + settings.print_pass = false + settings.master_volume = 0.3 + settings.music_volume = 0.0 + settings.effects_volume = 0.55 + settings.window_mode = 1 + settings.vsync = false + settings.max_fps = 144 + settings.player_name = " Wren of the Point " + settings.last_server = "example.org:24650" + settings.practice_bots = 7 + settings.practice_difficulty = 2 + assert_eq(settings.save(PATH), OK) + var loaded: GameSettings = GameSettings.load_from(PATH) + assert_near(loaded.mouse.mouse_sensitivity, 2.5, 0.0001) + assert_true(loaded.mouse.invert_y) + assert_eq(loaded.bindings.code_of("jump"), KEY_F) + assert_eq(loaded.quality, GameSettings.QUALITY_LOW) + assert_false(loaded.print_pass) + assert_near(loaded.master_volume, 0.3, 0.0001) + assert_near(loaded.music_volume, 0.0, 0.0001) + assert_near(loaded.effects_volume, 0.55, 0.0001) + assert_eq(loaded.window_mode, 1) + assert_false(loaded.vsync) + assert_eq(loaded.max_fps, 144) + assert_eq(loaded.player_name, "Wren of the Point") + assert_eq(loaded.last_server, "example.org:24650") + assert_eq(loaded.practice_bots, 7) + assert_eq(loaded.practice_difficulty, 2) + assert_eq(loaded.shadow_distance(), 0.0, "low has no shadows") + + +func test_a_missing_file_gives_defaults() -> void: + var loaded: GameSettings = GameSettings.load_from("user://no_such_settings.cfg") + _assert_defaults(loaded) + + +func test_a_corrupt_file_gives_defaults() -> void: + # The engine reports each file it can't parse; that's expected here. + expect_error("ConfigFile parse error") + expect_error("ConfigFile parse error") + for garbage: PackedByteArray in [ + "[graphics\nquality=???\n".to_utf8_buffer() + PackedByteArray([0, 1]), + PackedByteArray([0xFF, 0xFE, 0x00, 0x13, 0x37, 0x80, 0x81]), + "quality = 2 = 3 [[[".to_utf8_buffer(), + ]: + var file: FileAccess = FileAccess.open(PATH, FileAccess.WRITE) + file.store_buffer(garbage) + file.close() + _assert_defaults(GameSettings.load_from(PATH)) + + +func test_wrong_types_and_ranges_fall_back_value_by_value() -> void: + var config: ConfigFile = ConfigFile.new() + config.set_value("graphics", "quality", 99) + config.set_value("graphics", "print_pass", "yes") + config.set_value("audio", "master", 7.0) + config.set_value("audio", "music", NAN) + config.set_value("audio", "effects", [1, 2]) + config.set_value("display", "window_mode", -4) + config.set_value("display", "max_fps", 77) + config.set_value("player", "name", 12) + config.set_value("practice", "bots", 400) + config.set_value("input", "mouse_sensitivity", INF) + config.set_value("keys", "forward", KEY_UP) + assert_eq(config.save(PATH), OK) + var loaded: GameSettings = GameSettings.load_from(PATH) + assert_eq(loaded.quality, GameSettings.QUALITY_HIGH, "clamped to the top preset") + assert_true(loaded.print_pass, "not a bool: the default") + assert_near(loaded.master_volume, 1.0, 0.0001, "clamped") + assert_near(loaded.music_volume, GameSettings.new().music_volume, 0.0001, "NaN: the default") + assert_near(loaded.effects_volume, GameSettings.new().effects_volume, 0.0001) + assert_eq(loaded.window_mode, 0) + assert_eq(loaded.max_fps, 0, "not an offered cap") + assert_eq(loaded.player_name, ClientConfig.DEFAULT_NAME) + assert_eq(loaded.practice_bots, Tuning.SOLO_PLAYERS - 1) + assert_near(loaded.mouse.mouse_sensitivity, 1.0, 0.0001) + assert_eq(loaded.bindings.code_of("forward"), KEY_UP, "the one good value is kept") + + +func test_old_mouse_only_files_still_load() -> void: + var old: InputSettings = InputSettings.new() + old.mouse_sensitivity = 3.0 + assert_eq(old.save(PATH), OK) + var loaded: GameSettings = GameSettings.load_from(PATH) + assert_near(loaded.mouse.mouse_sensitivity, 3.0, 0.0001) + assert_eq(loaded.bindings.code_of("jump"), KEY_SPACE) + + +func test_applying_settings_sets_the_audio_buses() -> void: + var settings: GameSettings = GameSettings.new() + settings.music_volume = 0.0 + settings.effects_volume = 0.5 + settings.apply_to_program(null) + var music: int = AudioServer.get_bus_index("Music") + var effects: int = AudioServer.get_bus_index("Effects") + assert_true(music > 0 and effects > 0, "made the buses") + assert_true(AudioServer.is_bus_mute(music)) + assert_near(AudioServer.get_bus_volume_db(effects), linear_to_db(0.5), 0.01) + settings.apply_to_program(null) + assert_eq(AudioServer.bus_count, 3, "no extra buses the second time") + + +func _assert_defaults(loaded: GameSettings) -> void: + var fresh: GameSettings = GameSettings.new() + assert_eq(loaded.quality, fresh.quality) + assert_eq(loaded.print_pass, fresh.print_pass) + assert_eq(loaded.master_volume, fresh.master_volume) + assert_eq(loaded.window_mode, fresh.window_mode) + assert_eq(loaded.player_name, fresh.player_name) + assert_eq(loaded.mouse.mouse_sensitivity, fresh.mouse.mouse_sensitivity) + for action: Dictionary in KeyBindings.ACTIONS: + assert_eq(loaded.bindings.code_of(action["id"]), int(action["default"])) diff --git a/test/client/test_game_settings.gd.uid b/test/client/test_game_settings.gd.uid new file mode 100644 index 0000000..ae8809e --- /dev/null +++ b/test/client/test_game_settings.gd.uid @@ -0,0 +1 @@ +uid://cta4a1dero8fu diff --git a/test/client/test_key_bindings.gd b/test/client/test_key_bindings.gd new file mode 100644 index 0000000..b8e5e01 --- /dev/null +++ b/test/client/test_key_bindings.gd @@ -0,0 +1,85 @@ +extends TestCase + +## A10: key bindings, rebinding and conflicts. + + +func test_defaults_are_the_documented_keys_and_none_clash() -> void: + var bindings: KeyBindings = KeyBindings.new() + assert_eq(bindings.code_of("forward"), KEY_W) + assert_eq(bindings.code_of("build"), KEY_B) + assert_eq(bindings.code_of("fire"), -MOUSE_BUTTON_LEFT) + assert_eq(bindings.code_of("slot_0"), KEY_1) + assert_eq(bindings.conflicts(), [] as Array[String]) + for action: Dictionary in KeyBindings.ACTIONS: + assert_true(KeyBindings.is_valid_code(int(action["default"])), String(action["id"])) + + +func test_rebinding_to_a_free_key_works() -> void: + var bindings: KeyBindings = KeyBindings.new() + assert_eq(bindings.bind("jump", KEY_F), "") + assert_eq(bindings.code_of("jump"), KEY_F) + assert_eq(bindings.bind("aim", -MOUSE_BUTTON_MIDDLE), "") + assert_eq(bindings.action_using(-MOUSE_BUTTON_MIDDLE), "aim") + + +func test_rebinding_to_a_used_key_is_refused_and_names_the_clash() -> void: + var bindings: KeyBindings = KeyBindings.new() + assert_eq(bindings.bind("jump", KEY_W), "forward") + assert_eq(bindings.code_of("jump"), KEY_SPACE, "unchanged") + assert_eq(bindings.bind("aim", -MOUSE_BUTTON_LEFT), "fire") + # Binding an action to the key it already has is no clash. + assert_eq(bindings.bind("forward", KEY_W), "") + + +func test_escape_wheel_and_nonsense_cannot_be_bound() -> void: + var bindings: KeyBindings = KeyBindings.new() + assert_eq(bindings.bind("jump", KEY_ESCAPE), "reserved") + assert_eq(bindings.bind("jump", -MOUSE_BUTTON_WHEEL_UP), "not an input") + assert_eq(bindings.bind("jump", 0), "not an input") + assert_eq(bindings.bind("fly", KEY_F), "unknown action") + + +func test_a_hand_edited_clash_is_repaired_on_load() -> void: + var config: ConfigFile = ConfigFile.new() + config.set_value("keys", "jump", KEY_W) + config.set_value("keys", "sprint", "shift") + config.set_value("keys", "reload", KEY_ESCAPE) + var bindings: KeyBindings = KeyBindings.read(config) + assert_eq(bindings.code_of("forward"), KEY_W, "the first in the list keeps it") + assert_eq(bindings.code_of("jump"), KEY_SPACE, "the clashing one goes back to its default") + assert_eq(bindings.code_of("sprint"), KEY_SHIFT) + assert_eq(bindings.code_of("reload"), KEY_R) + assert_eq(bindings.conflicts(), [] as Array[String]) + + +func test_events_find_their_action() -> void: + var bindings: KeyBindings = KeyBindings.new() + var key: InputEventKey = InputEventKey.new() + key.physical_keycode = KEY_B + key.pressed = true + assert_eq(bindings.action_for_event(key), "build") + key.echo = true + assert_eq(bindings.action_for_event(key), "", "a held key's repeats don't act") + var click: InputEventMouseButton = InputEventMouseButton.new() + click.button_index = MOUSE_BUTTON_RIGHT + click.pressed = true + assert_eq(bindings.action_for_event(click), "aim") + + +func test_client_input_follows_rebound_keys() -> void: + var input: ClientInput = ClientInput.new() + assert_eq(input.bindings.bind("build", KEY_Q), "") + var key: InputEventKey = InputEventKey.new() + key.physical_keycode = KEY_Q + key.pressed = true + input.handle(key, true) + assert_true(input.build_mode, "Q now toggles build mode") + key.physical_keycode = KEY_B + input.handle(key, true) + assert_true(input.build_mode, "B no longer does") + + +func test_describe_names_keys_and_buttons() -> void: + assert_eq(KeyBindings.describe(KEY_W), "W") + assert_eq(KeyBindings.describe(-MOUSE_BUTTON_LEFT), "Left mouse") + assert_eq(KeyBindings.describe(0), "None") diff --git a/test/client/test_key_bindings.gd.uid b/test/client/test_key_bindings.gd.uid new file mode 100644 index 0000000..a0b1779 --- /dev/null +++ b/test/client/test_key_bindings.gd.uid @@ -0,0 +1 @@ +uid://d0svqwutsfu5y diff --git a/test/project/test_palette.gd b/test/project/test_palette.gd index 695a33f..8bb288d 100644 --- a/test/project/test_palette.gd +++ b/test/project/test_palette.gd @@ -18,6 +18,7 @@ func test_client_colours_come_from_the_palette() -> void: var named: RegEx = RegEx.create_from_string(NAMED) var paths: Array[String] = _scripts_under("res://src/client") paths.append_array(_scripts_under("res://src/app")) + paths.append_array(_scripts_under("res://src/ui")) assert_true(paths.size() > 10, "expected client scripts") for path: String in paths: if ALLOWED.has(path): diff --git a/test/ui/test_menus.gd b/test/ui/test_menus.gd new file mode 100644 index 0000000..a458136 --- /dev/null +++ b/test/ui/test_menus.gd @@ -0,0 +1,265 @@ +extends TestCase + +## A10: every menu reachable and navigable, key rebinding through the menu, and the +## program's flow from the main menu into a practice match, the pause menu, the +## results and back. + +const PATH: String = "user://test_menus_settings.cfg" + +var menus: Menus +var tree: SceneTree + + +func before_each() -> void: + super.before_each() + tree = Engine.get_main_loop() as SceneTree + menus = Menus.new() + menus.use_settings(GameSettings.new(), PATH) + tree.root.add_child(menus) + + +func after_each() -> void: + super.after_each() + if is_instance_valid(menus): + menus.free() + DirAccess.remove_absolute(ProjectSettings.globalize_path(PATH)) + + +func _press(screen: String, text: String) -> void: + var buttons: Dictionary = menus.buttons_of(screen) + assert_true(buttons.has(text), "%s has a '%s' button (has %s)" % [screen, text, buttons.keys()]) + if buttons.has(text): + (buttons[text] as Button).pressed.emit() + + +func _key(keycode: Key) -> InputEventKey: + var key: InputEventKey = InputEventKey.new() + key.physical_keycode = keycode + key.keycode = keycode + key.pressed = true + return key + + +func test_every_screen_is_reachable_from_the_main_menu_and_back() -> void: + menus.show_screen("main", false) + assert_eq(menus.current, "main") + for pair: Array in [["Practice against bots", "practice"], ["Join a server", "join"], ["Settings", "settings"]]: + _press("main", pair[0]) + assert_eq(menus.current, pair[1]) + assert_true((menus.screens[pair[1]] as Control).visible) + assert_false((menus.screens["main"] as Control).visible, "one screen at a time") + menus.back() + assert_eq(menus.current, "main", "back from %s" % pair[1]) + var quit: Array[bool] = [false] + menus.quit_requested.connect(func() -> void: quit[0] = true) + _press("main", "Quit") + assert_true(quit[0]) + + +func test_every_screen_takes_keyboard_focus_and_escape_goes_back() -> void: + for screen: String in Menus.SCREENS: + menus.show_screen(screen, false) + await tree.process_frame + var focused: Control = menus.get_viewport().gui_get_focus_owner() + assert_not_null(focused, "%s focuses something" % screen) + if focused != null: + assert_true(menus.screens[screen].is_ancestor_of(focused), "%s's focus is on its own screen" % screen) + menus.show_screen("main", false) + _press("main", "Settings") + await tree.process_frame + var cancel: InputEventAction = InputEventAction.new() + cancel.action = "ui_cancel" + cancel.pressed = true + menus._unhandled_input(cancel) + assert_eq(menus.current, "main", "Escape went back") + + +func test_focus_moves_through_the_main_menu_with_the_arrow_keys() -> void: + menus.show_screen("main", false) + await tree.process_frame + var seen: Array[String] = [] + var focused: Control = menus.get_viewport().gui_get_focus_owner() + for _step: int in 4: + assert_not_null(focused) + if focused == null: + return + seen.append((focused as Button).text) + var next: Control = focused.find_valid_focus_neighbor(SIDE_BOTTOM) + if next == null: + break + next.grab_focus() + focused = next + assert_eq(seen, ["Practice against bots", "Join a server", "Settings", "Quit"] as Array[String]) + + +func test_rebinding_in_the_menu_detects_conflicts() -> void: + menus.show_screen("settings", false) + menus.listen_for("jump") + assert_eq(menus.listening_for, "jump") + menus._unhandled_input(_key(KEY_W)) + assert_eq(menus.listening_for, "", "stopped listening") + assert_eq(menus.settings.bindings.code_of("jump"), KEY_SPACE, "W is forward's: refused") + menus.listen_for("jump") + menus._unhandled_input(_key(KEY_F)) + assert_eq(menus.settings.bindings.code_of("jump"), KEY_F) + assert_eq(GameSettings.load_from(PATH).bindings.code_of("jump"), KEY_F, "saved at once") + menus.listen_for("jump") + menus._unhandled_input(_key(KEY_ESCAPE)) + assert_eq(menus.settings.bindings.code_of("jump"), KEY_F, "Escape left it") + assert_eq(menus.current, "settings", "and stayed on the screen") + _press("settings", "Put every key back") + assert_eq(menus.settings.bindings.code_of("jump"), KEY_SPACE) + + +func test_settings_controls_change_and_save_the_settings() -> void: + menus.show_screen("main", false) + _press("main", "Settings") + menus._sensitivity.value = 2.0 + menus._invert.button_pressed = true + menus._quality.select(0) + menus._quality.item_selected.emit(0) + (menus._volumes["music"] as HSlider).value = 0.25 + menus._max_fps.select(2) + menus._max_fps.item_selected.emit(2) + menus._print_pass.button_pressed = false + menus.back() + var saved: GameSettings = GameSettings.load_from(PATH) + assert_near(saved.mouse.mouse_sensitivity, 2.0, 0.0001) + assert_true(saved.mouse.invert_y) + assert_eq(saved.quality, 0) + assert_near(saved.music_volume, 0.25, 0.0001) + assert_eq(saved.max_fps, GameSettings.FRAME_CAPS[2]) + assert_false(saved.print_pass) + # And the next time the screen opens, it shows them. + var reopened: Menus = Menus.new() + reopened.use_settings(saved, PATH) + assert_near(reopened._sensitivity.value, 2.0, 0.0001) + assert_eq(reopened._quality.selected, 0) + reopened.free() + + +func test_practice_and_join_say_what_was_asked() -> void: + var asked: Array = [] + menus.practice_requested.connect(func(bots: int, difficulty: int) -> void: asked.append(["practice", bots, difficulty])) + menus.join_requested.connect(func(host: String, port: int, player_name: String) -> void: asked.append(["join", host, port, player_name])) + menus.show_screen("practice", false) + menus._bots.value = 5 + menus._difficulty.select(1) + _press("practice", "Set out") + assert_eq(asked.pop_back(), ["practice", 5, 0]) + menus.show_screen("join", false) + menus._name.text = "Wren" + menus._address.text = "not a port:x" + _press("join", "Join this address") + assert_true(asked.is_empty(), "a bad address isn't joined") + assert_true(menus._join_note.text.contains("isn't an address")) + menus._address.text = "127.0.0.1:24999" + _press("join", "Join this address") + assert_eq(asked.pop_back(), ["join", "127.0.0.1", 24999, "Wren"]) + assert_eq(GameSettings.load_from(PATH).last_server, "127.0.0.1:24999") + # A found server, chosen from the list. + menus.show_servers([ + {"name": "Old", "players": 9, "max_players": 24, "address": "10.0.0.9", "port": 24650, "source": "lan", "compatible": false}, + {"name": "Harbour", "players": 3, "max_players": 24, "address": "127.0.0.1", "port": 24651, "source": "lan", "compatible": true}, + ] as Array[Dictionary]) + menus._servers.select(0) + _press("join", "Join the chosen server") + assert_true(asked.is_empty(), "another version can't be joined") + menus._servers.select(1) + _press("join", "Join the chosen server") + assert_eq(asked.pop_back(), ["join", "127.0.0.1", 24651, "Wren"]) + + +func test_results_say_where_you_placed() -> void: + menus.show_results(1, 24, 3, ["Ada drowned"] as Array[String]) + assert_eq(menus.current, "results") + assert_eq(menus._results_title.text, "Last on dry ground") + assert_true(menus._results_body.text.contains("Eliminations: 3")) + menus.show_results(7, 24, 0, [] as Array[String]) + assert_eq(menus._results_title.text, "Placed 7 of 24") + + +func test_the_shell_goes_from_the_menu_to_a_match_and_back() -> void: + menus.free() + var shell: AppShell = AppShell.new(GameSettings.new(), PATH) + shell.grab_mouse = false + tree.root.add_child(shell) + assert_eq(shell.menus.current, "main") + shell.menus.settings.practice_bots = 3 + _press_in(shell.menus, "main", "Practice against bots") + _press_in(shell.menus, "practice", "Set out") + assert_not_null(shell.session, "a match began") + assert_not_null(shell.session.local, "offline") + assert_false(shell.menus.visible, "the menus are out of the way") + for _frame: int in 30: + shell.session.pump(1.0 / 30.0) + shell.watch_match() + assert_true(shell.session.game.world != null, "the world arrived") + # Escape: the pause menu, and the player's keys stop. + shell.session.pause_requested.emit() + assert_eq(shell.menus.current, "pause") + assert_true(shell.session.paused) + _press_in(shell.menus, "pause", "Settings") + assert_eq(shell.menus.current, "settings") + shell.menus.back() + assert_eq(shell.menus.current, "pause", "settings goes back to the pause menu") + _press_in(shell.menus, "pause", "Back to the match") + assert_false(shell.session.paused) + assert_false(shell.menus.visible) + # Leaving: back to the main menu with no match. + shell.pause() + _press_in(shell.menus, "pause", "Leave the match") + assert_null(shell.session) + assert_eq(shell.menus.current, "main") + shell.free() + + +func test_the_shell_shows_results_when_a_match_you_played_ends() -> void: + menus.free() + var shell: AppShell = AppShell.new(GameSettings.new(), PATH) + shell.grab_mouse = false + tree.root.add_child(shell) + var rules: MatchRules = MatchRules.new() + rules.max_players = 2 + rules.min_players = 1 + rules.lobby_ticks = 2 + rules.countdown_ticks = 2 + rules.results_ticks = 600 + var practice: ClientSession = ClientSession.new() + practice.play_offline(4, 1, rules) + shell.adopt(practice) + var game: ClientGame = practice.game + var server: Match = practice.local.loop.match_flow + var frames: int = 0 + while not game.playing() and frames < 400: + practice.pump(1.0 / 30.0) + shell.watch_match() + frames += 1 + assert_true(game.playing(), "in the match") + # The bot falls to this player, and the match ends with them on top. + var bot_handle: int = -1 + for handle: int in server.participants: + if handle != LocalServer.HANDLE: + bot_handle = handle + var bot: SimEntity = server.sim.entities.find(int(server.entity_of[bot_handle])) + bot.health = 0 + bot.last_attacker = int(server.entity_of[LocalServer.HANDLE]) + bot.last_cause = SimEntity.CAUSE_WEAPON + while game.match_phase != Match.RESULTS and frames < 800: + practice.pump(1.0 / 30.0) + shell.watch_match() + frames += 1 + assert_eq(game.match_phase, Match.RESULTS) + assert_eq(shell.menus.current, "results") + assert_eq(shell.menus._results_title.text, "Last on dry ground") + assert_true(shell.menus._results_body.text.contains("Eliminations: 1"), shell.menus._results_body.text) + _press_in(shell.menus, "results", "Back to the main menu") + assert_eq(shell.menus.current, "main") + shell.free() + + +func _press_in(on: Menus, screen: String, text: String) -> void: + var buttons: Dictionary = on.buttons_of(screen) + assert_true(buttons.has(text), "%s has a '%s' button (has %s)" % [screen, text, buttons.keys()]) + if buttons.has(text): + (buttons[text] as Button).pressed.emit() diff --git a/test/ui/test_menus.gd.uid b/test/ui/test_menus.gd.uid new file mode 100644 index 0000000..70b721c --- /dev/null +++ b/test/ui/test_menus.gd.uid @@ -0,0 +1 @@ +uid://dlu5xen3omblh