diff --git a/docs/architecture.md b/docs/architecture.md index cf0d2a4e..9fb7060e 100644 --- a/docs/architecture.md +++ b/docs/architecture.md @@ -45,6 +45,8 @@ from other projects, with its license, is listed in [THIRD_PARTY_NOTICES.md](../ order it logged them: a line waits for the queue's lock, and one that finds the queue full is written after everything queued before it. A fatal error, the crash report and the end of the process write the queue out first (`rt_log_sync`). `NX2NAVI_LOG_ASYNC=0` writes each line where it is logged. +- Co-op (`coop.c`, `steam.c`, `coop_game.c`, [coop.md](coop.md)): a host thread that owns the Steam library and a room of + up to four players; the game side reads Link and the game's flags at the present. It never holds a virtual core. - OS calls the host makes go through `runtime/platform/` (`platform.h`, `win32.c`). #### Threads and cores diff --git a/docs/building.md b/docs/building.md index 2160889b..2e6ca997 100644 --- a/docs/building.md +++ b/docs/building.md @@ -379,7 +379,9 @@ instead of timing one. No game files. A change to the button prompts (`tools/make_romfs_patches.py --prompts`, `tools/button_icons.py`) passes `.venv-py314\Scripts\python tests\romfs_prompts_test.py`, which runs the tool on a RomFS it makes itself (no game -files); a change to the settings passes `nx2navi.exe --probe-cfg`. +files); a change to the settings passes `nx2navi.exe --probe-cfg`; a change to co-op (`runtime/coop*.c`, +`runtime/steam.c`, `runtime/ui/coop_page.cpp`) is run with one game and `python tests\coop_peer.py` as the second player +([coop.md](coop.md), "Checks"). A change to the action prompt's diamond of face buttons (`runtime/action_prompt.c`) or to the SARC and zstd dictionary helpers (`runtime/sarc.c`) passes `python tests\action_prompt_check.py`. It builds them alone, with the diff --git a/docs/coop.md b/docs/coop.md new file mode 100644 index 00000000..aba2febc --- /dev/null +++ b/docs/coop.md @@ -0,0 +1,151 @@ +# Co-op + +Up to four players, each in their own game with their own save, meet in a room through Steam. In a room you see the +other players' names where their Link stands in your world, you can chat, and progress is shared: what anyone achieves +counts for everyone. + +**Co-op is experimental and off by default.** Turn it on in the menu's Co-op tab (*Co-op (experimental)*), or with +`coop = 1` under `[coop]` in `nx2navi.ini`. With it off the game uses no network at all. + +Not in this version: the other players are shown as a name with a distance, not as a Link model, and enemies, pots +and the time of day are each game's own. + +## What you need + +- **Steam, running and signed in.** NX2navi is no Steam game of its own: it signs in to Steam as *Spacewar* (app 480), + the test app Valve gives every account. While co-op is on, Steam shows you as playing Spacewar. Nobody forwards a + port on a router and nobody runs a server: the room is a Steam lobby and the games talk through Steam's own network, + which finds a direct path between them or relays for them. +- **Steam's library file, `steam_api64.dll`, beside `ocarina.exe`.** NX2navi may not ship that file. Every Steam game + has one in its folder: copy one from a recent game (2021 or later) into the folder of `ocarina.exe`. The Co-op tab + says when the file is missing or too old. The game loads it from that one place only. +- **The same NX2navi version and game version (1.1.1)** as the others. A game of another version is told so and does + not get into the room. + +## Rooms + +- **Create a room** makes a room and shows its **room ID**, eight letters and digits as `XXXX-XXXX`. A press on the row + copies it. Your game is the room's host. +- **Join a room** takes a room ID (typed in any case, with or without the dash; Paste takes the clipboard's text). +- **Invite a friend** lists your Steam friends, those in co-op first, and sends a Steam invite to the one you choose. + The invite reaches a friend whose NX2navi is running with co-op on: it shows at the top of their screen and on their + Co-op tab, where *Join their room* accepts it. A friend whose game is not running gets Steam's own invite, which + would start Spacewar, not NX2navi: tell them the room ID instead. When the game was started from Steam (the + launcher's *Add to Steam*), Steam's own invite window is offered as well. +- **Players** lists who is in the room and the area each one's Link is in. The host can press a player to remove + them; a removed player cannot come back into that room. +- **Leave the room** asks first. When the host leaves, Steam hands the room to another player, whose game is the host + from then on. + +A room ID is the number of the Steam lobby. Anyone who has it can join while the room is open, so pass it on only to +the people you want in your game; the room is also visible to your Steam friends, who may join it from Steam. To be +rid of someone, the host removes them; to be sure, leave and create a new room. + +## What joining a room means for your save + +- **Your save is copied first.** When your game starts to share in a room (you are in the room and playing a save), + it copies your whole save (every slot) to `coop-backup/` in the profile folder, and takes nothing from + the room until the copy is made. The newest twelve copies are kept. "Going back" below says how to restore one. +- **Progress is shared while *Share progress* is on** (it is, by default): story, world and dungeon flags (events, + talks, chests, doors, switches, bosses, maps and compasses), items and equipment, songs, quest items, wallet, bag and + quiver sizes. A flag anyone has set is set for everyone, and of a count the highest wins. A player who joins later + gets what the room has, and the room what the joiner brings. Your game saves it as its own progress. +- **Each player keeps their own** small keys, rupees, ammunition, heart pieces and containers, gold skulltula tokens, + bottle contents, the trade sequence, the equipment worn, life and magic. +- **Nothing is undone.** Leaving a room keeps what was shared. A player in the room plays with you: what they do in + their world happens in yours, and a game that wants to can send progress it did not play for. Join rooms of people + you trust with your save, as you would hand them your controller, and go back to the copy if you regret it. +- With *Share progress* off, your game sends and takes no progress: only names, positions and chat. + +Every value from the room is checked against your game's own table of what is shared before it is used: the flag must +be one of the shared ones, an on/off flag can only be set to "done", an item count only up to 999. Anything else is +dropped and counted in the log. + +### Going back to your save from before a room + +1. Close the game. +2. In the profile folder, open `coop-backup` and pick the copy to go back to (the time is UTC). +3. Delete the folder `save-tx` (it may hold a save that was being written; it would otherwise be finished over the + copy at the next start). +4. Move the folder `save/` aside (keep it until you are sure), and copy the contents of the backup folder + into a new `save/` of the same name. +5. Start the game: every slot is as it was before the room's progress reached it. + +## Who can see what + +| Who | Sees | +|---|---| +| The players in the room | your Steam name, the area your Link is in and where he stands, your chat lines, the progress your game shares | +| Your Steam friends | that you play Spacewar, and the room (they may join it) | +| Valve | what Steam sees of any game that uses its lobbies and network: who is in which lobby, and the traffic's size and timing. Steam encrypts the traffic between the games | +| Your log (`logs/nx2navi.log`) and "Copy system info" | that a room was made or joined, the other players' Steam names, and the lines below; never a room ID or a Steam id. Steam's library prints lines of its own, one with your Steam id, to the console the game was started from; they are not in the log file, but they are in a file you redirect the game's output to yourself | + +## Settings + +`nx2navi.ini`, section `[coop]`; the menu's Co-op tab has a row for each. The environment variable is the key with +`NX2NAVI_`. + +| Key | Default | | +|---|---|---| +| `coop` | `0` | on or off, at once. On: the game signs in to Steam; off: no network | +| `coop_share` | `1` | in a room, share progress, items and songs (above) | +| `coop_names` | `1` | show the other players' names where they stand. Needs DLSS, FSR or TAA on: only then does the menu know where the camera looks | +| `coop_chat` | `1` | show new chat lines, and who joined or left, over the game for a few seconds while the menu is closed | + +A settings file cannot put a game into a room: a room is made or joined only from the menu. + +## In the log + +`coop: on, signed in to Steam as app 480`, `coop: Steam is not available: `, `coop: room made`, `coop: in the +lobby; asking the host`, `coop: joined the room`, ` joined the room`, ` left the room`, `coop: the host +left; this game is the host now`, `coop: left the room`, `coop: the save as it was before this room is in `, +`coop: a save is played: N flags and counts can be shared`, `coop: took N values of progress from the room`, `coop: N +values from the room were not ones this game shares; dropped`. + +## How it works + +For a reviewer. The code is `runtime/steam.c` (the Steam library), `runtime/coop.c` (the room), `runtime/coop_game.c` +(the game side) and `runtime/ui/coop_page.cpp` (the menu's tab and the names over the game). + +**The Steam library.** `steam.c` loads `steam_api64.dll` from beside the exe at run time and calls the plain C +functions it exports; it declares them itself, and nothing of the Steamworks SDK is in this repository. It sets +`SteamAppId` and `SteamGameId` to 480 in its own environment before the library loads. Callbacks are taken with the +library's manual dispatch on the co-op thread, the only thread that uses the library. A library that lacks one of the +calls is refused as too old. + +**The room.** A room is a friends-only Steam lobby that carries the note `nx2navi = 1`; a lobby without it belongs to +some other program that uses the test app and is left at once. The lobby's owner is the host. A game that entered the +lobby says HELLO to the host with its protocol number and game build; the host answers WELCOME or REFUSED and sends +everyone the list of the players it let in. Every game takes positions, chat and progress only from the players on +the host's list, and only a lobby member's session is accepted, so a stranger on Steam, a player the host removed and +a game of another version reach nobody. + +**Messages** go through Steam's networking messages (datagrams to a Steam id): positions unreliable, twenty a second +while Link is in the world; everything else reliable. Steam vouches for the sender's id and encrypts. Each message is +one kind byte and a body whose length is checked before it is read; `coop.c`'s header comment lists them. + +**Progress.** The game keeps its progress as flags in a database keyed by 32-bit hashes of flag names +(`coop_game.c`'s header comment has the layout). Between two frames the runtime reads the flags that changed and sends +the ones that rose; it sets the ones the room has and this game lacks through the game's own set routines, as if the +player had done it, at most sixteen a frame. Nothing is read or set on the title screen, while a save loads or an area +changes. A game that starts to share asks the others for their whole state and sends its own. Games merge only when +their tables of what is shared are the same (a sum over the table travels with every message). + +**The host's part is small**: it decides who is in the room. Progress has no arbiter, because every shared value only +ever rises: two games that set the same flag agree whatever the order. + +## Checks + +- Two games on one PC cannot both sign in to one Steam account, so the room, the messages and the game side are + tested with a stand-in for Steam: `NX2NAVI_COOP_LOCAL=` in the environment (never from `nx2navi.ini`) makes a + game the player whose id is that UDP port on 127.0.0.1; `NX2NAVI_COOP_LOCAL_MAKE=1` makes its room at once and + `NX2NAVI_COOP_LOCAL_JOIN=` joins another game's. `NX2NAVI_COOP_TRACE=1` logs every two seconds where this + game's Link is and where it has the others. +- `python tests/coop_peer.py --host ` is a second player without a second game (two games need twice the + memory): it joins the room of a game started with `NX2NAVI_COOP_LOCAL=` and `NX2NAVI_COOP_LOCAL_MAKE=1`, + stands two metres beside the game's Link so that its name shows there, says a chat line, asks for the game's + progress and, with `--flags`, sends flags as set. It ends with `peer: ok` when it was let in, saw the game's Link + in the world and got its progress. Run it on a copy of a profile: the flags it sends reach that save. +- `NX2NAVI_MENU_TEST_SET=:COOP_DO=create | leave | join: | chat: | page:join | page:invite | + page:chat | page:leave` (environment only) does what the Co-op tab's row or window does. +- `ocarina --probe-services` checks, among the rest, that every text of the tab has its four languages. diff --git a/docs/releases/v0.9.3.md b/docs/releases/v0.9.3.md index 74f0055a..934dcf77 100644 --- a/docs/releases/v0.9.3.md +++ b/docs/releases/v0.9.3.md @@ -19,6 +19,20 @@ `replay_pipe = 4`, 63.2 with `replay_small = 16` added, against 45.4 with all four settings off. The pictures matched there and through warps to five areas. +## New + +- **Experimental: co-op through Steam** (the menu's new Co-op tab; off by default; `coop = 1` in nx2navi.ini). Up to + four players, each in their own game and save, meet in a room: *Create a room* gives a room ID to pass on, *Join a + room* takes one, and *Invite a friend* sends a Steam invite. Nobody forwards a port and nobody runs a server: rooms + are Steam lobbies and the games talk through Steam's network. NX2navi signs in to Steam as its test app, so Steam + shows you as playing Spacewar. In a room you see the other players' names where their Link stands (with DLSS, FSR + or TAA on), you can chat, and progress is shared: story, chests, doors, items and songs count for everyone, while + small keys, rupees, ammunition and hearts stay each player's own. Your save is copied to `coop-backup` in the + profile folder before anything of a room reaches it. It needs Steam running and Steam's library file + `steam_api64.dll` beside `ocarina.exe` (copy one from any recent Steam game's folder; NX2navi may not ship it). Not + yet: the other players as a Link model, shared enemies, and invites that start the game for a friend who has it + closed. Everyone needs the same NX2navi version. `docs/coop.md` has the details and how to go back to a save. + ## Changed - **The draw replay on several CPU cores is off by default again** (`replay_workers = 0`). With three workers on by @@ -27,7 +41,6 @@ - **The other experimental performance settings have rows there too**: *Helpers work ahead* (`replay_pipe`, 0 to 4), *Helpers take small jobs* (`replay_small`, 0 to 64) and *Start next frame early* (`tail_early`). A row whose setting does nothing without another one is greyed out and says which it needs. -- **The hidden co-op beta is gone.** The co-op of 0.8.0 (shown only with `coop_beta = 1`) shared story progress - through a relay a player had to run and never showed the other players. Its code, its settings (the `[coop]` section - of nx2navi.ini), its relay script and its menu tab are removed; lines of it left in an nx2navi.ini do nothing, and a - bug report still keeps their values out. A new co-op is being built in its place. +- **The co-op beta of 0.8.0 is replaced.** It shared story progress through a relay a player had to run, with a + forwarded port, and never showed the other players. Its relay, its rules and pools, its settings and its hidden tab + are gone; lines of it left in an nx2navi.ini do nothing, and a bug report still keeps their values out. See "New". diff --git a/nx2navi.ini.example b/nx2navi.ini.example index c4385f08..9f393cef 100644 --- a/nx2navi.ini.example +++ b/nx2navi.ini.example @@ -637,6 +637,20 @@ # The key of the application's uploaded art asset (Rich Presence > Art Assets) shown as the status's large image. # discord_image = nx2navi_512x512 +[coop] +# Co-op, experimental: play with friends over Steam, each in their own game and save (docs/coop.md). The game signs in +# to Steam as its test app, so Steam shows you as playing Spacewar; it needs Steam running and Steam's library file +# steam_api64.dll beside ocarina.exe. Rooms are made and joined in the menu's Co-op tab, never from this file. +# 0 = off, the game uses no network. Takes effect at once. +# coop = 0 +# In a room, share progress, items and songs with the other players; your save is copied to coop-backup in the profile +# folder first. 0 = only names, positions and chat. +# coop_share = 1 +# Show the other players' names where their Link stands (needs DLSS, FSR or TAA on). +# coop_names = 1 +# Show new chat lines, and who joined or left, over the game while the menu is closed. +# coop_chat = 1 + [audio] # none mixes without opening an audio device. # audio = default diff --git a/runtime/boot.c b/runtime/boot.c index 15ed6cd4..9acf7512 100644 --- a/runtime/boot.c +++ b/runtime/boot.c @@ -15,6 +15,7 @@ #include #include "cfg.h" +#include "coop.h" #include "cheats.h" #include "fs.h" #include "kernel.h" @@ -323,6 +324,7 @@ void rt_frame_presented(const tex_t *t, uint64_t n) { stats_line(); fflush(stdout); fflush(stderr); + coop_shutdown(); // leaves the room, before the process ends fs_save_flush(); vk_pipeline_prewarm_marker_clear(); // an orderly end, not a driver crash in the boot's builds (vk_pipeline.c pm_skipped) vk_pipeline_save_exit(); // no-op without the Vulkan back end diff --git a/runtime/cfg.c b/runtime/cfg.c index a08defaf..23d352c6 100644 --- a/runtime/cfg.c +++ b/runtime/cfg.c @@ -80,9 +80,10 @@ static const char *const known[] = { "TEXUP_LOG_MS", "DYN_RES", "DYN_RES_TARGET", "DYN_RES_STEP", "TEXTURE_DETAIL", "RECORDER_CORE", "RECORDER_PRIO", "REPLAY_TIME", "LOCK_TIME", "POOL_CREATE_BUDGET", "POOL_CREATE_MS", "POOL_FINI_IDLE", "POOL_LOAD_BACKLOG", "POOL_LOAD_MS", "VMA_BLOCK_MB", "SYNC_WAKE_ALL", "LOG_ASYNC", "DEVICE_LOST_AT", "STAGING_FAIL_AT", "VRAM_BALLAST_MB", + "COOP", "COOP_SHARE", "COOP_NAMES", "COOP_CHAT", // co-op (coop.c, coop_game.c, ui/coop_page.cpp) // retired: the settings of the co-op of versions up to 0.9.2; read by nothing, listed so that a file which still // sets them logs no unknown key - "COOP", "COOP_BETA", "COOP_NAME", "COOP_SERVER", "COOP_PORT", "COOP_ROOM", "COOP_AUTO", "COOP_DROP", + "COOP_BETA", "COOP_NAME", "COOP_SERVER", "COOP_PORT", "COOP_ROOM", "COOP_AUTO", "COOP_DROP", "COOP_PROGRESS", "COOP_ITEMS", "COOP_SONGS", "COOP_QUEST", "COOP_KEYS", "COOP_RUPEES", "COOP_AMMO", "COOP_TEST_SET", "COOP_ACCEPT", "COOP_REMOVE", "COOP_RESET_POOLS", }; @@ -110,6 +111,7 @@ static const struct { const char *key, *section; } sections[] = { {"FRAMEGEN", "display"}, {"FRAMEGEN_MULTIPLIER", "display"}, {"FG_MULT", "display"}, {"DEVICE_PROFILE", "display"}, {"ASSUME_FOCUS", "display"}, {"DISCORD_RPC", "discord"}, {"DISCORD_APP_ID", "discord"}, {"DISCORD_IMAGE", "discord"}, + {"COOP", "coop"}, {"COOP_SHARE", "coop"}, {"COOP_NAMES", "coop"}, {"COOP_CHAT", "coop"}, {"SHADOW_SCALE", "display"}, {"SHADOW_RANGE", "display"}, {"CONTACT_SHADOWS", "display"}, {"PCSS", "display"}, {"MODS_DIR", "mods"}, {"MODS_ORDER", "mods"}, {"MODS_DISABLED", "mods"}, {"MODS_REBUILD", "mods"}, @@ -240,6 +242,11 @@ static const CfgMeta metas[] = { {"DISCORD_RPC", "1", "0|1", LIVE}, {"DISCORD_APP_ID", NX2NAVI_DISCORD_APP_ID_DEFAULT, NULL, LIVE}, {"DISCORD_IMAGE", NX2NAVI_DISCORD_IMAGE_DEFAULT, NULL, LIVE}, + // Co-op (coop.c): off until the player turns it on; then the game signs in to Steam as its test app and can make + // or join a room. In a room: COOP_SHARE shares progress, items and songs with the other players (coop_game.c), + // COOP_NAMES shows the other players' names where they stand, COOP_CHAT shows the chat's lines over the game. + {"COOP", "0", "0|1", LIVE}, {"COOP_SHARE", "1", "0|1", LIVE}, {"COOP_NAMES", "1", "0|1", LIVE}, + {"COOP_CHAT", "1", "0|1", LIVE}, // Advanced: scheduling {"ASYNC_PREEMPT", "1", "0|1|2", RESTART}, {"REPLAY_ASYNC", "0", "0|1", RESTART}, {"REPLAY_WORKERS", "0", "0..16", RESTART}, {"REPLAY_PIPE", "0", "0..4", RESTART}, diff --git a/runtime/coop.c b/runtime/coop.c new file mode 100644 index 00000000..d6379bc0 --- /dev/null +++ b/runtime/coop.c @@ -0,0 +1,736 @@ +// Co-op, the room (coop.h): one host thread that owns Steam (steam.c) and the room and talks to the other games. +// +// A room is a Steam lobby that carries the note nx2navi = 1; a lobby without it is somebody else's (the app id is +// shared with every program that uses Steam's test app) and is left at once. The lobby's owner is the host. Being in +// the lobby is not yet being in the room: a game that came says HELLO to the host with its protocol number and game +// build, the host answers WELCOME or REFUSED and lists the players it let in (ROSTER, at each change and every two +// seconds), and every game takes poses, chat and the game layer's messages only from the players on the host's list. +// So a player the host removed, or a game of another version, is in nobody's room though Steam still shows it in the +// lobby for a moment. When the host leaves, Steam makes another member the owner; that game carries on with the list +// it had. +// +// Messages are one kind byte and a body, in the byte order of the PCs this runs on (little-endian): +// HELLO u16 protocol, u32 game build to the host, every second until it answers +// WELCOME u16 protocol the host's yes +// REFUSED u8 why (REFUSE_*) the host's no; the game leaves the lobby +// ROSTER u8 count, count x u64 id the host's list, the host first +// POSE u32 number, the pose (pose_put) unreliable, 20 a second while Link is in the world, 2 a second else +// CHAT text, UTF-8, at most COOP_CHAT_CAP to everyone on the list +// from COOP_GAME_KIND on: the game layer's (coop_game.c), passed through +// Steam vouches for the sender of every message (its id is the Steam account's) and encrypts them; nothing here adds +// to that. Every length is checked before a body is read, a float that is not finite ends the message, and a name or +// a chat line is shown with its control characters replaced. +#include +#include +#include +#include + +#include "cfg.h" +#include "coop.h" +#include "coop_net.h" +#include "host.h" +#include "platform/platform.h" + +enum { + K_HELLO = 1, K_WELCOME, K_REFUSED, K_ROSTER, K_POSE, K_CHAT, + REFUSE_VERSION = 1, REFUSE_REMOVED, REFUSE_FULL, + GAME_BUILD = 0xe0f3ccfa, // the game build this runtime's co-op knows (1.1.1) + STEP_MS = 5, + HELLO_EVERY_MS = 1000, HOST_WAIT_MS = 15000, ROSTER_EVERY_MS = 2000, + POSE_EVERY_MS = 50, POSE_IDLE_MS = 500, POSE_STALE_MS = 3000, + STEAM_RETRY_MS = 5000, + COMMANDS = 16, OUTBOX = 256, REMOVED_MAX = 32, + POSE_BYTES = 4 + 12 + 12 + 4 + 1 + 1, // number, pos, vel, yaw, flags, scene length; then the scene +}; + +typedef enum { C_CREATE = 1, C_JOIN, C_JOIN_INVITE, C_DECLINE, C_LEAVE, C_RETRY, C_INVITE, C_INVITE_WINDOW, C_REMOVE, C_CHAT, C_FRIENDS } CmdKind; +typedef struct { CmdKind kind; uint64_t arg; char text[COOP_CHAT_CAP + 1]; } Cmd; +typedef struct { uint64_t to; uint16_t n; uint8_t reliable; uint8_t bytes[1 + COOP_MESSAGE_MAX]; } Out; + +typedef struct { + uint64_t id; + char name[COOP_NAME_CAP]; + int has_pose; + uint32_t pose_number; + uint64_t pose_at; + CoopPose pose; +} Player; + +// The co-op thread's own state. +static struct { + const CoopNet *net; + int up; + uint64_t retry_at; + CoopState state; + CoopNote note; + char steam_says[160]; + uint64_t room, owner; + int made; // this game made the room + int welcomed; // the host let this game in (always, for the host itself) + uint64_t entered_at, hello_at, roster_at, pose_sent_at; + uint32_t pose_number; + int n; + Player players[COOP_PLAYERS]; // the host's list as this game knows it; this game is among them once welcomed + int nremoved; + uint64_t removed[REMOVED_MAX]; + uint64_t invite_room, invite_from; + int nchat; + CoopChatLine chat[COOP_CHAT_LINES]; + uint32_t friends_serial; + int own_has; // this game's own pose, as last sent + CoopPose own_pose; +} G; + +// What the other threads share with it. +static struct { + PlatMutex lock; + PlatEvent stopped; + volatile int32_t stop; + volatile uint32_t serial; + CoopView view; + int ncmd; + Cmd cmd[COMMANDS]; + int nout; + Out *out; + int has_pose; + CoopPose pose; + int nfriends; + SteamFriend friends[COOP_FRIENDS]; + int in_room; // for coop_post: only then is a message queued +} P; + +// ---- text from outside: control characters and the characters that reorder a line are no part of a name or a chat line + +static void clean_text(char *s) { + for (unsigned char *p = (unsigned char *)s; *p; p++) { + if (*p < 0x20 || *p == 0x7f) *p = ' '; + // U+202A..U+202E and U+2066..U+2069 (E2 80 AA..AE, E2 81 A6..A9): direction overrides and isolates + if (p[0] == 0xe2 && ((p[1] == 0x80 && p[2] >= 0xaa && p[2] <= 0xae) || (p[1] == 0x81 && p[2] >= 0xa6 && p[2] <= 0xa9))) + p[0] = p[1] = p[2] = ' '; + } +} + +// ---- the players + +static Player *player_of(uint64_t id) { + for (int i = 0; i < G.n; i++) + if (G.players[i].id == id) return &G.players[i]; + return NULL; +} + +static void name_player(Player *p) { + if (p->name[0]) return; + G.net->name_of(p->id, p->name, sizeof p->name); + clean_text(p->name); +} + +static Player *player_add(uint64_t id) { + Player *p = player_of(id); + if (p || G.n >= COOP_PLAYERS) return p; + p = &G.players[G.n++]; + memset(p, 0, sizeof *p); + p->id = id; + name_player(p); + return p; +} + +static void chat_line(const char *name, const char *text, int notice, int joined) { + if (G.nchat == COOP_CHAT_LINES) memmove(G.chat, G.chat + 1, sizeof G.chat[0] * (size_t)--G.nchat); + CoopChatLine *l = &G.chat[G.nchat++]; + memset(l, 0, sizeof *l); + snprintf(l->name, sizeof l->name, "%s", name); + snprintf(l->text, sizeof l->text, "%s", text); + l->at_ms = plat_now_ms(), l->notice = (uint8_t)notice, l->joined = (uint8_t)joined; +} + +static void player_remove(uint64_t id) { + for (int i = 0; i < G.n; i++) { + if (G.players[i].id != id) continue; + if (G.welcomed && id != G.net->self()) { + rt_log("coop: %s left the room", G.players[i].name[0] ? G.players[i].name : "a player"); + chat_line(G.players[i].name, "", 1, 0); + } + memmove(G.players + i, G.players + i + 1, sizeof G.players[0] * (size_t)(G.n - i - 1)); + G.n--; + return; + } +} + +static int is_removed(uint64_t id) { + for (int i = 0; i < G.nremoved; i++) + if (G.removed[i] == id) return 1; + return 0; +} + +static int hosting(void) { return G.room && G.owner == G.net->self(); } + +// ---- sending + +static void send_kind(uint64_t to, uint8_t kind, const void *body, size_t n, int reliable) { + uint8_t d[1 + COOP_MESSAGE_MAX]; + if (n > COOP_MESSAGE_MAX) return; + d[0] = kind; + if (n) memcpy(d + 1, body, n); + G.net->send(to, d, n + 1, reliable); +} + +static void send_listed(uint8_t kind, const void *body, size_t n, int reliable) { + for (int i = 0; i < G.n; i++) + if (G.players[i].id != G.net->self()) send_kind(G.players[i].id, kind, body, n, reliable); +} + +static void send_roster(void) { + uint8_t d[1 + 8 * COOP_PLAYERS]; + d[0] = (uint8_t)G.n; + for (int i = 0; i < G.n; i++) memcpy(d + 1 + 8 * i, &G.players[i].id, 8); + send_listed(K_ROSTER, d, 1 + 8 * (size_t)G.n, 1); + G.roster_at = plat_now_ms(); +} + +static size_t pose_put(uint8_t *d, uint32_t number, const CoopPose *p) { + size_t sl = strnlen(p->scene, COOP_SCENE_CAP - 1); + memcpy(d, &number, 4), memcpy(d + 4, p->pos, 12), memcpy(d + 16, p->vel, 12), memcpy(d + 28, &p->yaw, 4); + d[32] = p->flags, d[33] = (uint8_t)sl; + memcpy(d + POSE_BYTES, p->scene, sl); + return POSE_BYTES + sl; +} + +static int pose_get(const uint8_t *d, size_t n, uint32_t *number, CoopPose *p) { + if (n < POSE_BYTES || d[33] >= COOP_SCENE_CAP || n != POSE_BYTES + (size_t)d[33]) return 0; + memset(p, 0, sizeof *p); + memcpy(number, d, 4), memcpy(p->pos, d + 4, 12), memcpy(p->vel, d + 16, 12), memcpy(&p->yaw, d + 28, 4); + p->flags = d[32]; + memcpy(p->scene, d + POSE_BYTES, d[33]); + for (int i = 0; i < 3; i++) + if (!isfinite(p->pos[i]) || !isfinite(p->vel[i]) || fabsf(p->pos[i]) > 1e6f) return 0; + if (!isfinite(p->yaw)) return 0; + clean_text(p->scene); + return 1; +} + +// ---- the room + +static void room_end(CoopNote note) { + if (G.room || G.state == COOP_ENTERING) { + G.net->room_leave(); + if (G.welcomed) coop_game_room(0); + if (G.room) rt_log("coop: left the room"); + } + G.room = G.owner = 0, G.made = G.welcomed = 0, G.n = 0, G.nremoved = 0; + G.state = COOP_READY; + G.note = note; +} + +static void welcomed(void) { + G.welcomed = 1; + G.state = COOP_IN_ROOM; + G.note = COOP_NOTE_NONE; + player_add(G.net->self()); + coop_game_room(1); +} + +static void on_entered(uint64_t room) { + G.room = room; + G.owner = G.net->room_owner(); + G.entered_at = plat_now_ms(), G.hello_at = 0; + G.n = 0, G.nremoved = 0, G.welcomed = 0; + if (G.made) { + G.net->room_set("nx2navi", "1"); + welcomed(); + char code[STEAM_CODE_CAP]; + steam_code_make(room, code); + rt_log("coop: room made%s", code[0] || G.net == &coop_net_local ? "" : " (it has no room id: invite through Steam)"); + return; + } + char ours[8]; + G.net->room_get("nx2navi", ours, sizeof ours); + if (strcmp(ours, "1")) { + rt_log("coop: that Steam lobby is no NX2navi room; left it"); + room_end(COOP_NOTE_NOT_OURS); + return; + } + rt_log("coop: in the lobby; asking the host"); +} + +static void on_message(uint64_t from, const uint8_t *d, size_t n) { + if (!G.room || n < 1) return; + uint8_t kind = d[0]; + const uint8_t *b = d + 1; + n--; + int from_host = from == G.owner; + if (kind == K_HELLO) { + if (!hosting() || n != 6) return; + uint16_t proto; + uint32_t build; + memcpy(&proto, b, 2), memcpy(&build, b + 2, 4); + uint8_t why = proto != COOP_PROTOCOL || build != GAME_BUILD ? REFUSE_VERSION : is_removed(from) ? REFUSE_REMOVED + : !player_of(from) && G.n >= COOP_PLAYERS ? REFUSE_FULL : 0; + if (why) { + send_kind(from, K_REFUSED, &why, 1, 1); + return; + } + int fresh = !player_of(from); + Player *p = player_add(from); + if (!p) return; + uint16_t mine = COOP_PROTOCOL; + send_kind(from, K_WELCOME, &mine, 2, 1); + send_roster(); + if (fresh) { + rt_log("coop: %s joined the room", p->name[0] ? p->name : "a player"); + chat_line(p->name, "", 1, 1); + coop_game_joined(from); + } + } else if (kind == K_WELCOME) { + if (from_host && !G.welcomed && n == 2) { + player_add(from); + welcomed(); + rt_log("coop: joined the room"); + coop_game_joined(from); + } + } else if (kind == K_REFUSED) { + if (from_host && n == 1 && !hosting()) + room_end(b[0] == REFUSE_VERSION ? COOP_NOTE_OTHER_VERSION : b[0] == REFUSE_REMOVED ? COOP_NOTE_REMOVED + : b[0] == REFUSE_FULL ? COOP_NOTE_FULL : COOP_NOTE_REFUSED); + } else if (kind == K_ROSTER) { + if (!from_host || hosting() || !G.welcomed || n < 1 || b[0] > COOP_PLAYERS || n != 1 + 8 * (size_t)b[0]) return; + uint64_t ids[COOP_PLAYERS]; + memcpy(ids, b + 1, 8 * (size_t)b[0]); + int listed = 0; + for (int i = 0; i < b[0]; i++) listed |= ids[i] == G.net->self(); + if (!listed) { // the host took this game off its list + room_end(COOP_NOTE_REMOVED); + return; + } + for (int i = G.n - 1; i >= 0; i--) { + int still = 0; + for (int k = 0; k < b[0]; k++) still |= ids[k] == G.players[i].id; + if (!still) player_remove(G.players[i].id); + } + for (int k = 0; k < b[0]; k++) { + if (player_of(ids[k])) continue; + Player *p = player_add(ids[k]); + if (p && ids[k] != G.owner) { + rt_log("coop: %s joined the room", p->name[0] ? p->name : "a player"); + chat_line(p->name, "", 1, 1); + } + if (p) coop_game_joined(ids[k]); + } + } else if (!G.welcomed || !player_of(from)) { + return; // everything below: only from a player on the host's list + } else if (kind == K_POSE) { + Player *p = player_of(from); + uint32_t number; + CoopPose pose; + if (!pose_get(b, n, &number, &pose)) return; + if (p->has_pose && (int32_t)(number - p->pose_number) <= 0) return; // late or twice + p->pose = pose, p->pose_number = number, p->pose_at = plat_now_ms(), p->has_pose = 1; + } else if (kind == K_CHAT) { + if (n < 1 || n > COOP_CHAT_CAP) return; + char text[COOP_CHAT_CAP + 1]; + memcpy(text, b, n), text[n] = 0; + clean_text(text); + Player *p = player_of(from); + name_player(p); + chat_line(p->name, text, 0, 0); + } else if (kind >= COOP_GAME_KIND) { + coop_game_message(from, kind, b, n); + } +} + +static void on_event(const SteamEvent *e, void *user) { + (void)user; + switch (e->kind) { + case STEAM_EV_ROOM_ENTERED: on_entered(e->a); break; + case STEAM_EV_ROOM_FAILED: + G.state = COOP_READY, G.made = 0; + G.note = e->code == STEAM_FAIL_CREATE ? COOP_NOTE_CREATE_FAILED : e->code == STEAM_FAIL_NO_ROOM ? COOP_NOTE_NO_ROOM + : e->code == STEAM_FAIL_FULL ? COOP_NOTE_FULL : COOP_NOTE_REFUSED; + rt_log("coop: the room could not be %s (%d)", e->code == STEAM_FAIL_CREATE ? "made" : "joined", e->code); + break; + case STEAM_EV_MEMBER_JOINED: break; // it says HELLO when it is one of ours + case STEAM_EV_MEMBER_LEFT: + if (player_of(e->a)) { + player_remove(e->a); + if (hosting()) send_roster(); + } + break; + case STEAM_EV_INVITED: + if (!G.room && G.state != COOP_ENTERING) G.invite_room = e->a, G.invite_from = e->b; + break; + case STEAM_EV_JOIN_ASKED: + // the player said yes in Steam itself: leave the room this game is in and go there + if (e->a != G.room) { + if (G.room || G.state == COOP_ENTERING) room_end(COOP_NOTE_NONE); + G.made = 0, G.invite_room = 0; + if (G.net->room_join(e->a)) G.state = COOP_ENTERING, G.entered_at = plat_now_ms(); + } + break; + case STEAM_EV_MESSAGE: on_message(e->a, e->data, e->n); break; + case STEAM_EV_LOST: + rt_log("coop: Steam lost its connection; the room is gone"); + if (G.welcomed) coop_game_room(0); + G.room = G.owner = 0, G.made = G.welcomed = 0, G.n = 0; + G.state = COOP_READY, G.note = COOP_NOTE_LOST; + break; + } +} + +// ---- the thread's step + +static void run_command(const Cmd *c) { + if (!G.up) { + if (c->kind == C_RETRY) G.retry_at = 0; + return; + } + switch (c->kind) { + case C_CREATE: + if (G.room || G.state == COOP_ENTERING) break; + if (G.net->room_create(COOP_PLAYERS)) G.state = COOP_ENTERING, G.made = 1, G.note = COOP_NOTE_NONE, G.entered_at = plat_now_ms(); + else G.note = COOP_NOTE_CREATE_FAILED; + break; + case C_JOIN: + case C_JOIN_INVITE: { + uint64_t room = c->kind == C_JOIN ? c->arg : G.invite_room; + G.invite_room = 0; + if (!room || G.room || G.state == COOP_ENTERING) break; + if (G.net->room_join(room)) G.state = COOP_ENTERING, G.made = 0, G.note = COOP_NOTE_NONE, G.entered_at = plat_now_ms(); + else G.note = COOP_NOTE_NO_ROOM; + break; + } + case C_DECLINE: G.invite_room = 0; break; + case C_LEAVE: + if (G.room || G.state == COOP_ENTERING) room_end(COOP_NOTE_LEFT); + break; + case C_RETRY: break; + case C_INVITE: + if (G.room && !coop_local_wanted()) steam_invite(c->arg); + break; + case C_INVITE_WINDOW: + if (G.room && !coop_local_wanted()) steam_invite_window(); + break; + case C_REMOVE: + if (!hosting() || c->arg == G.net->self() || !player_of(c->arg)) break; + if (G.nremoved < REMOVED_MAX) G.removed[G.nremoved++] = c->arg; + send_kind(c->arg, K_REFUSED, (uint8_t[]){REFUSE_REMOVED}, 1, 1); + player_remove(c->arg); + send_roster(); + break; + case C_CHAT: { + size_t n = strlen(c->text); + if (!G.welcomed || !n) break; + send_listed(K_CHAT, c->text, n, 1); + Player *me = player_of(G.net->self()); + if (me) name_player(me), chat_line(me->name, c->text, 0, 0); + break; + } + case C_FRIENDS: + if (!coop_local_wanted()) { + static SteamFriend list[COOP_FRIENDS]; + int n = steam_friends(list, COOP_FRIENDS); + plat_mutex_lock(&P.lock); + memcpy(P.friends, list, sizeof list[0] * (size_t)n); + P.nfriends = n; + plat_mutex_unlock(&P.lock); + G.friends_serial++; + } + break; + } +} + +static void tick(uint64_t now) { + if (!G.room) { + if (G.state == COOP_ENTERING && now - G.entered_at > HOST_WAIT_MS) room_end(COOP_NOTE_NO_ROOM); + return; + } + // the owner changed: the host left and Steam picked another member + uint64_t owner = G.net->room_owner(); + if (owner && owner != G.owner) { + G.owner = owner; + if (hosting() && G.welcomed) { + rt_log("coop: the host left; this game is the host now"); + send_roster(); + } + } + if (!G.welcomed) { + if (now - G.entered_at > HOST_WAIT_MS) { + rt_log("coop: the room's host did not answer"); + room_end(COOP_NOTE_HOST_SILENT); + } else if (now - G.hello_at >= HELLO_EVERY_MS) { + uint8_t d[6]; + uint16_t proto = COOP_PROTOCOL; + uint32_t build = GAME_BUILD; + memcpy(d, &proto, 2), memcpy(d + 2, &build, 4); + send_kind(G.owner, K_HELLO, d, sizeof d, 1); + G.hello_at = now; + } + return; + } + if (hosting() && now - G.roster_at >= ROSTER_EVERY_MS) send_roster(); + // a member Steam no longer lists is gone, whatever message was missed + uint64_t ids[STEAM_ROOM_MAX]; + int nm = G.net->room_members(ids, STEAM_ROOM_MAX); + for (int i = G.n - 1; i >= 0; i--) { + int there = G.players[i].id == G.net->self(); + for (int k = 0; k < nm; k++) there |= ids[k] == G.players[i].id; + if (!there) { + player_remove(G.players[i].id); + if (hosting()) send_roster(); + } + } + for (int i = 0; i < G.n; i++) name_player(&G.players[i]); + // this game's own pose + plat_mutex_lock(&P.lock); + int has = P.has_pose; + CoopPose pose = P.pose; + plat_mutex_unlock(&P.lock); + if (!has) memset(&pose, 0, sizeof pose); + G.own_has = has, G.own_pose = pose; + // NX2NAVI_COOP_TRACE=1 (tests, environment only): every two seconds where this game's Link is and where it has the others + static int trace = -1; + static uint64_t traced_at; + if (trace < 0) { + char v[8]; + trace = plat_getenv("NX2NAVI_COOP_TRACE", v, sizeof v) && v[0] == '1'; + } + if (trace && now - traced_at >= 2000) { + traced_at = now; + rt_log("coop: trace: own %s %.1f %.1f %.1f yaw %.2f; %d in the room", has ? pose.scene : "(not in the world)", pose.pos[0], + pose.pos[1], pose.pos[2], pose.yaw, G.n); + for (int i = 0; i < G.n; i++) { + const Player *p = &G.players[i]; + if (p->id == G.net->self()) continue; + rt_log("coop: trace: %s %s %.1f %.1f %.1f, %llu ms ago", p->name, p->has_pose ? p->pose.scene : "(no pose)", p->pose.pos[0], + p->pose.pos[1], p->pose.pos[2], (unsigned long long)(p->has_pose ? now - p->pose_at : 0)); + } + } + if (now - G.pose_sent_at >= (uint64_t)(has ? POSE_EVERY_MS : POSE_IDLE_MS)) { + uint8_t d[POSE_BYTES + COOP_SCENE_CAP]; + size_t n = pose_put(d, ++G.pose_number, &pose); + send_listed(K_POSE, d, n, 0); + G.pose_sent_at = now; + } +} + +static void drain_outbox(void) { + static Out batch[OUTBOX]; + plat_mutex_lock(&P.lock); + int n = P.nout; + if (n) memcpy(batch, P.out, sizeof batch[0] * (size_t)n); + P.nout = 0; + plat_mutex_unlock(&P.lock); + for (int i = 0; i < n && G.welcomed; i++) { + if (!batch[i].to) { + for (int k = 0; k < G.n; k++) + if (G.players[k].id != G.net->self()) G.net->send(G.players[k].id, batch[i].bytes, batch[i].n, batch[i].reliable); + } else if (player_of(batch[i].to)) { + G.net->send(batch[i].to, batch[i].bytes, batch[i].n, batch[i].reliable); + } + } +} + +static void publish(uint64_t now) { + static CoopView v; + memset(&v, 0, sizeof v); + v.state = G.state, v.note = G.note; + snprintf(v.steam_says, sizeof v.steam_says, "%s", G.steam_says); + v.local = G.net == &coop_net_local; + if (G.up && G.room && G.welcomed) { + if (v.local) snprintf(v.code, sizeof v.code, "%llu", (unsigned long long)G.room); + else steam_code_make(G.room, v.code); + v.host = (uint8_t)hosting(); + v.overlay = (uint8_t)(!v.local && steam_overlay()); + for (int i = 0; i < G.n; i++) { + CoopPlayer *o = &v.players[v.n++]; + const Player *p = &G.players[i]; + o->id = p->id; + snprintf(o->name, sizeof o->name, "%s", p->name); + o->self = p->id == G.net->self(), o->host = p->id == G.owner; + if (o->self) { + o->has_pose = (uint8_t)G.own_has, o->pose = G.own_pose; + } else { + o->has_pose = (uint8_t)(p->has_pose && now - p->pose_at < POSE_STALE_MS); + o->pose_ms = o->has_pose ? (uint32_t)(now - p->pose_at) : 0; + o->pose = p->pose; + } + } + } + if (G.invite_room) { + v.invite_room = G.invite_room; + G.net->name_of(G.invite_from, v.invite_from, sizeof v.invite_from); + clean_text(v.invite_from); + } + v.nchat = G.nchat; + memcpy(v.chat, G.chat, sizeof G.chat[0] * (size_t)G.nchat); + v.friends_serial = G.friends_serial; + plat_mutex_lock(&P.lock); + if (memcmp(&P.view, &v, sizeof v)) { + P.view = v; + __atomic_add_fetch(&P.serial, 1, __ATOMIC_RELEASE); + } + P.in_room = G.welcomed; + plat_mutex_unlock(&P.lock); +} + +static const CoopNet net_steam = {steam_start, steam_stop, steam_self, steam_name_of, steam_room_create, steam_room_join, + steam_room_leave, steam_room, steam_room_owner, steam_room_members, steam_room_set, + steam_room_get, steam_send, steam_pump}; + +static void net_down(void) { + if (!G.up) return; + room_end(COOP_NOTE_NONE); + G.net->stop(); + G.up = 0; + rt_log("coop: off"); +} + +static void coop_main(void *arg) { + (void)arg; + unsigned cfg_seen = ~0u; + int on = 0; + while (!__atomic_load_n(&P.stop, __ATOMIC_ACQUIRE)) { + uint64_t now = plat_now_ms(); + unsigned v = cfg_version(); + if (v != cfg_seen) cfg_seen = v, on = cfg_bool("NX2NAVI_COOP") && RT_V111; + if (!on) { + net_down(); + if (G.state != COOP_OFF) G.state = COOP_OFF, G.note = COOP_NOTE_NONE, publish(now); + plat_sleep_ms(200); + continue; + } + // commands, also while Steam is not up: Retry is one + Cmd cmds[COMMANDS]; + plat_mutex_lock(&P.lock); + int nc = P.ncmd; + memcpy(cmds, P.cmd, sizeof cmds[0] * (size_t)nc); + P.ncmd = 0; + plat_mutex_unlock(&P.lock); + for (int i = 0; i < nc; i++) run_command(&cmds[i]); + if (!G.up) { + if (now >= G.retry_at) { + G.net = coop_local_wanted() ? &coop_net_local : &net_steam; + int which = 0; + char why[160] = ""; + if (G.net->start(why, sizeof why, &which)) { + G.up = 1, G.state = COOP_READY, G.note = COOP_NOTE_NONE, G.steam_says[0] = 0; + rt_log("coop: on%s", G.net == &coop_net_local ? " (the test stand-in for Steam)" : ", signed in to Steam as app 480"); + if (G.net == &coop_net_local) { + if (coop_local_join()) run_command(&(Cmd){.kind = C_JOIN, .arg = coop_local_join()}); + else if (coop_local_makes()) run_command(&(Cmd){.kind = C_CREATE}); + } + } else { + CoopNote note = which == STEAM_WHY_NO_LIBRARY ? COOP_NOTE_NO_LIBRARY : which == STEAM_WHY_OLD_LIBRARY ? COOP_NOTE_OLD_LIBRARY + : which == STEAM_WHY_OTHER_OS ? COOP_NOTE_OTHER_OS : COOP_NOTE_NO_CLIENT; + if (G.state != COOP_NO_STEAM || G.note != note) rt_log("coop: Steam is not available: %s", why); + G.state = COOP_NO_STEAM, G.note = note; + snprintf(G.steam_says, sizeof G.steam_says, "%s", why); + G.retry_at = now + STEAM_RETRY_MS; + } + } + publish(now); + plat_sleep_ms(G.up ? STEP_MS : 100); + continue; + } + G.net->pump(on_event, NULL); + tick(now); + drain_outbox(); + publish(now); + plat_sleep_ms(STEP_MS); + } + net_down(); + plat_event_set(&P.stopped); +} + +// ---- for the other threads + +static int started; + +void coop_init(void) { + plat_mutex_init(&P.lock); + plat_event_init(&P.stopped, 1, 0); + P.out = calloc(OUTBOX, sizeof *P.out); + if (!P.out || !plat_thread_spawn(coop_main, NULL, "coop", 0)) { + rt_log("coop: cannot start the co-op thread"); + return; + } + started = 1; +} + +void coop_shutdown(void) { + if (!started) return; + started = 0; + __atomic_store_n(&P.stop, 1, __ATOMIC_RELEASE); + plat_event_wait_ns(&P.stopped, 1500ull * 1000000); // leaving a lobby is one call to Steam; do not hold the exit for it +} + +uint32_t coop_serial(void) { return __atomic_load_n(&P.serial, __ATOMIC_ACQUIRE); } + +void coop_view(CoopView *out) { + if (!started) { + memset(out, 0, sizeof *out); + return; + } + plat_mutex_lock(&P.lock); + *out = P.view; + plat_mutex_unlock(&P.lock); +} + +static void command(CmdKind kind, uint64_t arg, const char *text) { + if (!started) return; + plat_mutex_lock(&P.lock); + if (P.ncmd < COMMANDS) { + Cmd *c = &P.cmd[P.ncmd++]; + memset(c, 0, sizeof *c); + c->kind = kind, c->arg = arg; + if (text) snprintf(c->text, sizeof c->text, "%s", text); + } + plat_mutex_unlock(&P.lock); +} + +void coop_create(void) { command(C_CREATE, 0, NULL); } +int coop_join(const char *code) { + uint64_t room = steam_code_parse(code); + if (!room) return 0; + command(C_JOIN, room, NULL); + return 1; +} +void coop_join_invite(void) { command(C_JOIN_INVITE, 0, NULL); } +void coop_decline_invite(void) { command(C_DECLINE, 0, NULL); } +void coop_leave(void) { command(C_LEAVE, 0, NULL); } +void coop_retry(void) { command(C_RETRY, 0, NULL); } +void coop_invite(uint64_t friend_id) { command(C_INVITE, friend_id, NULL); } +void coop_invite_window(void) { command(C_INVITE_WINDOW, 0, NULL); } +void coop_remove(uint64_t player_id) { command(C_REMOVE, player_id, NULL); } +void coop_chat(const char *text) { command(C_CHAT, 0, text); } +void coop_friends_refresh(void) { command(C_FRIENDS, 0, NULL); } + +int coop_friends(SteamFriend *out, int max) { + if (!started) return 0; + plat_mutex_lock(&P.lock); + int n = P.nfriends < max ? P.nfriends : max; + memcpy(out, P.friends, sizeof out[0] * (size_t)n); + plat_mutex_unlock(&P.lock); + return n; +} + +void coop_pose_set(const CoopPose *pose) { + if (!started) return; + plat_mutex_lock(&P.lock); + P.has_pose = pose != NULL; + if (pose) P.pose = *pose; + plat_mutex_unlock(&P.lock); +} + +int coop_post(uint64_t to, uint8_t kind, const void *data, size_t n, int reliable) { + if (!started || kind < COOP_GAME_KIND || n > COOP_MESSAGE_MAX) return 0; + int ok = 0; + plat_mutex_lock(&P.lock); + if (P.in_room && P.nout < OUTBOX) { + Out *o = &P.out[P.nout++]; + o->to = to, o->n = (uint16_t)(n + 1), o->reliable = (uint8_t)reliable; + o->bytes[0] = kind; + if (n) memcpy(o->bytes + 1, data, n); + ok = 1; + } + plat_mutex_unlock(&P.lock); + return ok; +} diff --git a/runtime/coop.h b/runtime/coop.h new file mode 100644 index 00000000..1078a136 --- /dev/null +++ b/runtime/coop.h @@ -0,0 +1,124 @@ +// Co-op (coop.c): each player runs their own game; a room connects up to four of them through Steam (steam.h). The +// room is a Steam lobby, its maker's game is the host, and the games send each other where their Link is, chat lines +// and what the game layer shares (coop_game.c). docs/coop.md is the players' and the reviewers' description. +// +// One host thread (the co-op thread) owns Steam and the room. The menu and the game's thread never wait for it: they +// read the view it publishes at each step and hand it commands it carries out at its next one. +#pragma once + +#include +#include + +#include "steam.h" + +#ifdef __cplusplus +extern "C" { +#endif + +enum { + COOP_PROTOCOL = 1, // games of another number do not play together + COOP_PLAYERS = 4, + COOP_NAME_CAP = STEAM_NAME_CAP, + COOP_SCENE_CAP = 48, + COOP_CHAT_CAP = 200, // bytes of a chat line, UTF-8 + COOP_CHAT_LINES = 8, + COOP_FRIENDS = 64, + COOP_GAME_KIND = 16, // message kinds from here on belong to the game layer (coop_game.c) + COOP_MESSAGE_MAX = STEAM_MESSAGE_MAX - 1, // bytes of a message after its kind +}; + +typedef enum { + COOP_OFF, // the setting is off: no thread work, Steam untouched + COOP_NO_STEAM, // on, but Steam is not there (note says why); tried again every few seconds and at coop_retry + COOP_READY, // Steam is up, in no room + COOP_ENTERING, // making or joining a room, or waiting for its host to answer + COOP_IN_ROOM, +} CoopState; + +// Why the last attempt ended, for the menu's status line (ui/coop_page.cpp has the texts). +typedef enum { + COOP_NOTE_NONE, + COOP_NOTE_NO_LIBRARY, COOP_NOTE_OLD_LIBRARY, COOP_NOTE_NO_CLIENT, COOP_NOTE_OTHER_OS, + COOP_NOTE_CREATE_FAILED, COOP_NOTE_NO_ROOM, COOP_NOTE_FULL, COOP_NOTE_REFUSED, COOP_NOTE_NOT_OURS, + COOP_NOTE_OTHER_VERSION, COOP_NOTE_REMOVED, COOP_NOTE_HOST_SILENT, COOP_NOTE_LOST, COOP_NOTE_BAD_CODE, + COOP_NOTE_LEFT, +} CoopNote; + +// Where a player's Link is, as their game last said. +enum { COOP_POSE_ADULT = 1, COOP_POSE_PAUSED = 2 }; +typedef struct { + float pos[3]; // metres, the game's world + float vel[3]; // metres a second + float yaw; // radians about the up axis, the way Link faces + uint8_t flags; // COOP_POSE_* + char scene[COOP_SCENE_CAP]; // the area's name as the game has it; "": not in the world (title screen, loading) +} CoopPose; + +typedef struct { + uint64_t id; + char name[COOP_NAME_CAP]; + uint8_t self, host; + uint8_t has_pose; + uint32_t pose_ms; // how long ago the pose arrived + CoopPose pose; +} CoopPlayer; + +typedef struct { + char name[COOP_NAME_CAP]; + char text[COOP_CHAT_CAP + 1]; + uint64_t at_ms; // plat_now_ms when it arrived + uint8_t notice; // a line of the room itself ("... joined"): name holds the player, text is empty + uint8_t joined; // for a notice: 1 joined, 0 left +} CoopChatLine; + +typedef struct { + CoopState state; + CoopNote note; + char steam_says[160]; // with COOP_NO_STEAM: the Steam layer's own sentence, for the log's reader + char code[STEAM_CODE_CAP]; // the room's id, "" outside a room + uint8_t host; // this game is the room's host + uint8_t overlay; // Steam's own invite window can be shown + uint8_t local; // the test stand-in for Steam is in use (two games on one PC) + int n; + CoopPlayer players[COOP_PLAYERS]; + uint64_t invite_room; // a friend invites this player to a room (0 none) ... + char invite_from[COOP_NAME_CAP]; + int nchat; + CoopChatLine chat[COOP_CHAT_LINES]; // oldest first + uint32_t friends_serial; // changes when coop_friends has a new list +} CoopView; + +void coop_init(void); // starts the co-op thread; it idles while the COOP setting is off +void coop_shutdown(void); // leaves the room and signs out of Steam, before the process ends + +void coop_view(CoopView *out); +uint32_t coop_serial(void); // changes whenever the view does: a reader that keeps a copy compares this first + +// Commands, from any thread; each is carried out at the co-op thread's next step and none waits. +void coop_create(void); +int coop_join(const char *code); // 0: the text is no room id (nothing is asked of Steam) +void coop_join_invite(void); // the room of the invite the view shows +void coop_decline_invite(void); +void coop_leave(void); +void coop_retry(void); // look for Steam again now +void coop_invite(uint64_t friend_id); +void coop_invite_window(void); +void coop_remove(uint64_t player_id); // the host's: that player is out of the room and stays out +void coop_chat(const char *text); +void coop_friends_refresh(void); +int coop_friends(SteamFriend *out, int max); // the list of the last refresh + +// ---- for the game layer (coop_game.c) +void coop_pose_set(const CoopPose *pose); // this game's own Link, each frame he is in the world; NULL when he is not +// A message of the game layer to everyone in the room (to 0) or to one player; kind from COOP_GAME_KIND on, n at most +// COOP_MESSAGE_MAX. From any thread; it leaves at the co-op thread's next step. 0 outside a room. +int coop_post(uint64_t to, uint8_t kind, const void *data, size_t n, int reliable); +// coop_game.c's part, called on the co-op thread: a message of its kinds from a player of the room, and a player who +// came (the game layer sends that player what it shares) or went. +void coop_game_message(uint64_t from, uint8_t kind, const uint8_t *data, size_t n); +void coop_game_joined(uint64_t id); +void coop_game_room(int in_room); + +#ifdef __cplusplus +} +#endif diff --git a/runtime/coop_game.c b/runtime/coop_game.c new file mode 100644 index 00000000..f95a0449 --- /dev/null +++ b/runtime/coop_game.c @@ -0,0 +1,702 @@ +// Co-op, the game side (coop_game.h), for Ocarina 1.1.1: where this game's Link is, for the others, and the progress +// the players of a room share. It runs on the game's thread between two frames (coop_present, at the present) and +// talks to the room through coop.h; what the room sends arrives on the co-op thread and waits in an inbox. +// +// Link. The Player actor is [[main+0x4e371d0] + 0x480] while its name, [+0x20], reads "Player": its position in metres +// at +0x31c, its rotation as a 3x3 matrix at +0x328. The area is the game's text flag Sequence_CurrentBanc +// (debug_tools.c dbg_area). A pose goes out only while a save is being played (gate below): on the title screen and +// while an area loads the others see no Link of this game. +// +// The flag database. The game keeps its progress in one manager, *(u64 *)(main+0x4e842a8), as typed containers of 0x60 +// bytes from +8: Bool at +0x008, Int at +0x0c8, UInt at +0x788. A container holds its entry count (+0x08), entries +// (+0x10), an open-addressing table of {u32 hash, u32 entry} slots probed from hash % capacity (+0x18, capacity +0x24) and a +// ring of pending sets (+0x28 capacity, +0x30 slots, +0x38 counter, its low 20 bits the count). A Bool entry is 0x18 bytes +// (+0x08 the reset kinds, +0x10 the save file, -1 none, +0x15 default, +0x16 current value), an Int or UInt entry 0x28 +// (+0x08, +0x10 the same, +0x18 default, +0x1c current). Structs group flags: the struct table (+0xc10 count, +0xc18 +// entries of 0x20, +0xc20 slots, +0xc2c capacity) maps a struct's hash to an entry whose member table (+0x08, capacity +0x14) +// holds {u32 member hash, u32 flag or struct hash} slots. Flags are named by MurmurHash3 of their names; the names stay out +// of this file, the hashes it needs are numbers below. +// +// Writes go through the game's own set routines, SetBool (main+0x682b20) and SetInt (main+0x163b70), with x0 the manager, +// x1 the value and x2 the hash: they queue the change on the ring and the game's per-frame drain writes the current and +// saved values and its own bookkeeping, as for a change the game made. Reads are of the entries' current values. +// +// What is shared (docs/coop.md has the reasons), each value only ever raised: +// - progress: every Bool that goes to progress.sav (save file 0) and is reset only by a new game or a load (reset kinds 8, +// 16 and 32; flags with kind 1 or 256 revert at scene changes, 2 at a new day, 4 are options), except the heart +// rewards below. A flag counts as 1 once it differs from its default (63 of them start true and count down), and a +// flag anyone has at 1 becomes 1 for everyone. Story, world and dungeon flags are one kind: the game's flags carry +// no mark of which is which. +// - items, songs and quest items: the songs' and the items' "got it once" markers, the item counts of the pouch struct +// (except the lists below), the capacity struct (wallet, bag and quiver sizes) and the magic meter's size; the +// highest count wins. +// - per player always: small keys, rupees and ammunition (counters the game spends: a highest-count merge would hand +// back what was spent), the trade sequence, rented masks, the knife that breaks and amiibo items (the game takes +// them away again), heart pieces, gold skulltula tokens and the 11 heart reward flags (their pickups are flags of +// single objects this layer does not write, so a shared count would pay a piece twice); life, magic, bottle +// contents, the equipment worn and the time of day. +// +// The messages (kinds from COOP_GAME_KIND, reliable): FLAGS is u32 schema and up to 140 pairs of u32 hash and u32 +// value, sent to everyone when a value rises here and to one player as the parts of this game's whole state; ASK is +// u32 schema, "send me your whole state", sent when this game starts to share (a save is played in a room) and once +// more a few seconds later, since a player who joined a moment ago may not be on every game's list yet. The schema +// is a sum over this file's table (every shared hash with its type and limit): games whose tables differ do not +// merge. A value from the room is checked against the table before it is kept: the flag must be a shared one, a +// Bool's value 1, a count at most 999; anything else is dropped and counted in the log. +#include +#include +#include +#include + +#include "cfg.h" +#include "coop.h" +#include "coop_game.h" +#include "cpu.h" +#include "debug_tools.h" +#include "fs.h" +#include "host.h" +#include "layout.h" +#include "platform/platform.h" + +#define MGR_PTR (MOD_MAIN_BASE + 0x4e842a8ull) +#define SET_BOOL_FN (MOD_MAIN_BASE + 0x682b20ull) +#define SET_INT_FN (MOD_MAIN_BASE + 0x163b70ull) +#define PLAYER_PTR (MOD_MAIN_BASE + 0x4e371d0ull) + +enum { + C_BOOL = 0x008, C_INT = 0x0c8, C_UINT = 0x788, + CN_COUNT = 0x08, CN_ENTRIES = 0x10, CN_TABLE = 0x18, CN_CAP = 0x24, + BOOL_SIZE = 0x18, INT_SIZE = 0x28, + E_RESET = 0x08, E_FILE = 0x10, B_DEFAULT = 0x15, B_CURRENT = 0x16, I_CURRENT = 0x1c, + ST_COUNT = 0xc10, ST_ENTRIES = 0xc18, ST_TABLE = 0xc20, ST_CAP = 0xc2c, ST_SIZE = 0x20, STE_MEMBERS = 0x08, STE_MCAP = 0x14, + MGR_SIZE = 0xd80, + RESET_NEW_GAME = 8 | 16 | 32, RESET_TEMPORARY = 1 | 2 | 4 | 256, + SLICES = 4, // a quarter of the flags is read each frame: every flag every 4 frames + APPLY_PER_FRAME = 16, + INT_MAX_ITEM = 999, // the highest item count the room may set: the game's counters show three digits + CLOCK_MS = 2500, // the game clock advanced this recently: the game is being played + K_FLAGS = COOP_GAME_KIND, K_ASK, + PAIRS_PER_MESSAGE = 140, + INBOX = 16384, // pairs waiting for the game's thread + JOBS = 8, + PARTS_PER_FRAME = 4, // of a whole state on its way to one player + ASK_AGAIN_MS = 6000, + SAVE_COPIES = 12, +}; + +// Struct and member hashes (MurmurHash3 of the names the game uses). +#define S_POUCH 0x3da094e3u // item counts, one struct per item +#define M_STOCK 0x22344481u // an item's count +#define S_FIRST_GET 0xade0ef78u // "got it once" markers, one per item +#define S_DUNGEON 0xf5a32cdcu // one struct per dungeon: map, compass, boss key, small keys +#define M_SMALL_KEYS 0x1af87831u +#define S_CAPACITY 0xf80f8077u // wallet, bomb bag, quiver, seed bag, stick and nut capacities +#define F_RUPEES 0xa77921d7u +#define F_MAGIC_SIZE 0x12d63a97u +#define F_PLAY_CLOCK 0xe53eb6d1u // UInt: seconds played, advanced while the game runs (on the title screen too) +#define F_LOADING 0xf5deef0au // Bool: a save is being loaded + +// Scene changes in progress (Bool, not saved): nothing is read or written while one is set. +static const uint32_t transition_flags[] = {0x9a9506e7, 0xf8633c7f, 0xf96989b6, 0xe19dfdd6}; +static const uint32_t heart_reward_flags[] = {0x6b8fc751, 0x1d1793e9, 0xb5127e75, 0xe41e1597, 0x98ca7aab, 0xf1891f6e, + 0x3f43245b, 0x1657d7d8, 0xa666baa8, 0x5ff7aa30, 0xf2fab510}; +// Item counts that stay with each player: what the game takes away again, heart pieces and skulltula tokens. +static const uint32_t own_counts[] = {0x07f10aaf, 0x0165e7ca, 0x51d89ef0, 0x07de3e6f, 0x58c9bc78, 0xa862d276, 0x2815c82a, + 0x897cf7eb, 0x919ea324, 0x5c41a6b1, 0xded8e8d3, 0x24596e8e, 0xb6ca6093, 0x6be5c3b0, + 0x7e607033, 0x0e94a8df, 0xfc508da7, 0xb5c10899, 0x47b2d775, 0xf046629e, 0x96459cd3, + 0x924e9a46, 0xf5e647da, 0x486c59a4, 0x49d1c374, 0x20820479, 0x396a5c02, 0x8d02f5ea, + 0x600e29eb, 0x51ec97b3, 0x04735978}; +// Ammunition counts: spent by the game, so per player. +static const uint32_t ammo_counts[] = {0xdb1bcd4f, 0xdf7c517a, 0x518ec74b, 0xf30d9f54, 0x5fadf7fc, 0xb9494411, 0xb003124d}; + +static int in_list(const uint32_t *list, size_t n, uint32_t h) { + for (size_t i = 0; i < n; i++) + if (list[i] == h) return 1; + return 0; +} +#define IN(list, h) in_list(list, sizeof list / sizeof list[0], h) + +typedef struct { + uint32_t hash; + uint8_t is_int, inv; + uint8_t pending; // want is above the game's value: on the list of flags to set + uint32_t max; // the highest value the room may set: 1 for a Bool, INT_MAX_ITEM for a count + int32_t last; // the raw value last read + uint32_t sent; // the value the room last heard from this game + uint32_t want; // the highest value the room has sent + uint64_t addr; // the entry +} GFlag; + +// A set of hashes (open addressing, 0 empty), for the struct memberships while the table is built. +typedef struct { uint32_t *h; unsigned cap; } HSet; +static void hset_add(HSet *s, uint32_t h) { + if (!h || !s->h) return; + unsigned i = h & (s->cap - 1); + while (s->h[i] && s->h[i] != h) i = (i + 1) & (s->cap - 1); + s->h[i] = h; +} +static int hset_has(const HSet *s, uint32_t h) { + if (!h || !s->h) return 0; + unsigned i = h & (s->cap - 1); + while (s->h[i]) { + if (s->h[i] == h) return 1; + i = (i + 1) & (s->cap - 1); + } + return 0; +} + +typedef struct { uint32_t hash, value; } Pair; +typedef struct { uint64_t to; uint64_t at; int next; int live; } Job; // this game's whole state on its way to one player + +// The game thread's state. +static struct { + unsigned cfg_seen; + int on, share, said_version; + // the table + uint64_t mgr, bool_entries, int_entries; + int bound; + GFlag *flags; + int nflags, cap; + int *by_hash; + uint32_t schema; + int slice; + int *todo; // indices of flags with pending set + int ntodo; + // the gate + uint64_t gate_mgr, clock_entry, loading_entry, transition_entry[4]; + uint32_t clock; + uint64_t clock_at; + int titles, loaded, player, gate; + // the room + int sharing; + uint32_t room_epoch; // X.room_epoch when sharing started: another room since starts it again + int asks_left; // ASK messages still to send, the next at ask_at + uint64_t ask_at; + Job jobs[JOBS]; + uint32_t refused, applied; + uint64_t log_at; + // the pose + float last_pos[3]; + uint64_t last_pos_at; + int posed; +} G; + +// What the co-op thread hands over. +static struct { + PlatMutex lock; + volatile int32_t room; // in a room (coop_game_room) + volatile uint32_t room_epoch; // counts the rooms entered + volatile int32_t on; // the COOP setting, for coop_game_rom_open on the game's file threads + volatile int32_t save_copied; // the save was copied for this room: values may be set + volatile int32_t titles; // the title screen's starts (coop_game_rom_open) + int n; + Pair *pairs; // INBOX of them + int overflow; // pairs were dropped: ask for the whole state again + int njoined, nasked; + uint64_t joined[JOBS], asked[JOBS]; + uint32_t schema; // the table's, for the co-op thread's check of a message; 0 while there is none + uint32_t other_schema; // messages with another schema arrived (logged by the game thread) +} X; + +static int rd_ok(uint64_t a, uint64_t n) { return a >= 0x1000 && mem_readable(a, n); } + +// The entry of hash in the container at base (stride bytes per entry), 0 when absent. +static uint64_t entry_of(uint64_t mgr, unsigned base, unsigned stride, uint32_t hash) { + uint64_t c = mgr + base, table = LD64(c + CN_TABLE), entries = LD64(c + CN_ENTRIES); + uint32_t cap = LD32(c + CN_CAP), count = LD32(c + CN_COUNT); + if (!hash || !cap || !table || !entries) return 0; + for (uint32_t i = hash % cap, k = 0; k < cap; k++, i = i + 1 == cap ? 0 : i + 1) { + uint32_t h = LD32(table + 8ull * i); + if (h == hash) { + uint32_t idx = LD32(table + 8ull * i + 4); + return entries + (uint64_t)(idx < count ? idx : 0) * stride; + } + if (!h) return 0; + } + return 0; +} + +static uint64_t struct_of(uint64_t mgr, uint32_t hash) { + uint64_t table = LD64(mgr + ST_TABLE), entries = LD64(mgr + ST_ENTRIES); + uint32_t cap = LD32(mgr + ST_CAP), count = LD32(mgr + ST_COUNT); + if (!cap || !table || !entries || !rd_ok(table, 8ull * cap)) return 0; + for (uint32_t i = hash % cap, k = 0; k < cap; k++, i = i + 1 == cap ? 0 : i + 1) { + uint32_t h = LD32(table + 8ull * i); + if (h == hash) { + uint32_t idx = LD32(table + 8ull * i + 4); + uint64_t e = entries + (uint64_t)(idx < count ? idx : 0) * ST_SIZE; + return rd_ok(e, ST_SIZE) ? e : 0; + } + if (!h) return 0; + } + return 0; +} + +// fn(member hash, flag or struct hash, user) for each member of struct entry e. +static void members(uint64_t e, void (*fn)(uint32_t m, uint32_t v, void *u), void *u) { + uint64_t t = LD64(e + STE_MEMBERS); + uint32_t cap = LD32(e + STE_MCAP); + if (!t || !cap || cap > 65536 || !rd_ok(t, 8ull * cap)) return; + for (uint32_t i = 0; i < cap; i++) { + uint32_t m = LD32(t + 8ull * i); + if (m) fn(m, LD32(t + 8ull * i + 4), u); + } +} + +typedef struct { uint64_t mgr; HSet *set; uint32_t want; } Walk; +static void add_member(uint32_t m, uint32_t v, void *u) { (void)m, hset_add(((Walk *)u)->set, v); } +static void pick(uint32_t m, uint32_t v, void *u) { + Walk *w = u; + if (m == w->want) hset_add(w->set, v); +} +// A struct of structs: the flag of member want in each. +static void add_nested(uint32_t m, uint32_t v, void *u) { + (void)m; + Walk *w = u; + uint64_t e = struct_of(w->mgr, v); + if (e) members(e, pick, w); +} + +static GFlag *add_flag(void) { + if (G.nflags == G.cap) { + int nc = G.cap ? G.cap * 2 : 4096; + GFlag *nf = realloc(G.flags, (size_t)nc * sizeof *nf); + if (!nf) return NULL; + G.flags = nf, G.cap = nc; + } + GFlag *f = &G.flags[G.nflags++]; + memset(f, 0, sizeof *f); + return f; +} + +static int cmp_by_hash(const void *a, const void *b) { + uint32_t x = G.flags[*(const int *)a].hash, y = G.flags[*(const int *)b].hash; + return x < y ? -1 : x > y; +} + +// The table of the manager's shared flags (the header comment's rules). 0 when the database is not readable. +static int build_table(uint64_t mgr) { + G.nflags = 0; + HSet first_get = {0}, pouch = {0}, keys = {0}, capacity = {0}; + HSet *sets[] = {&first_get, &pouch, &keys, &capacity}; + for (int i = 0; i < 4; i++) { + sets[i]->cap = 1024; + sets[i]->h = calloc(sets[i]->cap, sizeof *sets[i]->h); + } + uint64_t e; + Walk w = {mgr, &first_get, 0}; + if ((e = struct_of(mgr, S_FIRST_GET))) members(e, add_member, &w); + w.set = &pouch, w.want = M_STOCK; + if ((e = struct_of(mgr, S_POUCH))) members(e, add_nested, &w); + w.set = &keys, w.want = M_SMALL_KEYS; + if ((e = struct_of(mgr, S_DUNGEON))) members(e, add_nested, &w); + w.set = &capacity; + if ((e = struct_of(mgr, S_CAPACITY))) members(e, add_member, &w); + + for (int type = 0; type < 2; type++) { + unsigned base = type ? C_INT : C_BOOL, stride = type ? INT_SIZE : BOOL_SIZE; + uint64_t c = mgr + base, table = LD64(c + CN_TABLE), entries = LD64(c + CN_ENTRIES); + uint32_t cap = LD32(c + CN_CAP), count = LD32(c + CN_COUNT); + if (!cap || !count || count > 1000000 || !rd_ok(table, 8ull * cap) || !rd_ok(entries, (uint64_t)count * stride)) continue; + for (uint32_t i = 0; i < cap; i++) { + uint32_t h = LD32(table + 8ull * i), idx = LD32(table + 8ull * i + 4); + if (!h || idx >= count) continue; + uint64_t a = entries + (uint64_t)idx * stride; + uint32_t reset = LD32(a + E_RESET); + int32_t file = (int32_t)LD32(a + E_FILE); + uint8_t inv = 0; + if (!type) { + if (file != 0 || reset & RESET_TEMPORARY || !(reset & RESET_NEW_GAME) || IN(heart_reward_flags, h)) continue; + inv = LD8(a + B_DEFAULT) != 0; + } else if (h == F_RUPEES || hset_has(&keys, h)) { + continue; + } else if (hset_has(&pouch, h)) { + if (IN(own_counts, h) || IN(ammo_counts, h)) continue; + } else if (!hset_has(&capacity, h) && h != F_MAGIC_SIZE) { + continue; + } + GFlag *f = add_flag(); + if (!f) break; + f->hash = h, f->is_int = (uint8_t)type, f->inv = inv, f->addr = a; + f->max = type ? INT_MAX_ITEM : 1; + } + } + for (int i = 0; i < 4; i++) free(sets[i]->h); + free(G.by_hash), free(G.todo); + G.by_hash = malloc((size_t)G.nflags * sizeof *G.by_hash); + G.todo = malloc((size_t)G.nflags * sizeof *G.todo); + G.ntodo = 0; + if (!G.by_hash || !G.todo) return 0; + for (int i = 0; i < G.nflags; i++) G.by_hash[i] = i; + qsort(G.by_hash, (size_t)G.nflags, sizeof *G.by_hash, cmp_by_hash); + // the schema: this layer's version, the game's, and the table (every hash with its type and limit), so that two + // builds that share or limit differently do not merge + uint64_t h = 0xcbf29ce484222325ull; + for (const char *p = "nx2navi-coop-share/1"; *p; p++) h = (h ^ (uint8_t)*p) * 0x100000001b3ull; + h = (h ^ (uint64_t)rt_game_version) * 0x100000001b3ull; + for (int i = 0; i < G.nflags; i++) { + const GFlag *f = &G.flags[G.by_hash[i]]; + uint64_t row[2] = {f->hash | (uint64_t)f->is_int << 40, f->max}; + for (int k = 0; k < 16; k++) h = (h ^ (uint8_t)(row[k / 8] >> 8 * (k % 8))) * 0x100000001b3ull; + } + G.schema = (uint32_t)(h ^ h >> 32); + if (!G.schema) G.schema = 1; + return G.nflags > 0; +} + +static int32_t raw_of(const GFlag *f) { return f->is_int ? (int32_t)LD32(f->addr + I_CURRENT) : LD8(f->addr + B_CURRENT); } +static uint32_t value_of(const GFlag *f, int32_t raw) { + if (!f->is_int) return (raw != 0) != f->inv; // 1: differs from its default + return raw > 0 ? (uint32_t)raw : 0; +} + +static int flag_index(uint32_t hash) { + int lo = 0, hi = G.nflags - 1; + while (lo <= hi) { + int mid = (lo + hi) / 2, i = G.by_hash[mid]; + if (G.flags[i].hash == hash) return i; + if (G.flags[i].hash < hash) lo = mid + 1; + else hi = mid - 1; + } + return -1; +} + +// ---- the co-op thread's side + +void coop_game_init(void) { + plat_mutex_init(&X.lock); + X.pairs = calloc(INBOX, sizeof *X.pairs); +} + +void coop_game_rom_open(const char *path) { + // the title screen's event flow is opened each time the title screen starts: at boot and after the pause menu's + // Title Screen + if (__atomic_load_n(&X.on, __ATOMIC_RELAXED) && strstr(path, "/Event/EventFlow/TitleEvent.bfevfl")) plat_inc32(&X.titles); +} + +// Before anything of a room reaches the save: a copy of it as it is, every slot. Slow (the whole save), so on a +// thread of its own, started when this game begins to share in a room (a save is played then: the game has its save +// storage open); values wait until the copy is there. arg: the room's count, so a copy that ends after the player +// went on to another room does not open that one. +static void copy_save(void *arg) { + uint32_t epoch = (uint32_t)(uintptr_t)arg; + char path[PLAT_PATH_MAX]; + int ok = fs_save_snapshot("coop-backup", NULL, SAVE_COPIES, path, sizeof path); + if (ok && path[0]) rt_log("coop: the save as it was before this room is in %s", path); + else if (ok) rt_log("coop: nothing is saved yet, so there is no save to copy before this room"); + else rt_log("coop: the save could not be copied; nothing of the room's progress is taken"); + if (ok && epoch == __atomic_load_n(&X.room_epoch, __ATOMIC_ACQUIRE)) __atomic_store_n(&X.save_copied, 1, __ATOMIC_RELEASE); +} + +void coop_game_room(int in_room) { + __atomic_store_n(&X.save_copied, 0, __ATOMIC_RELEASE); + plat_mutex_lock(&X.lock); + X.n = 0, X.overflow = 0, X.njoined = X.nasked = 0; + plat_mutex_unlock(&X.lock); + if (in_room) __atomic_add_fetch(&X.room_epoch, 1, __ATOMIC_RELEASE); + __atomic_store_n(&X.room, in_room, __ATOMIC_RELEASE); +} + +void coop_game_joined(uint64_t id) { + plat_mutex_lock(&X.lock); + if (X.njoined < JOBS) X.joined[X.njoined++] = id; + plat_mutex_unlock(&X.lock); +} + +void coop_game_message(uint64_t from, uint8_t kind, const uint8_t *data, size_t n) { + if (n < 4) return; + uint32_t schema; + memcpy(&schema, data, 4); + plat_mutex_lock(&X.lock); + if (X.schema && schema != X.schema) { + X.other_schema++; + } else if (kind == K_ASK && n == 4) { + if (X.nasked < JOBS) X.asked[X.nasked++] = from; + } else if (kind == K_FLAGS && (n - 4) % 8 == 0 && (n - 4) / 8 <= PAIRS_PER_MESSAGE) { + size_t count = (n - 4) / 8; + if (X.pairs && X.n + (int)count <= INBOX) { + memcpy(X.pairs + X.n, data + 4, count * 8); + X.n += (int)count; + } else { + X.overflow = 1; + } + } + plat_mutex_unlock(&X.lock); +} + +// ---- the game's thread + +// The table is the save's: another save, a load or the title screen ends it, and sharing with it. +static void unbind(void) { + G.bound = 0, G.sharing = 0, G.ntodo = 0; // the gate's own addresses stay: it reads through them this frame + memset(G.jobs, 0, sizeof G.jobs); +} + +static void bind(uint64_t mgr) { + if (!build_table(mgr)) return; + G.mgr = mgr, G.bool_entries = LD64(mgr + C_BOOL + CN_ENTRIES), G.int_entries = LD64(mgr + C_INT + CN_ENTRIES); + for (int i = 0; i < G.nflags; i++) G.flags[i].last = raw_of(&G.flags[i]); + G.bound = 1, G.slice = 0; + plat_mutex_lock(&X.lock); + X.schema = G.schema; + plat_mutex_unlock(&X.lock); + rt_log("coop: a save is played: %d flags and counts can be shared", G.nflags); +} + +static uint64_t player_actor(void) { + uint64_t m = rd_ok(PLAYER_PTR, 8) ? LD64(PLAYER_PTR) : 0, a = rd_ok(m + 0x480, 8) ? LD64(m + 0x480) : 0; + uint64_t name = rd_ok(a + 0x20, 8) ? LD64(a + 0x20) : 0; + if (!rd_ok(name, 7) || memcmp((const void *)(uintptr_t)name, "Player", 7) || !rd_ok(a + 0x31c, 12 + 36)) return 0; + return a; +} + +// Link stands in the world: the Player actor exists away from the origin. There is none on the title screen at the +// start, so this holds everything back while the first load builds the world; after a return to the title screen the +// actor stays (the title count marks that). +static int player_in_world(float pos[3]) { + uint64_t a = player_actor(); + if (!a) return 0; + memcpy(pos, (const void *)(uintptr_t)(a + 0x31c), 12); + return isfinite(pos[0]) && isfinite(pos[1]) && isfinite(pos[2]) && fabsf(pos[0]) + fabsf(pos[2]) >= 1.0f; +} + +// The game is being played: a save was loaded since the title screen, Link stands in the world, the clock runs, no save +// is loading, no scene is changing. Notes a save change (unbind). +static int gate(uint64_t mgr, float pos[3]) { + if (mgr != G.gate_mgr || !G.clock_entry) { // the addresses of the few flags read every frame + G.gate_mgr = mgr; + G.clock_entry = entry_of(mgr, C_UINT, INT_SIZE, F_PLAY_CLOCK); + G.loading_entry = entry_of(mgr, C_BOOL, BOOL_SIZE, F_LOADING); + for (int i = 0; i < 4; i++) G.transition_entry[i] = entry_of(mgr, C_BOOL, BOOL_SIZE, transition_flags[i]); + } + if (!G.clock_entry || !rd_ok(G.clock_entry, INT_SIZE)) return 0; + uint64_t now = plat_now_ms(); + int titles = __atomic_load_n(&X.titles, __ATOMIC_ACQUIRE); + if (titles != G.titles) { + G.titles = titles; + unbind(); + G.loaded = 0; + } + uint32_t clock = LD32(G.clock_entry + I_CURRENT); + int loading = G.loading_entry && LD8(G.loading_entry + B_CURRENT); + unsigned moving = 0; + for (int i = 0; i < 4; i++) moving |= (unsigned)(G.transition_entry[i] && LD8(G.transition_entry[i] + B_CURRENT)) << i; + if (clock != G.clock) { + // the clock counts seconds one by one, on the title screen too; any other change is a save being loaded (a load, + // a new game, the same save again from where it was saved), which also sets the flags: play starts at the next + // tick after one + int tick = clock > G.clock && clock - G.clock <= 5; + if (!tick) unbind(), G.loaded = 1; + G.clock = clock; + G.clock_at = tick ? now : 0; + } + if (loading) unbind(), G.loaded = 1; + G.player = player_in_world(pos); + G.gate = G.loaded && G.player && !loading && !moving && G.clock_at && now - G.clock_at < CLOCK_MS; + return G.gate; +} + +static void post_pose(const float pos[3], uint64_t now) { + CoopPose p; + memset(&p, 0, sizeof p); + memcpy(p.pos, pos, 12); + if (G.posed && now > G.last_pos_at && now - G.last_pos_at < 500) { + float dt = (float)(now - G.last_pos_at) / 1000.0f; + for (int i = 0; i < 3; i++) p.vel[i] = (pos[i] - G.last_pos[i]) / dt; + } + memcpy(G.last_pos, pos, 12), G.last_pos_at = now, G.posed = 1; + // the way Link faces, from his rotation's forward column; nothing draws by it yet + uint64_t a = player_actor(); + float m[9]; + if (a) { + memcpy(m, (const void *)(uintptr_t)(a + 0x328), sizeof m); + if (isfinite(m[2]) && isfinite(m[8])) p.yaw = atan2f(m[2], m[8]); + } + char area[64]; + if (dbg_area(area)) snprintf(p.scene, sizeof p.scene, "%s", area); + coop_pose_set(&p); +} + +static void set_flag(Cpu *c, uint64_t mgr, int is_int, uint32_t hash, int32_t value) { + rt_call(c, is_int ? SET_INT_FN : SET_BOOL_FN, 3, mgr, (uint64_t)(uint32_t)value, (uint64_t)hash); +} + +static int post_pairs(uint64_t to, const Pair *pairs, int n) { + uint8_t d[4 + 8 * PAIRS_PER_MESSAGE]; + memcpy(d, &G.schema, 4); + memcpy(d + 4, pairs, (size_t)n * 8); + return coop_post(to, K_FLAGS, d, 4 + (size_t)n * 8, 1); +} + +// Reads a quarter of the flags; what changed and is above what the room last heard goes to everyone. +static void scan(void) { + int from = G.nflags * G.slice / SLICES, to = G.nflags * (G.slice + 1) / SLICES; + G.slice = (G.slice + 1) % SLICES; + Pair out[PAIRS_PER_MESSAGE]; + int n = 0; + for (int i = from; i < to && n < PAIRS_PER_MESSAGE; i++) { + GFlag *f = &G.flags[i]; + int32_t raw = raw_of(f); + if (raw == f->last) continue; + f->last = raw; + uint32_t v = value_of(f, raw); + if (v > f->max) v = f->max; + if (v > f->sent) out[n++] = (Pair){f->hash, v}; + } + if (!n) return; + int sent = post_pairs(0, out, n); + for (int i = 0; i < n; i++) { + GFlag *f = &G.flags[flag_index(out[i].hash)]; + if (sent) f->sent = out[i].value; + else f->last = INT32_MIN; // the room's queue is full: read as changed again at the next pass + } +} + +// The inbox into the flags' wanted values. +static void take_inbox(void) { + static Pair batch[INBOX]; + uint64_t joined[JOBS], asked[JOBS]; + plat_mutex_lock(&X.lock); + int n = X.n, overflow = X.overflow, nj = X.njoined, na = X.nasked; + uint32_t other = X.other_schema; + memcpy(batch, X.pairs, (size_t)n * sizeof *batch); + memcpy(joined, X.joined, sizeof joined), memcpy(asked, X.asked, sizeof asked); + X.n = 0, X.overflow = 0, X.njoined = X.nasked = 0, X.other_schema = 0; + plat_mutex_unlock(&X.lock); + uint64_t now = plat_now_ms(); + if (other) rt_log("coop: %u messages came from a game that shares other things than this one (another version); not taken", other); + for (int i = 0; i < n; i++) { + int k = flag_index(batch[i].hash); + GFlag *f = k >= 0 ? &G.flags[k] : NULL; + if (!f || !batch[i].value || batch[i].value > f->max) { + G.refused++; + continue; + } + if (batch[i].value > f->want) f->want = batch[i].value; + if (batch[i].value > f->sent) f->sent = batch[i].value; // the room has it: no need to say it again + if (!f->pending && f->want > value_of(f, raw_of(f))) f->pending = 1, G.todo[G.ntodo++] = k; + } + // a whole state for each player who asked, and (a little later, when it is on everyone's list) for each who came + for (int pass = 0; pass < 2; pass++) { + int count = pass ? nj : na; + const uint64_t *ids = pass ? joined : asked; + for (int i = 0; i < count; i++) + for (int j = 0; j < JOBS; j++) + if (!G.jobs[j].live) { + G.jobs[j] = (Job){.to = ids[i], .at = now + (pass ? 2000 : 0), .next = 0, .live = 1}; + break; + } + } + if (overflow && !G.asks_left) G.asks_left = 1, G.ask_at = now; // pairs were dropped: the whole state once more +} + +static void apply(Cpu *c, uint64_t mgr) { + if (!__atomic_load_n(&X.save_copied, __ATOMIC_ACQUIRE)) return; // no copy of the save yet: values wait + int done = 0; + while (G.ntodo && done < APPLY_PER_FRAME) { + int k = G.todo[--G.ntodo]; + GFlag *f = &G.flags[k]; + f->pending = 0; + if (f->want <= value_of(f, raw_of(f))) continue; // the game got there itself meanwhile + set_flag(c, mgr, f->is_int, f->hash, f->is_int ? (int32_t)f->want : !f->inv); + G.applied++, done++; + } +} + +// This game's whole state to the players who wait for it, a few messages a frame. +static void run_jobs(uint64_t now) { + for (int j = 0; j < JOBS; j++) { + Job *job = &G.jobs[j]; + if (!job->live || now < job->at) continue; + for (int part = 0; part < PARTS_PER_FRAME && job->live; part++) { + Pair out[PAIRS_PER_MESSAGE]; + int n = 0, i = job->next; + for (; i < G.nflags && n < PAIRS_PER_MESSAGE; i++) { + const GFlag *f = &G.flags[i]; + uint32_t v = value_of(f, raw_of(f)); + if (v > f->max) v = f->max; + if (v) out[n++] = (Pair){f->hash, v}; + } + if (n && !post_pairs(job->to, out, n)) return; // the room's queue is full: go on at the next frame + if (!job->to) // everyone has these now: a later rise is what scan sends + for (int k = 0; k < n; k++) { + GFlag *f = &G.flags[flag_index(out[k].hash)]; + if (out[k].value > f->sent) f->sent = out[k].value; + } + job->next = i; + if (i >= G.nflags) job->live = 0; + } + } +} + +void coop_present(Cpu *c) { + unsigned v = cfg_version(); + if (v != G.cfg_seen) { + G.cfg_seen = v; + G.on = cfg_bool("NX2NAVI_COOP"); + __atomic_store_n(&X.on, G.on, __ATOMIC_RELAXED); + G.share = cfg_bool("NX2NAVI_COOP_SHARE"); + } + if (!G.on) { + if (G.posed) coop_pose_set(NULL), G.posed = 0; + return; + } + if (!RT_V111) { + if (!G.said_version) rt_log("coop: co-op knows game 1.1.1 only; this is %d", rt_game_version); + G.said_version = 1; + return; + } + uint64_t mgr = LD64(MGR_PTR); + if (!rd_ok(mgr, MGR_SIZE)) { + unbind(); + return; + } + if (G.bound && (mgr != G.mgr || LD64(mgr + C_BOOL + CN_ENTRIES) != G.bool_entries || LD64(mgr + C_INT + CN_ENTRIES) != G.int_entries)) + unbind(); + float pos[3]; + uint64_t now = plat_now_ms(); + if (!gate(mgr, pos)) { + if (G.posed) coop_pose_set(NULL), G.posed = 0; + return; + } + post_pose(pos, now); + int in_room = __atomic_load_n(&X.room, __ATOMIC_ACQUIRE); + if (!in_room || !G.share) { + if (G.sharing) { // left the room, or sharing was turned off: what the next room hears starts from nothing + G.sharing = 0, G.ntodo = 0; + memset(G.jobs, 0, sizeof G.jobs); + for (int i = 0; i < G.nflags; i++) G.flags[i].sent = G.flags[i].want = 0, G.flags[i].pending = 0; + } + return; + } + if (!G.bound) bind(mgr); + if (!G.bound) return; + Cpu keep = *c; + uint32_t epoch = __atomic_load_n(&X.room_epoch, __ATOMIC_ACQUIRE); + if (!G.sharing || epoch != G.room_epoch) { + // this game starts to share: the others send what they have, and get what this save has + G.sharing = 1, G.room_epoch = epoch; + if (!__atomic_load_n(&X.save_copied, __ATOMIC_ACQUIRE) && + !plat_thread_spawn(copy_save, (void *)(uintptr_t)epoch, "coop-save", 0)) + rt_log("coop: the save could not be copied; nothing of the room's progress is taken"); + for (int i = 0; i < G.nflags; i++) G.flags[i].sent = G.flags[i].want = 0, G.flags[i].pending = 0; + G.ntodo = 0; + G.asks_left = 2, G.ask_at = now; + memset(G.jobs, 0, sizeof G.jobs); + G.jobs[0] = (Job){.to = 0, .at = now, .next = 0, .live = 1}; + G.jobs[1] = (Job){.to = 0, .at = now + ASK_AGAIN_MS, .next = 0, .live = 1}; + } + if (G.asks_left && now >= G.ask_at && coop_post(0, K_ASK, &G.schema, 4, 1)) G.asks_left--, G.ask_at = now + ASK_AGAIN_MS; + take_inbox(); + scan(); + apply(c, mgr); + run_jobs(now); + memcpy(c->x, keep.x, sizeof c->x); + memcpy(c->v, keep.v, sizeof c->v); + c->nzcv = keep.nzcv, c->fpsr = keep.fpsr; + if (now - G.log_at >= 5000 && (G.applied || G.refused)) { + if (G.applied) rt_log("coop: took %u values of progress from the room", G.applied); + if (G.refused) rt_log("coop: %u values from the room were not ones this game shares; dropped", G.refused); + G.applied = G.refused = 0, G.log_at = now; + } +} diff --git a/runtime/coop_game.h b/runtime/coop_game.h new file mode 100644 index 00000000..211173b5 --- /dev/null +++ b/runtime/coop_game.h @@ -0,0 +1,12 @@ +// Co-op, the game side (coop_game.c): where this game's Link is and the progress a room shares. coop.h declares the +// part the co-op thread calls (coop_game_message, coop_game_joined, coop_game_room). +#pragma once + +#include "cpu.h" + +void coop_game_init(void); +// At each present, on the game's thread, between two frames: reads Link and the game's flags and sets the flags the +// room has and this game lacks, through the game's own routines. Does nothing while the COOP setting is off. +void coop_present(Cpu *c); +// Each RomFS file the game opens (fs_host.c): the title screen's start is told by its event flow being opened. +void coop_game_rom_open(const char *path); diff --git a/runtime/coop_local.c b/runtime/coop_local.c new file mode 100644 index 00000000..caa92970 --- /dev/null +++ b/runtime/coop_local.c @@ -0,0 +1,192 @@ +// The stand-in for Steam in tests of two or more games on one PC (coop_net.h): datagrams between UDP ports on +// 127.0.0.1. A player's id is its port, a room's number its maker's port. The maker keeps the member list: a member +// says JOIN once a second, the maker answers everyone with MEMBERS and drops a member it has not heard for five +// seconds. Loopback loses and reorders nothing in practice, so "reliable" is a plain datagram here. +// +// Only the environment turns it on: a settings file cannot. +#include +#include +#include + +#include "coop_net.h" +#include "platform/platform.h" + +enum { L_JOIN = 1, L_MEMBERS, L_DATA, L_LEAVE, L_MAX = 8, L_SILENT_MS = 5000, L_JOIN_EVERY_MS = 1000, L_JOIN_WAIT_MS = 4000 }; + +static struct { + PlatUdp *udp; + uint64_t self, room; + uint64_t joining; // the room asked for, until its maker answers + uint64_t join_since, join_sent, members_sent; + int n; + uint64_t ids[L_MAX]; + uint64_t heard[L_MAX]; // the maker's: when each member last said JOIN + int pending_entered; // the maker's own room: entered at the next pump +} L; + +static uint64_t env_number(const char *name) { + char v[32]; + return plat_getenv(name, v, sizeof v) ? strtoull(v, NULL, 10) : 0; +} + +int coop_local_wanted(void) { return env_number("NX2NAVI_COOP_LOCAL") != 0; } +uint64_t coop_local_join(void) { return env_number("NX2NAVI_COOP_LOCAL_JOIN"); } +int coop_local_makes(void) { return env_number("NX2NAVI_COOP_LOCAL_MAKE") == 1; } + +static void to_port(uint64_t port, const void *p, size_t n) { + static const uint8_t loopback[16] = {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0xff, 0xff, 127, 0, 0, 1}; + PlatAddr a; + plat_addr_set(&a, loopback, (uint16_t)port, 0); + plat_udp_send(L.udp, &a, p, n); +} + +static int l_start(char *why, size_t cap, int *which) { + if (L.udp) return 1; + uint64_t port = env_number("NX2NAVI_COOP_LOCAL"); + L.udp = port && port < 65536 ? plat_udp_open((uint16_t)port, 0) : NULL; + if (!L.udp) { + snprintf(why, cap, "the test port %llu cannot be opened", (unsigned long long)port); + if (which) *which = STEAM_WHY_NO_CLIENT; + return 0; + } + L.self = port; + if (which) *which = STEAM_WHY_OK; + return 1; +} + +static void l_room_leave(void) { + if (L.room && L.room != L.self) to_port(L.room, (uint8_t[]){L_LEAVE}, 1); + L.room = L.joining = 0, L.n = 0; +} + +static void l_stop(void) { + l_room_leave(); + if (L.udp) plat_udp_close(L.udp); + L.udp = NULL; +} + +static uint64_t l_self(void) { return L.self; } +static void l_name_of(uint64_t id, char *out, size_t cap) { snprintf(out, cap, "Player %llu", (unsigned long long)id); } + +static int l_room_create(int max_players) { + (void)max_players; + if (!L.udp || L.room) return 0; + L.room = L.self, L.n = 1, L.ids[0] = L.self, L.pending_entered = 1; + return 1; +} + +static int l_room_join(uint64_t room) { + if (!L.udp || L.room || !room || room == L.self) return 0; + L.joining = room, L.join_since = plat_now_ms(), L.join_sent = 0; + return 1; +} + +static uint64_t l_room(void) { return L.room; } +static uint64_t l_room_owner(void) { return L.room; } +static int l_room_members(uint64_t *out, int max) { + int n = L.room ? L.n : 0; + if (n > max) n = max; + memcpy(out, L.ids, (size_t)n * sizeof *out); + return n; +} +static int l_room_set(const char *key, const char *value) { (void)key, (void)value; return 1; } +static void l_room_get(const char *key, char *out, size_t cap) { + snprintf(out, cap, "%s", !strcmp(key, "nx2navi") ? "1" : ""); // every room of the stand-in is one of ours +} + +static int member(uint64_t id) { + for (int i = 0; i < L.n; i++) + if (L.ids[i] == id) return i; + return -1; +} + +static int l_send(uint64_t to, const void *data, size_t n, int reliable) { + (void)reliable; + if (!L.room || n > STEAM_MESSAGE_MAX || member(to) < 0) return 0; + uint8_t d[1 + STEAM_MESSAGE_MAX]; + d[0] = L_DATA; + memcpy(d + 1, data, n); + to_port(to, d, n + 1); + return 1; +} + +static void send_members(void) { + uint8_t d[1 + 8 * L_MAX]; + d[0] = L_MEMBERS; + memcpy(d + 1, L.ids, (size_t)L.n * 8); + for (int i = 1; i < L.n; i++) to_port(L.ids[i], d, 1 + (size_t)L.n * 8); + L.members_sent = plat_now_ms(); +} + +static void drop(int i, void (*on)(const SteamEvent *, void *), void *user) { + uint64_t id = L.ids[i]; + for (int k = i; k + 1 < L.n; k++) L.ids[k] = L.ids[k + 1], L.heard[k] = L.heard[k + 1]; + L.n--; + on(&(SteamEvent){.kind = STEAM_EV_MEMBER_LEFT, .a = id}, user); +} + +static void l_pump(void (*on)(const SteamEvent *e, void *user), void *user) { + if (!L.udp) return; + uint64_t now = plat_now_ms(); + if (L.pending_entered) { + L.pending_entered = 0; + on(&(SteamEvent){.kind = STEAM_EV_ROOM_ENTERED, .a = L.room}, user); + } + uint64_t maker = L.joining ? L.joining : L.room != L.self ? L.room : 0; + if (maker && now - L.join_sent >= L_JOIN_EVERY_MS) to_port(maker, (uint8_t[]){L_JOIN}, 1), L.join_sent = now; + if (L.joining && now - L.join_since > L_JOIN_WAIT_MS) { + L.joining = 0; + on(&(SteamEvent){.kind = STEAM_EV_ROOM_FAILED, .code = STEAM_FAIL_NO_ROOM}, user); + } + for (;;) { + uint8_t d[1 + STEAM_MESSAGE_MAX + 8]; + PlatAddr from; + int n = plat_udp_recv(L.udp, d, sizeof d, &from, 0); + if (n <= 0) break; + uint64_t who = plat_addr_port(&from); + if (d[0] == L_JOIN && L.room == L.self) { + int i = member(who); + if (i < 0 && L.n < L_MAX) { + i = L.n++; + L.ids[i] = who, L.heard[i] = now; + send_members(); + on(&(SteamEvent){.kind = STEAM_EV_MEMBER_JOINED, .a = who}, user); + } else if (i >= 0) { + L.heard[i] = now; + } + } else if (d[0] == L_LEAVE && L.room == L.self) { + int i = member(who); + if (i > 0) drop(i, on, user), send_members(); + } else if (d[0] == L_MEMBERS && (who == L.joining || (L.room && who == L.room && L.room != L.self))) { + uint64_t ids[L_MAX]; + int count = (n - 1) / 8; + if (count > L_MAX) count = L_MAX; + memcpy(ids, d + 1, (size_t)count * 8); + int entering = L.joining != 0; + if (entering) L.room = L.joining, L.joining = 0, L.n = 0; + // who left, then who came, against the list held + for (int i = L.n - 1; i >= 0; i--) { + int still = 0; + for (int k = 0; k < count; k++) still |= ids[k] == L.ids[i]; + if (!still) drop(i, on, user); + } + for (int k = 0; k < count; k++) { + if (member(ids[k]) >= 0 || L.n >= L_MAX) continue; + L.ids[L.n++] = ids[k]; + if (!entering && ids[k] != L.self) on(&(SteamEvent){.kind = STEAM_EV_MEMBER_JOINED, .a = ids[k]}, user); + } + if (entering) on(&(SteamEvent){.kind = STEAM_EV_ROOM_ENTERED, .a = L.room}, user); + } else if (d[0] == L_DATA && L.room && member(who) >= 0 && n > 1) { + on(&(SteamEvent){.kind = STEAM_EV_MESSAGE, .a = who, .data = d + 1, .n = (size_t)n - 1}, user); + } + if (!L.udp) return; // a handler stopped the stand-in + } + if (L.room == L.self) { + for (int i = L.n - 1; i > 0; i--) + if (now - L.heard[i] > L_SILENT_MS) drop(i, on, user), send_members(); + if (now - L.members_sent >= L_JOIN_EVERY_MS) send_members(); + } +} + +const CoopNet coop_net_local = {l_start, l_stop, l_self, l_name_of, l_room_create, l_room_join, l_room_leave, l_room, + l_room_owner, l_room_members, l_room_set, l_room_get, l_send, l_pump}; diff --git a/runtime/coop_net.h b/runtime/coop_net.h new file mode 100644 index 00000000..6f7d2639 --- /dev/null +++ b/runtime/coop_net.h @@ -0,0 +1,30 @@ +// What co-op (coop.c) needs from the network under it: Steam (steam.c), or the stand-in for tests of two games on one +// PC (coop_local.c), which one Steam account cannot do. The functions are steam.h's, with its events. +#pragma once + +#include "steam.h" + +typedef struct { + int (*start)(char *why, size_t cap, int *which); + void (*stop)(void); + uint64_t (*self)(void); + void (*name_of)(uint64_t id, char *out, size_t cap); + int (*room_create)(int max_players); + int (*room_join)(uint64_t room); + void (*room_leave)(void); + uint64_t (*room)(void); + uint64_t (*room_owner)(void); + int (*room_members)(uint64_t *out, int max); + int (*room_set)(const char *key, const char *value); + void (*room_get)(const char *key, char *out, size_t cap); + int (*send)(uint64_t to, const void *data, size_t n, int reliable); + void (*pump)(void (*on)(const SteamEvent *e, void *user), void *user); +} CoopNet; + +// The stand-in: NX2NAVI_COOP_LOCAL= in the environment (never from nx2navi.ini) makes this game the player +// whose id is that UDP port on 127.0.0.1; the room it makes has that number, and another game joins it with +// NX2NAVI_COOP_LOCAL_JOIN=. No Steam, no room ids, no invites. +extern const CoopNet coop_net_local; +int coop_local_wanted(void); // the variable is set +uint64_t coop_local_join(void); // the room NX2NAVI_COOP_LOCAL_JOIN names, 0 none +int coop_local_makes(void); // NX2NAVI_COOP_LOCAL_MAKE=1: this game makes its room at once diff --git a/runtime/debug_tools.c b/runtime/debug_tools.c index baf8f9d7..cd4b660e 100644 --- a/runtime/debug_tools.c +++ b/runtime/debug_tools.c @@ -495,6 +495,8 @@ static int text_get(const char *name, char out[64]) { } // A text written into the entry's own buffers (game thread). 0: the game has no such text. +int dbg_area(char out[64]) { return dbg_supported() && text_get("Sequence_CurrentBanc", out) && out[0]; } + static int text_set(const char *name, const char *value) { uint64_t e = gmd_entry(GD_TEXT64, 0x108, hash_of(name)), text = e ? rd_ptr(e + 0x68) : 0, other = e ? rd_ptr(e + 0x18) : 0; int32_t room = 0; diff --git a/runtime/debug_tools.h b/runtime/debug_tools.h index d9c78054..06e11cab 100644 --- a/runtime/debug_tools.h +++ b/runtime/debug_tools.h @@ -16,6 +16,7 @@ extern "C" { int dbg_supported(void); // this game build's structures are known (Ocarina of Time 1.1.1) int dbg_player_pos(float xyz[3]); // Link's position in metres; 0 while there is no player +int dbg_area(char out[64]); // the area the game is in, by its name in the game's files; 0 unknown float dbg_speed_factor(void); // the game's speed: 1 normal, 0.05 to 8 (frame_rate.c multiplies the game's step) void dbg_speed_set(float factor); diff --git a/runtime/fs_host.c b/runtime/fs_host.c index c2d9284b..852f2061 100644 --- a/runtime/fs_host.c +++ b/runtime/fs_host.c @@ -21,6 +21,7 @@ #include #include +#include "coop_game.h" #include "fs.h" #include "host.h" #include "platform/platform.h" @@ -1163,6 +1164,7 @@ static int64_t host_read_at(PlatFile *f, void *buf, uint32_t n, uint64_t off) { static uint32_t open_file(uint64_t *out, const char *path, int mode) { if (romfs_owns(path)) { + coop_game_rom_open(path); // coop_game.c: the title screen's start return romfs_open(out, path, mode); } fs_trace(mode & FS_OPEN_WRITE ? "write" : "read", path); diff --git a/runtime/gfx_present.c b/runtime/gfx_present.c index 994e5689..93ea8ce0 100644 --- a/runtime/gfx_present.c +++ b/runtime/gfx_present.c @@ -17,6 +17,7 @@ #include "audren.h" #include "cfg.h" +#include "coop.h" #include "flight.h" #include "fs.h" #include "gfx.h" @@ -88,6 +89,7 @@ void gfx_window_closed(void) { vk_pipeline_save_exit(); prof_write(); // plat_exit runs no atexit handlers rtss_limit_restore(); // RivaTuner Statistics Server's profile as it was + coop_shutdown(); // leaves the room, before the process ends fs_save_flush(); // last: the game's threads still run until plat_exit, and a Commit after this one is refused if (restart) { cfg_setenv("NX2NAVI_REEXEC", NULL); // the new process counts its own address-space retries (memory.c) diff --git a/runtime/main.c b/runtime/main.c index 0ce8aaf2..eb61126b 100644 --- a/runtime/main.c +++ b/runtime/main.c @@ -46,6 +46,8 @@ #include #include "cfg.h" +#include "coop.h" +#include "coop_game.h" #include "host.h" #include "logq.h" #include "prof.h" @@ -657,6 +659,8 @@ int main(int argc, char **argv) { cfg.boot = cfg.seconds > 0; // --seconds starts the game like --boot, with its checkpoints vk_driver_cache_env(); // before the threads below and rt_boot's, any of which may load the Vulkan driver discord_init(); // the Rich Presence thread (discord_rpc.c); it reads nx2navi.ini itself and idles while off + coop_game_init(); // co-op's game side (coop_game.c), before the thread that hands it messages + coop_init(); // the co-op thread (coop.c); the same, idle while the COOP setting is off rt_boot(); return 0; } diff --git a/runtime/nvn_api_obj.c b/runtime/nvn_api_obj.c index b30d3b5f..30193af2 100644 --- a/runtime/nvn_api_obj.c +++ b/runtime/nvn_api_obj.c @@ -12,6 +12,7 @@ #include "gfx.h" #include "cfg.h" +#include "coop_game.h" #include "host.h" #include "nvn_api.h" #include "nvn_hmap.h" @@ -873,6 +874,7 @@ NVN_API(nvnQueuePresentTexture) { int idx = (int)arg_x(c, 2); movie_tick(c); // ov_movie.c: hand over decoded movie frames that are due; needs the core, so before the wait res_present(c); // resolution.c: a DLSS mode change sets the game's render size again, between frames + coop_present(c); // coop_game.c: co-op reads Link and the game's flags and sets the flags the room has, between frames wide_present(); // widescreen.c: Ocarina's DLSS render scale NVN_BLOCKING(); if (o->magic != NVN_WIN_MAGIC || idx < 0 || idx >= o->ntex || idx >= 4 || !o->tex[idx]) diff --git a/runtime/steam.c b/runtime/steam.c new file mode 100644 index 00000000..9219fb52 --- /dev/null +++ b/runtime/steam.c @@ -0,0 +1,474 @@ +// Steam for co-op (steam.h): the Steamworks library loaded at run time and used through its C entry points. +// +// The library. steam_api64.dll exports one plain C function per method of each interface ("the flat API"): +// SteamAPI_ISteamMatchmaking_CreateLobby(self, ...), with self from an accessor whose name carries the interface's +// version (SteamAPI_SteamMatchmaking_v009). A library of another age exports other accessor versions, so each accessor +// is looked for under the versions known to have the calls below with these parameters, newest first; a library that +// lacks one of them, the manual dispatch calls or the networking messages interface (before 2020) is refused as too +// old. Nothing of the library's headers is used: the declarations here are the documented parameters of each call, a +// CSteamID passed and returned as the 64-bit number it is, a bool as one byte. +// +// The app id. The library signs in as the app SteamAppId names in the environment, set here to 480 before it loads: +// Steam's test app, which every account owns. A game started from Steam as a non-Steam shortcut has SteamGameId set +// to the shortcut's own number; both are set, so the library does not take the shortcut for the app. +// +// Callbacks. With manual dispatch the library queues what happened and steam_pump takes it out: a callback is a +// number and a block of bytes whose layout is fixed per number (8-byte packing on Windows). The numbers and offsets +// used are in the enum below; an asynchronous call (CreateLobby, JoinLobby) ends in callback 703, which names the +// call and the callback that holds its result. +// +// Messages. ISteamNetworkingMessages sends datagrams to a Steam id; Steam opens the session, finds a direct path or +// relays through its own network, encrypts, and vouches for the sender's id. A session a stranger opens is accepted +// only when that id is in the room, and a message is handed out only when its sender is. +#include +#include +#include + +#include "host.h" +#include "platform/platform.h" +#include "steam.h" + +#ifdef _WIN32 +#define STEAM_LIB "steam_api64.dll" +#else +#define STEAM_LIB "libsteam_api.so" +#endif + +enum { + CB_SERVERS_DISCONNECTED = 103, + CB_LOBBY_JOIN_REQUESTED = 333, // u64 lobby, u64 friend + CB_SHUTDOWN = 704, // Steam is closing + CB_CALL_COMPLETED = 703, // u64 call, i32 callback, u32 size + CB_LOBBY_INVITE = 503, // u64 user, u64 lobby, u64 game + CB_LOBBY_ENTER = 504, // u64 lobby, u32 permissions, u8 locked, u32 response at 16 + CB_LOBBY_CHAT_UPDATE = 506, // u64 lobby, u64 user changed, u64 user making the change, u32 change at 24 + CB_LOBBY_CREATED = 513, // i32 result, u64 lobby at 8 + CB_SESSION_REQUEST = 1251, // the identity of who asks + RESULT_OK = 1, + ENTER_OK = 1, ENTER_NO_ROOM = 2, ENTER_NOT_ALLOWED = 3, ENTER_FULL = 4, + CHANGE_ENTERED = 1, // the other bits: left, disconnected, kicked, banned + LOBBY_FRIENDS_ONLY = 1, // friends see and may join it; anyone else needs an invite or its number + FRIENDS_IMMEDIATE = 4, // the flag for "the player's friends" + SEND_UNRELIABLE_NO_DELAY = 5, SEND_RELIABLE = 8, SEND_AUTO_RESTART = 32, + IDENTITY_SIZE = 136, // SteamNetworkingIdentity + MSG_DATA = 0, MSG_SIZE = 8, MSG_PEER = 16, // SteamNetworkingMessage_t: void *data, i32 size, u32 conn, identity + CHANNEL = 0, + RECEIVE_BATCH = 32, + CALL_RESULT_CAP = 64, +}; + +typedef struct { int32_t user, id; uint8_t *param; int32_t size; } CallbackMsg; + +static struct { + void *lib; + int up; + int32_t pipe; + void *user, *friends, *mm, *utils, *msgs; + uint64_t self, room, call; // call: the CreateLobby or JoinLobby that has not answered yet + int creating; + // the library + void (*shutdown)(void); + int32_t (*get_pipe)(void); + void (*md_frame)(int32_t); + uint8_t (*md_next)(int32_t, CallbackMsg *); + void (*md_free)(int32_t); + uint8_t (*md_result)(int32_t, uint64_t, void *, int, int, uint8_t *); + uint64_t (*get_id)(void *); + uint8_t (*overlay)(void *); + const char *(*persona_of)(void *, uint64_t); + const char *(*persona)(void *); + int (*friend_count)(void *, int); + uint64_t (*friend_at)(void *, int, int); + int (*friend_state)(void *, uint64_t); + uint8_t (*friend_game)(void *, uint64_t, void *); + uint8_t (*has_friend)(void *, uint64_t, int); + void (*invite_dialog)(void *, uint64_t); + uint64_t (*create)(void *, int, int); + uint64_t (*join)(void *, uint64_t); + void (*leave)(void *, uint64_t); + uint8_t (*invite)(void *, uint64_t, uint64_t); + uint8_t (*set_data)(void *, uint64_t, const char *, const char *); + const char *(*get_data)(void *, uint64_t, const char *); + int (*member_count)(void *, uint64_t); + uint64_t (*member_at)(void *, uint64_t, int); + uint64_t (*owner)(void *, uint64_t); + int (*send)(void *, const void *, const void *, uint32_t, int, int); + int (*receive)(void *, int, void **, int); + uint8_t (*accept)(void *, const void *); + uint8_t (*close_session)(void *, const void *); + void (*msg_release)(void *); + void (*ident_clear)(void *); + void (*ident_set)(void *, uint64_t); + uint64_t (*ident_get)(void *); +} S; + +static void *sym(const char *name) { return plat_lib_sym(S.lib, name); } + +// The accessor of an interface under the first of the version names the library has; NULL: none. +static void *interface_of(const char *const *names) { + for (; *names; names++) { + void *(*get)(void) = sym(*names); + if (get) return get(); + } + return NULL; +} + +static int fail(char *why, size_t cap, int *which, int code, const char *text) { + snprintf(why, cap, "%s", text); + if (which) *which = code; + return 0; +} + +int steam_up(void) { return S.up; } +uint64_t steam_self(void) { return S.self; } +uint64_t steam_room(void) { return S.room; } + +int steam_start(char *why, size_t cap, int *which) { + if (S.up) return 1; + if (which) *which = STEAM_WHY_OK; + if (!S.lib) { + // beside the game's exe, nowhere else: a path from a settings file would load whatever file a stranger's + // nx2navi.ini names + char path[PLAT_PATH_MAX], exe[PLAT_PATH_MAX]; + if (!plat_exe_path(exe, sizeof exe)) return fail(why, cap, which, STEAM_WHY_NO_LIBRARY, "the game's folder is not known"); + char *sep = plat_last_sep(exe); + if (sep) *sep = 0; + snprintf(path, sizeof path, "%s/%s", exe, STEAM_LIB); + if (!plat_file_exists(path)) + return fail(why, cap, which, STEAM_WHY_NO_LIBRARY, STEAM_LIB " is not beside the game"); + plat_setenv("SteamAppId", "480"); + plat_setenv("SteamGameId", "480"); + S.lib = plat_lib_open(path); + if (!S.lib) return fail(why, cap, which, STEAM_WHY_NO_LIBRARY, STEAM_LIB " beside the game does not load"); + } +#define NEED(field, name) \ + if (!(S.field = sym(name))) return fail(why, cap, which, STEAM_WHY_OLD_LIBRARY, STEAM_LIB " is too old: it lacks " name); + void (*md_init)(void) = sym("SteamAPI_ManualDispatch_Init"); + if (!md_init) return fail(why, cap, which, STEAM_WHY_OLD_LIBRARY, STEAM_LIB " is too old: it lacks SteamAPI_ManualDispatch_Init"); + NEED(shutdown, "SteamAPI_Shutdown") NEED(get_pipe, "SteamAPI_GetHSteamPipe") + NEED(md_frame, "SteamAPI_ManualDispatch_RunFrame") NEED(md_next, "SteamAPI_ManualDispatch_GetNextCallback") + NEED(md_free, "SteamAPI_ManualDispatch_FreeLastCallback") NEED(md_result, "SteamAPI_ManualDispatch_GetAPICallResult") + NEED(get_id, "SteamAPI_ISteamUser_GetSteamID") NEED(overlay, "SteamAPI_ISteamUtils_IsOverlayEnabled") + NEED(persona_of, "SteamAPI_ISteamFriends_GetFriendPersonaName") NEED(persona, "SteamAPI_ISteamFriends_GetPersonaName") + NEED(friend_count, "SteamAPI_ISteamFriends_GetFriendCount") NEED(friend_at, "SteamAPI_ISteamFriends_GetFriendByIndex") + NEED(friend_state, "SteamAPI_ISteamFriends_GetFriendPersonaState") NEED(friend_game, "SteamAPI_ISteamFriends_GetFriendGamePlayed") + NEED(has_friend, "SteamAPI_ISteamFriends_HasFriend") NEED(invite_dialog, "SteamAPI_ISteamFriends_ActivateGameOverlayInviteDialog") + NEED(create, "SteamAPI_ISteamMatchmaking_CreateLobby") NEED(join, "SteamAPI_ISteamMatchmaking_JoinLobby") + NEED(leave, "SteamAPI_ISteamMatchmaking_LeaveLobby") NEED(invite, "SteamAPI_ISteamMatchmaking_InviteUserToLobby") + NEED(set_data, "SteamAPI_ISteamMatchmaking_SetLobbyData") NEED(get_data, "SteamAPI_ISteamMatchmaking_GetLobbyData") + NEED(member_count, "SteamAPI_ISteamMatchmaking_GetNumLobbyMembers") NEED(member_at, "SteamAPI_ISteamMatchmaking_GetLobbyMemberByIndex") + NEED(owner, "SteamAPI_ISteamMatchmaking_GetLobbyOwner") + NEED(send, "SteamAPI_ISteamNetworkingMessages_SendMessageToUser") NEED(receive, "SteamAPI_ISteamNetworkingMessages_ReceiveMessagesOnChannel") + NEED(accept, "SteamAPI_ISteamNetworkingMessages_AcceptSessionWithUser") NEED(close_session, "SteamAPI_ISteamNetworkingMessages_CloseSessionWithUser") + NEED(msg_release, "SteamAPI_SteamNetworkingMessage_t_Release") NEED(ident_clear, "SteamAPI_SteamNetworkingIdentity_Clear") + NEED(ident_set, "SteamAPI_SteamNetworkingIdentity_SetSteamID64") NEED(ident_get, "SteamAPI_SteamNetworkingIdentity_GetSteamID64") +#undef NEED + // signing in: the newest entry point says why it failed, the older ones only that they did + int (*init_flat)(char *) = sym("SteamAPI_InitFlat"); + uint8_t (*init_safe)(void) = sym("SteamAPI_InitSafe"); + uint8_t (*init_old)(void) = sym("SteamAPI_Init"); + char err[1024] = ""; + int ok = init_flat ? init_flat(err) == 0 : init_safe ? init_safe() : init_old ? init_old() : 0; + if (!ok) { + char text[200]; + snprintf(text, sizeof text, "Steam did not answer: is it running and signed in?%s%.100s", *err ? " Steam says: " : "", err); + return fail(why, cap, which, STEAM_WHY_NO_CLIENT, text); + } + md_init(); + S.user = interface_of((const char *const[]){"SteamAPI_SteamUser_v023", "SteamAPI_SteamUser_v022", "SteamAPI_SteamUser_v021", + "SteamAPI_SteamUser_v020", NULL}); + S.friends = interface_of((const char *const[]){"SteamAPI_SteamFriends_v018", "SteamAPI_SteamFriends_v017", NULL}); + S.mm = interface_of((const char *const[]){"SteamAPI_SteamMatchmaking_v009", NULL}); + S.utils = interface_of((const char *const[]){"SteamAPI_SteamUtils_v010", "SteamAPI_SteamUtils_v009", NULL}); + S.msgs = interface_of((const char *const[]){"SteamAPI_SteamNetworkingMessages_SteamAPI_v002", NULL}); + if (!S.user || !S.friends || !S.mm || !S.utils || !S.msgs) { + S.shutdown(); + return fail(why, cap, which, STEAM_WHY_OLD_LIBRARY, STEAM_LIB " is too old or too new: an interface this version knows is missing"); + } + // Steam's relay network takes a few seconds to measure its routes: started now, the first message does not wait + void *nu = interface_of((const char *const[]){"SteamAPI_SteamNetworkingUtils_SteamAPI_v004", + "SteamAPI_SteamNetworkingUtils_SteamAPI_v003", NULL}); + void (*relay_init)(void *) = sym("SteamAPI_ISteamNetworkingUtils_InitRelayNetworkAccess"); + if (nu && relay_init) relay_init(nu); + S.pipe = S.get_pipe(); + S.self = S.get_id(S.user); + S.room = S.call = 0; + S.up = 1; + return 1; +} + +void steam_stop(void) { + if (!S.up) return; + steam_room_leave(); + S.shutdown(); + S.up = 0; +} + +void steam_name_of(uint64_t id, char *out, size_t cap) { + const char *name = !S.up ? "" : id == S.self ? S.persona(S.friends) : S.persona_of(S.friends, id); + // Steam answers "[unknown]" for a player whose name it has not fetched yet + snprintf(out, cap, "%s", name && strcmp(name, "[unknown]") ? name : ""); +} + +int steam_is_friend(uint64_t id) { return S.up && S.has_friend(S.friends, id, FRIENDS_IMMEDIATE); } +int steam_overlay(void) { return S.up && S.overlay(S.utils); } + +int steam_room_create(int max_players) { + if (!S.up || S.room || S.call) return 0; + S.call = S.create(S.mm, LOBBY_FRIENDS_ONLY, max_players); + S.creating = 1; + return S.call != 0; +} + +int steam_room_join(uint64_t room) { + if (!S.up || S.room || S.call || !room) return 0; + S.call = S.join(S.mm, room); + S.creating = 0; + return S.call != 0; +} + +static void identity_of(uint8_t ident[IDENTITY_SIZE], uint64_t id) { + S.ident_clear(ident); + S.ident_set(ident, id); +} + +void steam_room_leave(void) { + if (!S.up || !S.room) return; + uint64_t ids[STEAM_ROOM_MAX]; + int n = steam_room_members(ids, STEAM_ROOM_MAX); + for (int i = 0; i < n; i++) { + if (ids[i] == S.self) continue; + uint8_t ident[IDENTITY_SIZE]; + identity_of(ident, ids[i]); + S.close_session(S.msgs, ident); + } + S.leave(S.mm, S.room); + S.room = 0; +} + +uint64_t steam_room_owner(void) { return S.up && S.room ? S.owner(S.mm, S.room) : 0; } + +int steam_room_members(uint64_t *out, int max) { + if (!S.up || !S.room) return 0; + int n = S.member_count(S.mm, S.room); + if (n > max) n = max; + for (int i = 0; i < n; i++) out[i] = S.member_at(S.mm, S.room, i); + return n; +} + +static int in_room(uint64_t id) { + uint64_t ids[STEAM_ROOM_MAX]; + int n = steam_room_members(ids, STEAM_ROOM_MAX); + for (int i = 0; i < n; i++) + if (ids[i] == id) return 1; + return 0; +} + +int steam_room_set(const char *key, const char *value) { return S.up && S.room && S.set_data(S.mm, S.room, key, value); } + +void steam_room_get(const char *key, char *out, size_t cap) { + const char *v = S.up && S.room ? S.get_data(S.mm, S.room, key) : NULL; + snprintf(out, cap, "%s", v ? v : ""); +} + +static int friend_rank(const SteamFriend *f) { return f->in_app ? 0 : f->online ? 1 : 2; } +static int friend_cmp(const void *a, const void *b) { + const SteamFriend *x = a, *y = b; + int d = friend_rank(x) - friend_rank(y); + return d ? d : strcmp(x->name, y->name); +} + +int steam_friends(SteamFriend *out, int max) { + if (!S.up) return 0; + int total = S.friend_count(S.friends, FRIENDS_IMMEDIATE), n = 0; + for (int i = 0; i < total && n < max; i++) { + SteamFriend *f = &out[n]; + f->id = S.friend_at(S.friends, i, FRIENDS_IMMEDIATE); + steam_name_of(f->id, f->name, sizeof f->name); + if (!f->name[0]) continue; + f->online = S.friend_state(S.friends, f->id) != 0; + // FriendGameInfo_t: u64 game id (the app in its low 24 bits), u32 address, u16 and u16 ports, u64 lobby + uint8_t game[24] = {0}; + uint64_t game_id = 0; + if (S.friend_game(S.friends, f->id, game)) memcpy(&game_id, game, 8); + f->in_app = (game_id & 0xffffff) == STEAM_APP_ID; + n++; + } + qsort(out, (size_t)n, sizeof *out, friend_cmp); + return n; +} + +int steam_invite(uint64_t friend_id) { return S.up && S.room && S.invite(S.mm, S.room, friend_id); } +void steam_invite_window(void) { + if (S.up && S.room) S.invite_dialog(S.friends, S.room); +} + +int steam_send(uint64_t to, const void *data, size_t n, int reliable) { + if (!S.up || !S.room || n > STEAM_MESSAGE_MAX) return 0; + uint8_t ident[IDENTITY_SIZE]; + identity_of(ident, to); + // a session that broke (the other player's connection dropped for a moment) is opened again by the next message + int flags = (reliable ? SEND_RELIABLE : SEND_UNRELIABLE_NO_DELAY) | SEND_AUTO_RESTART; + return S.send(S.msgs, ident, data, (uint32_t)n, flags, CHANNEL) == RESULT_OK; +} + +static uint64_t u64_at(const uint8_t *p, size_t off) { + uint64_t v; + memcpy(&v, p + off, 8); + return v; +} +static uint32_t u32_at(const uint8_t *p, size_t off) { + uint32_t v; + memcpy(&v, p + off, 4); + return v; +} + +static void entered(uint64_t room, uint32_t response, void (*on)(const SteamEvent *, void *), void *user) { + S.call = 0; + if (response == ENTER_OK) { + S.room = room; + on(&(SteamEvent){.kind = STEAM_EV_ROOM_ENTERED, .a = room}, user); + } else { + int code = response == ENTER_NO_ROOM ? STEAM_FAIL_NO_ROOM : response == ENTER_FULL ? STEAM_FAIL_FULL + : response == ENTER_NOT_ALLOWED ? STEAM_FAIL_REFUSED : STEAM_FAIL_OTHER; + on(&(SteamEvent){.kind = STEAM_EV_ROOM_FAILED, .code = code}, user); + } +} + +static void callback(int id, const uint8_t *p, int size, void (*on)(const SteamEvent *, void *), void *user) { + switch (id) { + case CB_CALL_COMPLETED: { + if (size < 16) break; + uint64_t call = u64_at(p, 0); + int32_t result_id = (int32_t)u32_at(p, 8); + uint32_t n = u32_at(p, 12); + if (call != S.call || n > CALL_RESULT_CAP) break; // a call of the library's own + uint8_t r[CALL_RESULT_CAP] = {0}, failed = 0; + if (!S.md_result(S.pipe, call, r, (int)n, result_id, &failed) || failed) { + S.call = 0; + on(&(SteamEvent){.kind = STEAM_EV_ROOM_FAILED, .code = S.creating ? STEAM_FAIL_CREATE : STEAM_FAIL_OTHER}, user); + } else if (result_id == CB_LOBBY_CREATED && n >= 16) { + if (u32_at(r, 0) == RESULT_OK) { + entered(u64_at(r, 8), ENTER_OK, on, user); + } else { + S.call = 0; + on(&(SteamEvent){.kind = STEAM_EV_ROOM_FAILED, .code = STEAM_FAIL_CREATE}, user); + } + } else if (result_id == CB_LOBBY_ENTER && n >= 20) { + entered(u64_at(r, 0), u32_at(r, 16), on, user); + } + break; + } + case CB_LOBBY_CHAT_UPDATE: + if (size >= 28 && u64_at(p, 0) == S.room && u64_at(p, 8) != S.self) { + uint64_t who = u64_at(p, 8); + int came = u32_at(p, 24) == CHANGE_ENTERED; + if (!came) { + uint8_t ident[IDENTITY_SIZE]; + identity_of(ident, who); + S.close_session(S.msgs, ident); + } + on(&(SteamEvent){.kind = came ? STEAM_EV_MEMBER_JOINED : STEAM_EV_MEMBER_LEFT, .a = who}, user); + } + break; + case CB_LOBBY_INVITE: + if (size >= 24 && (u64_at(p, 16) & 0xffffff) == STEAM_APP_ID) + on(&(SteamEvent){.kind = STEAM_EV_INVITED, .a = u64_at(p, 8), .b = u64_at(p, 0)}, user); + break; + case CB_LOBBY_JOIN_REQUESTED: + if (size >= 16) on(&(SteamEvent){.kind = STEAM_EV_JOIN_ASKED, .a = u64_at(p, 0), .b = u64_at(p, 8)}, user); + break; + case CB_SESSION_REQUEST: + // only a player in the room may open a session: anyone on Steam can ask + if (size >= IDENTITY_SIZE) { + uint8_t ident[IDENTITY_SIZE]; + memcpy(ident, p, IDENTITY_SIZE); + if (in_room(S.ident_get(ident))) S.accept(S.msgs, ident); + } + break; + case CB_SERVERS_DISCONNECTED: + case CB_SHUTDOWN: + if (S.room) { + S.room = S.call = 0; + on(&(SteamEvent){.kind = STEAM_EV_LOST}, user); + } + break; + } +} + +void steam_pump(void (*on)(const SteamEvent *e, void *user), void *user) { + if (!S.up) return; + S.md_frame(S.pipe); + CallbackMsg m; + while (S.md_next(S.pipe, &m)) { + // the block is the library's until it is freed, and a handler may call the library: copy first + uint8_t copy[512]; + int size = m.size < 0 ? 0 : m.size > (int)sizeof copy ? (int)sizeof copy : m.size; + if (size) memcpy(copy, m.param, (size_t)size); + int id = m.id; + S.md_free(S.pipe); + callback(id, copy, size, on, user); + if (!S.up) return; + } + for (;;) { + void *batch[RECEIVE_BATCH]; + int n = S.receive(S.msgs, CHANNEL, batch, RECEIVE_BATCH); + for (int i = 0; i < n; i++) { + const uint8_t *msg = batch[i]; + const uint8_t *data; + int32_t size; + uint8_t ident[IDENTITY_SIZE]; + memcpy(&data, msg + MSG_DATA, sizeof data); + memcpy(&size, msg + MSG_SIZE, 4); + memcpy(ident, msg + MSG_PEER, IDENTITY_SIZE); + uint64_t from = S.ident_get(ident); + if (size > 0 && size <= STEAM_MESSAGE_MAX && from && from != S.self && in_room(from)) + on(&(SteamEvent){.kind = STEAM_EV_MESSAGE, .a = from, .data = data, .n = (size_t)size}, user); + S.msg_release(batch[i]); + } + if (n < RECEIVE_BATCH) break; + } +} + +// ---- room ids +// +// Every lobby's 64-bit number starts with the same 32 bits (universe 1, the chat type, the lobby flag: 0x01860000); the +// other 32 name the lobby. A room id is those 32 bits and an 8-bit check of them, 40 bits as 8 symbols of 5 bits. + +#define LOBBY_HIGH 0x01860000ull +static const char code_symbols[] = "23456789ABCDEFGHJKLMNPQRSTUVWXYZ"; // no 0, 1, I or O + +static uint32_t code_check(uint32_t low) { + uint32_t h = low * 2654435761u; + return (h >> 24) & 0xff; +} + +void steam_code_make(uint64_t room, char out[STEAM_CODE_CAP]) { + out[0] = 0; + if (room >> 32 != LOBBY_HIGH) return; // a lobby of a kind this version does not know: it has no room id + uint32_t low = (uint32_t)room; + uint64_t v = (uint64_t)low << 8 | code_check(low); + int o = 0; + for (int i = 7; i >= 0; i--) { + out[o++] = code_symbols[(v >> (5 * i)) & 31]; + if (i == 4) out[o++] = '-'; + } + out[o] = 0; +} + +uint64_t steam_code_parse(const char *text) { + uint64_t v = 0; + int n = 0; + for (; *text; text++) { + char c = *text; + if (c == '-' || c == ' ' || c == '\t') continue; + if (c >= 'a' && c <= 'z') c = (char)(c - 'a' + 'A'); + const char *at = strchr(code_symbols, c); + if (!at || !c || ++n > 8) return 0; + v = v << 5 | (uint64_t)(at - code_symbols); + } + if (n != 8) return 0; + uint32_t low = (uint32_t)(v >> 8); + if ((v & 0xff) != code_check(low)) return 0; + return LOBBY_HIGH << 32 | low; +} diff --git a/runtime/steam.h b/runtime/steam.h new file mode 100644 index 00000000..fdca12d1 --- /dev/null +++ b/runtime/steam.h @@ -0,0 +1,83 @@ +// Steam for co-op (steam.c): rooms are Steam lobbies, players are invited through Steam, and the games talk through +// Steam's networking, so nobody forwards a port and nobody runs a server. NX2navi is no Steam app of its own: it signs +// in as Steam's public test app (id 480, "Spacewar"), which every account may use; Steam then shows the player as +// playing that app. +// +// The Steamworks library is not part of NX2navi and is never in its repository. steam.c declares the functions it +// calls itself and loads steam_api64.dll from beside the game at run time; without the file, or without a running +// Steam client that is signed in, steam_start fails and says why. +// +// Every function here is called from one thread (the co-op thread, coop.c): the library is used single-threaded. +#pragma once + +#include +#include + +enum { STEAM_APP_ID = 480, STEAM_NAME_CAP = 64, STEAM_ROOM_MAX = 8, STEAM_MESSAGE_MAX = 1200 }; + +typedef enum { + STEAM_EV_ROOM_ENTERED, // a: the room. This game made or joined it + STEAM_EV_ROOM_FAILED, // code: why (STEAM_FAIL_*) + STEAM_EV_MEMBER_JOINED, // a: the player's id + STEAM_EV_MEMBER_LEFT, // a: the player's id + STEAM_EV_INVITED, // a: the room, b: the friend who invites. Shown to the player, who may join + STEAM_EV_JOIN_ASKED, // a: the room. The player accepted an invite, or chose Join Game, in Steam itself + STEAM_EV_MESSAGE, // a: the sender, data and n: the message. Only from players in the room + STEAM_EV_LOST, // Steam lost its connection or closed: the room is gone +} SteamEventKind; + +enum { STEAM_FAIL_CREATE = 1, STEAM_FAIL_NO_ROOM, STEAM_FAIL_FULL, STEAM_FAIL_REFUSED, STEAM_FAIL_OTHER }; + +typedef struct { + SteamEventKind kind; + uint64_t a, b; + int code; + const uint8_t *data; + size_t n; +} SteamEvent; + +typedef struct { + uint64_t id; + char name[STEAM_NAME_CAP]; + int online; // signed in to Steam now + int in_app; // shown as playing app 480: probably in NX2navi with co-op on, so an invite can reach the game +} SteamFriend; + +// Loads the library, signs in as app 480 and takes the interfaces. 1 when Steam is up; 0 with the reason in why (a +// sentence for the log and the menu's status line; STEAM_WHY_* says which, for the menu's own text). +enum { STEAM_WHY_OK, STEAM_WHY_NO_LIBRARY, STEAM_WHY_OLD_LIBRARY, STEAM_WHY_NO_CLIENT, STEAM_WHY_OTHER_OS }; +int steam_start(char *why, size_t cap, int *which); +void steam_stop(void); // leaves the room and signs out +int steam_up(void); + +uint64_t steam_self(void); +void steam_name_of(uint64_t id, char *out, size_t cap); // the player's Steam name; "" while Steam has not got it +int steam_is_friend(uint64_t id); +int steam_overlay(void); // Steam's overlay is in this game (it was started from Steam): its invite window works + +// Rooms. Create and join answer later with STEAM_EV_ROOM_ENTERED or STEAM_EV_ROOM_FAILED. +int steam_room_create(int max_players); +int steam_room_join(uint64_t room); +void steam_room_leave(void); +uint64_t steam_room(void); // 0: in none +uint64_t steam_room_owner(void); // whose game made it; Steam hands it to another member when that player leaves +int steam_room_members(uint64_t *out, int max); +int steam_room_set(const char *key, const char *value); // the owner's notes on the room, read by everyone +void steam_room_get(const char *key, char *out, size_t cap); + +int steam_friends(SteamFriend *out, int max); // the player's friends, those in the app first, then online, then the rest +int steam_invite(uint64_t friend_id); // Steam shows the friend an invite to this room +void steam_invite_window(void); // Steam's own invite window (only with steam_overlay) + +// A message to a player in the room. reliable: it arrives, in order; else it may be lost and is never late. +int steam_send(uint64_t to, const void *data, size_t n, int reliable); + +// Runs Steam's callbacks and hands out what happened. Call it many times a second. +void steam_pump(void (*on)(const SteamEvent *e, void *user), void *user); + +// A room's id as players pass it on, "XXXX-XXXX": the part of the lobby's number that differs between lobbies and a +// check of it, in letters and digits that cannot be mixed up (no 0, 1, I or O). steam_code_parse takes it in any case, with or +// without the dash and spaces; 0 when it is no room id. +enum { STEAM_CODE_CAP = 16 }; +void steam_code_make(uint64_t room, char out[STEAM_CODE_CAP]); +uint64_t steam_code_parse(const char *text); diff --git a/runtime/svc.c b/runtime/svc.c index 39d4840f..7ce3955a 100644 --- a/runtime/svc.c +++ b/runtime/svc.c @@ -5,6 +5,7 @@ #include #include +#include "coop.h" #include "fs.h" #include "host.h" #include "kernel.h" @@ -243,6 +244,7 @@ static void svc_body(Cpu *c, uint32_t imm, uint64_t pc) { // profile saved, logs flushed, exit code 0 char at[160]; rt_log("guest ExitProcess at %s; exiting", ldr_describe(pc, at, sizeof at)); + coop_shutdown(); // leaves the room, before the process ends fs_save_flush(); vk_pipeline_prewarm_marker_clear(); // as the window's close (gfx_present.c gfx_window_closed) vk_pipeline_save_exit(); diff --git a/runtime/ui/coop_page.cpp b/runtime/ui/coop_page.cpp new file mode 100644 index 00000000..34887965 --- /dev/null +++ b/runtime/ui/coop_page.cpp @@ -0,0 +1,527 @@ +// The menu's Co-op tab and co-op's drawing over the game (ui/coop_page.h). +// +// The page reads the co-op thread's view once a frame (coop_view) and hands it commands (coop_create, coop_join, ...); +// nothing here waits for Steam. What the page shows follows the view's state: off, Steam missing, in no room, on the +// way into one, in one. A press that turns co-op on and wants a room at once (Create a room while co-op is off) is +// kept for a few seconds until the thread has reached Steam. +// +// Names over the game: a player's position is projected with the frame's camera as the upscaler's pass knows it +// (vk_dlaa_fg_camera: position, right, up and forward in the world's metres, the vertical field of view and the +// aspect). Without a temporal upscaler there is no camera and no names; the player list still says where each is. +#include +#include +#include +#include + +#include "imgui.h" +#include "imgui_internal.h" +#include "menu_sound.h" +#include "ui/coop_page.h" +#include "ui/menu_skin.h" +#include "ui/option_rows.h" + +extern "C" { +#include "cfg.h" +#include "coop.h" +#include "platform/platform.h" +#include "ui/menu.h" +#include "ui_text.h" +#include "vk_dlaa.h" +} + +enum Page { P_NONE, P_JOIN, P_CHAT, P_INVITE, P_REMOVE, P_LEAVE }; +enum { FIELD_CAP = COOP_CHAT_CAP + 1, PASTE_FRAMES = 120, PENDING_MS = 8000, CHAT_SHOWN_MS = 8000, CHAT_FADE_MS = 1000 }; + +static bool g_open, g_window_shown, g_page_new, g_by_pad; +static int g_page; +static char g_field[FIELD_CAP]; +static bool g_field_bad, g_paste_empty; +static int g_paste_wait; // frames left to wait for the clipboard's text (gfx_window_paste) +static char g_return[48]; // the row the cursor goes back to when the window closes +static CoopView g_view; // this frame's copy of the layer's state +static int g_layout = -1; // the page's last kind, to move the cursor when its rows change +static uint64_t g_copied_at; // when the room ID was last copied +static uint64_t g_remove_id; +static char g_remove_name[COOP_NAME_CAP]; +static char g_invited_name[COOP_NAME_CAP]; // the friend the last invite went to +static uint64_t g_invited_at; +static SteamFriend g_friends[COOP_FRIENDS]; +static int g_nfriends; +// a command that waits for co-op to come up: 1 create, 2 join g_pending_code +static int g_pending; +static char g_pending_code[STEAM_CODE_CAP]; +static uint64_t g_pending_until; + +static bool in_room(void) { return g_view.state == COOP_IN_ROOM; } + +static UiTextId note_text(CoopNote n) { + switch (n) { + case COOP_NOTE_NO_LIBRARY: return UI_MENU_COOP_NO_LIBRARY; + case COOP_NOTE_OLD_LIBRARY: return UI_MENU_COOP_OLD_LIBRARY; + case COOP_NOTE_NO_CLIENT: + case COOP_NOTE_OTHER_OS: return UI_MENU_COOP_NO_CLIENT; + case COOP_NOTE_CREATE_FAILED: return UI_MENU_COOP_N_CREATE_FAILED; + case COOP_NOTE_NO_ROOM: + case COOP_NOTE_BAD_CODE: return UI_MENU_COOP_N_NO_ROOM; + case COOP_NOTE_FULL: return UI_MENU_COOP_N_FULL; + case COOP_NOTE_REFUSED: return UI_MENU_COOP_N_REFUSED; + case COOP_NOTE_NOT_OURS: return UI_MENU_COOP_N_NOT_OURS; + case COOP_NOTE_OTHER_VERSION: return UI_MENU_COOP_N_OTHER_VERSION; + case COOP_NOTE_REMOVED: return UI_MENU_COOP_N_REMOVED; + case COOP_NOTE_HOST_SILENT: return UI_MENU_COOP_N_HOST_SILENT; + case COOP_NOTE_LOST: return UI_MENU_COOP_N_LOST; + case COOP_NOTE_LEFT: return UI_MENU_COOP_N_LEFT; + default: return UI_TEXT_COUNT; + } +} + +// Create or join, turning co-op on first when it is off: the command then waits for the thread to reach Steam. +static void want_room(int what, const char *code) { + if (g_view.state == COOP_READY) { + if (what == 1) coop_create(); + else coop_join(code); + return; + } + if (g_view.state == COOP_OFF) opt_apply("NX2NAVI_COOP", "1"); + g_pending = what; + snprintf(g_pending_code, sizeof g_pending_code, "%s", code ? code : ""); + g_pending_until = plat_now_ms() + PENDING_MS; +} + +static void pending_tick(void) { + if (!g_pending) return; + if (g_view.state == COOP_READY) { + if (g_pending == 1) coop_create(); + else coop_join(g_pending_code); + g_pending = 0; + } else if (g_view.state == COOP_NO_STEAM || plat_now_ms() > g_pending_until) { + g_pending = 0; // the page says why Steam is not there + } +} + +static void open_window(int page, const char *ret) { + g_open = true, g_page = page, g_page_new = true; + g_by_pad = ImGui::IsKeyDown(ImGuiKey_GamepadFaceDown); // a pad's A opened it: no keyboard to type with + g_field_bad = g_paste_empty = false, g_paste_wait = 0; + g_field[0] = 0; + snprintf(g_return, sizeof g_return, "%s", ret); +} + +static void settings_rows(void) { + opt_group(UI_MENU_COOP_SETTINGS); + opt_toggle("NX2NAVI_COOP_SHARE", UI_MENU_COOP_SHARE, UI_MENU_COOP_SHARE_DESC); + opt_toggle("NX2NAVI_COOP_NAMES", UI_MENU_COOP_NAMES, UI_MENU_COOP_NAMES_DESC); + opt_toggle("NX2NAVI_COOP_CHAT", UI_MENU_COOP_CHAT_SHOW, UI_MENU_COOP_CHAT_SHOW_DESC); + opt_toggle("NX2NAVI_COOP", UI_MENU_COOP_ON, UI_MENU_COOP_ON_DESC); +} + +static void chat_text(const CoopChatLine &l, char *out, size_t cap) { + if (l.notice) snprintf(out, cap, menu_text(l.joined ? UI_MENU_COOP_CHAT_JOINED : UI_MENU_COOP_CHAT_LEFT), l.name); + else snprintf(out, cap, "%s: %s", l.name, l.text); +} + +static void rows_out(void) { + if (g_view.state == COOP_OFF && !g_pending) { + opt_toggle("NX2NAVI_COOP", UI_MENU_COOP_ON, UI_MENU_COOP_ON_DESC); + return; + } + if (g_view.local) opt_text(UI_MENU_COOP_LOCAL); + if (g_view.state == COOP_NO_STEAM) { + const UiTextId why = note_text(g_view.note); + if (why != UI_TEXT_COUNT) opt_text(why, true); + if (opt_button("##coop_retry", UI_MENU_COOP_RETRY, UI_MENU_COOP_RETRY_DESC)) coop_retry(); + settings_rows(); + return; + } + if (g_view.state == COOP_ENTERING || g_pending) { + if (opt_button("##coop_stop", UI_MENU_COOP_STOP, UI_MENU_COOP_STOP_DESC)) { + g_pending = 0; + coop_leave(); + } + opt_text(UI_MENU_COOP_JOINING); + return; + } + if (g_view.invite_room) { + char line[COOP_NAME_CAP + 96]; + snprintf(line, sizeof line, menu_text(UI_MENU_COOP_INVITED), g_view.invite_from); + opt_text_str(line); + if (opt_button("##coop_invited_join", UI_MENU_COOP_INVITED_JOIN, UI_MENU_COOP_INVITED_JOIN_DESC)) coop_join_invite(); + if (opt_button("##coop_invited_no", UI_MENU_COOP_INVITED_NO, UI_MENU_COOP_INVITED_NO_DESC)) coop_decline_invite(); + } + if (opt_button("##coop_create", UI_MENU_COOP_CREATE, UI_MENU_COOP_CREATE_DESC)) want_room(1, nullptr); + if (opt_button("##coop_join", UI_MENU_COOP_JOIN, UI_MENU_COOP_JOIN_DESC)) open_window(P_JOIN, "##coop_join"); + const UiTextId why = note_text(g_view.note); + if (why != UI_TEXT_COUNT) opt_text(why, g_view.note != COOP_NOTE_LEFT); + settings_rows(); +} + +static void rows_room(void) { + const uint64_t now = plat_now_ms(); + if (g_view.local) opt_text(UI_MENU_COOP_LOCAL); + if (g_view.code[0]) { + const bool copied = g_copied_at && now - g_copied_at < 3000; + if (opt_text_row("##coop_code", menu_text(UI_MENU_COOP_ROOM_ID), g_view.code, copied ? menu_text(UI_MENU_COOP_COPIED) : nullptr, + menu_text(UI_MENU_COOP_ROOM_ID_DESC), false) == 2 && + plat_clipboard_set(g_view.code)) + g_copied_at = now; + } + if (!g_view.local && opt_button("##coop_invite", UI_MENU_COOP_INVITE, UI_MENU_COOP_INVITE_DESC)) { + coop_friends_refresh(); + open_window(P_INVITE, "##coop_invite"); + } + if (g_invited_at && now - g_invited_at < 5000) { + char line[COOP_NAME_CAP + 64]; + snprintf(line, sizeof line, menu_text(UI_MENU_COOP_INVITE_SENT), g_invited_name); + opt_text_str(line); + } + opt_group(UI_MENU_COOP_PLAYERS); + for (int i = 0; i < g_view.n; i++) { + const CoopPlayer &p = g_view.players[i]; + char id[40], note[96], where[COOP_SCENE_CAP + 16]; + snprintf(id, sizeof id, "##coop_player%d", i); + snprintf(note, sizeof note, "%s%s%s", p.self ? menu_text(UI_MENU_COOP_YOU) : "", p.self && p.host ? ", " : "", + p.host ? menu_text(UI_MENU_COOP_HOST) : ""); + const bool here = p.self ? false : p.has_pose && p.pose.scene[0]; + snprintf(where, sizeof where, "%s", p.self ? "" : here ? p.pose.scene : menu_text(UI_MENU_COOP_PLAYER_AWAY)); + const bool removable = g_view.host && !p.self; + if (opt_text_row(id, p.name[0] ? p.name : "…", where, note[0] ? note : nullptr, + menu_text(removable ? UI_MENU_COOP_PLAYER_REMOVE_DESC : UI_MENU_COOP_PLAYER_DESC), false) == 2 && + removable) { + g_remove_id = p.id; + snprintf(g_remove_name, sizeof g_remove_name, "%s", p.name); + open_window(P_REMOVE, id); + } + } + opt_group(UI_MENU_COOP_CHAT); + for (int i = 0; i < g_view.nchat; i++) { + char line[COOP_NAME_CAP + COOP_CHAT_CAP + 8]; + chat_text(g_view.chat[i], line, sizeof line); + opt_text_str(line); + } + if (opt_button("##coop_chat", UI_MENU_COOP_CHAT_WRITE, UI_MENU_COOP_CHAT_WRITE_DESC)) open_window(P_CHAT, "##coop_chat"); + if (opt_button("##coop_leave", UI_MENU_COOP_LEAVE, UI_MENU_COOP_LEAVE_DESC)) open_window(P_LEAVE, "##coop_leave"); + settings_rows(); +} + +void coop_rows(float scale) { + (void)scale; + coop_view(&g_view); + pending_tick(); + // the page changes its rows when the player gets into a room, reaches for one or leaves it: the cursor goes to a row + // of the new page whose press changes nothing at once + const int layout = in_room() ? 2 : g_view.state == COOP_ENTERING || g_pending ? 1 : 0; + if (layout != g_layout) { + if (g_layout >= 0) opt_focus_key(layout == 2 ? "##coop_code" : layout == 1 ? "##coop_stop" : "##coop_join"); + g_layout = layout; + } + if (layout == 2) rows_room(); + else rows_out(); +} + +// ---- the window + +// The cursor on the item just drawn, shown (as option_rows.cpp puts it on a row). SetItemDefaultFocus as well: on the +// window's first frame ImGui's own pick of a first item would replace the cursor set here. +static void take_cursor(void) { + ImGui::SetItemDefaultFocus(); + ImGui::SetFocusID(ImGui::GetItemID(), ImGui::GetCurrentWindow()); + ImGui::SetNavCursorVisible(true); +} + +static bool field_page(void) { return g_page == P_JOIN || g_page == P_CHAT; } + +// Two buttons side by side, the safe one first: 1 the first, 2 the second. The cursor goes to the safe one when the +// window opens (fresh); in a field's window typed by keyboard the field has the cursor instead. ImGui activates a +// button on a press, not on a held key's repeats. +static int two_buttons(const char *no, const char *yes, bool yes_enabled, bool fresh, float scale) { + const ImGuiStyle &st = ImGui::GetStyle(); + float bw = (ImGui::CalcTextSize(no).x > ImGui::CalcTextSize(yes).x ? ImGui::CalcTextSize(no).x : ImGui::CalcTextSize(yes).x) + + st.FramePadding.x * 4; + char id[160]; + snprintf(id, sizeof id, "%s##no", no); + int r = skin_widget_button(id, ImVec2(bw, 0), scale) ? 1 : 0; + if (fresh && !(field_page() && !g_by_pad)) take_cursor(); + ImGui::SameLine(0, st.ItemSpacing.x + skin_cursor_reach(scale)); + ImGui::BeginDisabled(!yes_enabled); + snprintf(id, sizeof id, "%s##yes", yes); + if (skin_widget_button(id, ImVec2(bw, 0), scale)) r = 2; + ImGui::EndDisabled(); + return r; +} + +static void gold(const char *text) { + ImGui::PushStyleColor(ImGuiCol_Text, ImGui::ColorConvertU32ToFloat4(SKIN_GOLD)); + ImGui::TextUnformatted(text); + ImGui::PopStyleColor(); +} + +static void warn(const char *text) { ImGui::TextColored(ImVec4(0.95f, 0.45f, 0.35f, 1), "%s", text); } + +// A pasted room ID: the characters one is typed with, no line ends or tabs. +static void take_paste(const char *text) { + char out[32]; + size_t k = 0; + for (const char *p = text; *p && k + 1 < sizeof out; p++) + if ((*p >= '0' && *p <= '9') || (*p >= 'A' && *p <= 'Z') || (*p >= 'a' && *p <= 'z') || *p == '-') + out[k++] = *p >= 'a' && *p <= 'z' ? (char)(*p - 'a' + 'A') : *p; + out[k] = 0; + g_paste_empty = !k; + if (k) snprintf(g_field, sizeof g_field, "%s", out), g_field_bad = false; +} + +static void trimmed(char *out, size_t cap) { + const char *s = g_field; + while (*s == ' ') s++; + size_t n = strlen(s); + while (n && s[n - 1] == ' ') n--; + snprintf(out, cap, "%.*s", (int)n, s); +} + +// The field's window: a room ID (Cancel, Join; Paste) or a chat line (Cancel, Send). +static void field_window(bool fresh, float scale, float wrap, bool *close, bool *back) { + const bool join = g_page == P_JOIN; + gold(menu_text(join ? UI_MENU_COOP_ROOM_ID : UI_MENU_COOP_CHAT_WRITE)); + if (join) ImGui::TextDisabled("%s", menu_text(UI_MENU_COOP_ROOM_ID_HINT)); + if (fresh && !g_by_pad) ImGui::SetKeyboardFocusHere(); + ImGui::SetNextItemWidth(wrap); + const bool enter = ImGui::InputText("##coop_field", g_field, join ? 24 : sizeof g_field, + ImGuiInputTextFlags_EnterReturnsTrue | (join ? ImGuiInputTextFlags_CharsUppercase : 0)); + if (ImGui::IsItemEdited()) g_field_bad = g_paste_empty = false; + if (join) { + char text[256]; + if (g_paste_wait > 0 && menu_paste_take(text, sizeof text)) take_paste(text), g_paste_wait = 0; + else if (g_paste_wait > 0) g_paste_wait--; + const float bw = ImGui::CalcTextSize(menu_text(UI_MENU_COOP_PASTE)).x + ImGui::GetStyle().FramePadding.x * 4; + if (skin_widget_button(menu_text(UI_MENU_COOP_PASTE), ImVec2(bw, 0), scale)) { + menu_paste_take(text, sizeof text); // an answer of an earlier Paste is not this one's + gfx_window_paste(); + g_paste_wait = PASTE_FRAMES; + } + if (g_field_bad) warn(menu_text(UI_MENU_COOP_ROOM_ID_BAD)); + if (g_paste_empty) warn(menu_text(UI_MENU_COOP_PASTE_EMPTY)); + } + ImGui::Spacing(); + char text[FIELD_CAP]; + trimmed(text, sizeof text); + const int r = two_buttons(menu_text(UI_MENU_RESET_NO), menu_text(join ? UI_MENU_COOP_JOIN : UI_MENU_COOP_SEND), text[0] != 0, fresh, scale); + if (r == 1) *back = true; + if ((r != 2 && !enter) || !text[0]) return; + if (join) { + if (!steam_code_parse(text)) { + g_field_bad = true; + return; + } + want_room(2, text); + } else { + coop_chat(text); + } + *close = true; +} + +// The player's friends, each a button that sends the invite; Steam's own window when the game was started from Steam. +static void invite_window(bool fresh, float scale, bool *close, bool *back) { + static uint32_t serial; + if (fresh || serial != g_view.friends_serial) serial = g_view.friends_serial, g_nfriends = coop_friends(g_friends, COOP_FRIENDS); + gold(menu_text(UI_MENU_COOP_INVITE_TITLE)); + const float bw = ImGui::GetFontSize() * 22; + if (skin_widget_button(menu_text(UI_MENU_COOP_INVITE_CLOSE), ImVec2(bw, 0), scale)) *back = true; + if (fresh) take_cursor(); + if (g_view.overlay && skin_widget_button(menu_text(UI_MENU_COOP_INVITE_STEAM), ImVec2(bw, 0), scale)) { + coop_invite_window(); + *close = true; + } + if (!g_nfriends) ImGui::TextDisabled("%s", menu_text(UI_MENU_COOP_INVITE_NONE)); + ImGui::BeginChild("##coop_friends", ImVec2(bw + ImGui::GetStyle().ScrollbarSize + skin_cursor_reach(scale) * 2, ImGui::GetFontSize() * 14), + ImGuiChildFlags_NavFlattened); + for (int i = 0; i < g_nfriends; i++) { + const SteamFriend &f = g_friends[i]; + char label[STEAM_NAME_CAP + 64]; + snprintf(label, sizeof label, "%s (%s)##f%d", f.name, menu_text(f.in_app ? UI_MENU_COOP_INVITE_IN_GAME : f.online ? UI_MENU_COOP_INVITE_ONLINE + : UI_MENU_COOP_INVITE_OFFLINE), i); + if (skin_widget_button(label, ImVec2(bw, 0), scale)) { + coop_invite(f.id); + snprintf(g_invited_name, sizeof g_invited_name, "%s", f.name); + g_invited_at = plat_now_ms(); + *close = true; + } + } + ImGui::EndChild(); +} + +static void confirm_window(bool fresh, float scale, bool *close, bool *back) { + const bool remove = g_page == P_REMOVE; + char line[COOP_NAME_CAP + 160]; + if (remove) snprintf(line, sizeof line, menu_text(UI_MENU_COOP_REMOVE_CONFIRM), g_remove_name); + else snprintf(line, sizeof line, "%s", menu_text(UI_MENU_COOP_LEAVE_CONFIRM)); + gold(line); + if (!remove && g_view.host && g_view.n > 1) ImGui::TextUnformatted(menu_text(UI_MENU_COOP_LEAVE_HOST)); + ImGui::Spacing(); + const int r = two_buttons(menu_text(remove ? UI_MENU_RESET_NO : UI_MENU_COOP_STAY), menu_text(remove ? UI_MENU_COOP_REMOVE : UI_MENU_COOP_LEAVE), + true, fresh, scale); + if (r == 1) *back = true; + if (r == 2) { + if (remove) coop_remove(g_remove_id); + else coop_leave(), g_return[0] = 0; // the page's rows change; coop_rows puts the cursor on the new page + *close = true; + } +} + +void coop_after_page(float scale) { + g_window_shown = false; + if (g_open && !ImGui::IsPopupOpen("##coopwin")) ImGui::OpenPopup("##coopwin"); + ImGui::SetNextWindowPos(ImGui::GetMainViewport()->GetCenter(), ImGuiCond_Always, ImVec2(0.5f, 0.5f)); + ImGui::PushStyleVar(ImGuiStyleVar_PopupBorderSize, 0); + const bool shown = ImGui::BeginPopupModal("##coopwin", nullptr, ImGuiWindowFlags_NoDecoration | ImGuiWindowFlags_AlwaysAutoResize); + ImGui::PopStyleVar(); + if (!shown) { + g_open = false; + return; + } + g_window_shown = true; + // a window opened since the last frame: latched and cleared before it is drawn (as the Saves tab's file window) + const bool fresh = g_page_new; + g_page_new = false; + const ImVec2 box = ImGui::GetWindowPos(), box_size = ImGui::GetWindowSize(); + skin_panel(ImGui::GetWindowDrawList(), box, ImVec2(box.x + box_size.x, box.y + box_size.y), scale); + const float wrap = ImGui::GetFontSize() * 30; + bool close = false, back = false; + ImGui::PushTextWrapPos(ImGui::GetCursorPosX() + wrap); + const bool needs_room = g_page == P_CHAT || g_page == P_INVITE || g_page == P_REMOVE || g_page == P_LEAVE; + if (needs_room && !in_room()) close = true; // the room ended under the window + else if (field_page()) field_window(fresh, scale, wrap, &close, &back); + else if (g_page == P_INVITE) invite_window(fresh, scale, &close, &back); + else if (g_page == P_REMOVE || g_page == P_LEAVE) confirm_window(fresh, scale, &close, &back); + else close = true; + ImGui::PopTextWrapPos(); + if (!fresh && !ImGui::IsAnyItemActive() && + (ImGui::IsKeyPressed(ImGuiKey_Escape, false) || ImGui::IsKeyPressed(ImGuiKey_GamepadFaceRight, false))) { + back = true; + menu_sound_play(MENU_SOUND_CANCEL); + } + if (back || close) { + g_open = false; + g_page = P_NONE; + g_field[0] = 0; + ImGui::CloseCurrentPopup(); + if (g_return[0]) opt_focus_key(g_return); // back on the row that opened it + } + ImGui::EndPopup(); +} + +bool coop_modal(void) { return g_open || g_window_shown; } + +void coop_cancel(void) { + g_open = false; + g_page = P_NONE; + g_field[0] = 0; +} + +int coop_test_set(const char *key, const char *value) { + if (strcmp(key, "NX2NAVI_COOP_DO")) return 0; + coop_view(&g_view); + if (!strcmp(value, "create")) want_room(1, nullptr); + else if (!strcmp(value, "leave")) coop_leave(); + else if (!strncmp(value, "join:", 5)) want_room(2, value + 5); + else if (!strncmp(value, "chat:", 5)) coop_chat(value + 5); + else if (!strcmp(value, "page:join")) open_window(P_JOIN, "##coop_join"); + else if (!strcmp(value, "page:invite")) coop_friends_refresh(), open_window(P_INVITE, "##coop_invite"); + else if (!strcmp(value, "page:chat")) open_window(P_CHAT, "##coop_chat"); + else if (!strcmp(value, "page:leave")) open_window(P_LEAVE, "##coop_leave"); + g_by_pad = true; // the cursor as a pad's A would leave it: on the safe button + return 1; +} + +// ---- over the game + +static CoopView g_over; +static bool g_over_on; + +bool coop_overlay_tick(void) { + static unsigned cfg_seen = ~0u; + static uint32_t serial; + if (unsigned v = cfg_version(); v != cfg_seen) cfg_seen = v, g_over_on = cfg_bool("NX2NAVI_COOP") != 0; + if (!g_over_on) return false; + if (uint32_t s = coop_serial(); s != serial) serial = s, coop_view(&g_over); + if (g_over.invite_room) return true; + if (g_over.state != COOP_IN_ROOM) return false; + if (g_over.n > 1) return true; + const uint64_t now = plat_now_ms(); + return g_over.nchat && now - g_over.chat[g_over.nchat - 1].at_ms < CHAT_SHOWN_MS; +} + +// The label of a small panel centred on x, its top at y. +static float label(ImDrawList *dl, float x, float y, const char *text, float scale, float alpha) { + const float padx = 10 * scale, pady = 5 * scale; + const ImVec2 sz = ImGui::CalcTextSize(text); + const ImVec2 p(x - sz.x * 0.5f - padx, y); + skin_panel(dl, p, ImVec2(p.x + sz.x + padx * 2, p.y + sz.y + pady * 2), scale * 0.5f, 0.85f * alpha); + dl->AddText(ImVec2(p.x + padx, p.y + pady), IM_COL32(244, 236, 214, (int)(255 * alpha)), text); + return sz.y + pady * 2; +} + +void coop_overlay_draw(float w, float h, float scale, bool menu_open) { + if (!g_over_on) return; + const uint64_t now = plat_now_ms(); + ImDrawList *dl = menu_open ? ImGui::GetBackgroundDrawList() : ImGui::GetForegroundDrawList(); + // the other players' names where their Link stands, in the area this game's Link is in + VkDlaaCamera cam; + const CoopPlayer *me = nullptr; + for (int i = 0; i < g_over.n; i++) + if (g_over.players[i].self) me = &g_over.players[i]; + if (!menu_open && g_over.state == COOP_IN_ROOM && cfg_bool("NX2NAVI_COOP_NAMES") && vk_dlaa_fg_camera(&cam)) { + const float ty = tanf(cam.fov_y * 0.5f), tx = ty * cam.aspect; + // the game's picture in the frame: centred, with bars above and below or at the sides when its shape differs + const float pw = cam.aspect > w / h ? w : h * cam.aspect, ph = cam.aspect > w / h ? w / cam.aspect : h; + for (int i = 0; i < g_over.n; i++) { + const CoopPlayer &p = g_over.players[i]; + if (p.self || !p.has_pose || !p.pose.scene[0]) continue; + // only a player in the area this game's Link is in + if (me && me->has_pose && me->pose.scene[0] && strcmp(me->pose.scene, p.pose.scene)) continue; + // a moment ahead along the velocity: the pose is up to a twentieth of a second old + float age = (float)p.pose_ms / 1000.0f; + if (age > 0.25f) age = 0.25f; + float d[3]; + for (int k = 0; k < 3; k++) d[k] = p.pose.pos[k] + p.pose.vel[k] * age - cam.pos[k]; + d[1] += 1.9f; // above the head of an adult Link; a child's name floats a little higher + const float z = d[0] * cam.fwd[0] + d[1] * cam.fwd[1] + d[2] * cam.fwd[2]; + float x = d[0] * cam.right[0] + d[1] * cam.right[1] + d[2] * cam.right[2]; + float y = d[0] * cam.up[0] + d[1] * cam.up[1] + d[2] * cam.up[2]; + const float dist = sqrtf(d[0] * d[0] + d[1] * d[1] + d[2] * d[2]); + char text[COOP_NAME_CAP + 24]; + snprintf(text, sizeof text, "%s %.0f m", p.name[0] ? p.name : "?", dist); + float nx, ny; + bool on_screen = z > 0.1f; + if (on_screen) { + nx = x / (z * tx), ny = y / (z * ty); + on_screen = fabsf(nx) < 0.96f && fabsf(ny) < 0.92f; + } + if (!on_screen) { + // beside or behind the picture: at its edge, in the direction to turn to + float len = sqrtf(x * x + y * y); + if (len < 1e-4f) x = 1, y = 0, len = 1; + nx = x / len, ny = y / len; + const float m = fabsf(nx) / 0.96f > fabsf(ny) / 0.88f ? fabsf(nx) / 0.96f : fabsf(ny) / 0.88f; + nx /= m, ny /= m; + } + label(dl, w * 0.5f + nx * 0.5f * pw, h * 0.5f - ny * 0.5f * ph, text, scale, on_screen ? 1.0f : 0.75f); + } + } + if (menu_open) return; + float y = 12 * scale; + if (g_over.invite_room) { + char text[COOP_NAME_CAP + 160]; + snprintf(text, sizeof text, menu_text(UI_MENU_COOP_TOAST_INVITE), g_over.invite_from); + y += label(dl, w * 0.5f, y, text, scale * 1.2f, 1) + 6 * scale; + } + if (g_over.state == COOP_IN_ROOM && cfg_bool("NX2NAVI_COOP_CHAT")) { + // the top middle: the game's hearts and rupees are at the left, the performance overlay at the right + for (int i = 0; i < g_over.nchat; i++) { + const uint64_t age = now - g_over.chat[i].at_ms; + if (age >= CHAT_SHOWN_MS) continue; + const float alpha = age > CHAT_SHOWN_MS - CHAT_FADE_MS ? (float)(CHAT_SHOWN_MS - age) / CHAT_FADE_MS : 1.0f; + char text[COOP_NAME_CAP + COOP_CHAT_CAP + 8]; + chat_text(g_over.chat[i], text, sizeof text); + y += label(dl, w * 0.5f, y, text, scale * 1.2f, alpha) + 6 * scale; + } + } +} diff --git a/runtime/ui/coop_page.h b/runtime/ui/coop_page.h new file mode 100644 index 00000000..4b3fed49 --- /dev/null +++ b/runtime/ui/coop_page.h @@ -0,0 +1,24 @@ +// The menu's Co-op tab and what co-op draws over the game (ui/coop_page.cpp, docs/coop.md). Present path only (ImGui). +#pragma once + +// Inside the page's opt_begin / opt_end. Co-op off: its switch. Steam not there: why, and Look for Steam again. In no +// room: an invite that waits, Create a room, Join a room, the settings. In a room: the room ID (a press copies it), +// Invite a friend, the players (the host's press removes one), the chat and Leave. +void coop_rows(float scale); +// After opt_end: the window a row opens: a room ID or a chat line to type, the friends to invite, and the +// confirmations of Remove and Leave, each opening with the cursor on its safe button. +void coop_after_page(float scale); +// The window is open: B, Esc, L / R and the tab keys stay with it. +bool coop_modal(void); +// The menu opened or closed (menu.cpp): the window closes. +void coop_cancel(void); +// NX2NAVI_MENU_TEST_SET pseudo-keys (menu.cpp test_apply_sets), from the environment only: COOP_DO=create | leave | +// join: | chat: | page:join | page:invite | page:chat | page:leave does what the row or the window's +// button does. 1 when key is one of them. +int coop_test_set(const char *key, const char *value); + +// Over the game, menu open or not: the other players' names where they stand, and while the menu is closed the chat's +// new lines and an invite that waits. coop_overlay_tick on every overlay frame (it costs a copy of the co-op view while +// co-op is on): true while there is something to draw. coop_overlay_draw draws into a w x h frame. +bool coop_overlay_tick(void); +void coop_overlay_draw(float w, float h, float scale, bool menu_open); diff --git a/runtime/ui/menu.cpp b/runtime/ui/menu.cpp index 95c5bb16..e7dc2a03 100644 --- a/runtime/ui/menu.cpp +++ b/runtime/ui/menu.cpp @@ -37,6 +37,7 @@ static int g_font_bad; #include "ui/amiibo_page.h" #include "ui/binds_page.h" #include "ui/debug_menu.h" +#include "ui/coop_page.h" #include "ui/option_rows.h" #include "ui/perf_panel.h" @@ -190,7 +191,7 @@ extern "C" void menu_event_mouse_pos(float x, float y) { push({EV_POS, 0, 0, x, extern "C" void menu_event_mouse_button(int button, int down) { push({EV_BUTTON, button, down, 0, 0}); } extern "C" void menu_event_wheel(float dx, float dy) { push({EV_WHEEL, 0, 0, dx, dy}); } extern "C" void menu_event_focus(int focused) { push({EV_FOCUS, focused, 0, 0, 0}); } -// a typed character, for the text fields of the debug menu +// a typed character, for the text fields of the co-op page and the debug menu extern "C" void menu_event_char(unsigned c) { push({EV_CHAR, (int)c, 0, 0, 0}); } // The clipboard's text a page asked for (gfx_window_paste): the window thread reads it, the page takes it a frame later. @@ -504,7 +505,7 @@ static int fonts_up(float scale) { // what the title face shows in the CJK languages: the menu's title and tabs (Simplified Chinese menu text) and // the boot screen's title (the game's language) static const UiTextId titles[] = {UI_MENU_TITLE, UI_MENU_TAB_SCREEN, UI_MENU_TAB_GAME, UI_MENU_TAB_SOUND, - UI_MENU_TAB_CONTROLS, UI_BOOT_TITLE}; + UI_MENU_TAB_CONTROLS, UI_MENU_TAB_COOP, UI_BOOT_TITLE}; for (int i = 0; i < N; i++) { if (!data[i]) continue; ImFontGlyphRangesBuilder b; @@ -570,9 +571,10 @@ extern "C" void menu_vk_release(void) { // optional) at that presented frame; changes live settings with no input, menu open or not. nx2navi.ini is written only by // the pseudo-key SAVE=1 (cfg_save, as a row change does; a failed write shows the menu's save note). FOCUS= (the // NX2NAVI_ prefix optional) puts the cursor on that setting's row and scrolls it into view when the row is next drawn -// (opt_focus_key), so a page's shot shows a row below the first screenful; it does not switch tabs. -// Ocarina of Time: the options this port has -enum { TAB_SCREEN, TAB_GAME, TAB_SOUND, TAB_CONTROLS, TAB_COUNT }; +// (opt_focus_key), so a page's shot shows a row below the first screenful; it does not switch tabs. COOP_DO drives the +// Co-op tab (ui/coop_page.h coop_test_set). +// Ocarina of Time: the options this port has, and co-op (ui/coop_page.cpp) +enum { TAB_SCREEN, TAB_GAME, TAB_SOUND, TAB_CONTROLS, TAB_COOP, TAB_COUNT }; enum { TEST_PAGE_FRAMES = 30, TEST_SETS = 16, TEST_OPENS = 8 }; struct TestSet { uint64_t frame; char key[64], value[64]; }; static struct { @@ -638,7 +640,11 @@ static void test_apply_sets(uint64_t frame) { char row[80]; snprintf(row, sizeof row, "%s%s", strncmp(t.value, "NX2NAVI_", strlen("NX2NAVI_")) ? "NX2NAVI_" : "", t.value); opt_focus_key(row); - } else { + } else if (!strcmp(t.key, "NX2NAVI_COOP_DO") && !cfg_from_env("NX2NAVI_MENU_TEST_SET")) { + // From nx2navi.ini the hook drives no part of the Co-op tab: a settings file someone hands a player could + // otherwise put them into a room. A test sets it in the environment. + rt_log("menu: test hook: %s is taken from the environment only, not from nx2navi.ini", t.key); + } else if (!coop_test_set(t.key, t.value)) { cfg_set(t.key, t.value); } } @@ -1697,8 +1703,16 @@ static void rows_low_end(void) { #endif } +// The Co-op tab (ui/coop_page.cpp): the rows, then the window a row opens. +static void tab_coop(float scale) { + opt_begin("##coop", scale); + coop_rows(scale); + opt_end(); + coop_after_page(scale); +} + static const UiTextId kTabNames[TAB_COUNT] = {UI_MENU_TAB_SCREEN, UI_MENU_TAB_GAME, UI_MENU_TAB_SOUND, - UI_MENU_TAB_CONTROLS}; + UI_MENU_TAB_CONTROLS, UI_MENU_TAB_COOP}; static int g_tab; // the tab shown static int g_tab_request = -1; // select this tab at the next layout; -1 none static int g_focus_page = -1; // this tab's first row takes the cursor once it is shown; -1 none @@ -1785,7 +1799,7 @@ static void layout_menu(uint32_t w, uint32_t h, float scale) { } // a text field takes Q and E as letters, and a window of a page keeps the tab keys - const bool keeps_keys = g_modal || binds_modal() || ImGui::GetIO().WantTextInput; + const bool keeps_keys = g_modal || binds_modal() || coop_modal() || ImGui::GetIO().WantTextInput; int step = keeps_keys ? 0 : ImGui::IsKeyPressed(ImGuiKey_GamepadR1, false) || ImGui::IsKeyPressed(ImGuiKey_E, false) ? 1 : ImGui::IsKeyPressed(ImGuiKey_GamepadL1, false) || ImGui::IsKeyPressed(ImGuiKey_Q, false) ? -1 @@ -1819,6 +1833,7 @@ static void layout_menu(uint32_t w, uint32_t h, float scale) { case TAB_GAME: tab_game(scale); break; case TAB_SOUND: tab_sound(scale); break; case TAB_CONTROLS: tab_controls(scale); break; + case TAB_COOP: tab_coop(scale); break; } ImGui::EndTabItem(); } @@ -1878,7 +1893,7 @@ static void layout_menu(uint32_t w, uint32_t h, float scale) { if (skin_widget_button(quit, ImVec2(bw, 0), scale)) g_confirm_quit = true, ImGui::OpenPopup("##confirm"); restart_confirm(scale); menu_sounds_frame(); - bool was_modal = g_modal || binds_modal() || ImGui::GetIO().WantTextInput; + bool was_modal = g_modal || binds_modal() || coop_modal() || ImGui::GetIO().WantTextInput; if (!was_modal && (ImGui::IsKeyPressed(ImGuiKey_Escape, false) || ImGui::IsKeyPressed(ImGuiKey_GamepadFaceRight, false))) set_open(0); ImGui::End(); @@ -2051,6 +2066,7 @@ static int overlay_frame(uint64_t frame, const MenuTarget *t, const char **shot) if (g_perf_save.exchange(0)) cfg_save(); perf_tick(plat_now_ns(), t); amiibo_tick(); + const bool coop_draws = coop_overlay_tick(); // names of the other players, chat lines, an invite: over the game if (g_booting.load(std::memory_order_relaxed)) g_booting.store(0, std::memory_order_release); // the game runs bool open = g_open.load(std::memory_order_relaxed); // the frame the menu is first laid out after opening: also when its g_reset went to an earlier frame of the overlay @@ -2068,7 +2084,7 @@ static int overlay_frame(uint64_t frame, const MenuTarget *t, const char **shot) if (g_debug.load()) debug_menu_tab(0); set_open(1); open = true; - } else if (!g_perf_mode) { + } else if (!g_perf_mode && !coop_draws) { return 0; } } @@ -2102,6 +2118,7 @@ static int overlay_frame(uint64_t frame, const MenuTarget *t, const char **shot) io.ClearInputKeys(); io.ClearInputMouse(); binds_cancel(); // a cell waiting for a press when the menu closed: no press binds on the next opening + coop_cancel(); // the Co-op tab's window closes g_sound_fresh = true; g_last_ns = 0; g_focus_page = g_tab_request >= 0 ? g_tab_request : g_tab; // opening: the first row has the cursor @@ -2133,6 +2150,7 @@ static int overlay_frame(uint64_t frame, const MenuTarget *t, const char **shot) layout_menu(t->width, t->height, scale); } perf_draw(t, scale); + if (coop_draws) coop_overlay_draw((float)t->width, (float)t->height, scale, open); ImGui::Render(); if (open) g_save_pending = opt_save_tick(0); g_cost_ns += plat_now_ns() - t0; diff --git a/runtime/ui_text.c b/runtime/ui_text.c index db4a6381..0389e73c 100644 --- a/runtime/ui_text.c +++ b/runtime/ui_text.c @@ -644,6 +644,93 @@ static const char *const text_en[UI_TEXT_COUNT] = { [UI_MENU_SAVE_E_NEWER] = "%s was made by a newer NX2navi: update NX2navi first.", [UI_MENU_SAVE_E_DAMAGED] = "%s is damaged: download it again.", [UI_MENU_SAVE_E_UNSAFE] = "%s was refused: it holds files outside a save, links, or far more than a save.", + [UI_MENU_TAB_COOP] = "Co-op", + [UI_MENU_COOP_ON] = "Co-op (experimental)", + [UI_MENU_COOP_ON_DESC] = "Play with friends over Steam, each in their own game and save. Nobody sets up a router: rooms " + "and invites go through Steam, which shows you as playing Spacewar, its test app. Needs Steam " + "running and its library file steam_api64.dll beside the game. Off: the game uses no network.", + [UI_MENU_COOP_NO_LIBRARY] = "Steam's library file, steam_api64.dll, is not beside the game. Copy one from any Steam game's " + "folder into the folder of ocarina.exe, then choose Look for Steam again.", + [UI_MENU_COOP_OLD_LIBRARY] = "The steam_api64.dll beside the game is too old for co-op. Replace it with one from a newer Steam " + "game.", + [UI_MENU_COOP_NO_CLIENT] = "Steam did not answer. Start Steam and sign in, then choose Look for Steam again.", + [UI_MENU_COOP_RETRY] = "Look for Steam again", + [UI_MENU_COOP_RETRY_DESC] = "Tries now to reach Steam; the game also tries by itself every few seconds.", + [UI_MENU_COOP_CREATE] = "Create a room", + [UI_MENU_COOP_CREATE_DESC] = "Makes a room for up to four players. You get a room ID to pass on, and you can invite Steam " + "friends.", + [UI_MENU_COOP_JOIN] = "Join a room", + [UI_MENU_COOP_JOIN_DESC] = "Joins the room whose ID a friend gave you.", + [UI_MENU_COOP_ROOM_ID] = "Room ID", + [UI_MENU_COOP_ROOM_ID_DESC] = "Friends type this into Join a room. Press to copy it. Anyone who has it can join, so pass it on " + "only to the people you want in your game.", + [UI_MENU_COOP_ROOM_ID_HINT] = "8 letters and digits, as XXXX-XXXX: any case, with or without the dash.", + [UI_MENU_COOP_ROOM_ID_BAD] = "This is not a room ID: check it for a mistyped character.", + [UI_MENU_COOP_PASTE] = "Paste", + [UI_MENU_COOP_PASTE_EMPTY] = "The clipboard has no text.", + [UI_MENU_COOP_COPIED] = "copied", + [UI_MENU_COOP_OK] = "OK", + [UI_MENU_COOP_JOINING] = "Getting into the room…", + [UI_MENU_COOP_STOP] = "Stop", + [UI_MENU_COOP_STOP_DESC] = "Stops trying to get into the room.", + [UI_MENU_COOP_INVITE] = "Invite a friend", + [UI_MENU_COOP_INVITE_DESC] = "Sends a Steam invite to a friend. It reaches a friend whose NX2navi is running with co-op on; " + "anyone else can use the room ID.", + [UI_MENU_COOP_INVITE_TITLE] = "Invite a Steam friend", + [UI_MENU_COOP_INVITE_NONE] = "Steam shows no friends.", + [UI_MENU_COOP_INVITE_SENT] = "Invite sent to %s.", + [UI_MENU_COOP_INVITE_IN_GAME] = "in co-op now", + [UI_MENU_COOP_INVITE_ONLINE] = "online", + [UI_MENU_COOP_INVITE_OFFLINE] = "offline", + [UI_MENU_COOP_INVITE_STEAM] = "Steam's invite window", + [UI_MENU_COOP_INVITE_CLOSE] = "Close", + [UI_MENU_COOP_INVITED] = "%s invites you to a room.", + [UI_MENU_COOP_INVITED_JOIN] = "Join their room", + [UI_MENU_COOP_INVITED_JOIN_DESC] = "Joins the room you were invited to.", + [UI_MENU_COOP_INVITED_NO] = "Not now", + [UI_MENU_COOP_INVITED_NO_DESC] = "Puts the invite away.", + [UI_MENU_COOP_PLAYERS] = "Players", + [UI_MENU_COOP_YOU] = "you", + [UI_MENU_COOP_HOST] = "host", + [UI_MENU_COOP_PLAYER_DESC] = "A player in the room, and the area their Link is in.", + [UI_MENU_COOP_PLAYER_REMOVE_DESC] = "A player in the room. As the host you can press to remove them from the room.", + [UI_MENU_COOP_PLAYER_AWAY] = "not in the world", + [UI_MENU_COOP_REMOVE] = "Remove", + [UI_MENU_COOP_REMOVE_CONFIRM] = "Remove %s from the room? They cannot come back into this room.", + [UI_MENU_COOP_LEAVE] = "Leave the room", + [UI_MENU_COOP_LEAVE_DESC] = "Leaves the room. Your game and save go on as they are.", + [UI_MENU_COOP_LEAVE_CONFIRM] = "Leave the room?", + [UI_MENU_COOP_LEAVE_HOST] = "You are the host: the room goes on with another player as its host.", + [UI_MENU_COOP_STAY] = "Stay", + [UI_MENU_COOP_CHAT] = "Chat", + [UI_MENU_COOP_CHAT_WRITE] = "Write a message", + [UI_MENU_COOP_CHAT_WRITE_DESC] = "Sends a line of text to everyone in the room.", + [UI_MENU_COOP_SEND] = "Send", + [UI_MENU_COOP_CHAT_JOINED] = "%s joined the room", + [UI_MENU_COOP_CHAT_LEFT] = "%s left the room", + [UI_MENU_COOP_SETTINGS] = "Co-op settings", + [UI_MENU_COOP_SHARE] = "Share progress", + [UI_MENU_COOP_SHARE_DESC] = "In a room, what anyone achieves counts for everyone: story progress, chests, doors, items and " + "songs. Before anything from a room reaches your save, the save is copied to coop-backup in the " + "profile folder. Small keys, rupees, ammunition and hearts stay your own. Off: only names and " + "chat are shared.", + [UI_MENU_COOP_NAMES] = "Show player names", + [UI_MENU_COOP_NAMES_DESC] = "Shows the name of each other player where their Link stands in your world, with the distance. " + "Needs DLSS, FSR or TAA on (the game tells the menu where the camera looks only then).", + [UI_MENU_COOP_CHAT_SHOW] = "Show chat over the game", + [UI_MENU_COOP_CHAT_SHOW_DESC] = "New chat lines and who joined or left show for a few seconds while the menu is closed.", + [UI_MENU_COOP_N_CREATE_FAILED] = "Steam could not make the room. Try again in a moment.", + [UI_MENU_COOP_N_NO_ROOM] = "No room has this ID: check it, or ask your friend whether the room is still open.", + [UI_MENU_COOP_N_FULL] = "The room is full.", + [UI_MENU_COOP_N_REFUSED] = "The room did not let you in.", + [UI_MENU_COOP_N_NOT_OURS] = "That is not an NX2navi room.", + [UI_MENU_COOP_N_OTHER_VERSION] = "The room's host runs another version of NX2navi or of the game: use the same versions.", + [UI_MENU_COOP_N_REMOVED] = "The host removed you from the room.", + [UI_MENU_COOP_N_HOST_SILENT] = "The room's host did not answer.", + [UI_MENU_COOP_N_LOST] = "Steam lost its connection; the room is gone.", + [UI_MENU_COOP_N_LEFT] = "You left the room.", + [UI_MENU_COOP_LOCAL] = "Test mode: a stand-in for Steam on this PC.", + [UI_MENU_COOP_TOAST_INVITE] = "%s invites you to a room: open the menu's Co-op tab.", [UI_BOOT_TITLE] = "Preparing shaders", [UI_BOOT_STARTING] = "Starting", [UI_BOOT_SHADERS] = "Shaders: %lld of %lld", [UI_BOOT_PIPELINES] = "Pipelines: %lld of %lld", [UI_MENU_UPSCALING] = "Upscaling", @@ -1201,6 +1288,95 @@ static const char *const text_ru[UI_TEXT_COUNT] = { [UI_MENU_SAVE_E_NEWER] = "%s создан более новой версией NX2navi: сначала обновите NX2navi.", [UI_MENU_SAVE_E_DAMAGED] = "%s повреждён: скачайте его заново.", [UI_MENU_SAVE_E_UNSAFE] = "%s отклонён: в нём файлы вне сохранения, ссылки или слишком много данных.", + [UI_MENU_TAB_COOP] = "Кооператив", + [UI_MENU_COOP_ON] = "Кооператив (эксперимент)", + [UI_MENU_COOP_ON_DESC] = "Играйте с друзьями через Steam, каждый в своей игре и со своим сохранением. Настраивать роутер " + "не нужно: комнаты и приглашения идут через Steam, который показывает, что вы играете в Spacewar, " + "его тестовое приложение. Нужны запущенный Steam и файл его библиотеки steam_api64.dll рядом с " + "игрой. Выкл.: игра не использует сеть.", + [UI_MENU_COOP_NO_LIBRARY] = "Файла библиотеки Steam, steam_api64.dll, нет рядом с игрой. Скопируйте его из папки любой игры " + "Steam в папку с ocarina.exe и выберите «Искать Steam снова».", + [UI_MENU_COOP_OLD_LIBRARY] = "Файл steam_api64.dll рядом с игрой слишком старый для кооператива. Замените его файлом из более " + "новой игры Steam.", + [UI_MENU_COOP_NO_CLIENT] = "Steam не ответил. Запустите Steam, войдите в аккаунт и выберите «Искать Steam снова».", + [UI_MENU_COOP_RETRY] = "Искать Steam снова", + [UI_MENU_COOP_RETRY_DESC] = "Пробует связаться со Steam сейчас; игра и сама пробует каждые несколько секунд.", + [UI_MENU_COOP_CREATE] = "Создать комнату", + [UI_MENU_COOP_CREATE_DESC] = "Создаёт комнату до четырёх игроков. Вы получите ID комнаты, который можно передать, и сможете " + "пригласить друзей из Steam.", + [UI_MENU_COOP_JOIN] = "Войти в комнату", + [UI_MENU_COOP_JOIN_DESC] = "Вход в комнату, ID которой вам дал друг.", + [UI_MENU_COOP_ROOM_ID] = "ID комнаты", + [UI_MENU_COOP_ROOM_ID_DESC] = "Друзья вводят его в «Войти в комнату». Нажмите, чтобы скопировать. Войти может любой, у кого он " + "есть, поэтому передавайте его только тем, кого хотите видеть в своей игре.", + [UI_MENU_COOP_ROOM_ID_HINT] = "8 букв и цифр в виде XXXX-XXXX: в любом регистре, с дефисом или без.", + [UI_MENU_COOP_ROOM_ID_BAD] = "Это не ID комнаты: проверьте, нет ли опечатки.", + [UI_MENU_COOP_PASTE] = "Вставить", + [UI_MENU_COOP_PASTE_EMPTY] = "В буфере обмена нет текста.", + [UI_MENU_COOP_COPIED] = "скопировано", + [UI_MENU_COOP_OK] = "ОК", + [UI_MENU_COOP_JOINING] = "Вход в комнату…", + [UI_MENU_COOP_STOP] = "Остановить", + [UI_MENU_COOP_STOP_DESC] = "Прекращает попытку войти в комнату.", + [UI_MENU_COOP_INVITE] = "Пригласить друга", + [UI_MENU_COOP_INVITE_DESC] = "Отправляет другу приглашение через Steam. Оно дойдёт до друга, у которого запущена NX2navi с " + "включённым кооперативом; остальные могут воспользоваться ID комнаты.", + [UI_MENU_COOP_INVITE_TITLE] = "Пригласить друга из Steam", + [UI_MENU_COOP_INVITE_NONE] = "Steam не показывает друзей.", + [UI_MENU_COOP_INVITE_SENT] = "Приглашение отправлено: %s.", + [UI_MENU_COOP_INVITE_IN_GAME] = "сейчас в кооперативе", + [UI_MENU_COOP_INVITE_ONLINE] = "в сети", + [UI_MENU_COOP_INVITE_OFFLINE] = "не в сети", + [UI_MENU_COOP_INVITE_STEAM] = "Окно приглашений Steam", + [UI_MENU_COOP_INVITE_CLOSE] = "Закрыть", + [UI_MENU_COOP_INVITED] = "%s приглашает вас в комнату.", + [UI_MENU_COOP_INVITED_JOIN] = "Войти в их комнату", + [UI_MENU_COOP_INVITED_JOIN_DESC] = "Вход в комнату, в которую вас пригласили.", + [UI_MENU_COOP_INVITED_NO] = "Не сейчас", + [UI_MENU_COOP_INVITED_NO_DESC] = "Убирает приглашение.", + [UI_MENU_COOP_PLAYERS] = "Игроки", + [UI_MENU_COOP_YOU] = "вы", + [UI_MENU_COOP_HOST] = "хост", + [UI_MENU_COOP_PLAYER_DESC] = "Игрок в комнате и область, в которой находится его Линк.", + [UI_MENU_COOP_PLAYER_REMOVE_DESC] = "Игрок в комнате. Как хост вы можете нажать, чтобы удалить его из комнаты.", + [UI_MENU_COOP_PLAYER_AWAY] = "не в мире", + [UI_MENU_COOP_REMOVE] = "Удалить", + [UI_MENU_COOP_REMOVE_CONFIRM] = "Удалить %s из комнаты? Вернуться в эту комнату он не сможет.", + [UI_MENU_COOP_LEAVE] = "Выйти из комнаты", + [UI_MENU_COOP_LEAVE_DESC] = "Выход из комнаты. Ваша игра и сохранение остаются как есть.", + [UI_MENU_COOP_LEAVE_CONFIRM] = "Выйти из комнаты?", + [UI_MENU_COOP_LEAVE_HOST] = "Вы хост: комната продолжит работу, хостом станет другой игрок.", + [UI_MENU_COOP_STAY] = "Остаться", + [UI_MENU_COOP_CHAT] = "Чат", + [UI_MENU_COOP_CHAT_WRITE] = "Написать сообщение", + [UI_MENU_COOP_CHAT_WRITE_DESC] = "Отправляет строку текста всем в комнате.", + [UI_MENU_COOP_SEND] = "Отправить", + [UI_MENU_COOP_CHAT_JOINED] = "%s входит в комнату", + [UI_MENU_COOP_CHAT_LEFT] = "%s выходит из комнаты", + [UI_MENU_COOP_SETTINGS] = "Настройки кооператива", + [UI_MENU_COOP_SHARE] = "Общий прогресс", + [UI_MENU_COOP_SHARE_DESC] = "В комнате достижения любого игрока засчитываются всем: сюжет, сундуки, двери, предметы и песни. " + "Прежде чем что-либо из комнаты попадёт в ваше сохранение, оно копируется в coop-backup в папке " + "профиля. Малые ключи, рупии, боеприпасы и сердца остаются вашими. Выкл.: общими остаются только " + "имена и чат.", + [UI_MENU_COOP_NAMES] = "Показывать имена игроков", + [UI_MENU_COOP_NAMES_DESC] = "Показывает имя каждого другого игрока там, где его Линк стоит в вашем мире, и расстояние до " + "него. Нужны включённые DLSS, FSR или TAA (только тогда меню знает, куда смотрит камера).", + [UI_MENU_COOP_CHAT_SHOW] = "Показывать чат поверх игры", + [UI_MENU_COOP_CHAT_SHOW_DESC] = "Новые строки чата и сообщения о входе и выходе игроков показываются несколько секунд, пока меню " + "закрыто.", + [UI_MENU_COOP_N_CREATE_FAILED] = "Steam не смог создать комнату. Попробуйте ещё раз чуть позже.", + [UI_MENU_COOP_N_NO_ROOM] = "Комнаты с таким ID нет: проверьте его или спросите друга, открыта ли ещё комната.", + [UI_MENU_COOP_N_FULL] = "Комната заполнена.", + [UI_MENU_COOP_N_REFUSED] = "Комната вас не впустила.", + [UI_MENU_COOP_N_NOT_OURS] = "Это не комната NX2navi.", + [UI_MENU_COOP_N_OTHER_VERSION] = "У хоста комнаты другая версия NX2navi или игры: используйте одинаковые версии.", + [UI_MENU_COOP_N_REMOVED] = "Хост удалил вас из комнаты.", + [UI_MENU_COOP_N_HOST_SILENT] = "Хост комнаты не ответил.", + [UI_MENU_COOP_N_LOST] = "Steam потерял соединение; комнаты больше нет.", + [UI_MENU_COOP_N_LEFT] = "Вы вышли из комнаты.", + [UI_MENU_COOP_LOCAL] = "Тестовый режим: замена Steam на этом ПК.", + [UI_MENU_COOP_TOAST_INVITE] = "%s приглашает вас в комнату: откройте вкладку «Кооператив» в меню.", [UI_BOOT_TITLE] = "Подготовка шейдеров", [UI_BOOT_STARTING] = "Запуск", [UI_BOOT_SHADERS] = "Шейдеры: %lld из %lld", [UI_BOOT_PIPELINES] = "Конвейеры: %lld из %lld", [UI_MENU_CHEATS_REBUILD] = "Пересобрать игру сейчас", @@ -1742,6 +1918,94 @@ static const char *const text_pt_br[UI_TEXT_COUNT] = { [UI_MENU_SAVE_E_NEWER] = "%s foi feito por um NX2navi mais novo: atualize o NX2navi primeiro.", [UI_MENU_SAVE_E_DAMAGED] = "%s está danificado: baixe-o de novo.", [UI_MENU_SAVE_E_UNSAFE] = "%s foi recusado: contém arquivos fora de um save, links ou dados demais.", + [UI_MENU_TAB_COOP] = "Co-op", + [UI_MENU_COOP_ON] = "Co-op (experimental)", + [UI_MENU_COOP_ON_DESC] = "Jogue com amigos pela Steam, cada um no seu jogo e no seu save. Ninguém configura roteador: " + "salas e convites passam pela Steam, que mostra você jogando Spacewar, o app de teste dela. " + "Precisa da Steam aberta e do arquivo steam_api64.dll ao lado do jogo. Desligado: o jogo não usa " + "a rede.", + [UI_MENU_COOP_NO_LIBRARY] = "O arquivo da biblioteca da Steam, steam_api64.dll, não está ao lado do jogo. Copie um da pasta " + "de qualquer jogo da Steam para a pasta do ocarina.exe e escolha Procurar a Steam de novo.", + [UI_MENU_COOP_OLD_LIBRARY] = "O steam_api64.dll ao lado do jogo é antigo demais para o co-op. Troque por um de um jogo mais " + "novo da Steam.", + [UI_MENU_COOP_NO_CLIENT] = "A Steam não respondeu. Abra a Steam, entre na sua conta e escolha Procurar a Steam de novo.", + [UI_MENU_COOP_RETRY] = "Procurar a Steam de novo", + [UI_MENU_COOP_RETRY_DESC] = "Tenta falar com a Steam agora; o jogo também tenta sozinho a cada poucos segundos.", + [UI_MENU_COOP_CREATE] = "Criar uma sala", + [UI_MENU_COOP_CREATE_DESC] = "Cria uma sala para até quatro jogadores. Você recebe um ID da sala para passar adiante e pode " + "convidar amigos da Steam.", + [UI_MENU_COOP_JOIN] = "Entrar em uma sala", + [UI_MENU_COOP_JOIN_DESC] = "Entra na sala cujo ID um amigo passou para você.", + [UI_MENU_COOP_ROOM_ID] = "ID da sala", + [UI_MENU_COOP_ROOM_ID_DESC] = "Os amigos digitam isto em Entrar em uma sala. Pressione para copiar. Quem tiver o ID pode " + "entrar, então passe só para quem você quer no seu jogo.", + [UI_MENU_COOP_ROOM_ID_HINT] = "8 letras e números, como XXXX-XXXX: maiúsculas ou minúsculas, com ou sem o traço.", + [UI_MENU_COOP_ROOM_ID_BAD] = "Isto não é um ID de sala: veja se há algum caractere errado.", + [UI_MENU_COOP_PASTE] = "Colar", + [UI_MENU_COOP_PASTE_EMPTY] = "A área de transferência não tem texto.", + [UI_MENU_COOP_COPIED] = "copiado", + [UI_MENU_COOP_OK] = "OK", + [UI_MENU_COOP_JOINING] = "Entrando na sala…", + [UI_MENU_COOP_STOP] = "Parar", + [UI_MENU_COOP_STOP_DESC] = "Para de tentar entrar na sala.", + [UI_MENU_COOP_INVITE] = "Convidar um amigo", + [UI_MENU_COOP_INVITE_DESC] = "Envia um convite da Steam a um amigo. Ele chega a quem está com o NX2navi aberto e o co-op " + "ligado; os outros podem usar o ID da sala.", + [UI_MENU_COOP_INVITE_TITLE] = "Convidar um amigo da Steam", + [UI_MENU_COOP_INVITE_NONE] = "A Steam não mostra amigos.", + [UI_MENU_COOP_INVITE_SENT] = "Convite enviado para %s.", + [UI_MENU_COOP_INVITE_IN_GAME] = "no co-op agora", + [UI_MENU_COOP_INVITE_ONLINE] = "online", + [UI_MENU_COOP_INVITE_OFFLINE] = "offline", + [UI_MENU_COOP_INVITE_STEAM] = "Janela de convites da Steam", + [UI_MENU_COOP_INVITE_CLOSE] = "Fechar", + [UI_MENU_COOP_INVITED] = "%s convida você para uma sala.", + [UI_MENU_COOP_INVITED_JOIN] = "Entrar na sala", + [UI_MENU_COOP_INVITED_JOIN_DESC] = "Entra na sala para a qual você foi convidado.", + [UI_MENU_COOP_INVITED_NO] = "Agora não", + [UI_MENU_COOP_INVITED_NO_DESC] = "Dispensa o convite.", + [UI_MENU_COOP_PLAYERS] = "Jogadores", + [UI_MENU_COOP_YOU] = "você", + [UI_MENU_COOP_HOST] = "anfitrião", + [UI_MENU_COOP_PLAYER_DESC] = "Um jogador da sala e a área em que o Link dele está.", + [UI_MENU_COOP_PLAYER_REMOVE_DESC] = "Um jogador da sala. Como anfitrião, você pode pressionar para removê-lo da sala.", + [UI_MENU_COOP_PLAYER_AWAY] = "fora do mundo", + [UI_MENU_COOP_REMOVE] = "Remover", + [UI_MENU_COOP_REMOVE_CONFIRM] = "Remover %s da sala? Essa pessoa não poderá voltar a esta sala.", + [UI_MENU_COOP_LEAVE] = "Sair da sala", + [UI_MENU_COOP_LEAVE_DESC] = "Sai da sala. Seu jogo e seu save continuam como estão.", + [UI_MENU_COOP_LEAVE_CONFIRM] = "Sair da sala?", + [UI_MENU_COOP_LEAVE_HOST] = "Você é o anfitrião: a sala continua com outro jogador como anfitrião.", + [UI_MENU_COOP_STAY] = "Ficar", + [UI_MENU_COOP_CHAT] = "Chat", + [UI_MENU_COOP_CHAT_WRITE] = "Escrever uma mensagem", + [UI_MENU_COOP_CHAT_WRITE_DESC] = "Envia uma linha de texto a todos na sala.", + [UI_MENU_COOP_SEND] = "Enviar", + [UI_MENU_COOP_CHAT_JOINED] = "%s entrou na sala", + [UI_MENU_COOP_CHAT_LEFT] = "%s saiu da sala", + [UI_MENU_COOP_SETTINGS] = "Configurações do co-op", + [UI_MENU_COOP_SHARE] = "Compartilhar progresso", + [UI_MENU_COOP_SHARE_DESC] = "Em uma sala, o que qualquer um conquista vale para todos: história, baús, portas, itens e " + "canções. Antes de algo da sala chegar ao seu save, ele é copiado para coop-backup na pasta do " + "perfil. Chaves pequenas, rupias, munição e corações continuam seus. Desligado: só nomes e chat " + "são compartilhados.", + [UI_MENU_COOP_NAMES] = "Mostrar nomes dos jogadores", + [UI_MENU_COOP_NAMES_DESC] = "Mostra o nome de cada outro jogador onde o Link dele está no seu mundo, com a distância. Precisa " + "de DLSS, FSR ou TAA ligado (só assim o menu sabe para onde a câmera olha).", + [UI_MENU_COOP_CHAT_SHOW] = "Mostrar o chat sobre o jogo", + [UI_MENU_COOP_CHAT_SHOW_DESC] = "Novas linhas do chat e quem entrou ou saiu aparecem por alguns segundos com o menu fechado.", + [UI_MENU_COOP_N_CREATE_FAILED] = "A Steam não conseguiu criar a sala. Tente de novo em instantes.", + [UI_MENU_COOP_N_NO_ROOM] = "Nenhuma sala tem esse ID: confira, ou pergunte ao seu amigo se a sala ainda está aberta.", + [UI_MENU_COOP_N_FULL] = "A sala está cheia.", + [UI_MENU_COOP_N_REFUSED] = "A sala não deixou você entrar.", + [UI_MENU_COOP_N_NOT_OURS] = "Essa não é uma sala do NX2navi.", + [UI_MENU_COOP_N_OTHER_VERSION] = "O anfitrião da sala usa outra versão do NX2navi ou do jogo: usem as mesmas versões.", + [UI_MENU_COOP_N_REMOVED] = "O anfitrião removeu você da sala.", + [UI_MENU_COOP_N_HOST_SILENT] = "O anfitrião da sala não respondeu.", + [UI_MENU_COOP_N_LOST] = "A Steam perdeu a conexão; a sala acabou.", + [UI_MENU_COOP_N_LEFT] = "Você saiu da sala.", + [UI_MENU_COOP_LOCAL] = "Modo de teste: um substituto da Steam neste PC.", + [UI_MENU_COOP_TOAST_INVITE] = "%s convida você para uma sala: abra a aba Co-op do menu.", [UI_BOOT_TITLE] = "Preparando shaders", [UI_BOOT_STARTING] = "Iniciando", [UI_BOOT_SHADERS] = "Shaders: %lld de %lld", [UI_BOOT_PIPELINES] = "Pipelines: %lld de %lld", [UI_MENU_CHEATS_REBUILD] = "Recompilar o jogo agora", @@ -2374,6 +2638,84 @@ static const char *const text_zh_hans[UI_TEXT_COUNT] = { [UI_MENU_SAVE_E_NEWER] = "%s 由更新版本的 NX2navi 制作:请先更新 NX2navi。", [UI_MENU_SAVE_E_DAMAGED] = "%s 已损坏:请重新下载。", [UI_MENU_SAVE_E_UNSAFE] = "%s 被拒绝:其中含有存档以外的文件、链接或过多的数据。", + [UI_MENU_TAB_COOP] = "合作", + [UI_MENU_COOP_ON] = "合作(实验性)", + [UI_MENU_COOP_ON_DESC] = "通过 Steam 与朋友一起玩,各自运行自己的游戏和存档。无需设置路由器:房间和邀请都经由 Steam,Steam 会显示你正在玩它的测试应用 Spacewar。需要 Steam " + "正在运行,并且游戏旁边有它的库文件 steam_api64.dll。关闭:游戏不使用网络。", + [UI_MENU_COOP_NO_LIBRARY] = "游戏旁边没有 Steam 的库文件 steam_api64.dll。从任意 Steam 游戏的文件夹里复制一个到 ocarina.exe 所在的文件夹,然后选择“重新查找 Steam”。", + [UI_MENU_COOP_OLD_LIBRARY] = "游戏旁边的 steam_api64.dll 对合作模式来说太旧。请换成较新的 Steam 游戏里的那个文件。", + [UI_MENU_COOP_NO_CLIENT] = "Steam 没有响应。请启动 Steam 并登录,然后选择“重新查找 Steam”。", + [UI_MENU_COOP_RETRY] = "重新查找 Steam", + [UI_MENU_COOP_RETRY_DESC] = "立即尝试连接 Steam;游戏每隔几秒也会自动尝试。", + [UI_MENU_COOP_CREATE] = "创建房间", + [UI_MENU_COOP_CREATE_DESC] = "创建一个最多四人的房间。你会得到一个可以告诉别人的房间 ID,也可以邀请 Steam 好友。", + [UI_MENU_COOP_JOIN] = "加入房间", + [UI_MENU_COOP_JOIN_DESC] = "加入朋友给你的房间 ID 对应的房间。", + [UI_MENU_COOP_ROOM_ID] = "房间 ID", + [UI_MENU_COOP_ROOM_ID_DESC] = "朋友在“加入房间”里输入它。按下即可复制。拿到它的人都能加入,所以只告诉你想一起玩的人。", + [UI_MENU_COOP_ROOM_ID_HINT] = "8 位字母和数字,形如 XXXX-XXXX:不分大小写,带不带连字符都可以。", + [UI_MENU_COOP_ROOM_ID_BAD] = "这不是房间 ID:请检查是否输错了字符。", + [UI_MENU_COOP_PASTE] = "粘贴", + [UI_MENU_COOP_PASTE_EMPTY] = "剪贴板里没有文字。", + [UI_MENU_COOP_COPIED] = "已复制", + [UI_MENU_COOP_OK] = "确定", + [UI_MENU_COOP_JOINING] = "正在进入房间…", + [UI_MENU_COOP_STOP] = "停止", + [UI_MENU_COOP_STOP_DESC] = "停止尝试进入房间。", + [UI_MENU_COOP_INVITE] = "邀请好友", + [UI_MENU_COOP_INVITE_DESC] = "向好友发送 Steam 邀请。只有正在运行 NX2navi 并开启了合作模式的好友能收到;其他人可以使用房间 ID。", + [UI_MENU_COOP_INVITE_TITLE] = "邀请 Steam 好友", + [UI_MENU_COOP_INVITE_NONE] = "Steam 没有显示任何好友。", + [UI_MENU_COOP_INVITE_SENT] = "已向 %s 发送邀请。", + [UI_MENU_COOP_INVITE_IN_GAME] = "正在合作模式中", + [UI_MENU_COOP_INVITE_ONLINE] = "在线", + [UI_MENU_COOP_INVITE_OFFLINE] = "离线", + [UI_MENU_COOP_INVITE_STEAM] = "Steam 的邀请窗口", + [UI_MENU_COOP_INVITE_CLOSE] = "关闭", + [UI_MENU_COOP_INVITED] = "%s 邀请你加入房间。", + [UI_MENU_COOP_INVITED_JOIN] = "加入对方的房间", + [UI_MENU_COOP_INVITED_JOIN_DESC] = "加入邀请你的那个房间。", + [UI_MENU_COOP_INVITED_NO] = "暂不", + [UI_MENU_COOP_INVITED_NO_DESC] = "忽略这次邀请。", + [UI_MENU_COOP_PLAYERS] = "玩家", + [UI_MENU_COOP_YOU] = "你", + [UI_MENU_COOP_HOST] = "房主", + [UI_MENU_COOP_PLAYER_DESC] = "房间里的一名玩家,以及其林克所在的区域。", + [UI_MENU_COOP_PLAYER_REMOVE_DESC] = "房间里的一名玩家。作为房主,你可以按下将其移出房间。", + [UI_MENU_COOP_PLAYER_AWAY] = "不在世界中", + [UI_MENU_COOP_REMOVE] = "移出", + [UI_MENU_COOP_REMOVE_CONFIRM] = "将 %s 移出房间?对方将无法再回到这个房间。", + [UI_MENU_COOP_LEAVE] = "离开房间", + [UI_MENU_COOP_LEAVE_DESC] = "离开房间。你的游戏和存档保持现状。", + [UI_MENU_COOP_LEAVE_CONFIRM] = "离开房间?", + [UI_MENU_COOP_LEAVE_HOST] = "你是房主:房间会继续存在,由另一名玩家担任房主。", + [UI_MENU_COOP_STAY] = "留下", + [UI_MENU_COOP_CHAT] = "聊天", + [UI_MENU_COOP_CHAT_WRITE] = "写消息", + [UI_MENU_COOP_CHAT_WRITE_DESC] = "向房间里的所有人发送一行文字。", + [UI_MENU_COOP_SEND] = "发送", + [UI_MENU_COOP_CHAT_JOINED] = "%s 加入了房间", + [UI_MENU_COOP_CHAT_LEFT] = "%s 离开了房间", + [UI_MENU_COOP_SETTINGS] = "合作设置", + [UI_MENU_COOP_SHARE] = "共享进度", + [UI_MENU_COOP_SHARE_DESC] = "在房间里,任何人取得的进展都算作所有人的:剧情、宝箱、门、道具和乐曲。在房间里的任何内容写入你的存档之前,存档会先复制到配置文件夹里的 " + "coop-backup。小钥匙、卢比、弹药和心保持各自独立。关闭:只共享名字和聊天。", + [UI_MENU_COOP_NAMES] = "显示玩家名字", + [UI_MENU_COOP_NAMES_DESC] = "在其他玩家的林克所处的位置显示其名字和距离。需要开启 DLSS、FSR 或 TAA(只有这样菜单才知道摄像机的朝向)。", + [UI_MENU_COOP_CHAT_SHOW] = "在游戏画面上显示聊天", + [UI_MENU_COOP_CHAT_SHOW_DESC] = "菜单关闭时,新的聊天内容以及玩家加入或离开的提示会显示几秒钟。", + [UI_MENU_COOP_N_CREATE_FAILED] = "Steam 无法创建房间。请稍后再试。", + [UI_MENU_COOP_N_NO_ROOM] = "没有使用这个 ID 的房间:请检查一下,或者问问朋友房间是否还开着。", + [UI_MENU_COOP_N_FULL] = "房间已满。", + [UI_MENU_COOP_N_REFUSED] = "房间没有让你进入。", + [UI_MENU_COOP_N_NOT_OURS] = "那不是 NX2navi 的房间。", + [UI_MENU_COOP_N_OTHER_VERSION] = "房主使用的 NX2navi 或游戏版本与你不同:请使用相同的版本。", + [UI_MENU_COOP_N_REMOVED] = "房主已将你移出房间。", + [UI_MENU_COOP_N_HOST_SILENT] = "房主没有响应。", + [UI_MENU_COOP_N_LOST] = "Steam 断开了连接;房间已不存在。", + [UI_MENU_COOP_N_LEFT] = "你已离开房间。", + [UI_MENU_COOP_LOCAL] = "测试模式:在本机上代替 Steam。", + [UI_MENU_COOP_TOAST_INVITE] = "%s 邀请你加入房间:请打开菜单的“合作”页。", [UI_BOOT_TITLE] = "正在准备着色器", [UI_BOOT_STARTING] = "正在启动", [UI_BOOT_SHADERS] = "着色器:%lld / %lld", [UI_BOOT_PIPELINES] = "管线:%lld / %lld", [UI_MENU_CHEATS_REBUILD] = "立即重新构建游戏", diff --git a/runtime/ui_text.h b/runtime/ui_text.h index 9f6e1828..7f099824 100644 --- a/runtime/ui_text.h +++ b/runtime/ui_text.h @@ -267,7 +267,27 @@ typedef enum { UI_MENU_SAVE_E_STAGE, UI_MENU_SAVE_E_NOT_SAVE, UI_MENU_SAVE_E_OTHER_GAME, UI_MENU_SAVE_E_NEWER, UI_MENU_SAVE_E_DAMAGED, UI_MENU_SAVE_E_UNSAFE, - UI_MENU_LAST_ID = UI_MENU_SAVE_E_UNSAFE, + // the Co-op tab and what co-op draws over the game (ui/coop_page.cpp, docs/coop.md) + UI_MENU_TAB_COOP, UI_MENU_COOP_ON, UI_MENU_COOP_ON_DESC, UI_MENU_COOP_NO_LIBRARY, UI_MENU_COOP_OLD_LIBRARY, + UI_MENU_COOP_NO_CLIENT, UI_MENU_COOP_RETRY, UI_MENU_COOP_RETRY_DESC, UI_MENU_COOP_CREATE, + UI_MENU_COOP_CREATE_DESC, UI_MENU_COOP_JOIN, UI_MENU_COOP_JOIN_DESC, UI_MENU_COOP_ROOM_ID, + UI_MENU_COOP_ROOM_ID_DESC, UI_MENU_COOP_ROOM_ID_HINT, UI_MENU_COOP_ROOM_ID_BAD, UI_MENU_COOP_PASTE, + UI_MENU_COOP_PASTE_EMPTY, UI_MENU_COOP_COPIED, UI_MENU_COOP_OK, UI_MENU_COOP_JOINING, UI_MENU_COOP_STOP, + UI_MENU_COOP_STOP_DESC, UI_MENU_COOP_INVITE, UI_MENU_COOP_INVITE_DESC, UI_MENU_COOP_INVITE_TITLE, + UI_MENU_COOP_INVITE_NONE, UI_MENU_COOP_INVITE_SENT, UI_MENU_COOP_INVITE_IN_GAME, UI_MENU_COOP_INVITE_ONLINE, + UI_MENU_COOP_INVITE_OFFLINE, UI_MENU_COOP_INVITE_STEAM, UI_MENU_COOP_INVITE_CLOSE, UI_MENU_COOP_INVITED, + UI_MENU_COOP_INVITED_JOIN, UI_MENU_COOP_INVITED_JOIN_DESC, UI_MENU_COOP_INVITED_NO, + UI_MENU_COOP_INVITED_NO_DESC, UI_MENU_COOP_PLAYERS, UI_MENU_COOP_YOU, UI_MENU_COOP_HOST, + UI_MENU_COOP_PLAYER_DESC, UI_MENU_COOP_PLAYER_REMOVE_DESC, UI_MENU_COOP_PLAYER_AWAY, UI_MENU_COOP_REMOVE, + UI_MENU_COOP_REMOVE_CONFIRM, UI_MENU_COOP_LEAVE, UI_MENU_COOP_LEAVE_DESC, UI_MENU_COOP_LEAVE_CONFIRM, + UI_MENU_COOP_LEAVE_HOST, UI_MENU_COOP_STAY, UI_MENU_COOP_CHAT, UI_MENU_COOP_CHAT_WRITE, + UI_MENU_COOP_CHAT_WRITE_DESC, UI_MENU_COOP_SEND, UI_MENU_COOP_CHAT_JOINED, UI_MENU_COOP_CHAT_LEFT, + UI_MENU_COOP_SETTINGS, UI_MENU_COOP_SHARE, UI_MENU_COOP_SHARE_DESC, UI_MENU_COOP_NAMES, UI_MENU_COOP_NAMES_DESC, + UI_MENU_COOP_CHAT_SHOW, UI_MENU_COOP_CHAT_SHOW_DESC, UI_MENU_COOP_N_CREATE_FAILED, UI_MENU_COOP_N_NO_ROOM, + UI_MENU_COOP_N_FULL, UI_MENU_COOP_N_REFUSED, UI_MENU_COOP_N_NOT_OURS, UI_MENU_COOP_N_OTHER_VERSION, + UI_MENU_COOP_N_REMOVED, UI_MENU_COOP_N_HOST_SILENT, UI_MENU_COOP_N_LOST, UI_MENU_COOP_N_LEFT, + UI_MENU_COOP_LOCAL, UI_MENU_COOP_TOAST_INVITE, + UI_MENU_LAST_ID = UI_MENU_COOP_TOAST_INVITE, // the boot screen while the boot prewarm prepares shaders and pipelines (boot.c, ui/menu.cpp menu_boot_frame) UI_BOOT_TITLE, UI_BOOT_STARTING, UI_BOOT_SHADERS, UI_BOOT_PIPELINES, // printf: "%lld" done, "%lld" total diff --git a/tests/coop_peer.py b/tests/coop_peer.py new file mode 100644 index 00000000..a72d9a73 --- /dev/null +++ b/tests/coop_peer.py @@ -0,0 +1,130 @@ +"""A second co-op player without a second game, for tests on one PC (docs/coop.md, "Checks"). + +It speaks the stand-in for Steam (runtime/coop_local.c: datagrams between UDP ports on 127.0.0.1) and the room's +messages (runtime/coop.c, runtime/coop_game.c) to a game started with NX2NAVI_COOP_LOCAL= and +NX2NAVI_COOP_LOCAL_MAKE=1: + + python tests/coop_peer.py --host 27601 [--port 27602] [--seconds 120] [--flags HASH[,HASH...]] + +It joins the game's room, says HELLO, and once the game's Link is in the world stands two metres beside him (so the +game shows its name there), says a chat line, asks for the game's shared progress and, with --flags, sends those flags +(hex hashes of on/off flags) as set. It prints what the game sends and ends with "peer: ok" when it was let in, saw +the game's Link in the world and got its progress; python's exit code says the same. Standard library only. +""" +import argparse +import socket +import struct +import sys +import time + +L_JOIN, L_MEMBERS, L_DATA, L_LEAVE = 1, 2, 3, 4 +K_HELLO, K_WELCOME, K_REFUSED, K_ROSTER, K_POSE, K_CHAT = 1, 2, 3, 4, 5, 6 +K_FLAGS, K_ASK = 16, 17 +PROTOCOL, GAME_BUILD = 1, 0xE0F3CCFA + + +def pose_bytes(number, pos, scene): + s = scene.encode() + return struct.pack('= 1.0: + sock.sendto(bytes([L_JOIN]), host) + last_join = now + if in_lobby and not welcomed and now - last_hello >= 1.0: + send(K_HELLO, struct.pack('= 0.05: + number += 1 + if host_pose and host_pose[0]: + send(K_POSE, pose_bytes(number, (host_pose[1] + 2.0, host_pose[2], host_pose[3] + 2.0), host_pose[0])) + else: + send(K_POSE, pose_bytes(number, (0.0, 0.0, 0.0), '')) + last_pose = now + if welcomed and host_pose and host_pose[0] and not chatted: + send(K_CHAT, 'hello from the test peer'.encode()) + chatted = True + print('peer: sent a chat line') + if welcomed and schema is not None and now - last_ask >= 5.0: + send(K_ASK, struct.pack('= 2: + kind, b = d[1], d[2:] + if kind == K_WELCOME: + welcomed = True + print('peer: the host let it in') + elif kind == K_REFUSED: + print(f'peer: REFUSED, reason {b[0] if b else "?"}') + return 1 + elif kind == K_ROSTER and b: + if b[0] != roster: + roster = b[0] + print(f'peer: the host lists {roster} players: {[struct.unpack_from("= 34: + n, x, y, z, vx, vy, vz, yaw, fl, sl = struct.unpack_from('= 4: + if schema is None: + schema = struct.unpack_from(' 0 + print('peer: ok' if ok else 'peer: FAILED') + return 0 if ok else 1 + + +if __name__ == '__main__': + sys.exit(main()) diff --git a/tests/save_share_check.c b/tests/save_share_check.c index f36e04f1..7528a098 100644 --- a/tests/save_share_check.c +++ b/tests/save_share_check.c @@ -65,6 +65,7 @@ int romfs_owns(const char *path) { (void)path; return 0; } int mem_probing(void) { return 0; } // write_file asks before each write: no probe, no lazy heap here void mem_kernel_access(uint64_t a, uint64_t n) { (void)a, (void)n; } void fs_trace(const char *what, const char *path) { (void)what, (void)path; } +void coop_game_rom_open(const char *path) { (void)path; } // co-op watches for the title screen's start: not here int main(int argc, char **argv) { if (argc < 3) return 2;