diff --git a/CHANGELOG.md b/CHANGELOG.md index 0a31527b..06b68229 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -18,6 +18,18 @@ - Now: each button is drawn where it sits on your controller: A at the bottom, B at the right, X at the left, Y at the top. A remapped button layout is followed the same way - Until **Set up again** has run, the prompt stays as it was +### Link Play +- **Split screen:** two to four players on one PC (#684). **Link Play > Split screen > Start split screen** in the launcher runs the game once per player, each in a window of their own that shares the screen (two halves, or a quarter each), and the others join player 1's world on their own + - **Join player 1 automatically** (on): once every player has loaded their save, the others are taken to player 1's world. Nobody walks to the PC or opens the Link Play menu, and it works before the game unlocks Link Play, from the first minutes of a new game. A waiting screen covers a joining player's picture until they are there. Off: the players meet through the game's Link Play menu, as in any Link Play session + - **Start next to player 1** (on): a player who joined starts where player 1 stands, not at the PC, where the game lets a visitor arrive. A new game's first cave cannot be reached from the PC. Switch it off once player 1 can be reached from there + - Each player plays one controller; player 1 can play with the keyboard and mouse instead + - Every other player is a profile with a save of their own; one without a save starts from a copy of player 1's + - The other players' windows are silent unless you turn their sound on. Each game needs about 7 GB of memory: 32 GB is recommended for two players, 64 GB for four + +### For developers +- Split screen is one process per player: the runtime's `[split]` keys (`runtime/include/nxrt/split.h`, `runtime/src/gfx/play/play_split.cpp`) keep a window in its part of the screen and give it one controller, the launcher's `split.rs` starts the group with those keys in each process's environment, and `pkp_save_uuid.cpp` gives a copied save a player UUID of its own +- `[split] meet` and `together` (`pkp_split_session.cpp`): the game layer makes the requests the game's multiplayer menu makes of its Link Play session manager (open a session, search, join), on the game thread, and takes a visitor to the first player with the game's own warp of a player. `pkp_wait_screen.{h,cpp}` is a waiting screen over the picture that any feature can show + ## 0.13.8 (build Q: Quokka Hotfix a5) **Update:** press **Update** in the launcher, then **Set up again** (it relinks the game; saves and shaders are kept, no shader is translated again). diff --git a/game-build/src/pkp_main.cpp b/game-build/src/pkp_main.cpp index 4615c66b..8c1d6ea4 100644 --- a/game-build/src/pkp_main.cpp +++ b/game-build/src/pkp_main.cpp @@ -447,11 +447,14 @@ int main(int argc, char** argv) { nxrt::play::DisplayConfig disp; if (!headless) { disp = nxrt::play::display(); // controls.ini: window size, present mode, frame cap - nxrt::platform::init(); + nxrt::platform::InitOptions po; + po.place_windows = disp.places_window; + nxrt::platform::init(po); nxrt::platform::WindowDesc wd; wd.title = nxrt::game::info().title; wd.width = disp.width; wd.height = disp.height; + wd.focusable = disp.takes_focus; if (!nxrt::platform::create_window(wd)) die("cannot create the game window. The game needs a graphics driver with Vulkan 1.3: update the driver for your graphics card and try again. The reason is in pkp.log."); } nxrt::gfx::DeviceDesc dd; diff --git a/launcher/src-tauri/src/launch.rs b/launcher/src-tauri/src/launch.rs index 22282c0a..7bc71828 100644 --- a/launcher/src-tauri/src/launch.rs +++ b/launcher/src-tauri/src/launch.rs @@ -8,16 +8,13 @@ use crate::config::load_config; use crate::guard::{ensure_idle, Need}; use crate::paths::game_dir_of; use crate::readiness::readiness; -use crate::{play, profiles, settings}; +use crate::{play, profiles, settings, split}; -/// `without_mods`: this one start runs without mods (the runtime's [mods] off, passed in the game's environment only). -#[tauri::command] -pub fn play(app: AppHandle, without_mods: Option) -> Result<(), String> { - // an update may be preparing: Play waits only for its swap, and holds it off until this game has started (play::start) - let updates = app.updates(); - let _swap = updates.hold_swap(); - ensure_idle(&app, &[Need::Swap, Need::Storage])?; - let cfg = load_config(&app); +/// What both ways of starting the game check and write first: nothing that Play must wait for is busy, setup is finished, pkp.ini +/// names the dump and the active profile. Returns the game folder and the launcher's options. +fn ready_to_play(app: &AppHandle) -> Result<(std::path::PathBuf, crate::config::Config), String> { + ensure_idle(app, &[Need::Swap, Need::Storage])?; + let cfg = load_config(app); let probe = readiness(&cfg); if probe.readiness.kind != "ready" { return Err(probe.readiness.detail); @@ -29,7 +26,35 @@ pub fn play(app: AppHandle, without_mods: Option) -> Result<(), String> { settings::ensure_play_paths(&dir, &paths.exefs, &paths.romfs, &paths.romfs_base, &paths.aoc_dir)?; } profiles::apply_active(&dir)?; - play::start(&app, &dir, &cfg, without_mods.unwrap_or(false)) + Ok((dir, cfg)) +} + +/// `without_mods`: this one start runs without mods (the runtime's [mods] off, passed in the game's environment only). +#[tauri::command] +pub fn play(app: AppHandle, without_mods: Option) -> Result<(), String> { + // an update may be preparing: Play waits only for its swap, and holds it off until this game has started (play::start) + let updates = app.updates(); + let _swap = updates.hold_swap(); + let (dir, cfg) = ready_to_play(&app)?; + play::start(&app, &dir, &cfg, without_mods.unwrap_or(false), None) +} + +/// Split screen: the game once per player, the active profile in the first window and the other players in theirs (split.rs). +#[tauri::command] +pub fn play_split(app: AppHandle, options: split::Options) -> Result<(), String> { + let updates = app.updates(); + let _swap = updates.hold_swap(); + // the other players' saves are made before the start: no game may hold the save folder open + ensure_idle(&app, &[Need::Game("The game is running. Close it first, then start split screen.")])?; + let (dir, cfg) = ready_to_play(&app)?; + let group = split::prepare(&dir, &options)?; + play::start(&app, &dir, &cfg, false, Some(group)) +} + +/// Who would play split screen: the active profile, and the profiles that can be the other players. +#[tauri::command] +pub fn split_players(app: AppHandle) -> split::Players { + split::players(&crate::config::game_dir(&app)) } #[tauri::command] diff --git a/launcher/src-tauri/src/main.rs b/launcher/src-tauri/src/main.rs index 7dfe56e5..c20b5cb2 100644 --- a/launcher/src-tauri/src/main.rs +++ b/launcher/src-tauri/src/main.rs @@ -69,6 +69,7 @@ mod setup_job; mod setuplog; mod shader_archive; mod shaders; +mod split; mod steam; mod steam_cmds; mod states; @@ -160,6 +161,8 @@ fn main() { settings_cmds::write_settings, settings_cmds::prompt_icon_pack, launch::play, + launch::play_split, + launch::split_players, setup_job::setup_status, setup_job::start_setup, setup_job::preflight, diff --git a/launcher/src-tauri/src/play.rs b/launcher/src-tauri/src/play.rs index 0054ade2..a6b76768 100644 --- a/launcher/src-tauri/src/play.rs +++ b/launcher/src-tauri/src/play.rs @@ -63,7 +63,9 @@ fn report_files(dir: &Path, started: SystemTime) -> Vec { .collect() } -pub fn start(app: &AppHandle, game_dir: &Path, cfg: &Config, without_mods: bool) -> Result<(), String> { +/// `split`: split screen (split.rs). The game is started once per player, the other windows once the first runs, and they end with +/// the first. Everything else (the status, the save backups, the shaders afterwards) follows the first window, the player's own game. +pub fn start(app: &AppHandle, game_dir: &Path, cfg: &Config, without_mods: bool, split: Option) -> Result<(), String> { let (minimize, discord) = (cfg.minimize_on_play, cfg.discord_presence); let gentle = cfg.gentle_build; { @@ -115,13 +117,18 @@ pub fn start(app: &AppHandle, game_dir: &Path, cfg: &Config, without_mods: bool) eprintln!("branding: {e}"); } // Calculate after shader preparation, immediately before the process starts, so a long preparation cannot age the offset. - let mut cmd = match crate::events::override_for(&dir).and_then(|clock| game_command(&exe, &dir, clock, without_mods)) { + let clock = crate::events::override_for(&dir); + let first_log = split.as_ref().map_or("pkp.log", |p| p.first.log.as_str()); + let mut cmd = match clock.clone().and_then(|clock| game_command(&exe, &dir, clock, without_mods, first_log)) { Ok(c) => c, Err(e) => { set_status(&app2, Status { state: GameState::Exited, crashed: true, message: format!("Could not start pkp.exe: {}", e), ..Default::default() }); return; } }; + if let Some(pair) = &split { + pair.first.apply(&mut cmd); + } let started = SystemTime::now(); let mut child = match cmd.spawn() { Ok(c) => c, @@ -130,7 +137,22 @@ pub fn start(app: &AppHandle, game_dir: &Path, cfg: &Config, without_mods: bool) return; } }; - set_status(&app2, Status { state: GameState::Running, message: format!("pkp.exe started (process {})", child.id()), ..Default::default() }); + // split screen: the other windows, with the same clock. One that does not start leaves the others their game. + let mut others = vec![]; + let mut window_notes = String::new(); + for (i, window) in split.iter().flat_map(|group| &group.others).enumerate() { + let spawned = clock.clone().and_then(|clock| game_command(&exe, &dir, clock, without_mods, &window.log)).and_then(|mut c| { + window.apply(&mut c); + c.spawn().map_err(|e| e.to_string()) + }); + match spawned { + Ok(c) => others.push(c), + Err(e) => window_notes.push_str(&format!(" Window {} did not start: {}.", i + 2, e)), + } + } + // (the page reads the start of this message: action.js gamePhase) + let dot = if window_notes.is_empty() { "" } else { "." }; + set_status(&app2, Status { state: GameState::Running, message: format!("pkp.exe started (process {}){}{}", child.id(), dot, window_notes), ..Default::default() }); if minimize { if let Some(w) = app2.get_webview_window("main") { let _ = w.minimize(); @@ -141,6 +163,11 @@ pub fn start(app: &AppHandle, game_dir: &Path, cfg: &Config, without_mods: bool) let presence = crate::presence::Watch::start(discord); let online = crate::online::Watch::start(&app2, &dir); let result = wait_with_memory_guard(&mut child); + // the first window closed: the others go with it (one may have been closed before; then there is nothing to end) + for c in others.iter_mut() { + let _ = c.kill(); + let _ = c.wait(); + } online.finish(); presence.finish(); backups.finish(); @@ -172,7 +199,7 @@ pub fn start(app: &AppHandle, game_dir: &Path, cfg: &Config, without_mods: bool) (None, Some(c)) => format!("pkp.exe exited with code {} (0x{:08X}).", c, c as u32), (None, None) => "pkp.exe was ended by the system.".to_string(), }; - set_status(&app2, Status { state: GameState::Exited, code, crashed, files, message: message + &prep + &shaders }); + set_status(&app2, Status { state: GameState::Exited, code, crashed, files, message: message + &window_notes + &prep + &shaders }); if minimize { if let Some(w) = app2.get_webview_window("main") { let _ = w.unminimize(); @@ -184,15 +211,16 @@ pub fn start(app: &AppHandle, game_dir: &Path, cfg: &Config, without_mods: bool) } /// How Play starts the game: `pkp` in its folder on macOS and Linux, `pkp.exe` on Windows (host.rs). Every path (exefs, romfs, shader -/// cache) comes from pkp.ini next to it. `without_mods`: this start runs without mods. -fn game_command(exe: &Path, dir: &Path, clock: Option, without_mods: bool) -> Result { +/// cache) comes from pkp.ini next to it. `without_mods`: this start runs without mods. `log`: the log file, relative to the folder +/// (pkp.log; split screen's other windows have their own). +fn game_command(exe: &Path, dir: &Path, clock: Option, without_mods: bool, log: &str) -> Result { if !crate::host::native_game() { crate::host::sync_runtime_files(&crate::paths::exe_dir(), dir)?; // pkp_rt.dll and the ASTC decoders: Windows files } #[cfg(target_os = "macos")] crate::host::sync_macos_runtime(dir)?; // libpkp_rt.dylib and MoltenVK: a launcher update brings newer ones let mut cmd = std::process::Command::new(exe); - cmd.current_dir(dir).args(["--log", "pkp.log"]); + cmd.current_dir(dir).args(["--log", log]); // macOS: the folder is not the release's installed layout (no exefs/main next to the binary), so name the settings file; // the game reads exefs and romfs from it. if crate::host::native_game() && dir.join(crate::settings::PKP_INI).is_file() { @@ -259,7 +287,7 @@ pub fn run_cli(game_dir: &Path, tools: &Path) -> i32 { Err(e) => return fail(e), }; let backups = crate::savebackup::Watch::start(game_dir); // the same save backups as Play in the window - let status = game_command(&exe, game_dir, clock, false).and_then(|mut c| { + let status = game_command(&exe, game_dir, clock, false, "pkp.log").and_then(|mut c| { let mut child = c.spawn().map_err(|e| format!("Could not start {}: {}", crate::host::game_exe_name(), e))?; wait_with_memory_guard(&mut child).map_err(|e| format!("Lost track of {}: {}", crate::host::game_exe_name(), e)) }); diff --git a/launcher/src-tauri/src/saveimport.rs b/launcher/src-tauri/src/saveimport.rs index 64b6f165..4f8ffdf3 100644 --- a/launcher/src-tauri/src/saveimport.rs +++ b/launcher/src-tauri/src/saveimport.rs @@ -266,15 +266,31 @@ fn put_back(old: &[PathBuf], bacc: &Path) { /// Brings `src` (a folder holding G00 and S00, optionally B00) in as the game's committed account save. The source is only read. The /// caller has checked that the game is not running. pub fn import(save_dir: &Path, key: &str, src: &Path) -> Result { + let canon = |p: &Path| fs::canonicalize(p).unwrap_or_else(|_| p.to_path_buf()); + if is_save_folder(src) && canon(src).starts_with(canon(save_dir)) { + return Err(format!("{} is inside the save folder the game plays. Pick a copy outside it.", fwd(src))); + } + place(save_dir, key, src) +} + +/// One account's save as a copy of another's in the same save folder (split screen's second player starts from the first player's +/// save). Only for an account that has no save yet: `to_key`'s folder must not exist. The source is only read; the caller has checked +/// that the game is not running. +pub fn copy_account(save_dir: &Path, from_key: &str, to_key: &str) -> Result { + let acc = save_dir.join("account"); + if from_key == to_key || acc.join(to_key).exists() { + return Err(format!("{} already holds a save.", fwd(&acc.join(to_key)))); + } + place(save_dir, to_key, &acc.join(from_key)) +} + +/// The copy itself: `src` staged beside the account folder, an old save moved aside, the copy put in its place, its .meta written. +fn place(save_dir: &Path, key: &str, src: &Path) -> Result { if !is_save_folder(src) { return Err(format!("{} holds no Pokopia save (no G00 and S00 folders).", fwd(src))); } let acc = save_dir.join("account"); let root = acc.join(key); - let canon = |p: &Path| fs::canonicalize(p).unwrap_or_else(|_| p.to_path_buf()); - if canon(src).starts_with(canon(save_dir)) { - return Err(format!("{} is inside the save folder the game plays. Pick a copy outside it.", fwd(src))); - } fs::create_dir_all(&acc).map_err(|e| format!("Cannot create {}: {}", fwd(&acc), e))?; let t = crate::fsutil::file_stamp(); diff --git a/launcher/src-tauri/src/split.rs b/launcher/src-tauri/src/split.rs new file mode 100644 index 00000000..80b39ab4 --- /dev/null +++ b/launcher/src-tauri/src/split.rs @@ -0,0 +1,417 @@ +// SPDX-License-Identifier: GPL-3.0-or-later +//! Split screen: two to four players on this PC, each in a window of their own (the runtime's [split] keys, +//! runtime/include/nxrt/split.h). +//! +//! Play starts the game once per player. The first window is the active profile and hosts; every other one is another profile and +//! visits it through Link Play on 127.0.0.1. Nothing is written to pkp.ini: each window gets its role in its environment, which the +//! runtime reads before the file. A visiting player is a profile like any other (profiles.rs), so their save is a folder of their +//! own in the same save folder. One who has no save yet starts from a copy of the first player's, because a new game cannot visit +//! before its story has opened Link Play; the runtime gives that copy a player UUID of its own (the host refuses a visitor with its +//! own, and two copies must differ from each other too). + +use serde::{Deserialize, Serialize}; +use std::fs; +use std::path::Path; +use std::process::Command; + +use crate::profiles::{self, Profile, Store}; +use crate::saveimport; +use crate::settings::CONTROLS_INI; + +/// The group's own port, so it does not meet a normal Link Play host on this PC (47600) or a relay (47610). +pub const PORT: u16 = 47620; +/// The visiting windows' own files, inside the game folder: `split//` holds that window's log and its copy of controls.ini. +const DIR: &str = "split"; +/// The game's own limit for one Link Play session, and so the most windows. +pub const MAX_PLAYERS: usize = 4; + +/// What the page asks for. Every field has the default a first start uses. +#[derive(Deserialize, Clone, Debug)] +#[serde(default)] +pub struct Options { + /// How many play: 2 to 4 (anything else is 2). + pub players: usize, + /// Two players: left and right halves, else top and bottom. Three: the first player has the left half, else the top half. + pub side: bool, + /// The first player plays with the keyboard and mouse, so the others get the controllers from the first one on. + pub keyboard: bool, + /// The visiting windows play their sound too. + pub sound: bool, + /// The profile ids of players 2, 3 and 4, in that order. A missing or empty one: the next profile that can be one, made when + /// there is none. + pub others: Vec, + /// The players come together on their own: the first window opens its session and the others join it, once each player is in + /// the world (the runtime's [split] meet). Off: the players meet through the game's Link Play menu. + pub meet: bool, + /// With meet: a player who joined starts where the first player stands, not where the game lets a visitor arrive (the + /// runtime's [split] together). For the part of the game in which the first player cannot be reached from there. + pub together: bool, +} + +impl Default for Options { + fn default() -> Self { + Options { players: 2, side: false, keyboard: false, sound: false, others: Vec::new(), meet: true, together: true } + } +} + +impl Options { + fn players(&self) -> usize { + if (2..=MAX_PLAYERS).contains(&self.players) { self.players } else { 2 } + } +} + +/// One window: its log file (relative to the game folder) and what its environment adds. +pub struct Window { + pub log: String, + env: Vec<(&'static str, String)>, +} + +impl Window { + pub fn apply(&self, cmd: &mut Command) { + for (k, v) in &self.env { + cmd.env(k, v); + } + } +} + +/// The windows of one start: the first player's, and the visiting ones in player order. +pub struct Group { + pub first: Window, + pub others: Vec, +} + +/// Who can visit: any profile but the active one and the first one. The first profile is the existing save with the runtime's +/// built-in user, which has no id of its own to hand to another window. +pub fn candidates(s: &Store) -> Vec<&Profile> { + s.profiles.iter().filter(|p| p.id != s.active && p.id != profiles::DEFAULT_ID).collect() +} + +/// What the page shows before a start: the first player, and who can be one of the others. +#[derive(Serialize)] +pub struct Players { + pub first: String, + pub candidates: Vec, +} + +#[derive(Serialize)] +pub struct Candidate { + pub id: String, + pub name: String, +} + +pub fn players(game_dir: &Path) -> Players { + let s = profiles::load(game_dir); + Players { + first: s.active_profile().name.clone(), + candidates: candidates(&s).into_iter().map(|p| Candidate { id: p.id.clone(), name: p.name.clone() }).collect(), + } +} + +const NO_PROFILE: &str = "A player's profile could not be made."; + +/// The visiting players' profiles, for players 2 to `players`: the ones asked for, then for every player left open the next +/// candidate nobody has, then a new profile ("Player 2", or the next free number). Nobody plays twice. +fn other_profiles(game_dir: &Path, players: usize, wanted: &[String]) -> Result, String> { + let mut s = profiles::load(game_dir); + let mut out: Vec> = vec![None; players - 1]; + for (slot, id) in out.iter_mut().zip(wanted).filter(|(_, id)| !id.is_empty()) { + let p = candidates(&s).into_iter().find(|p| p.id == *id).cloned().ok_or("That profile cannot be one of the other players.")?; + *slot = Some(p); + } + let taken = |out: &[Option], id: &str| out.iter().flatten().any(|p| p.id == id); + for i in 0..out.len() { + if out[i].is_some() { + if out[..i].iter().flatten().any(|p| p.id == out[i].as_ref().unwrap().id) { + return Err("The same profile cannot play in two windows.".into()); + } + continue; + } + let free = candidates(&s).into_iter().find(|p| !taken(&out, &p.id)).cloned(); + out[i] = Some(match free { + Some(p) => p, + None => { + let name = (2..100) + .map(|n| format!("Player {}", n)) + .find(|n| !s.profiles.iter().any(|p| p.name.eq_ignore_ascii_case(n))) + .ok_or(NO_PROFILE)?; + s = profiles::add(game_dir, &name)?; + s.profiles.last().cloned().ok_or(NO_PROFILE)? + } + }); + } + Ok(out.into_iter().flatten().collect()) +} + +/// The nickname as a window's environment can carry it. Windows hands the runtime its environment in the ANSI code page, which +/// loses a name outside it; such a name plays as "Player " in split screen. +fn env_nickname(p: &Profile, player: usize) -> String { + if p.nickname.is_empty() || (cfg!(windows) && !p.nickname.is_ascii()) { + format!("Player {}", player) + } else { + p.nickname.clone() + } +} + +/// What every window of the group gets: how the screen is shared, and Link Play on this PC only. +fn shared_env(opt: &Options) -> Vec<(&'static str, String)> { + vec![ + ("NXRT_SPLIT_COUNT", opt.players().to_string()), + ("NXRT_SPLIT_LAYOUT", if opt.side { "side" } else { "stacked" }.into()), + ("NXRT_SPLIT_MEET", opt.meet.to_string()), + ("NXRT_SPLIT_TOGETHER", (opt.meet && opt.together).to_string()), + ("NXRT_NET_PROTOCOL", "native".into()), + ("NXRT_NET_INTERNET", "false".into()), + ] +} + +/// The first window: the active profile, as pkp.ini has it. It hosts on the group's port. +fn first_window(opt: &Options) -> Window { + let mut env = shared_env(opt); + env.extend([ + ("NXRT_SPLIT_WINDOW", "1".to_string()), + ("NXRT_SPLIT_PAD", if opt.keyboard { "0" } else { "1" }.to_string()), + ("NXRT_NET_MODE", format!("auto:{}", PORT)), + ]); + Window { log: "pkp.log".into(), env } +} + +/// A visiting window (`player` 2 to 4): the player's account and Link Play identity, the first player's account to differ from (its +/// folder name: Windows hands the runtime its environment in the ANSI code page, which does not carry every path) and files of its +/// own for what a running game writes next to itself. It only reads the pipeline cache: several processes writing one file would race. +fn other_window(opt: &Options, player: usize, profile: &Profile, first_key: &str) -> Window { + let mut env = shared_env(opt); + env.extend([ + ("NXRT_SPLIT_WINDOW", player.to_string()), + // with the first player on the keyboard, the controllers start at the second player + ("NXRT_SPLIT_PAD", (if opt.keyboard { player - 1 } else { player }).to_string()), + ("NXRT_SPLIT_MUTE", if opt.sound { "false" } else { "true" }.to_string()), + ("NXRT_SPLIT_FIRST_ACCOUNT", first_key.to_string()), + ("NXRT_ACCOUNT_UID", profile.uid.clone()), + ("NXRT_ACCOUNT_NICKNAME", env_nickname(profile, player)), + ("NXRT_NET_UID", profile.net_uid.clone()), + ("NXRT_NET_MODE", format!("join:127.0.0.1:{}", PORT)), + ("NXRT_PLAY_CONTROLS", format!("{}/{}/{}", DIR, player, CONTROLS_INI)), + ("NXRT_NVN_PIPELINE_CACHE_SAVE", "off".to_string()), + ]); + Window { log: format!("{}/{}/pkp.log", DIR, player), env } +} + +/// The first player's account folder: the one of the active profile's uid. The first profile's save can be older than its uid (a save +/// from before pkp.ini named one): then it is `found`, the folder the launcher's other save tools use (saveimport::locate), unless +/// that is one of the other players'. +fn first_key(s: &Store, account: &Path, found: String, other_keys: &[String]) -> String { + let p = s.active_profile(); + let own = saveimport::account_key_of(&p.uid); + if p.id != profiles::DEFAULT_ID || saveimport::is_save_folder(&account.join(&own)) || other_keys.contains(&found) { + return own; + } + found +} + +/// Everything a split start needs before a process runs: the other players' profiles, their saves (a copy of the first player's for +/// one who has none) and each visiting window's copy of controls.ini. The caller has checked that the game is not running. +pub fn prepare(game_dir: &Path, opt: &Options) -> Result { + let profiles = other_profiles(game_dir, opt.players(), &opt.others)?; + let (save_dir, found_key) = saveimport::locate(game_dir); + let keys = profiles.iter().map(|p| saveimport::uid_key(&p.uid).ok_or(NO_PROFILE.to_string())).collect::, _>>()?; + let account = save_dir.join("account"); + let first_key = first_key(&profiles::load(game_dir), &account, found_key, &keys); + let first_save = account.join(&first_key); + for key in keys.iter().filter(|k| !account.join(k).exists()) { + if !saveimport::is_save_folder(&first_save) { + break; // no save to start from: these players begin a new game + } + // the runtime's own rule (fs_volume.cpp): with .commit beside it the folder is not one consistent save + if account.join(format!("{}.commit", first_key)).exists() { + return Err("Your save has a write the game did not finish. Start the game once without split screen, then try again.".into()); + } + saveimport::copy_account(&save_dir, &first_key, key).map_err(|e| format!("A player's save could not be made: {}", e))?; + } + + // A visiting window starts every time from the settings as they are now: what is changed in it lasts for that session. + let not_prepared = |e: std::io::Error| format!("A window's settings could not be prepared: {}", e); + let mut others = vec![]; + for (i, profile) in profiles.iter().enumerate() { + let player = i + 2; + let own = game_dir.join(DIR).join(player.to_string()); + fs::create_dir_all(&own).map_err(not_prepared)?; + let (from, to) = (game_dir.join(CONTROLS_INI), own.join(CONTROLS_INI)); + if from.is_file() { + fs::copy(&from, &to).map_err(not_prepared)?; + } else { + let _ = fs::remove_file(&to); // no settings yet: the window writes the factory ones, as the first does + } + others.push(other_window(opt, player, profile, &first_key)); + } + Ok(Group { first: first_window(opt), others }) +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::settings::PKP_INI; + + fn tmp(tag: &str) -> std::path::PathBuf { + static N: std::sync::atomic::AtomicUsize = std::sync::atomic::AtomicUsize::new(0); + let d = std::env::temp_dir().join(format!("pkp-split-{}-{}-{}", tag, std::process::id(), N.fetch_add(1, std::sync::atomic::Ordering::SeqCst))); + let _ = fs::remove_dir_all(&d); + fs::create_dir_all(&d).unwrap(); + fs::write(d.join(PKP_INI), "[fs]\nsave_dir = save\n").unwrap(); + d + } + + fn env_of<'a>(w: &'a Window, key: &str) -> Option<&'a str> { + w.env.iter().find(|(k, _)| *k == key).map(|(_, v)| v.as_str()) + } + + /// A save of the first (built-in) user, the way the game leaves it. + fn first_save(d: &Path) -> std::path::PathBuf { + let root = d.join("save").join("account").join(saveimport::account_key_of("")); + for part in ["G00", "S00"] { + fs::create_dir_all(root.join(part)).unwrap(); + } + fs::write(root.join("G00").join("CMNDAT.BIN"), b"common").unwrap(); + fs::write(root.join("S00").join("SYDAT.BIN"), b"system").unwrap(); + root + } + + fn save_of(d: &Path, p: &Profile) -> std::path::PathBuf { + d.join("save").join("account").join(saveimport::uid_key(&p.uid).unwrap()) + } + + #[test] + fn a_first_start_makes_the_second_player_from_the_first_players_save() { + let d = tmp("first"); + let first = first_save(&d); + fs::write(d.join(CONTROLS_INI), "[display]\nwidth = 1600\n").unwrap(); + let group = prepare(&d, &Options::default()).unwrap(); + assert_eq!(group.others.len(), 1, "two players unless the page says more"); + let other = &group.others[0]; + + let s = profiles::load(&d); + let second = s.profiles.iter().find(|p| p.name == "Player 2").expect("a profile for the second player"); + assert_eq!(s.active, profiles::DEFAULT_ID, "the first player stays the active profile"); + assert_eq!(fs::read(save_of(&d, second).join("S00").join("SYDAT.BIN")).unwrap(), b"system"); + assert_eq!(fs::read(first.join("G00").join("CMNDAT.BIN")).unwrap(), b"common", "the first player's save is only read"); + assert_eq!(fs::read_to_string(d.join(DIR).join("2").join(CONTROLS_INI)).unwrap(), "[display]\nwidth = 1600\n"); + + assert_eq!(env_of(&group.first, "NXRT_SPLIT_WINDOW"), Some("1")); + assert_eq!(env_of(&group.first, "NXRT_SPLIT_COUNT"), Some("2")); + assert_eq!(env_of(&group.first, "NXRT_SPLIT_PAD"), Some("1")); + assert_eq!(env_of(&group.first, "NXRT_SPLIT_MEET"), Some("true"), "the players meet on their own unless the page says no"); + assert_eq!(env_of(other, "NXRT_SPLIT_TOGETHER"), Some("true")); + assert_eq!(env_of(&group.first, "NXRT_NET_MODE"), Some("auto:47620")); + assert_eq!(env_of(&group.first, "NXRT_ACCOUNT_UID"), None, "the first window plays the account in pkp.ini"); + assert_eq!(env_of(other, "NXRT_SPLIT_WINDOW"), Some("2")); + assert_eq!(env_of(other, "NXRT_SPLIT_PAD"), Some("2")); + assert_eq!(env_of(other, "NXRT_SPLIT_MUTE"), Some("true")); + assert_eq!(env_of(other, "NXRT_NET_MODE"), Some("join:127.0.0.1:47620")); + assert_eq!(env_of(other, "NXRT_ACCOUNT_UID"), Some(second.uid.as_str())); + assert_eq!(env_of(other, "NXRT_NET_UID"), Some(second.net_uid.as_str())); + assert_eq!(env_of(other, "NXRT_SPLIT_FIRST_ACCOUNT"), first.file_name().and_then(|n| n.to_str())); + assert_eq!(other.log, "split/2/pkp.log"); + } + + #[test] + fn a_second_start_keeps_the_second_players_save_and_profile() { + let d = tmp("again"); + first_save(&d); + prepare(&d, &Options::default()).unwrap(); + let s = profiles::load(&d); + let second = s.profiles.iter().find(|p| p.name == "Player 2").unwrap().clone(); + let copy = save_of(&d, &second); + fs::write(copy.join("S00").join("SYDAT.BIN"), b"their own progress").unwrap(); + + let group = prepare(&d, &Options { side: true, keyboard: true, sound: true, meet: false, ..Default::default() }).unwrap(); + assert_eq!(profiles::load(&d).profiles.len(), 2, "no second Player 2"); + assert_eq!(fs::read(copy.join("S00").join("SYDAT.BIN")).unwrap(), b"their own progress"); + assert_eq!(env_of(&group.others[0], "NXRT_ACCOUNT_UID"), Some(second.uid.as_str())); + // one-controller mode: the first player has the keyboard, the only controller is the second player's + assert_eq!(env_of(&group.first, "NXRT_SPLIT_PAD"), Some("0")); + assert_eq!(env_of(&group.others[0], "NXRT_SPLIT_PAD"), Some("1")); + assert_eq!(env_of(&group.others[0], "NXRT_SPLIT_MUTE"), Some("false")); + assert_eq!(env_of(&group.first, "NXRT_SPLIT_LAYOUT"), Some("side")); + assert_eq!(env_of(&group.others[0], "NXRT_SPLIT_MEET"), Some("false")); + assert_eq!(env_of(&group.others[0], "NXRT_SPLIT_TOGETHER"), Some("false"), "nobody is moved when the players meet by hand"); + } + + #[test] + fn four_players_are_four_windows_with_a_profile_and_a_save_each() { + let d = tmp("four"); + first_save(&d); + let misty = profiles::add(&d, "Misty").unwrap().profiles.last().unwrap().clone(); + let group = prepare(&d, &Options { players: 4, keyboard: true, ..Default::default() }).unwrap(); + assert_eq!(group.others.len(), 3); + + let s = profiles::load(&d); + let names: Vec<&str> = s.profiles.iter().map(|p| p.name.as_str()).collect(); + assert_eq!(names[1..], ["Misty", "Player 2", "Player 3"], "the profile that was there plays, two are made"); + assert_eq!(env_of(&group.others[0], "NXRT_ACCOUNT_UID"), Some(misty.uid.as_str())); + let mut uids = vec![]; + for (i, w) in group.others.iter().enumerate() { + let player = i + 2; + assert_eq!(env_of(w, "NXRT_SPLIT_WINDOW"), Some(player.to_string().as_str())); + assert_eq!(env_of(w, "NXRT_SPLIT_COUNT"), Some("4")); + assert_eq!(env_of(w, "NXRT_SPLIT_PAD"), Some((player - 1).to_string().as_str()), "the keyboard is the first player's"); + assert_eq!(w.log, format!("split/{}/pkp.log", player)); + uids.push(env_of(w, "NXRT_ACCOUNT_UID").unwrap().to_string()); + } + uids.sort(); + uids.dedup(); + assert_eq!(uids.len(), 3, "nobody plays twice"); + for p in &s.profiles[1..] { + assert!(saveimport::is_save_folder(&save_of(&d, p)), "{} starts from a copy of the first save", p.name); + } + // a third start with one player fewer leaves the profiles as they are + prepare(&d, &Options { players: 3, ..Default::default() }).unwrap(); + assert_eq!(profiles::load(&d).profiles.len(), 4); + } + + #[test] + fn the_page_can_say_who_plays_where() { + let d = tmp("pick"); + first_save(&d); + let misty = profiles::add(&d, "Misty").unwrap().profiles.last().unwrap().clone(); + let brock = profiles::add(&d, "Brock").unwrap().profiles.last().unwrap().clone(); + let group = prepare(&d, &Options { players: 3, others: vec![brock.id.clone(), misty.id.clone()], ..Default::default() }).unwrap(); + assert_eq!(env_of(&group.others[0], "NXRT_ACCOUNT_UID"), Some(brock.uid.as_str())); + assert_eq!(env_of(&group.others[1], "NXRT_ACCOUNT_UID"), Some(misty.uid.as_str())); + // only player 3 is said: player 2 is the candidate that is left + let group = prepare(&d, &Options { players: 3, others: vec![String::new(), misty.id.clone()], ..Default::default() }).unwrap(); + assert_eq!(env_of(&group.others[0], "NXRT_ACCOUNT_UID"), Some(brock.uid.as_str())); + assert!(prepare(&d, &Options { players: 3, others: vec![misty.id.clone(), misty.id.clone()], ..Default::default() }).is_err()); + } + + #[test] + fn only_another_profile_with_its_own_id_can_visit() { + let d = tmp("who"); + first_save(&d); + let s = profiles::add(&d, "Misty").unwrap(); + let misty = s.profiles.last().unwrap().clone(); + assert_eq!(players(&d).candidates.iter().map(|c| c.name.as_str()).collect::>(), ["Misty"]); + // the first profile is the built-in user: never a visitor, also while another profile is active + profiles::select(&d, &misty.id).unwrap(); + assert!(players(&d).candidates.is_empty()); + assert!(prepare(&d, &Options { others: vec![profiles::DEFAULT_ID.into()], ..Default::default() }).is_err()); + assert!(prepare(&d, &Options { others: vec![misty.id.clone()], ..Default::default() }).is_err(), "the active profile is the first player"); + } + + #[test] + fn a_player_without_a_first_save_starts_a_new_game() { + let d = tmp("new"); + let group = prepare(&d, &Options::default()).unwrap(); + let s = profiles::load(&d); + let second = s.profiles.last().unwrap(); + assert!(!save_of(&d, second).exists()); + assert_eq!(env_of(&group.others[0], "NXRT_SPLIT_WINDOW"), Some("2")); + assert!(!d.join(DIR).join("2").join(CONTROLS_INI).exists()); + } + + #[test] + fn an_unfinished_write_in_the_first_save_stops_the_copy() { + let d = tmp("commit"); + let first = first_save(&d); + fs::write(first.with_file_name(format!("{}.commit", first.file_name().unwrap().to_string_lossy())), b"").unwrap(); + assert!(prepare(&d, &Options::default()).is_err()); + } +} diff --git a/launcher/src/api.js b/launcher/src/api.js index 2e940dd0..3fe69829 100644 --- a/launcher/src/api.js +++ b/launcher/src/api.js @@ -41,6 +41,8 @@ export const api = { // Play and setup play: (args) => invoke('play', args), // { withoutMods } (optional: this one start runs without mods) + playSplit: (args) => invoke('play_split', args), // { options: { players, side, keyboard, sound, others, meet, together } }: split screen, the game once per player + splitPlayers: () => invoke('split_players'), // { first, candidates: [{ id, name }] } gameStatus: () => invoke('game_status'), setupStatus: () => invoke('setup_status'), startSetup: (args) => invoke('start_setup', args), // { gentle } diff --git a/launcher/src/backend-text.js b/launcher/src/backend-text.js index 4b33960f..1a1ba795 100644 --- a/launcher/src/backend-text.js +++ b/launcher/src/backend-text.js @@ -170,6 +170,16 @@ const TEXTS = [ msg('Setup has not finished: open the launcher and press Set up.'), msg('The profile could not be applied, so the game was not started: {1}'), + // launch.rs, split.rs, play.rs: split screen + msg('The game is running. Close it first, then start split screen.'), + msg('That profile cannot be one of the other players.'), + msg('The same profile cannot play in two windows.'), + msg("A player's profile could not be made."), + msg('Your save has a write the game did not finish. Start the game once without split screen, then try again.'), + msg("A player's save could not be made: {1}"), + msg("A window's settings could not be prepared: {1}"), + msg('Window {n1} did not start: {1}.'), + // preflight.rs: the checks before Set up msg('Not enough free disk space'), msg('{1} has {2} free and setup needs about {3} (the game build, then about 5 GB of shader sources that are deleted at the end and about {4} of translated shaders that stay). Free some space, or move the game folder to a bigger drive (Settings, game folder).'), diff --git a/launcher/src/dev/mock.js b/launcher/src/dev/mock.js index 144ce2e8..aff6bcde 100644 --- a/launcher/src/dev/mock.js +++ b/launcher/src/dev/mock.js @@ -425,6 +425,18 @@ function handle(cmd, args) { case 'install_update': return runUpdate(); case 'cancel_update': return updateStop?.(); case 'play': return runPlay(); + // split screen: a start makes a profile for every player who has none, as split.rs does + case 'play_split': { + const free = () => mockProfiles.profiles.filter((p) => p.id !== mockProfiles.active && p.id !== 'default').length; + for (let n = 2; free() < (args.options.players || 2) - 1; n++) { + if (!mockProfiles.profiles.some((p) => p.name === `Player ${n}`)) mockProfiles.profiles.push({ id: `p${n}`, name: `Player ${n}`, uid: '', nickname: `Player ${n}`, net_uid: '' }); + } + return runPlay(); + } + case 'split_players': return { + first: mockProfiles.profiles.find((p) => p.id === mockProfiles.active).name, + candidates: mockProfiles.profiles.filter((p) => p.id !== mockProfiles.active && p.id !== 'default').map(({ id, name }) => ({ id, name })), + }; case 'preflight': return sleep(500).then(() => ({ ...PREFLIGHT[sc.preflight || 'ok'], need_bytes: (looseShaders ? 31 : 14) * 2 ** 30 })); case 'start_setup': return runSetup(); case 'cancel_setup': return pauseSetup(); diff --git a/launcher/src/i18n/de.js b/launcher/src/i18n/de.js index 0a93bddb..bd37b592 100644 --- a/launcher/src/i18n/de.js +++ b/launcher/src/i18n/de.js @@ -936,4 +936,32 @@ export default { 'You no longer show as online': 'Du wirst nicht mehr als online angezeigt', 'Online': 'Online', 'The same switch is on Home and in the game\'s own Settings, on the Online tab.': 'Derselbe Schalter ist auf der Startseite und in den Einstellungen des Spiels im Tab Online.', + 'The game is running. Close it first, then start split screen.': 'Das Spiel läuft. Schließe es zuerst und starte dann den Splitscreen.', + 'Your save has a write the game did not finish. Start the game once without split screen, then try again.': 'Dein Spielstand enthält einen Schreibvorgang, den das Spiel nicht abgeschlossen hat. Starte das Spiel einmal ohne Splitscreen und versuche es dann erneut.', + 'Split screen': 'Splitscreen', + 'Screen': 'Bildschirm', + 'Top and bottom': 'Oben und unten', + 'Side by side': 'Nebeneinander', + 'Player 1 plays with': 'Spieler 1 spielt mit', + 'Controller': 'Controller', + 'Start split screen': 'Splitscreen starten', + 'That profile cannot be one of the other players.': 'Dieses Profil kann keiner der anderen Spieler sein.', + 'The same profile cannot play in two windows.': 'Dasselbe Profil kann nicht in zwei Fenstern spielen.', + 'A player\'s profile could not be made.': 'Das Profil eines Spielers konnte nicht erstellt werden.', + 'A player\'s save could not be made: {1}': 'Der Spielstand eines Spielers konnte nicht erstellt werden: {1}', + 'A window\'s settings could not be prepared: {1}': 'Die Einstellungen eines Fensters konnten nicht vorbereitet werden: {1}', + 'Window {n1} did not start: {1}.': 'Fenster {n1} wurde nicht gestartet: {1}.', + 'Player {n}': 'Spieler {n}', + 'Player 1 plays with the keyboard and mouse, the others with the controllers in the order they were connected.': 'Spieler 1 spielt mit Tastatur und Maus, die anderen mit den Controllern in der Reihenfolge, in der sie verbunden wurden.', + 'Each player plays with one controller, in the order the controllers were connected.': 'Jeder Spieler spielt mit einem Controller, in der Reihenfolge, in der die Controller verbunden wurden.', + 'Players': 'Spieler', + 'Sound from the other windows': 'Ton aus den anderen Fenstern', + 'Join player 1 automatically': 'Spieler 1 automatisch beitreten', + 'Start next to player 1': 'Bei Spieler 1 starten', + 'They start where player 1 stands. Switch that off once player 1 can be reached from the PC.': 'Sie starten dort, wo Spieler 1 steht. Schalte das aus, sobald Spieler 1 vom PC aus erreichbar ist.', + 'Each player loads their save; the others then join player 1 on their own.': 'Jeder Spieler lädt seinen Spielstand; die anderen treten Spieler 1 dann von selbst bei.', + 'The players meet in the Link Play menu of the game.': 'Die Spieler treffen sich im Link-Play-Menü des Spiels.', + 'The others': 'Die anderen', + 'The game runs once per player, each in a window of their own, and the others visit player 1.': 'Das Spiel läuft einmal pro Spieler, jeder in einem eigenen Fenster, und die anderen besuchen Spieler 1.', + 'A player without a save starts from a copy of yours. Each game needs about 7 GB of memory: 32 GB is recommended for two players, 64 GB for four.': 'Ein Spieler ohne Spielstand beginnt mit einer Kopie von deinem. Jedes Spiel braucht etwa 7 GB Arbeitsspeicher: 32 GB werden für zwei Spieler empfohlen, 64 GB für vier.', }; diff --git a/launcher/src/i18n/es.js b/launcher/src/i18n/es.js index 455a426e..5952a2aa 100644 --- a/launcher/src/i18n/es.js +++ b/launcher/src/i18n/es.js @@ -936,4 +936,32 @@ export default { 'You no longer show as online': 'Ya no apareces en línea', 'Online': 'En línea', 'The same switch is on Home and in the game\'s own Settings, on the Online tab.': 'El mismo interruptor está en Inicio y en los ajustes del propio juego, en la pestaña En línea.', + 'The game is running. Close it first, then start split screen.': 'El juego está en ejecución. Ciérralo primero y luego inicia la pantalla dividida.', + 'Your save has a write the game did not finish. Start the game once without split screen, then try again.': 'Tu partida tiene una escritura que el juego no terminó. Inicia el juego una vez sin pantalla dividida y vuelve a intentarlo.', + 'Split screen': 'Pantalla dividida', + 'Screen': 'Pantalla', + 'Top and bottom': 'Arriba y abajo', + 'Side by side': 'Lado a lado', + 'Player 1 plays with': 'El jugador 1 juega con', + 'Controller': 'Mando', + 'Start split screen': 'Iniciar pantalla dividida', + 'That profile cannot be one of the other players.': 'Ese perfil no puede ser uno de los otros jugadores.', + 'The same profile cannot play in two windows.': 'El mismo perfil no puede jugar en dos ventanas.', + 'A player\'s profile could not be made.': 'No se pudo crear el perfil de un jugador.', + 'A player\'s save could not be made: {1}': 'No se pudo crear la partida de un jugador: {1}', + 'A window\'s settings could not be prepared: {1}': 'No se pudieron preparar los ajustes de una ventana: {1}', + 'Window {n1} did not start: {1}.': 'La ventana {n1} no se inició: {1}.', + 'Player {n}': 'Jugador {n}', + 'Player 1 plays with the keyboard and mouse, the others with the controllers in the order they were connected.': 'El jugador 1 juega con teclado y ratón, los demás con los mandos en el orden en que se conectaron.', + 'Each player plays with one controller, in the order the controllers were connected.': 'Cada jugador juega con un mando, en el orden en que se conectaron los mandos.', + 'Players': 'Jugadores', + 'Sound from the other windows': 'Sonido de las otras ventanas', + 'Join player 1 automatically': 'Unirse al jugador 1 automáticamente', + 'Start next to player 1': 'Empezar junto al jugador 1', + 'They start where player 1 stands. Switch that off once player 1 can be reached from the PC.': 'Empiezan donde está el jugador 1. Desactívalo cuando se pueda llegar al jugador 1 desde el PC.', + 'Each player loads their save; the others then join player 1 on their own.': 'Cada jugador carga su partida; los demás se unen después al jugador 1 por sí solos.', + 'The players meet in the Link Play menu of the game.': 'Los jugadores se encuentran en el menú Link Play del juego.', + 'The others': 'Los demás', + 'The game runs once per player, each in a window of their own, and the others visit player 1.': 'El juego se ejecuta una vez por jugador, cada uno en su propia ventana, y los demás visitan al jugador 1.', + 'A player without a save starts from a copy of yours. Each game needs about 7 GB of memory: 32 GB is recommended for two players, 64 GB for four.': 'Un jugador sin partida empieza con una copia de la tuya. Cada juego necesita unos 7 GB de memoria: se recomiendan 32 GB para dos jugadores y 64 GB para cuatro.', }; diff --git a/launcher/src/i18n/fr.js b/launcher/src/i18n/fr.js index 0569f402..dd70783f 100644 --- a/launcher/src/i18n/fr.js +++ b/launcher/src/i18n/fr.js @@ -936,4 +936,32 @@ export default { 'You no longer show as online': 'Tu n\'apparais plus en ligne', 'Online': 'En ligne', 'The same switch is on Home and in the game\'s own Settings, on the Online tab.': 'Le même interrupteur se trouve sur l\'accueil et dans les paramètres du jeu, onglet En ligne.', + 'The game is running. Close it first, then start split screen.': 'Le jeu est en cours d\'exécution. Fermez-le d\'abord, puis lancez l\'écran partagé.', + 'Your save has a write the game did not finish. Start the game once without split screen, then try again.': 'Votre sauvegarde contient une écriture que le jeu n\'a pas terminée. Lancez le jeu une fois sans écran partagé, puis réessayez.', + 'Split screen': 'Écran partagé', + 'Screen': 'Écran', + 'Top and bottom': 'Haut et bas', + 'Side by side': 'Côte à côte', + 'Player 1 plays with': 'Le joueur 1 joue avec', + 'Controller': 'Manette', + 'Start split screen': 'Lancer l\'écran partagé', + 'That profile cannot be one of the other players.': 'Ce profil ne peut pas être l\'un des autres joueurs.', + 'The same profile cannot play in two windows.': 'Le même profil ne peut pas jouer dans deux fenêtres.', + 'A player\'s profile could not be made.': 'Le profil d\'un joueur n\'a pas pu être créé.', + 'A player\'s save could not be made: {1}': 'La sauvegarde d\'un joueur n\'a pas pu être créée : {1}', + 'A window\'s settings could not be prepared: {1}': 'Les paramètres d\'une fenêtre n\'ont pas pu être préparés : {1}', + 'Window {n1} did not start: {1}.': 'La fenêtre {n1} n\'a pas démarré : {1}.', + 'Player {n}': 'Joueur {n}', + 'Player 1 plays with the keyboard and mouse, the others with the controllers in the order they were connected.': 'Le joueur 1 joue au clavier et à la souris, les autres avec les manettes dans l\'ordre où elles ont été connectées.', + 'Each player plays with one controller, in the order the controllers were connected.': 'Chaque joueur joue avec une manette, dans l\'ordre où les manettes ont été connectées.', + 'Players': 'Joueurs', + 'Sound from the other windows': 'Son des autres fenêtres', + 'Join player 1 automatically': 'Rejoindre le joueur 1 automatiquement', + 'Start next to player 1': 'Commencer à côté du joueur 1', + 'They start where player 1 stands. Switch that off once player 1 can be reached from the PC.': 'Ils commencent là où se trouve le joueur 1. Désactivez cette option dès que le joueur 1 est accessible depuis le PC.', + 'Each player loads their save; the others then join player 1 on their own.': 'Chaque joueur charge sa sauvegarde ; les autres rejoignent ensuite le joueur 1 d\'eux-mêmes.', + 'The players meet in the Link Play menu of the game.': 'Les joueurs se retrouvent dans le menu Link Play du jeu.', + 'The others': 'Les autres', + 'The game runs once per player, each in a window of their own, and the others visit player 1.': 'Le jeu tourne une fois par joueur, chacun dans sa propre fenêtre, et les autres rendent visite au joueur 1.', + 'A player without a save starts from a copy of yours. Each game needs about 7 GB of memory: 32 GB is recommended for two players, 64 GB for four.': 'Un joueur sans sauvegarde commence avec une copie de la vôtre. Chaque jeu demande environ 7 Go de mémoire : 32 Go sont recommandés pour deux joueurs, 64 Go pour quatre.', }; diff --git a/launcher/src/i18n/it.js b/launcher/src/i18n/it.js index f6529e1d..141c9df2 100644 --- a/launcher/src/i18n/it.js +++ b/launcher/src/i18n/it.js @@ -936,4 +936,32 @@ export default { 'You no longer show as online': 'Non risulti più online', 'Online': 'Online', 'The same switch is on Home and in the game\'s own Settings, on the Online tab.': 'Lo stesso interruttore è nella Home e nelle impostazioni del gioco, nella scheda Online.', + 'The game is running. Close it first, then start split screen.': 'Il gioco è in esecuzione. Chiudilo prima, poi avvia lo schermo condiviso.', + 'Your save has a write the game did not finish. Start the game once without split screen, then try again.': 'Il tuo salvataggio contiene una scrittura che il gioco non ha completato. Avvia il gioco una volta senza schermo condiviso, poi riprova.', + 'Split screen': 'Schermo condiviso', + 'Screen': 'Schermo', + 'Top and bottom': 'Sopra e sotto', + 'Side by side': 'Affiancati', + 'Player 1 plays with': 'Il giocatore 1 gioca con', + 'Controller': 'Controller', + 'Start split screen': 'Avvia schermo condiviso', + 'That profile cannot be one of the other players.': 'Quel profilo non può essere uno degli altri giocatori.', + 'The same profile cannot play in two windows.': 'Lo stesso profilo non può giocare in due finestre.', + 'A player\'s profile could not be made.': 'Non è stato possibile creare il profilo di un giocatore.', + 'A player\'s save could not be made: {1}': 'Non è stato possibile creare il salvataggio di un giocatore: {1}', + 'A window\'s settings could not be prepared: {1}': 'Non è stato possibile preparare le impostazioni di una finestra: {1}', + 'Window {n1} did not start: {1}.': 'La finestra {n1} non si è avviata: {1}.', + 'Player {n}': 'Giocatore {n}', + 'Player 1 plays with the keyboard and mouse, the others with the controllers in the order they were connected.': 'Il giocatore 1 gioca con tastiera e mouse, gli altri con i controller nell\'ordine in cui sono stati collegati.', + 'Each player plays with one controller, in the order the controllers were connected.': 'Ogni giocatore gioca con un controller, nell\'ordine in cui i controller sono stati collegati.', + 'Players': 'Giocatori', + 'Sound from the other windows': 'Audio delle altre finestre', + 'Join player 1 automatically': 'Unisciti al giocatore 1 automaticamente', + 'Start next to player 1': 'Inizia accanto al giocatore 1', + 'They start where player 1 stands. Switch that off once player 1 can be reached from the PC.': 'Iniziano dove si trova il giocatore 1. Disattivalo quando il giocatore 1 è raggiungibile dal PC.', + 'Each player loads their save; the others then join player 1 on their own.': 'Ogni giocatore carica il proprio salvataggio; gli altri si uniscono poi al giocatore 1 da soli.', + 'The players meet in the Link Play menu of the game.': 'I giocatori si incontrano nel menu Link Play del gioco.', + 'The others': 'Gli altri', + 'The game runs once per player, each in a window of their own, and the others visit player 1.': 'Il gioco gira una volta per giocatore, ognuno nella propria finestra, e gli altri visitano il giocatore 1.', + 'A player without a save starts from a copy of yours. Each game needs about 7 GB of memory: 32 GB is recommended for two players, 64 GB for four.': 'Un giocatore senza salvataggio parte da una copia del tuo. Ogni gioco richiede circa 7 GB di memoria: si consigliano 32 GB per due giocatori, 64 GB per quattro.', }; diff --git a/launcher/src/i18n/ja.js b/launcher/src/i18n/ja.js index 16674660..71a5c7a5 100644 --- a/launcher/src/i18n/ja.js +++ b/launcher/src/i18n/ja.js @@ -936,4 +936,32 @@ export default { 'You no longer show as online': 'オンラインとして表示されなくなりました', 'Online': 'オンライン', 'The same switch is on Home and in the game\'s own Settings, on the Online tab.': '同じスイッチがホームとゲーム内の設定の「Online」タブにあります。', + 'The game is running. Close it first, then start split screen.': 'ゲームが実行中です。先にゲームを閉じてから、画面分割を開始してください。', + 'Your save has a write the game did not finish. Start the game once without split screen, then try again.': 'セーブに、ゲームが完了していない書き込みがあります。画面分割なしで一度ゲームを起動してから、もう一度お試しください。', + 'Split screen': '画面分割', + 'Screen': '画面', + 'Top and bottom': '上下', + 'Side by side': '左右', + 'Player 1 plays with': 'プレイヤー1の操作', + 'Controller': 'コントローラー', + 'Start split screen': '画面分割を開始', + 'That profile cannot be one of the other players.': 'そのプロファイルは他のプレイヤーにできません。', + 'The same profile cannot play in two windows.': '同じプロファイルは2つのウィンドウで遊べません。', + 'A player\'s profile could not be made.': 'プレイヤーのプロファイルを作成できませんでした。', + 'A player\'s save could not be made: {1}': 'プレイヤーのセーブを作成できませんでした: {1}', + 'A window\'s settings could not be prepared: {1}': 'ウィンドウの設定を準備できませんでした: {1}', + 'Window {n1} did not start: {1}.': 'ウィンドウ{n1}が起動しませんでした: {1}。', + 'Player {n}': 'プレイヤー{n}', + 'Player 1 plays with the keyboard and mouse, the others with the controllers in the order they were connected.': 'プレイヤー1はキーボードとマウス、他のプレイヤーは接続した順のコントローラーで遊びます。', + 'Each player plays with one controller, in the order the controllers were connected.': '各プレイヤーは、接続した順にコントローラーを1台ずつ使います。', + 'Players': 'プレイヤー数', + 'Sound from the other windows': '他のウィンドウの音', + 'Join player 1 automatically': 'プレイヤー1に自動で合流', + 'Start next to player 1': 'プレイヤー1のそばから始める', + 'They start where player 1 stands. Switch that off once player 1 can be reached from the PC.': 'プレイヤー1のいる場所から始まります。パソコンからプレイヤー1のところへ行けるようになったらオフにしてください。', + 'Each player loads their save; the others then join player 1 on their own.': '各プレイヤーがセーブデータを読み込むと、他のプレイヤーは自動でプレイヤー1に合流します。', + 'The players meet in the Link Play menu of the game.': 'プレイヤーはゲームのLink Playメニューで合流します。', + 'The others': '他のプレイヤー', + 'The game runs once per player, each in a window of their own, and the others visit player 1.': 'ゲームをプレイヤーごとに1つ起動し、それぞれ自分のウィンドウで、他のプレイヤーがプレイヤー1を訪問します。', + 'A player without a save starts from a copy of yours. Each game needs about 7 GB of memory: 32 GB is recommended for two players, 64 GB for four.': 'セーブのないプレイヤーは、あなたのセーブのコピーから始めます。ゲーム1つにつきメモリが約7 GB必要です。2人なら32 GB、4人なら64 GBを推奨します。', }; diff --git a/launcher/src/i18n/ko.js b/launcher/src/i18n/ko.js index 2ddeb70f..fc8f11dd 100644 --- a/launcher/src/i18n/ko.js +++ b/launcher/src/i18n/ko.js @@ -936,4 +936,32 @@ export default { 'You no longer show as online': '더 이상 온라인으로 표시되지 않습니다', 'Online': '온라인', 'The same switch is on Home and in the game\'s own Settings, on the Online tab.': '같은 스위치가 홈과 게임 자체 설정의 Online 탭에 있습니다.', + 'The game is running. Close it first, then start split screen.': '게임이 실행 중입니다. 먼저 게임을 닫은 다음 화면 분할을 시작하세요.', + 'Your save has a write the game did not finish. Start the game once without split screen, then try again.': '세이브에 게임이 끝내지 못한 쓰기 작업이 있습니다. 화면 분할 없이 게임을 한 번 실행한 다음 다시 시도하세요.', + 'Split screen': '화면 분할', + 'Screen': '화면', + 'Top and bottom': '위아래', + 'Side by side': '좌우', + 'Player 1 plays with': '플레이어 1 조작', + 'Controller': '컨트롤러', + 'Start split screen': '화면 분할 시작', + 'That profile cannot be one of the other players.': '그 프로필은 다른 플레이어가 될 수 없습니다.', + 'The same profile cannot play in two windows.': '같은 프로필은 두 창에서 플레이할 수 없습니다.', + 'A player\'s profile could not be made.': '플레이어의 프로필을 만들 수 없습니다.', + 'A player\'s save could not be made: {1}': '플레이어의 세이브를 만들 수 없습니다: {1}', + 'A window\'s settings could not be prepared: {1}': '창의 설정을 준비할 수 없습니다: {1}', + 'Window {n1} did not start: {1}.': '창 {n1}이(가) 시작되지 않았습니다: {1}.', + 'Player {n}': '플레이어 {n}', + 'Player 1 plays with the keyboard and mouse, the others with the controllers in the order they were connected.': '플레이어 1은 키보드와 마우스로, 나머지는 연결된 순서대로 컨트롤러로 플레이합니다.', + 'Each player plays with one controller, in the order the controllers were connected.': '각 플레이어는 컨트롤러가 연결된 순서대로 하나씩 사용합니다.', + 'Players': '플레이어 수', + 'Sound from the other windows': '다른 창의 소리', + 'Join player 1 automatically': '플레이어 1에게 자동으로 합류', + 'Start next to player 1': '플레이어 1 옆에서 시작', + 'They start where player 1 stands. Switch that off once player 1 can be reached from the PC.': '플레이어 1이 있는 곳에서 시작합니다. PC에서 플레이어 1에게 갈 수 있게 되면 이 옵션을 끄세요.', + 'Each player loads their save; the others then join player 1 on their own.': '각 플레이어가 저장 데이터를 불러오면 나머지 플레이어가 자동으로 플레이어 1에게 합류합니다.', + 'The players meet in the Link Play menu of the game.': '플레이어들은 게임의 Link Play 메뉴에서 만납니다.', + 'The others': '나머지 플레이어', + 'The game runs once per player, each in a window of their own, and the others visit player 1.': '게임이 플레이어마다 한 번씩, 각자의 창에서 실행되고, 나머지 플레이어가 플레이어 1을 방문합니다.', + 'A player without a save starts from a copy of yours. Each game needs about 7 GB of memory: 32 GB is recommended for two players, 64 GB for four.': '세이브가 없는 플레이어는 내 세이브의 복사본으로 시작합니다. 게임 하나에 메모리가 약 7 GB 필요합니다. 2명은 32 GB, 4명은 64 GB를 권장합니다.', }; diff --git a/launcher/src/i18n/pt-BR.js b/launcher/src/i18n/pt-BR.js index 23ed60f5..dc762181 100644 --- a/launcher/src/i18n/pt-BR.js +++ b/launcher/src/i18n/pt-BR.js @@ -934,4 +934,32 @@ export default { 'You no longer show as online': 'Você não aparece mais como online', 'Online': 'Online', 'The same switch is on Home and in the game\'s own Settings, on the Online tab.': 'O mesmo botão está no Início e nas configurações do próprio jogo, na aba Online.', + 'The game is running. Close it first, then start split screen.': 'O jogo está aberto. Feche-o antes, depois inicie a tela dividida.', + 'Your save has a write the game did not finish. Start the game once without split screen, then try again.': 'Seu save tem uma gravação que o jogo não terminou. Inicie o jogo uma vez sem tela dividida e tente de novo.', + 'Split screen': 'Tela dividida', + 'Screen': 'Tela', + 'Top and bottom': 'Em cima e embaixo', + 'Side by side': 'Lado a lado', + 'Player 1 plays with': 'O jogador 1 joga com', + 'Controller': 'Controle', + 'Start split screen': 'Iniciar tela dividida', + 'That profile cannot be one of the other players.': 'Esse perfil não pode ser um dos outros jogadores.', + 'The same profile cannot play in two windows.': 'O mesmo perfil não pode jogar em duas janelas.', + 'A player\'s profile could not be made.': 'Não foi possível criar o perfil de um jogador.', + 'A player\'s save could not be made: {1}': 'Não foi possível criar o save de um jogador: {1}', + 'A window\'s settings could not be prepared: {1}': 'Não foi possível preparar as configurações de uma janela: {1}', + 'Window {n1} did not start: {1}.': 'A janela {n1} não iniciou: {1}.', + 'Player {n}': 'Jogador {n}', + 'Player 1 plays with the keyboard and mouse, the others with the controllers in the order they were connected.': 'O jogador 1 joga com teclado e mouse, os outros com os controles na ordem em que foram conectados.', + 'Each player plays with one controller, in the order the controllers were connected.': 'Cada jogador joga com um controle, na ordem em que os controles foram conectados.', + 'Players': 'Jogadores', + 'Sound from the other windows': 'Som das outras janelas', + 'Join player 1 automatically': 'Entrar com o jogador 1 automaticamente', + 'Start next to player 1': 'Começar ao lado do jogador 1', + 'They start where player 1 stands. Switch that off once player 1 can be reached from the PC.': 'Eles começam onde o jogador 1 está. Desative isso quando for possível chegar ao jogador 1 a partir do PC.', + 'Each player loads their save; the others then join player 1 on their own.': 'Cada jogador carrega seu jogo salvo; depois os outros entram com o jogador 1 sozinhos.', + 'The players meet in the Link Play menu of the game.': 'Os jogadores se encontram no menu Link Play do jogo.', + 'The others': 'Os outros', + 'The game runs once per player, each in a window of their own, and the others visit player 1.': 'O jogo roda uma vez por jogador, cada um em sua própria janela, e os outros visitam o jogador 1.', + 'A player without a save starts from a copy of yours. Each game needs about 7 GB of memory: 32 GB is recommended for two players, 64 GB for four.': 'Um jogador sem save começa com uma cópia do seu. Cada jogo precisa de cerca de 7 GB de memória: 32 GB são recomendados para dois jogadores, 64 GB para quatro.', }; diff --git a/launcher/src/i18n/zh-CN.js b/launcher/src/i18n/zh-CN.js index 53004452..fdf2f461 100644 --- a/launcher/src/i18n/zh-CN.js +++ b/launcher/src/i18n/zh-CN.js @@ -936,4 +936,32 @@ export default { 'You no longer show as online': '你不再显示为在线', 'Online': '在线', 'The same switch is on Home and in the game\'s own Settings, on the Online tab.': '同一个开关也在主页和游戏自身设置的 Online 标签页中。', + 'The game is running. Close it first, then start split screen.': '游戏正在运行。请先关闭游戏,再开始分屏。', + 'Your save has a write the game did not finish. Start the game once without split screen, then try again.': '你的存档中有一次游戏未完成的写入。请先不使用分屏启动一次游戏,然后重试。', + 'Split screen': '分屏', + 'Screen': '屏幕', + 'Top and bottom': '上下', + 'Side by side': '左右', + 'Player 1 plays with': '玩家 1 的操作方式', + 'Controller': '手柄', + 'Start split screen': '开始分屏', + 'That profile cannot be one of the other players.': '该配置文件不能作为其他玩家。', + 'The same profile cannot play in two windows.': '同一个配置文件不能在两个窗口中游玩。', + 'A player\'s profile could not be made.': '无法创建玩家的配置文件。', + 'A player\'s save could not be made: {1}': '无法创建玩家的存档:{1}', + 'A window\'s settings could not be prepared: {1}': '无法准备窗口的设置:{1}', + 'Window {n1} did not start: {1}.': '窗口 {n1} 未能启动:{1}。', + 'Player {n}': '玩家 {n}', + 'Player 1 plays with the keyboard and mouse, the others with the controllers in the order they were connected.': '玩家 1 使用键盘和鼠标,其他玩家按连接顺序使用手柄。', + 'Each player plays with one controller, in the order the controllers were connected.': '每位玩家使用一个手柄,按手柄的连接顺序分配。', + 'Players': '玩家人数', + 'Sound from the other windows': '其他窗口的声音', + 'Join player 1 automatically': '自动加入玩家 1', + 'Start next to player 1': '从玩家 1 身边开始', + 'They start where player 1 stands. Switch that off once player 1 can be reached from the PC.': '他们会从玩家 1 所在的位置开始。等到能从电脑处走到玩家 1 那里后,请关闭此选项。', + 'Each player loads their save; the others then join player 1 on their own.': '每位玩家载入自己的存档后,其他玩家会自动加入玩家 1。', + 'The players meet in the Link Play menu of the game.': '玩家在游戏的 Link Play 菜单中会合。', + 'The others': '其他玩家', + 'The game runs once per player, each in a window of their own, and the others visit player 1.': '游戏会为每位玩家运行一次,每人一个窗口,其他玩家拜访玩家 1。', + 'A player without a save starts from a copy of yours. Each game needs about 7 GB of memory: 32 GB is recommended for two players, 64 GB for four.': '没有存档的玩家会从你的存档副本开始。每个游戏大约需要 7 GB 内存:两位玩家建议 32 GB,四位玩家建议 64 GB。', }; diff --git a/launcher/src/i18n/zh-TW.js b/launcher/src/i18n/zh-TW.js index 85829644..5b2f53b1 100644 --- a/launcher/src/i18n/zh-TW.js +++ b/launcher/src/i18n/zh-TW.js @@ -936,4 +936,32 @@ export default { 'You no longer show as online': '你不再顯示為線上', 'Online': '線上', 'The same switch is on Home and in the game\'s own Settings, on the Online tab.': '同一個開關也在首頁和遊戲本身設定的 Online 分頁中。', + 'The game is running. Close it first, then start split screen.': '遊戲正在執行。請先關閉遊戲,再開始分割畫面。', + 'Your save has a write the game did not finish. Start the game once without split screen, then try again.': '你的存檔中有一次遊戲未完成的寫入。請先不使用分割畫面啟動一次遊戲,然後再試一次。', + 'Split screen': '分割畫面', + 'Screen': '螢幕', + 'Top and bottom': '上下', + 'Side by side': '左右', + 'Player 1 plays with': '玩家 1 的操作方式', + 'Controller': '控制器', + 'Start split screen': '開始分割畫面', + 'That profile cannot be one of the other players.': '該設定檔不能作為其他玩家。', + 'The same profile cannot play in two windows.': '同一個設定檔不能在兩個視窗中遊玩。', + 'A player\'s profile could not be made.': '無法建立玩家的設定檔。', + 'A player\'s save could not be made: {1}': '無法建立玩家的存檔:{1}', + 'A window\'s settings could not be prepared: {1}': '無法準備視窗的設定:{1}', + 'Window {n1} did not start: {1}.': '視窗 {n1} 未能啟動:{1}。', + 'Player {n}': '玩家 {n}', + 'Player 1 plays with the keyboard and mouse, the others with the controllers in the order they were connected.': '玩家 1 使用鍵盤和滑鼠,其他玩家依連接順序使用控制器。', + 'Each player plays with one controller, in the order the controllers were connected.': '每位玩家使用一個控制器,依控制器的連接順序分配。', + 'Players': '玩家人數', + 'Sound from the other windows': '其他視窗的聲音', + 'Join player 1 automatically': '自動加入玩家 1', + 'Start next to player 1': '從玩家 1 身邊開始', + 'They start where player 1 stands. Switch that off once player 1 can be reached from the PC.': '他們會從玩家 1 所在的位置開始。等到能從電腦處走到玩家 1 那裡後,請關閉此選項。', + 'Each player loads their save; the others then join player 1 on their own.': '每位玩家載入自己的存檔後,其他玩家會自動加入玩家 1。', + 'The players meet in the Link Play menu of the game.': '玩家在遊戲的 Link Play 選單中會合。', + 'The others': '其他玩家', + 'The game runs once per player, each in a window of their own, and the others visit player 1.': '遊戲會為每位玩家執行一次,每人一個視窗,其他玩家拜訪玩家 1。', + 'A player without a save starts from a copy of yours. Each game needs about 7 GB of memory: 32 GB is recommended for two players, 64 GB for four.': '沒有存檔的玩家會從你的存檔副本開始。每個遊戲大約需要 7 GB 記憶體:兩位玩家建議 32 GB,四位玩家建議 64 GB。', }; diff --git a/launcher/src/pages/linkplay-split.js b/launcher/src/pages/linkplay-split.js new file mode 100644 index 00000000..f8274780 --- /dev/null +++ b/launcher/src/pages/linkplay-split.js @@ -0,0 +1,139 @@ +// Link Play: split screen, two to four players on this PC. The game runs once per player, each in a window of their own, and the +// others visit player 1. The choices are this page's own (remembered here, nothing goes to pkp.ini): Rust hands each window its role +// when it starts the group (src-tauri/src/split.rs). The players then come together on their own once each has loaded their save; +// with that switched off they meet in the game's own Link Play menu, which the two lines beside the button name. +import { api } from '../api.js'; +import { t } from '../i18n.js'; +import { esc, group, icon, row, segmented, select, toggle } from '../ui.js'; +import { store } from '../store.js'; +import { gamePhase } from '../action.js'; + +const LS = 'pkp.split'; +const MAX_PLAYERS = 4; // the game's own limit for one session (split.rs MAX_PLAYERS) + +const stored = () => { try { return JSON.parse(localStorage.getItem(LS)) || {}; } catch { return {}; } }; +const keep = (opt) => { try { localStorage.setItem(LS, JSON.stringify(opt)); } catch { /* private window: fine */ } }; + +const busy = (s) => s.starting || ['starting', 'running', 'finishing'].includes(gamePhase(s.game)); +const canStart = (s) => s.app?.readiness?.kind === 'ready' && !busy(s); + +/** Draws the section into `el` and keeps it current. */ +export async function renderSplit(el, ctx) { + const mem = stored(); + const opt = { + players: [2, 3, 4].includes(mem.players) ? mem.players : 2, + side: !!mem.side, + keyboard: !!mem.keyboard, + sound: !!mem.sound, + meet: mem.meet !== false, // on unless the player switched it off + together: mem.together !== false, + others: Array.isArray(mem.others) ? mem.others.map((id) => (typeof id === 'string' ? id : '')) : [], // players 2, 3, 4 + }; + let players = { first: '', candidates: [] }; + + // A profile remembered for a player may be gone, be the active one now, or sit with another player: each player then gets the + // first profile nobody has, and one for whom none is left gets a new profile at the start (''). + function assign() { + const taken = new Set(); + for (let i = 0; i < MAX_PLAYERS - 1; i++) { + const known = (id) => players.candidates.some((c) => c.id === id) && !taken.has(id); + if (!known(opt.others[i])) opt.others[i] = i < opt.players - 1 ? players.candidates.find((c) => !taken.has(c.id))?.id ?? '' : ''; + if (opt.others[i]) taken.add(opt.others[i]); + } + } + async function loadPlayers() { + players = await api.splitPlayers().catch(() => players); + assign(); + } + + const pathLine = (who, last) => `
+ ${icon('gamepad-2')}${esc(who)} + ${['Link Play', t('Local connection'), last].map((p) => `${esc(p)}`).join(icon('chevron-right'))} +
`; + + // one row per visiting player: a profile nobody else has; with none left, the start makes a new one + function playerRow(n) { + const mine = opt.others[n - 2]; + const elsewhere = new Set(opt.others.slice(0, opt.players - 1).filter((id, i) => id && i !== n - 2)); + const list = players.candidates.filter((c) => !elsewhere.has(c.id)); + const control = list.length + ? select(`split-player-${n}`, list.map((c) => [c.id, c.name]), mine) + : `${esc(t('New profile'))}`; + return row(t('Player {n}', { n }), control); + } + + function html() { + const pads = opt.keyboard + ? t('Player 1 plays with the keyboard and mouse, the others with the controllers in the order they were connected.') + : t('Each player plays with one controller, in the order the controllers were connected.'); + const meet = opt.meet + ? `${t('Each player loads their save; the others then join player 1 on their own.')}${opt.together ? ` ${t('They start where player 1 stands. Switch that off once player 1 can be reached from the PC.')}` : ''}` + : t('The players meet in the Link Play menu of the game.'); + // four windows are a quarter each: nothing to choose + const screen = opt.players === 4 ? [] : [row(t('Screen'), segmented('split-layout', [['stacked', t('Top and bottom')], ['side', t('Side by side')]], opt.side ? 'side' : 'stacked', { label: t('Screen') }))]; + return `${group(t('Split screen'), [ + row(t('Players'), segmented('split-players', [2, 3, 4].map((n) => [n, String(n)]), opt.players, { label: t('Players') })), + ...screen, + row(t('Player 1 plays with'), segmented('split-input', [['pad', t('Controller')], ['kbm', t('Keyboard and mouse')]], opt.keyboard ? 'kbm' : 'pad', { label: t('Player 1 plays with') })), + ...Array.from({ length: opt.players - 1 }, (_, i) => playerRow(i + 2)), + row(t('Sound from the other windows'), toggle('split-sound', opt.sound)), + row(t('Join player 1 automatically'), toggle('split-meet', opt.meet)), + ...(opt.meet ? [row(t('Start next to player 1'), toggle('split-together', opt.together))] : []), + ])} +
+ +
${opt.meet ? '' : ` + ${pathLine(t('Player {n}', { n: 1 }), t('Invite Others to Visit'))} + ${pathLine(t('The others'), t('Visit a Friend'))}`} +
+
+ `; + } + + // rewritten only when it changed, and the focused control keeps the focus (the page's own rule, linkplay.js patch) + function draw() { + const next = html(); + if (el.dataset.html === next) return; + const a = document.activeElement; + const key = el.contains(a) ? (a.id ? `#${a.id}` : a.name ? `input[name="${a.name}"]:checked` : null) : null; + el.innerHTML = next; + el.dataset.html = next; + if (key) el.querySelector(key)?.focus(); + } + + el.addEventListener('change', (e) => { + const c = e.target; + const player = /^split-player-(\d)$/.exec(c.id); + if (c.name === 'split-players') opt.players = Number(c.value); + else if (c.name === 'split-layout') opt.side = c.value === 'side'; + else if (c.name === 'split-input') opt.keyboard = c.value === 'kbm'; + else if (player) opt.others[player[1] - 2] = c.value; + else if (c.id === 'split-sound') opt.sound = c.checked; + else if (c.id === 'split-meet') opt.meet = c.checked; + else if (c.id === 'split-together') opt.together = c.checked; + else return; + if (c.name === 'split-players') assign(); // a player who joins gets a profile, one who leaves frees theirs + keep(opt); + draw(); + }); + el.addEventListener('click', (e) => { + const b = e.target.closest('#split-start'); + if (b && !b.disabled) store.play({ split: { ...opt, others: opt.others.slice(0, opt.players - 1) } }); + }); + + // a start can make a player's profile, and a game that ended frees the button: both show at the next change of phase + let phase = gamePhase(store.state.game); + ctx.on(async (s) => { + const now = gamePhase(s.game); + if (now !== phase) { + phase = now; + await loadPlayers(); + } + draw(); + }); + + await loadPlayers(); + draw(); +} diff --git a/launcher/src/pages/linkplay.css b/launcher/src/pages/linkplay.css index 7a8a3f2f..0fff2264 100644 --- a/launcher/src/pages/linkplay.css +++ b/launcher/src/pages/linkplay.css @@ -25,6 +25,10 @@ .lp-field { display: flex; flex-direction: column; align-items: flex-end; gap: var(--space-1); min-width: 0; } .lp-msg { color: var(--color-danger); font-size: var(--text-xs); text-align: right; } +/* split screen: the start button, and beside it where each player goes in the game */ +.lp-split-go { display: flex; flex-wrap: wrap; align-items: center; gap: var(--space-3) var(--space-5); } +.lp-split-paths { display: flex; flex-direction: column; gap: var(--space-2); min-width: 0; } + /* the last address is offered by a datalist: no arrow on the field */ .linkplay input::-webkit-calendar-picker-indicator { display: none !important; } diff --git a/launcher/src/pages/linkplay.js b/launcher/src/pages/linkplay.js index 9e8782e6..311bf976 100644 --- a/launcher/src/pages/linkplay.js +++ b/launcher/src/pages/linkplay.js @@ -12,6 +12,7 @@ import { HOST_PORT, RELAY_PORT, addrProblem, addressRows, applyEdits, editsFor, interactEdits, internetShare, pathParts, protocolEdits, readIni, relayPort, storyEdits, uiFrom, } from '../linkplay-model.js'; +import { renderSplit } from './linkplay-split.js'; const LS = 'pkp.linkplay'; const POLL_MS = 3000; // this PC's relay and its link count, while the own-relay Host view is on screen @@ -346,6 +347,7 @@ export async function render(el, ctx) {
+
`; el.addEventListener('input', (e) => { @@ -408,5 +410,6 @@ export async function render(el, ctx) { draw(); enter(); api.modsList().then((v) => { gameplayMods = v.gameplay; patch(part('lp-shared'), sharedHtml()); }).catch(() => {}); + renderSplit(part('lp-split'), ctx).catch((e) => console.warn('split screen', e)); // its own section: never holds the page back return () => clearInterval(timer); } diff --git a/launcher/src/store.js b/launcher/src/store.js index c8991bee..0a8982de 100644 --- a/launcher/src/store.js +++ b/launcher/src/store.js @@ -233,13 +233,15 @@ export const store = { } }, - /** `withoutMods`: this one start runs without mods (the player's way out when a mod keeps the game from starting). */ - async play({ withoutMods = false } = {}) { + /** `withoutMods`: this one start runs without mods (the player's way out when a mod keeps the game from starting). + * `split`: split screen, the game once per player ({ players, side, keyboard, sound, others, meet, together }; pages/linkplay-split.js). */ + async play({ withoutMods = false, split = null } = {}) { if (store.state.starting) return; await askOnlineOnce(); // once per install, before the first Play: online presence is off unless the player says yes set({ starting: true }, 'task'); try { - await api.play(withoutMods ? { withoutMods } : undefined); + if (split) await api.playSplit({ options: split }); + else await api.play(withoutMods ? { withoutMods } : undefined); } catch (e) { toast(errText(e), 'error'); store.refresh(); diff --git a/runtime/docs/CONFIG.md b/runtime/docs/CONFIG.md index 1a97a48f..aab463fa 100644 --- a/runtime/docs/CONFIG.md +++ b/runtime/docs/CONFIG.md @@ -284,6 +284,14 @@ Rules: | `play` | `pointer_draw` | `false` | `NXRT_PLAY_POINTER_DRAW` | `src/gfx/play/play.cpp` | Test aid: draws an arrow at the menu pointer into the game's own frame, so a game screenshot shows where the pointer is (the OS cursor is not part of the frame). | | `play` | `selftest` | empty | `NXRT_PLAY_SELFTEST` | `src/gfx/play/play_selftest.h` | Window self-test script for the oracles (steps are listed in that header). | | `play` | `late_sample` | `true` | `NXRT_PLAY_LATE_SAMPLE` | `src/gfx/play/play.cpp` | Pump the window's events again right before the first `ProcessInput` of a frame takes the mouse counts, so the aim includes what the mouse did since the frame boundary. | +| `split` | `window` | `0` | `NXRT_SPLIT_WINDOW` | `src/gfx/play/play_split.cpp` | Split screen (`include/nxrt/split.h`): the game runs once per player on one PC, two to four times, and each process is a window in its part of the screen; they meet through Link Play on 127.0.0.1. `1`: this process is the first window, `2` to `4`: another one, `0`: no split screen. The launcher's **Split screen** sets it for the processes it starts, in their environment only. The window has no frame, fills its part of the work area of the `[display] monitor` display (else the primary one) and is put back when anything moves, resizes or maximises it; `[display] window_mode`, the window size and Alt+Enter do nothing. Where the window system places windows itself (a Wayland session without XWayland) the window is left where it is and a warning says so; X11 is asked for first on Linux. Every window but the first cannot take the keyboard focus until it is in its place, so starting it leaves the keyboard with the first; after that a click gives a window the keyboard and mouse. `[audio] mute_unfocused` does not apply. | +| `split` | `count` | `2` | `NXRT_SPLIT_COUNT` | `src/gfx/play/play_split.cpp` | How many windows share the screen: `2`, `3` or `4`. | +| `split` | `layout` | `stacked` | `NXRT_SPLIT_LAYOUT` | `src/gfx/play/play_split.cpp` | Two windows: `stacked` = top and bottom halves, each as wide as the screen (window 1 on top); `side` = left and right halves (window 1 on the left). Three windows: window 1 has the top half (`stacked`) or the left half (`side`), windows 2 and 3 share the other half. Four windows: a quarter each (1 and 2 on top, 3 and 4 below), whatever this says. | +| `split` | `pad` | the window's number | `NXRT_SPLIT_PAD` | `src/gfx/play/play_split.cpp` | The one controller this window plays, by its place in the order the controllers were connected (`1` = the first); every other controller does nothing in this window, its quit and overlay combinations included. `0`: none, the window is played with the keyboard and mouse only. | +| `split` | `mute` | `false` | `NXRT_SPLIT_MUTE` | `src/gfx/play/play_split.cpp` | This window plays no sound (several copies of the same music). | +| `split` | `first_account` | empty | `NXRT_SPLIT_FIRST_ACCOUNT` | `src/gfx/play/play_split.cpp`, `games/pkp/core/pkp_save_uuid.cpp` | Windows 2 to 4: the folder name of the first player's account save (`/account/`, 32 hex digits; the windows share the save folder). Pokopia: a save in such a window that has the same player UUID as that save (a copy of it, made for a player without a save) gets a UUID of its own before the game reads it, as `uuid_repair` does, because the host refuses a visitor with its own UUID. | +| `split` | `meet` | `false` | `NXRT_SPLIT_MEET` | `src/gfx/play/play_split.cpp`, `games/pkp/core/pkp_split_session.cpp` | The windows come together without the players' doing. Pokopia: window 1 opens a local Link Play session once its player walks in the world, and the other windows look for it and join, through the same requests the game's multiplayer menu makes (no menu is opened). The game's own unlock of that menu (Environment Level 2) is not asked for. | +| `split` | `together` | `false` | `NXRT_SPLIT_TOGETHER` | `src/gfx/play/play_split.cpp`, `games/pkp/core/pkp_split_session.cpp` | With `meet`: a player who joined is put where the first player stands, instead of where the game lets a visitor arrive (Pokopia: the PC, which the first cave of a new game cannot be reached from). A waiting screen covers the picture meanwhile. | | `prompts` | `style` | `auto` | none (controls.ini only) | `src/gfx/play/play_config.cpp` (read from `controls.ini`) | Button icons the game's prompts show. `auto` (the default) shows keyboard and mouse icons until a controller is used, then that controller's icons, and goes back to the keyboard when a key or mouse button is pressed. The other values are `switch` (the game's own icons), `xbox`, `playstation`, `steam` (Steam Controller), `steamdeck` (Steam Deck), `switch1` (Nintendo Switch: Kenney's art, not the game's own), `switch2` (Nintendo Switch 2), `wiiu` (Wii U), `steamframe` (Steam Frame), `index` (Valve Index: A, B, the triggers and the trackpad; the left stick stands for the d-pad), `touch` (touch-screen gestures) and `keyboard` (keyboard and mouse). `auto` picks `steamdeck` for a Steam pad on a handheld and `steam` elsewhere. Also accepts `ps`, `ps4`, `ps5`, `dualsense`, `steamcontroller`, `deck`, `steam_deck`, `nintendo_switch`, `ns1`, `ns2`, `switch_2`, `nintendo_switch_2`, `wii_u`, `steam_frame`, `frame`, `valve_index`, `touchscreen`, `kbm`, `mouse` and `keyboard_mouse`. Stored in `controls.ini` under `[prompts]`, not in `nxrt.ini`. Set it in the launcher (Controls tab) or on the F1 page (Controller tab, Button prompts); both show a preview of the chosen style's icon for each Switch button (the launcher with the factory mapping, F1 with the current one). Changes apply on the next frame, with no restart. Keyboard icons show the keys the action is bound to: a rebound jump key shows the new key, and a key with no icon of its own gets a plain key icon. Every controller set follows `[padmap]` (a button the controller has no icon for keeps the game's own) and are read from the icon pack `assets/prompts/prompt_icons.pak` next to pkp.exe (shipped in the release zip; see `prompts dir`). | | `fps` | `show` | `0` | none (controls.ini only) | `src/gfx/play/play.cpp`, `src/gfx/overlay.cpp` | Frame rate counter in a corner of the game window. Off by default. While it is off, the overlay does one atomic read per frame and nothing else. The hotkey (`key`), the Display tab of the F1 page and the launcher's Extras tab can turn it on or off, and the choice is saved. | | `fps` | `key` | `F2` | none (controls.ini only) | `src/gfx/play/play.cpp` | Keyboard key that shows and hides the counter. The game never receives it, so do not bind the same key to an action. Any SDL scancode name. | diff --git a/runtime/games/pkp/CMakeLists.txt b/runtime/games/pkp/CMakeLists.txt index 31cf3123..6ead9f76 100644 --- a/runtime/games/pkp/CMakeLists.txt +++ b/runtime/games/pkp/CMakeLists.txt @@ -39,6 +39,7 @@ if(TARGET nxrt_gfx) "${_pkp}/core/pkp_save_files.cpp" "${_pkp}/core/pkp_save_uuid.cpp" "${_pkp}/core/pkp_settings.cpp" + "${_pkp}/core/pkp_split_session.cpp" "${_pkp}/core/pkp_story_guard.cpp" "${_pkp}/core/pkp_story_hold.cpp" "${_pkp}/core/pkp_story_pickups.cpp" @@ -88,7 +89,8 @@ if(TARGET nxrt_gfx) "${_pkp}/ui/pkp_craft.cpp" "${_pkp}/ui/pkp_save_now.cpp" "${_pkp}/ui/pkp_item_edit.cpp" - "${_pkp}/ui/pkp_time.cpp") + "${_pkp}/ui/pkp_time.cpp" + "${_pkp}/ui/pkp_wait_screen.cpp") if(NXRT_TESTTOOLS) target_sources(nxrt_game_pkp PRIVATE "${_pkp}/test/pkp_movie_test.cpp" diff --git a/runtime/games/pkp/core/pkp_game.cpp b/runtime/games/pkp/core/pkp_game.cpp index b88b8439..99e5178e 100644 --- a/runtime/games/pkp/core/pkp_game.cpp +++ b/runtime/games/pkp/core/pkp_game.cpp @@ -29,6 +29,7 @@ #include "core/pkp_pokemon_cap.h" #include "core/pkp_save_uuid.h" #include "ui/pkp_save_now.h" +#include "core/pkp_split_session.h" #include "core/pkp_story_guard.h" #include "core/pkp_story_hold.h" #include "core/pkp_story_pickups.h" @@ -36,6 +37,7 @@ #include "ui/pkp_sort.h" #include "render/pkp_taa.h" #include "ui/pkp_title.h" +#include "ui/pkp_wait_screen.h" #include #include @@ -63,6 +65,8 @@ constexpr uint64_t kFrameUpdate = 0x1fdcde4; // linkplay before play: its frame callback (the one-time check of main) runs first in play mode's frame // story_guard after save_uuid: its install copies the save, which is then the repaired one (pkp_story_guard.h) // story_hold after story_guard, whose journal it writes to (pkp_story_hold.h) +// split_session no hooks; it asks the session manager on the game thread, in no order with the others (pkp_split_session.h) +// wait_screen last: its layer covers the picture, so it is drawn over the other features' layers (pkp_wait_screen.h) // mods the Modtopia mods' frame tick (pkp_mods.h): first of the game-frame callbacks, so mods see each frame before our // features change anything in it // play, kbm play's status fields come first in the status line, kbm's right after them @@ -92,7 +96,7 @@ constexpr Entry port(const Feature* f) { return {f, {settings::Key::Count, setti using enum settings::Key; constexpr Entry kEntries[] = { - port(&kSaveUuidFeature), port(&kLinkplayFeature), port(&kStoryGuardFeature), port(&kStoryHoldFeature), port(&kStoryPickupsFeature), port(&kLinkTripsFeature), port(&kLinkDigSpotsFeature), port(&kModsFeature), port(&kPlayFeature), port(&kKbmFeature), + port(&kSaveUuidFeature), port(&kLinkplayFeature), port(&kStoryGuardFeature), port(&kStoryHoldFeature), port(&kStoryPickupsFeature), port(&kLinkTripsFeature), port(&kLinkDigSpotsFeature), port(&kSplitSessionFeature), port(&kModsFeature), port(&kPlayFeature), port(&kKbmFeature), #if NXRT_TESTTOOLS port(&kMovieTestFeature), #endif @@ -108,6 +112,7 @@ constexpr Entry kEntries[] = { port(&key_guide::kKeyGuideFeature), port(&kOptionsFeature), port(&kPlayTimeFeature), + port(&kWaitScreenFeature), }; constexpr size_t kFeatureCount = std::size(kEntries); diff --git a/runtime/games/pkp/core/pkp_layout.h b/runtime/games/pkp/core/pkp_layout.h index c9ccc6f8..5a71b1f9 100644 --- a/runtime/games/pkp/core/pkp_layout.h +++ b/runtime/games/pkp/core/pkp_layout.h @@ -10,11 +10,17 @@ namespace nxrt::games::pkp::layout { // ---- globals in main (qword pointers) ---- constexpr uint64_t kPlayerManager = 0x3561928; // the player manager (26344 bytes, made in 0x71000ae380) constexpr uint64_t kManagerPlayer = 0x30; // player manager: the local player's character (+0x38 the second one) +constexpr uint64_t kManagerOther = 0x38; // player manager: the other player's character in a Link Play session of two constexpr uint64_t kSaveRoot = 0x3561930; // the save data (the save/options block) constexpr uint64_t kGameState = 0x3561710; // the game state (stage, session) constexpr uint64_t kStateStage = 0x18; // game state: u8, the stage the player is in constexpr uint64_t kStateSession = 0x90; // game state: u8 Link Play session bits (kSession*); 0 offline constexpr uint8_t kSessionOnline = 0x01, kSessionHost = 0x02, kSessionVisitor = 0x04; +constexpr uint64_t kSessionOwner = 0x3561780; // the object that owns the Link Play session manager +constexpr uint64_t kOwnerSession = 0x11f0; // owner: the session manager (made at start-up, ticked every frame by 0x103a7e0) +constexpr uint64_t kSessionState = 0x0; // session manager: u32, 0 idle, else the step of the request it works on +constexpr uint64_t kSessionFound = 0x1358; // session manager: u32, the sessions the last search found +constexpr uint64_t kSessionSize = 0x1a90; // session manager: its size as far as it is read here constexpr uint64_t kInputMgr = 0x3561718; // the input manager constexpr uint64_t kTables = 0x35618f0; // the data-table manager (the sprite sheet lookups read it too) constexpr uint64_t kUiMgr = 0x35aebf8; // the UI manager (UI resource manager: holds the loaded sprite sheets and the layout pools) @@ -127,6 +133,14 @@ constexpr uint64_t kFrameStep = 0xbfc4fc; // ---- game functions ---- constexpr uint64_t kOnline = 0x376c4; // () -> bit 0: Link Play session +// The session manager's requests, the ones the multiplayer menu makes for "Local connection" (its step function 0xf282a8). Each is +// refused (0) unless the manager is idle and answers 1 when it took the request; the manager then works on it frame by frame. +constexpr uint64_t kSessionCreate = 0xe7d644; // (manager): open a session with the code at manager + 4 (empty: no password). It saves first +constexpr uint64_t kSessionSearch = 0xe7d8d0; // (manager, 0): look for sessions; kSessionFound holds how many when the manager is idle again +constexpr uint64_t kSessionJoin = 0xe7ffc8; // (index): join that found session; the manager then starts the trip to the host's world +// (character, vec4* position, 0, 1, 1, 1, 0, 0, stack: u8 0) as the script command at 0x444b44 calls it: the player stands there at once, +// in every game of the session +constexpr uint64_t kPlayerWarp = 0x275760; constexpr uint64_t kMaxStack = 0x2a7f0c; // () -> the max stack (u16), one value for every item constexpr uint64_t kNameOf = 0xa34e1c; // (name id, form) -> UTF-8 name in the game's language constexpr uint64_t kLayoutOf = 0x9132fc; // (source) -> layout diff --git a/runtime/games/pkp/core/pkp_save_uuid.cpp b/runtime/games/pkp/core/pkp_save_uuid.cpp index 74f3b58c..c03acf69 100644 --- a/runtime/games/pkp/core/pkp_save_uuid.cpp +++ b/runtime/games/pkp/core/pkp_save_uuid.cpp @@ -1,5 +1,5 @@ // SPDX-License-Identifier: GPL-3.0-or-later -// Pokémon Pokopia: repair of the shared player UUID (pkp_save_uuid.h). CMNDAT layout from berichan/PokoHex (GPL-3.0, SaveFile.cs): +// Pokémon Pokopia: a save's player UUID made its own (pkp_save_uuid.h). CMNDAT layout from berichan/PokoHex (GPL-3.0, SaveFile.cs): // magic 0x31227687, end of the compressed data at +0x10, zlib stream from 0x130. The rewrite is the one work/tools/pkp_uuid.py made // (checked in game: a save so changed joins a host made from the same original save). #include "core/pkp_save_uuid.h" @@ -21,6 +21,7 @@ #include "miniz.h" #include "nxrt/log.h" #include "nxrt/entropy.h" +#include "nxrt/split.h" namespace nxrt::games::pkp { namespace { @@ -33,6 +34,7 @@ constexpr uint8_t kShared[16] = {0xb9, 0xae, 0x85, 0xed, 0x20, 0xe7, 0x4f, 0x6b, constexpr uint32_t kCmnMagic = 0x31227687; constexpr size_t kCmnHeader = 0x130; constexpr size_t kCmnEndAt = 0x10; +constexpr size_t kSysUuidAt = 0x61; // S00/SYDAT.BIN: the player UUID's plain copy (2.0.1 saves; read_uuid checks what it finds there) using Bytes = std::vector; @@ -82,13 +84,14 @@ uint32_t rd32(const Bytes& b, size_t at) { return v; } -// A file with the UUID replaced: *count places, *out the new contents. False when it cannot be read or is not the expected layout. -bool rewrite(const stdfs::path& p, bool cmndat, const uint8_t* uuid, size_t* count, Bytes* out, std::string* why) { +// A file with the UUID `from` replaced by `uuid`: *count places, *out the new contents. False when it cannot be read or is not the +// expected layout. +bool rewrite(const stdfs::path& p, bool cmndat, const uint8_t* from, const uint8_t* uuid, size_t* count, Bytes* out, std::string* why) { Bytes file; if (!read_all(p, &file)) { *why = "cannot be read"; return false; } if (!cmndat) { *out = file; - *count = replace_all(*out, kShared, uuid); + *count = replace_all(*out, from, uuid); return true; } if (file.size() < kCmnHeader || rd32(file, 0) != kCmnMagic) { *why = "not a Pokopia common save"; return false; } @@ -99,7 +102,7 @@ bool rewrite(const stdfs::path& p, bool cmndat, const uint8_t* uuid, size_t* cou if (!raw_p) { *why = "does not decompress"; return false; } Bytes raw(static_cast(raw_p), static_cast(raw_p) + raw_n); mz_free(raw_p); - *count = replace_all(raw, kShared, uuid); + *count = replace_all(raw, from, uuid); if (*count == 0) { *out = file; return true; } size_t z_n = 0; const int flags = static_cast(tdefl_create_comp_flags_from_zip_params(9, 15, MZ_DEFAULT_STRATEGY)); // zlib header, level 9 @@ -130,14 +133,24 @@ std::string uuid_str(const uint8_t* u) { return s; } -void repair() { +// What swap_uuid did: the new UUID, how many places held the old one (G00, B00, S00) and where the copy of the save is. +struct Swap { + uint8_t to[16] = {}; + size_t total = 0, counts[3] = {}; + stdfs::path backup; +}; + +// Gives the account save a new random player UUID in every place that holds `from`: the owner stamps in CMNDAT (G00 and B00) and the +// plain copy in SYDAT. A copy of the whole account folder is kept first. False when nothing was written: no save, a pending commit or a +// failure (logged, the save is as it was). True with total 0: the save does not hold `from`. +bool swap_uuid(const uint8_t* from, Swap* r) { const stdfs::path root = save_files::account_dir(); std::error_code ec; - if (!stdfs::is_directory(root, ec)) return; // no save yet: a new game gets a random UUID now + if (!stdfs::is_directory(root, ec)) return false; // no save yet: a new game gets a random UUID now if (save_files::commit_pending()) { NXLOG_W(kTag, "player UUID: not checked, the save has an interrupted commit (%s.commit) the game finishes first; checked again next start", u8(root).c_str()); - return; + return false; } struct Part { const char* rel; @@ -147,35 +160,31 @@ void repair() { }; Part parts[] = {{"G00/CMNDAT.BIN", true}, {"B00/CMNDAT.BIN", true}, {"S00/SYDAT.BIN", false}}; - uint8_t uuid[16]; do { - entropy::fill(uuid, sizeof uuid); - uuid[6] = static_cast((uuid[6] & 0x0F) | 0x40); // version 4 - uuid[8] = static_cast((uuid[8] & 0x3F) | 0x80); // RFC 4122 variant - } while (std::memcmp(uuid, kShared, 16) == 0); + entropy::fill(r->to, sizeof r->to); + r->to[6] = static_cast((r->to[6] & 0x0F) | 0x40); // version 4 + r->to[8] = static_cast((r->to[8] & 0x3F) | 0x80); // RFC 4122 variant + } while (std::memcmp(r->to, kShared, 16) == 0 || std::memcmp(r->to, from, 16) == 0); - size_t total = 0; - for (Part& pt : parts) { + for (size_t i = 0; i < 3; ++i) { + Part& pt = parts[i]; const stdfs::path p = root / stdfs::path(pt.rel); if (!stdfs::is_regular_file(p, ec)) continue; std::string why; - if (!rewrite(p, pt.cmndat, uuid, &pt.count, &pt.data, &why)) { + if (!rewrite(p, pt.cmndat, from, r->to, &pt.count, &pt.data, &why)) { NXLOG_W(kTag, "player UUID: %s %s; the save is left as it is", u8(p).c_str(), why.c_str()); - return; + return false; } - total += pt.count; - } - if (total == 0) { - NXLOG_I(kTag, "player UUID: this save has its own (not the shared one), nothing to repair"); - return; + r->counts[i] = pt.count; + r->total += pt.count; } + if (r->total == 0) return true; // a copy of the whole account folder first - stdfs::path backup; std::string error; - if (!save_files::copy_account("uuid-backup", 0, &backup, &error)) { - NXLOG_E(kTag, "player UUID: the backup to %s failed (%s); the save is left as it is", u8(backup).c_str(), error.c_str()); - return; + if (!save_files::copy_account("uuid-backup", 0, &r->backup, &error)) { + NXLOG_E(kTag, "player UUID: the backup to %s failed (%s); the save is left as it is", u8(r->backup).c_str(), error.c_str()); + return false; } for (const Part& pt : parts) { @@ -187,15 +196,59 @@ void repair() { for (const Part& q : parts) { if (q.count == 0) continue; std::error_code e2; - stdfs::copy_file(backup / stdfs::path(q.rel), root / stdfs::path(q.rel), stdfs::copy_options::overwrite_existing, e2); + stdfs::copy_file(r->backup / stdfs::path(q.rel), root / stdfs::path(q.rel), stdfs::copy_options::overwrite_existing, e2); } NXLOG_E(kTag, "player UUID: writing %s failed (Win32 error %lu); the save was put back from %s", u8(p).c_str(), - static_cast(err), u8(backup).c_str()); + static_cast(err), u8(r->backup).c_str()); + return false; + } + return true; +} + +void repair() { + Swap r; + if (!swap_uuid(kShared, &r)) return; + if (r.total == 0) { + NXLOG_I(kTag, "player UUID: this save has its own (not the shared one), nothing to repair"); return; } NXLOG_W(kTag, "player UUID: this save had %s, the UUID every save made with older builds shares (Link Play refused visits with error " "9005); now %s (%zu places: G00 %zu, B00 %zu, S00 %zu). Backup: %s", - uuid_str(kShared).c_str(), uuid_str(uuid).c_str(), total, parts[0].count, parts[1].count, parts[2].count, u8(backup).c_str()); + uuid_str(kShared).c_str(), uuid_str(r.to).c_str(), r.total, r.counts[0], r.counts[1], r.counts[2], u8(r.backup).c_str()); +} + +// The player UUID of the account save in `root`, from its plain copy in SYDAT. False without that file or when the bytes there are not +// a version 4 UUID (nn::util::GenerateUuid makes one): then nothing is known and nothing is changed. +bool read_uuid(const stdfs::path& root, uint8_t out[16]) { + Bytes sy; + if (!read_all(root / "S00" / "SYDAT.BIN", &sy) || sy.size() < kSysUuidAt + 16) return false; + const uint8_t* u = sy.data() + kSysUuidAt; + if ((u[6] & 0xF0) != 0x40 || (u[8] & 0xC0) != 0x80) return false; + std::memcpy(out, u, 16); + return true; +} + +// A split screen window that visits (windows 2 to 4): its save may be a copy of the first player's (the launcher makes one for a +// player who has no save), and the first window's game refuses a visitor with its own UUID. So a save here with the first save's UUID +// gets a new one, random, so two copies of the same save differ from each other too. +void visiting_player() { + const std::string first = split::first_account(); + if (split::window() < 2 || first.empty()) return; + uint8_t mine[16], theirs[16]; + if (!read_uuid(save_files::account_dir(), mine)) { + NXLOG_I(kTag, "split screen: this player has no save with a player UUID yet (a new game makes one)"); + return; + } + if (!read_uuid(save_files::save_dir() / "account" / first, theirs) || std::memcmp(mine, theirs, 16) != 0) { + NXLOG_I(kTag, "split screen: this player's save has a player UUID of its own (%s)", uuid_str(mine).c_str()); + return; + } + Swap r; + if (!swap_uuid(mine, &r)) return; + if (r.total == 0) return; + NXLOG_I(kTag, "split screen: this player's save was a copy of the first player's (player UUID %s); now %s (%zu places: G00 %zu, " + "B00 %zu, S00 %zu). Backup: %s", + uuid_str(mine).c_str(), uuid_str(r.to).c_str(), r.total, r.counts[0], r.counts[1], r.counts[2], u8(r.backup).c_str()); } } // namespace @@ -211,7 +264,10 @@ void save_uuid_repair() { } namespace { -void install(const FeatureInstall&) { save_uuid_repair(); } +void install(const FeatureInstall&) { + save_uuid_repair(); + visiting_player(); +} } // namespace const Feature kSaveUuidFeature = {.name = "save_uuid", .install = &install}; diff --git a/runtime/games/pkp/core/pkp_save_uuid.h b/runtime/games/pkp/core/pkp_save_uuid.h index 0b291913..194debae 100644 --- a/runtime/games/pkp/core/pkp_save_uuid.h +++ b/runtime/games/pkp/core/pkp_save_uuid.h @@ -1,11 +1,15 @@ // SPDX-License-Identifier: GPL-3.0-or-later -// Pokémon Pokopia: repair of the shared player UUID (pkp_save_uuid.cpp, [pkp] uuid_repair). +// Pokémon Pokopia: a save's player UUID made its own (pkp_save_uuid.cpp): the repair of the shared one ([pkp] uuid_repair), and split +// screen's visiting players. // Every save is given a player UUID at new game (main 0x5aef60, nn::util::GenerateUuid at 0x5af08c), and Link Play's host refuses a // visitor with its own UUID (0x5463c0, error 9005). Until GetInfo RandomEntropy came from the OS (src/kernel/svc_info.cpp) it was one // fixed value, so every save made with this runtime got the same UUID, b9ae85ed-20e7-4f6b-89a1-9f30fcf9f0f9, and no two players could // visit each other. At start, before the game reads its save, a save with that UUID gets a fresh random one in every place it is stored: // the owner stamps in CMNDAT (G00 and its backup B00; zlib from 0x130, end offset at +0x10) and the plain copy in S00/SYDAT. STGDAT has // none. A copy of the account folder is kept first, in /uuid-backup/