From 9efcc090d25144116cf24326f25075c2e55664d1 Mon Sep 17 00:00:00 2001 From: NewBarkTownKris <349535944+NewBarkTownKris@users.noreply.github.com> Date: Mon, 2 Nov 2026 13:30:12 -0500 Subject: [PATCH] feat: add Battle Revolution save support --- README.md | 18 +- .../Android/AndroidEmulatorScanner.cs | 6 +- src/PKForge.App/Services/TransferService.cs | 2 + .../ViewModels/BoxBrowserViewModel.cs | 30 ++ src/PKForge.App/Views/BoxBrowserPage.cs | 20 + src/PKForge.App/Views/HomePage.cs | 6 +- src/PKForge.Domain/Contracts.cs | 11 +- src/PKForge.Domain/SaveProfiles.cs | 12 + src/PKForge.Engine/SaveEngine.cs | 6 +- src/PKForge.Engine/SaveEngineSession.cs | 59 ++- src/PKForge.Engine/WriteSafety.cs | 46 ++- .../EmulatorSaveHeuristics.cs | 7 +- src/PKForge.Infrastructure/SafeSaveWriter.cs | 9 + .../SaveSessionService.cs | 18 +- .../EmulatorSaveHeuristicsTests.cs | 17 +- .../BattleRevolutionTests.cs | 345 ++++++++++++++++++ 16 files changed, 591 insertions(+), 21 deletions(-) create mode 100644 src/PKForge.Domain/SaveProfiles.cs create mode 100644 tests/PKForge.Engine.Tests/BattleRevolutionTests.cs diff --git a/README.md b/README.md index 7af6a7a5..139261d1 100644 --- a/README.md +++ b/README.md @@ -146,6 +146,22 @@ games and popular romhacks: - **Generation IX:** Scarlet, Violet - **Romhacks:** Pokémon Unbound, Radical Red, GS Chronicles, Luminescent Platinum, Pokémon Compass +Battle Revolution: open the raw `GeniusPbr/PbrSaveData` file, then choose +**Tools > Save profile** in Storage to browse its four profiles. Every edit uses +the existing whole-file restore points; switching profiles alone writes nothing. +Wii `data.bin` archives must first be imported with Dolphin's **Import Wii Save**; +`banner.bin` is not a save. When linking Dolphin, choose its entry in Android's +file picker to grant access to its user files. Stop emulation before editing. + +Native no-op exports, profile isolation, Unicode text and nickname edits were +verified on seven distinct saves covering English, German, Spanish, French, +Italian and Japanese. Dolphin discovery, all four profiles and party edits were +tested on an AYN Thor; the English USA save also passed in-game save/reload in +Dolphin 2609a. Other regional game builds and dedicated battle-pass editing have +not been verified. The pinned core cannot encode every profile name: names it +cannot round-trip are refused before changing the profile; existing names are +preserved. + ## Supported emulators Link a storage unit and PKForge finds your saves automatically: @@ -153,7 +169,7 @@ Link a storage unit and PKForge finds your saves automatically: - **Game Boy / Game Boy Color:** RetroArch, Linkboy, Pizza Boy C - **Game Boy Advance:** RetroArch, Linkboy, Pizza Boy A - **Nintendo DS:** melonDS, DraStic, RetroArch -- **GameCube:** Dolphin +- **GameCube / Wii:** Dolphin (Battle Revolution uses raw `PbrSaveData`) - **Nintendo 3DS:** Azahar, Lime3DS, Citra MMJ - **Nintendo Switch:** Eden diff --git a/src/PKForge.App/Platforms/Android/AndroidEmulatorScanner.cs b/src/PKForge.App/Platforms/Android/AndroidEmulatorScanner.cs index 08b4d5ee..9882750b 100644 --- a/src/PKForge.App/Platforms/Android/AndroidEmulatorScanner.cs +++ b/src/PKForge.App/Platforms/Android/AndroidEmulatorScanner.cs @@ -154,12 +154,14 @@ void OnFile(ChildDocument child) var rootChildren = ListChildren(treeUri, rootDocId); string[] preferredFolders = kind switch { - EmulatorKind.Dolphin => ["GC"], + EmulatorKind.Dolphin => ["GC", "Wii"], EmulatorKind.DraStic => ["backup"], EmulatorKind.PizzaBoyGba or EmulatorKind.PizzaBoyGbc => ["save", "saves"], _ => ["saves"], }; - var savesDirs = rootChildren.Where(x => x.IsDirectory && preferredFolders.Contains(x.Name, StringComparer.OrdinalIgnoreCase)).ToArray(); + var savesDirs = rootChildren.Where(x => x.IsDirectory && (kind == EmulatorKind.Dolphin + ? EmulatorSaveHeuristics.IsDolphinSaveFolder(x.Name) + : preferredFolders.Contains(x.Name, StringComparer.OrdinalIgnoreCase))).ToArray(); if (savesDirs.Length > 0) { state.Siblings = rootChildren.Where(x => !x.IsDirectory).Select(x => x.Name).ToArray(); diff --git a/src/PKForge.App/Services/TransferService.cs b/src/PKForge.App/Services/TransferService.cs index f512dbc7..2c092493 100644 --- a/src/PKForge.App/Services/TransferService.cs +++ b/src/PKForge.App/Services/TransferService.cs @@ -87,6 +87,8 @@ public TransferPreviewOutcome PreviewIntoConnected(ReadOnlyMemory entityBy return new TransferPreviewOutcome(false, "No game is connected."); const string label = "the connected game"; using var scratch = engine.OpenSession(live.Serialize().ToArray(), sessions.Current?.Document.DisplayName); + if (live.Snapshot.ProfileIndex is { } profile && scratch is IProfiledSaveSession profiles) + profiles.SelectProfile(profile); var preview = new TransferPreviewService(legality).Preview(scratch, box, slot, entityBytes.ToArray(), format); if (preview is null) return new TransferPreviewOutcome(false, Refusal(entityBytes, nickname, scratch.Snapshot, label, format)); diff --git a/src/PKForge.App/ViewModels/BoxBrowserViewModel.cs b/src/PKForge.App/ViewModels/BoxBrowserViewModel.cs index fbe12eab..0be3190c 100644 --- a/src/PKForge.App/ViewModels/BoxBrowserViewModel.cs +++ b/src/PKForge.App/ViewModels/BoxBrowserViewModel.cs @@ -319,6 +319,36 @@ public void RefreshFromCurrentSession() Status = "READY"; } + public IReadOnlyList SaveProfiles => + _sessions.CurrentSession is IProfiledSaveSession profiles ? profiles.Profiles : []; + + public int CurrentProfile => + _sessions.CurrentSession is IProfiledSaveSession profiles ? profiles.CurrentProfile : 0; + + public async Task SelectSaveProfileAsync(int index) + { + if (IsBusy || _movesInFlight > 0 || _dropWaiting) return false; + try + { + IsBusy = true; + // Selecting a profile also decodes its storage snapshot; keep that work + // off the UI thread, just like an ordinary storage mutation. + await Task.Run(() => _sessions.SelectProfile(index)); + CancelCarry(); + ClearMarksQuietly(); + RefreshFromCurrentSession(); + Status = $"PROFILE {index + 1} · {_sessions.CurrentSession?.GetTrainer().Name}"; + return true; + } + catch (Exception error) + { + DiscardPartialEdits(); + Status = $"Could not select profile: {error.Message}"; + return false; + } + finally { IsBusy = false; } + } + // ── Legality sweep: cached verdicts for the whole save ── /// The last sweep's verdicts while they still match the save's write diff --git a/src/PKForge.App/Views/BoxBrowserPage.cs b/src/PKForge.App/Views/BoxBrowserPage.cs index 459ccdb9..8a59e49c 100644 --- a/src/PKForge.App/Views/BoxBrowserPage.cs +++ b/src/PKForge.App/Views/BoxBrowserPage.cs @@ -194,6 +194,7 @@ private void PaintBoxBar(object? sender, SKPaintSurfaceEventArgs args) : $"Box {_viewModel.BoxIndex + 1:00}"; if (_boxManageMode) boxName = _boxHeld ? $"Holding · {boxName}" : $"Manage · {boxName}"; else if (_viewModel.SelectMode) boxName = $"{boxName} · marked {_viewModel.MarkedInCurrentBox}/{_viewModel.MarkedCount}"; + if (_viewModel.Save?.ProfileIndex is { } profile) boxName = $"P{profile + 1} · {boxName}"; StoragePaint.BoxHeader(canvas, bounds, boxName, font, canPrev: _viewModel.BoxIndex > 0, canNext: _viewModel.BoxIndex < _viewModel.BoxCount - 1, unit); @@ -625,6 +626,7 @@ private sealed record EditorFocusNeighbors(int Left, int Right, int Up, int Down private async Task ShowToolsAsync() { + if (_viewModel.IsBusy) return; if (_viewModel.SelectMode) { await ShowOrganizerMenuAsync(); @@ -638,6 +640,9 @@ private async Task ShowToolsAsync() new("Multi-select (- button)", IconPath: "select", Detail: "Mark several Pokémon to move, copy or edit them together."), new("Box manager…", IconPath: "box", Detail: "Reorder, copy, lock or empty whole boxes."), }; + if (_viewModel.SaveProfiles.Count > 1) + options.Insert(0, new("Save profile…", IconPath: "profile", + Detail: $"Profile {_viewModel.CurrentProfile + 1}: {_viewModel.SaveProfiles[_viewModel.CurrentProfile].Name}")); options.AddRange(Menu( Allowed(SaveAction.CreateMon, new("Import .pk files", IconPath: "import", Detail: "Pick Pokémon files to fill this box's empty slots.")), Allowed(SaveAction.CreateMon, new("Import Showdown team", IconPath: "script", Detail: "Paste Showdown sets, see their legality, then place them in empty slots.")), @@ -670,6 +675,21 @@ private async Task ShowToolsAsync() var choice = await PadMenu.ShowAsync(_hostGrid, "Storage tools", Note(null), options.ToArray()); switch (choice) { + case "Save profile…": + { + var profiles = _viewModel.SaveProfiles; + var labels = profiles.Select(p => $"{p.Index + 1}: {p.Name}").ToArray(); + var selected = await PadMenu.ShowAsync(_hostGrid, "Save profile", "Choose the profile to browse and edit.", + labels.Select(label => new PadOption(label, IconPath: "profile")).ToArray()); + var index = Array.IndexOf(labels, selected); + if (index >= 0 && await _viewModel.SelectSaveProfileAsync(profiles[index].Index)) + { + _lockedSlots.Clear(); + _markedBoxes.Clear(); + RepaintStorage(); + } + return; + } case "Multi-select (- button)": EnterSelectMode(); return; diff --git a/src/PKForge.App/Views/HomePage.cs b/src/PKForge.App/Views/HomePage.cs index e2a45b0b..39c01931 100644 --- a/src/PKForge.App/Views/HomePage.cs +++ b/src/PKForge.App/Views/HomePage.cs @@ -519,7 +519,7 @@ private async Task ShowLinkMenuAsync() new PadOption("Game Boy / Game Boy Color", IconPath: "platform-gb"), new PadOption("Game Boy Advance", IconPath: "platform-gba"), new PadOption("Nintendo DS", IconPath: "platform-ds"), - new PadOption("GameCube", IconPath: "platform-gc"), + new PadOption("GameCube / Wii", IconPath: "platform-gc"), new PadOption("Nintendo 3DS", IconPath: "azahar"), new PadOption("Nintendo Switch", IconPath: "eden"), new PadOption("Single save file", IconPath: "file")); @@ -545,7 +545,7 @@ private async Task ShowLinkMenuAsync() new PadOption("DraStic", IconPath: "drastic"), new PadOption("RetroArch", IconPath: "retroarch"), }, - "GameCube" => new[] { new PadOption("Dolphin", IconPath: "dolphin") }, + "GameCube / Wii" => new[] { new PadOption("Dolphin", IconPath: "dolphin") }, "Nintendo 3DS" => new[] { new PadOption("Azahar / Lime3DS", IconPath: "azahar"), @@ -557,7 +557,7 @@ private async Task ShowLinkMenuAsync() if (choice is null) continue; var guidance = choice switch { - "Dolphin" => "Save in game and stop emulation before editing Colosseum or XD. Select Dolphin's GC folder, a region folder, or Card A / Card B containing .gci saves. For .raw memory cards, export the game as GCI with Dolphin's Memory Card Manager, or configure that card slot as GCI Folder. After editing, start the game normally; loading an old save state can undo your edits.", + "Dolphin" => "Save in game and stop emulation before editing. For Colosseum or XD, select GC, a region folder, or Card A / Card B containing .gci saves. Export .raw cards as GCI with Dolphin's Memory Card Manager. For Battle Revolution, select the Wii save folder containing GeniusPbr/PbrSaveData, or open PbrSaveData as a single file. Wii data.bin archives must be extracted first. Storage tools lets you choose the save profile. Start the game normally after editing; an old save state can undo your edits.", "DraStic" => "Save in game and close DraStic. Select its backup folder containing .dsv battery saves, or the DraStic data folder. Save states are not supported. Restart the game normally after editing.", "Pizza Boy A (GBA)" or "Pizza Boy C (GB/GBC)" => "Save in game and close Pizza Boy. Select the folder containing its battery saves (.sav), not save states. If Android hides the folder, export the battery save in Pizza Boy and link that export. Import the edited export back into Pizza Boy, then restart the game normally.", "Azahar / Lime3DS" => "Save in game and close the emulator. Select the user folder you chose in its setup (the one containing sdmc); sdmc, Nintendo 3DS or a folder above the user folder also work. Restart the game normally after editing.", diff --git a/src/PKForge.Domain/Contracts.cs b/src/PKForge.Domain/Contracts.cs index f7a61ad4..1b8d1237 100644 --- a/src/PKForge.Domain/Contracts.cs +++ b/src/PKForge.Domain/Contracts.cs @@ -119,6 +119,9 @@ public interface ISaveSessionService /// void MarkWritten(string documentId, ReadOnlyMemory written); + /// Changes the viewed profile without changing the whole-file backup baseline. + void SelectProfile(int index) => throw new NotSupportedException("This session has no profiles."); + /// /// Discards whatever the live engine session holds beyond the tracked baseline (the bytes /// last read or written), reopening it from that baseline. Used when a mutation failed @@ -176,6 +179,8 @@ void RevokeLayoutRisk(string documentId) { } /// public sealed record WriteScope(IReadOnlyCollection Slots, bool Unrestricted = false) { + /// The profile these slot coordinates address; null uses the session's profile. + public int? ProfileIndex { get; init; } public static WriteScope Everything { get; } = new([], Unrestricted: true); public static WriteScope Only(params SlotRef[] slots) => new(slots); } @@ -277,7 +282,11 @@ public sealed record SaveSnapshot( int Generation, ReadOnlyMemory OriginalBytes, IReadOnlyList Slots, - string? DisplayName); + string? DisplayName) +{ + /// Selected profile in a multi-profile file; null for a single-profile save. + public int? ProfileIndex { get; init; } +} /// The held item's national (PKHeX) item id, 0 when empty. ROM-hack /// sessions bridge their own ids to national ones; unknown bridges still read non-zero. diff --git a/src/PKForge.Domain/SaveProfiles.cs b/src/PKForge.Domain/SaveProfiles.cs new file mode 100644 index 00000000..1cd620b9 --- /dev/null +++ b/src/PKForge.Domain/SaveProfiles.cs @@ -0,0 +1,12 @@ +namespace PKForge.Domain; + +/// A named profile within one save file. Indices are stable even for empty profiles. +public sealed record SaveProfile(int Index, string Name, bool IsEmpty); + +/// Optional profile selection. All profiles share one whole-file restore point. +public interface IProfiledSaveSession +{ + IReadOnlyList Profiles { get; } + int CurrentProfile { get; } + void SelectProfile(int index); +} diff --git a/src/PKForge.Engine/SaveEngine.cs b/src/PKForge.Engine/SaveEngine.cs index a4a21920..5e5c20e0 100644 --- a/src/PKForge.Engine/SaveEngine.cs +++ b/src/PKForge.Engine/SaveEngine.cs @@ -63,7 +63,8 @@ public SaveSnapshot Open(ReadOnlyMemory bytes, string? displayName = null) } } - return new SaveSnapshot(save.Context.ToString(), save.Generation, bytes.ToArray(), slots, displayName); + return new SaveSnapshot(save.Context.ToString(), save.Generation, bytes.ToArray(), slots, displayName) + { ProfileIndex = save is SAV4BR pbr ? pbr.CurrentSlot : null }; } public ISaveEngineSession OpenSession(ReadOnlyMemory bytes, string? displayName = null) @@ -190,6 +191,9 @@ public ISaveEngineSession OpenBlankSession(int generation, string? displayName = if (!SaveParser.TryGetSaveFile(raw, out var save) || save is null) return null; + if (save is SAV4BR pbr) + return new SaveDescription("Battle Revolution", save.Generation, pbr.CurrentOT, save.PlayTimeString, LanguageTag(save)); + if (SaveParser.IsLuminescentPlatinum(raw)) return new SaveDescription("Luminescent Platinum", save.Generation, save.OT, save.PlayTimeString, LanguageTag(save)); diff --git a/src/PKForge.Engine/SaveEngineSession.cs b/src/PKForge.Engine/SaveEngineSession.cs index 40e57f69..f96d4a81 100644 --- a/src/PKForge.Engine/SaveEngineSession.cs +++ b/src/PKForge.Engine/SaveEngineSession.cs @@ -6,7 +6,7 @@ namespace PKForge.Engine; /// Holds a pinned PKHeX and exposes entity access without leaking engine types. -public sealed class SaveEngineSession : ISaveEngineSession +public sealed class SaveEngineSession : ISaveEngineSession, IProfiledSaveSession { private readonly SaveFile _save; static SaveEngineSession() => LegalityRules.Apply(); @@ -59,6 +59,40 @@ internal SaveEngineSession(SaveFile save, string? displayName) /// session (generate, import, move), not the state of the file at open time. public SaveSnapshot Snapshot => BuildSnapshot(_displayName); + public IReadOnlyList Profiles + { + get + { + ThrowIfDisposed(); + if (_save is not SAV4BR pbr) return []; + var selected = pbr.CurrentSlot; + try + { + return Enumerable.Range(0, pbr.SaveNames.Count).Select(index => + { + pbr.CurrentSlot = index; + var name = pbr.CurrentOT; + var empty = string.IsNullOrWhiteSpace(name); + return new SaveProfile(index, empty ? $"Empty {index + 1}" : name, empty); + }).ToArray(); + } + finally { pbr.CurrentSlot = selected; } + } + } + + public int CurrentProfile => _save is SAV4BR pbr ? pbr.CurrentSlot : 0; + + public void SelectProfile(int index) + { + ThrowIfDisposed(); + if (_save is not SAV4BR pbr) + throw new NotSupportedException("This save has no profiles."); + // The core setter saves the old profile before loading the next. Validate + // first so an invalid selection cannot leave that buffer half-switched. + ArgumentOutOfRangeException.ThrowIfGreaterThanOrEqual((uint)index, (uint)pbr.SaveNames.Count); + pbr.CurrentSlot = index; + } + internal PKM GetEntity(int box, int slot) { ThrowIfDisposed(); @@ -1530,7 +1564,8 @@ public bool ImportSlot(int box, int slot, byte[] fileBytes, string? format = nul public TrainerInfo GetTrainer() { ThrowIfDisposed(); - return new TrainerInfo(_save.OT, _save.TID16, _save.SID16, ReadMoneySafe(), _save.Gender); + return new TrainerInfo(_save is SAV4BR pbr ? pbr.CurrentOT : _save.OT, + _save.TID16, _save.SID16, ReadMoneySafe(), _save.Gender); } public void SetTrainer(TrainerInfo trainer) @@ -1538,8 +1573,21 @@ public void SetTrainer(TrainerInfo trainer) ThrowIfDisposed(); if (_save is SAV3 sav3 && !string.Equals(_save.OT, trainer.Name, StringComparison.Ordinal)) PrefillTrainerName3(sav3.SmallBlock.OriginalTrainerTrash, sav3.Japanese); - _save.OT = trainer.Name; - if (!string.Equals(_save.OT, trainer.Name, StringComparison.Ordinal)) + if (_save is SAV4BR pbr) + { + if (!string.Equals(pbr.CurrentOT, trainer.Name, StringComparison.Ordinal)) + { + // The pinned core limits BR string writes in bytes. Test its encoder + // before touching the profile so an unrepresentable name fails safely. + Span name = stackalloc byte[(pbr.MaxStringLengthTrainer + 1) * 2]; + pbr.SetString(name, trainer.Name, pbr.MaxStringLengthTrainer, StringConverterOption.ClearZero); + if (!string.Equals(pbr.GetString(name), trainer.Name, StringComparison.Ordinal)) + throw new InvalidOperationException("This Battle Revolution profile name cannot be stored exactly. Try a shorter name."); + pbr.CurrentOT = trainer.Name; + } + } + else _save.OT = trainer.Name; + if (!string.Equals(_save is SAV4BR br ? br.CurrentOT : _save.OT, trainer.Name, StringComparison.Ordinal)) throw new InvalidOperationException("This save's character set cannot store that trainer name."); _save.TID16 = (ushort)Math.Clamp(trainer.TID, 0, ushort.MaxValue); _save.SID16 = (ushort)Math.Clamp(trainer.SID, 0, ushort.MaxValue); @@ -2765,7 +2813,8 @@ private SaveSnapshot BuildSnapshot(string? displayName) slots.Add(new SlotSummary(-1, i, partyMon.Species == 0 ? null : partyMon.Species, partyMon.Species == 0 ? null : partyMon.Nickname, partyMon.IsShiny, true, partyMon.Form, partyMon.IsEgg, partyMon.HeldItem, EntitySprite.Traits(partyMon))); } - return new SaveSnapshot(_save.Context.ToString(), _save.Generation, _originalBytes, slots, displayName); + return new SaveSnapshot(_save.Context.ToString(), _save.Generation, _originalBytes, slots, displayName) + { ProfileIndex = _save is SAV4BR pbr ? pbr.CurrentSlot : null }; } private void ValidateCoordinates(int box, int slot) diff --git a/src/PKForge.Engine/WriteSafety.cs b/src/PKForge.Engine/WriteSafety.cs index f424aeb9..3bef4415 100644 --- a/src/PKForge.Engine/WriteSafety.cs +++ b/src/PKForge.Engine/WriteSafety.cs @@ -4,7 +4,7 @@ namespace PKForge.Engine; /// One slot's raw bytes plus its readability, the unit of the write-safety diff. -internal readonly record struct SlotImage(SlotRef Slot, byte[] Bytes, bool Empty, bool Valid); +internal readonly record struct SlotImage(SlotRef Slot, byte[] Bytes, bool Empty, bool Valid, int Profile = 0); /// /// The structural safety net behind and @@ -50,6 +50,23 @@ private sealed record Parsed(string Route, Func> Images } private static List StockImages(SaveFile save) + { + if (save is not SAV4BR pbr) return ProfileImages(save); + var selected = pbr.CurrentSlot; + var images = new List(); + try + { + for (var profile = 0; profile < pbr.SaveNames.Count; profile++) + { + pbr.CurrentSlot = profile; + images.AddRange(ProfileImages(pbr).Select(image => image with { Profile = profile })); + } + } + finally { pbr.CurrentSlot = selected; } + return images; + } + + private static List ProfileImages(SaveFile save) { var images = new List(); if (save.HasParty) @@ -78,7 +95,8 @@ static SlotImage Image(SlotRef where, PKM pk, byte[] data) // structural diff wave through an overwrite of it. var species = pk is G3PKM g3 ? g3.SpeciesInternal : pk.Species; var empty = data.All(b => b == 0) || species == 0 && pk.ChecksumValid; - return new SlotImage(where, data, empty, empty || pk.ChecksumValid); + // BK4 sanity flags can establish validity even without a stored checksum. + return new SlotImage(where, data, empty, empty || (pk is BK4 ? pk.Valid : pk.ChecksumValid)); } } @@ -186,6 +204,22 @@ private static IEnumerable Mons(SAV3 save) if (before.Route != after.Route) return $"the write would turn a {before.Route} save into a {after.Route} one."; + var profile = scope?.ProfileIndex ?? (before.Stock is SAV4BR pbr ? pbr.CurrentSlot : 0); + if (before.Stock is SAV4BR oldPbr && after.Stock is SAV4BR newPbr) + { + if ((uint)profile >= (uint)oldPbr.SaveNames.Count) + return "the targeted save profile does not exist."; + // Slot diffs alone miss another profile's trainer, passes and unknown + // bytes. Compare its entire native buffer, using the core's profile API. + for (var index = 0; index < oldPbr.SaveNames.Count; index++) + { + if (index == profile) continue; + oldPbr.CurrentSlot = newPbr.CurrentSlot = index; + if (!oldPbr.Buffer.Span.SequenceEqual(newPbr.Buffer.Span)) + return $"save profile {index + 1} changed although this edit did not target it."; + } + } + IReadOnlyList a, b; try { @@ -204,16 +238,18 @@ private static IEnumerable Mons(SAV3 save) { var old = a[i]; var now = b[i]; + var location = Label(old.Slot) + (before.Stock is SAV4BR ? $" in profile {old.Profile + 1}" : ""); if (old.Valid && !old.Empty && !now.Valid) - return $"{Label(old.Slot)} held a readable Pokémon that the new bytes corrupt."; + return $"{location} held a readable Pokémon that the new bytes corrupt."; if (scope is null) continue; var changed = old.Empty != now.Empty || (!(old.Empty && now.Empty) && !old.Bytes.AsSpan().SequenceEqual(now.Bytes)); if (!changed) continue; - var allowed = scope.Slots.Contains(old.Slot) || (old.Slot.Box == -1 && partyInScope); + var allowed = old.Profile == profile && + (scope.Slots.Contains(old.Slot) || (old.Slot.Box == -1 && partyInScope)); if (!allowed) - return $"{Label(old.Slot)} changed although this edit did not target it."; + return $"{location} changed although this edit did not target it."; } return null; } diff --git a/src/PKForge.Infrastructure/EmulatorSaveHeuristics.cs b/src/PKForge.Infrastructure/EmulatorSaveHeuristics.cs index 923be16c..0cc84743 100644 --- a/src/PKForge.Infrastructure/EmulatorSaveHeuristics.cs +++ b/src/PKForge.Infrastructure/EmulatorSaveHeuristics.cs @@ -33,12 +33,17 @@ public static bool IsCandidateFileName(string fileName) return CandidateExtensions.Contains(extension); } - /// Dolphin links individual GCI saves, never whole multi-game memory cards. + /// Dolphin links GameCube GCI saves and the raw Wii Battle Revolution save. public static bool IsCandidateFileName(string fileName, EmulatorKind kind) => kind == EmulatorKind.Dolphin ? fileName.EndsWith(".gci", StringComparison.OrdinalIgnoreCase) + || fileName.Equals("PbrSaveData", StringComparison.OrdinalIgnoreCase) : IsCandidateFileName(fileName); + /// Both console save trees are searched when Dolphin's whole user folder is granted. + public static bool IsDolphinSaveFolder(string folderName) => + folderName.Equals("GC", StringComparison.OrdinalIgnoreCase) || folderName.Equals("Wii", StringComparison.OrdinalIgnoreCase); + public static bool IsDolphinMemoryCard(string fileName) => Path.GetExtension(fileName).Equals(".raw", StringComparison.OrdinalIgnoreCase) || Path.GetExtension(fileName).Equals(".gcp", StringComparison.OrdinalIgnoreCase); diff --git a/src/PKForge.Infrastructure/SafeSaveWriter.cs b/src/PKForge.Infrastructure/SafeSaveWriter.cs index 12796273..060440b2 100644 --- a/src/PKForge.Infrastructure/SafeSaveWriter.cs +++ b/src/PKForge.Infrastructure/SafeSaveWriter.cs @@ -135,6 +135,15 @@ private async ValueTask WriteCoreAsync( { if (Refusal(documentId, original) is { } refusal) throw refusal; + if (original.ProfileIndex is { } profile) + { + if (scope?.ProfileIndex is { } requested && requested != profile) + throw new UnsafeSaveWriteException("Write refused: the selected save profile changed."); + // Whole-profile operations still may not change another profile. + scope = (scope ?? new WriteScope(original.Slots.Select(s => new SlotRef(s.Box, s.Slot)) + .Concat(Enumerable.Range(0, 6).Select(slot => new SlotRef(-1, slot))).ToArray())) + with { ProfileIndex = profile }; + } if (engine.CheckWriteSafety(original.OriginalBytes, candidate, scope) is { } unsafeDiff) throw new UnsafeSaveWriteException($"Write refused: {unsafeDiff} The original was not touched."); } diff --git a/src/PKForge.Infrastructure/SaveSessionService.cs b/src/PKForge.Infrastructure/SaveSessionService.cs index 5a9cc2c5..9152571b 100644 --- a/src/PKForge.Infrastructure/SaveSessionService.cs +++ b/src/PKForge.Infrastructure/SaveSessionService.cs @@ -36,12 +36,28 @@ public void MarkWritten(string documentId, ReadOnlyMemory written) Current = current with { Snapshot = current.Snapshot with { OriginalBytes = written.ToArray() } }; } + public void SelectProfile(int index) + { + if (Current is not { } current || CurrentSession is not IProfiledSaveSession profiles) + throw new NotSupportedException("This session has no profiles."); + profiles.SelectProfile(index); + Current = current with + { + Snapshot = CurrentSession.Snapshot with { OriginalBytes = current.Snapshot.OriginalBytes }, + }; + } + public void RevertToBaseline() { if (Current is not { } current) return; var format = SaveIdentityRules.FormatOfChoice(identities?.Get(current.Document.DocumentId)?.GameChoiceId); ISaveEngineSession reopened; - try { reopened = engine.OpenSession(current.Snapshot.OriginalBytes, current.Document.DisplayName, format); } + try + { + reopened = engine.OpenSession(current.Snapshot.OriginalBytes, current.Document.DisplayName, format); + if (current.Snapshot.ProfileIndex is { } profile && reopened is IProfiledSaveSession profiles) + profiles.SelectProfile(profile); + } catch { // The baseline no longer opens: a session that cannot be trusted is not kept. diff --git a/tests/PKForge.Domain.Tests/EmulatorSaveHeuristicsTests.cs b/tests/PKForge.Domain.Tests/EmulatorSaveHeuristicsTests.cs index 34e7412e..27a9ce94 100644 --- a/tests/PKForge.Domain.Tests/EmulatorSaveHeuristicsTests.cs +++ b/tests/PKForge.Domain.Tests/EmulatorSaveHeuristicsTests.cs @@ -23,9 +23,24 @@ public void CandidateFileNameFilter(string name, bool expected) => [InlineData("MemoryCardA.USA.raw", false)] [InlineData("game.sav", false)] [InlineData("game.s01", false)] - public void DolphinLinksOnlyIndividualGciSaves(string name, bool expected) => + [InlineData("PbrSaveData", true)] + [InlineData("pbrsavedata", true)] + [InlineData("PbrSaveData.bak", false)] + [InlineData("data.bin", false)] + [InlineData("banner.bin", false)] + [InlineData("main", false)] + public void DolphinLinksIndividualGameCubeAndBattleRevolutionSaves(string name, bool expected) => Assert.Equal(expected, EmulatorSaveHeuristics.IsCandidateFileName(name, EmulatorKind.Dolphin)); + [Theory] + [InlineData("GC", true)] + [InlineData("Wii", true)] + [InlineData("wii", true)] + [InlineData("Cache", false)] + [InlineData("Load", false)] + public void DolphinSearchesBothConsoleSaveTrees(string name, bool expected) => + Assert.Equal(expected, EmulatorSaveHeuristics.IsDolphinSaveFolder(name)); + [Theory] [InlineData("MemoryCardA.USA.raw", true)] [InlineData("MemoryCardB.GCP", true)] diff --git a/tests/PKForge.Engine.Tests/BattleRevolutionTests.cs b/tests/PKForge.Engine.Tests/BattleRevolutionTests.cs new file mode 100644 index 00000000..3e9cbeae --- /dev/null +++ b/tests/PKForge.Engine.Tests/BattleRevolutionTests.cs @@ -0,0 +1,345 @@ +using PKForge.Domain; +using PKForge.Engine; +using PKForge.Infrastructure; +using PKHeX.Core; +using Xunit; + +namespace PKForge.Engine.Tests; + +public sealed class BattleRevolutionTests +{ + private static readonly SaveEngine Engine = new(); + + // SAV4BR @91e9c886: a zero-filled decrypted container has valid zero bit-count + // checksums. Seed all profiles through its native API, then finalize/encrypt. + // Fixtures are generated in memory; no player saves or game data are bundled. + internal static byte[] Fixture(int language = (int)LanguageID.English) + { + var save = new SAV4BR(new byte[SaveUtil.SIZE_G4BR], decrypt: false); + for (var profile = 0; profile < 4; profile++) + { + save.CurrentSlot = profile; + save.Language = language; + save.CurrentOT = $"P{profile}"; + var pk = new BK4 { Species = 25, PID = 1234, EXP = 1000, Language = language, + OriginalTrainerName = "TEST", Nickname = "PIKACHU" }; + pk.RefreshChecksum(); + save.SetBoxSlotAtIndex(pk, 0, 0, EntityImportSettings.None); + save.SetPartySlotAtIndex(pk.Clone(), 0, EntityImportSettings.None); + } + return save.Write().ToArray(); + } + + private static byte[] Rename(byte[] original, int profile) + { + var save = new SAV4BR(original.ToArray()); + save.CurrentSlot = profile; + var pk = save.GetBoxSlotAtIndex(0, 0); + pk.Nickname = "CHANGED"; + pk.RefreshChecksum(); + save.SetBoxSlotAtIndex(pk, 0, 0, EntityImportSettings.None); + return save.Write().ToArray(); + } + + [Fact] + public void SyntheticSaveRoundTripsThroughTheEngine() + { + var original = Fixture(); + Assert.True(Engine.Validate(original)); + using var session = Engine.OpenSession(original); + Assert.True(session.Serialize().Span.SequenceEqual(original)); + } + + [Theory] + [InlineData(1)] + [InlineData(2)] + [InlineData(3)] + public void ScopeCannotHideChangesInAnotherProfile(int profile) + { + var original = Fixture(); + Assert.NotNull(Engine.CheckWriteSafety(original, Rename(original, profile), + WriteScope.Only(new SlotRef(0, 0)))); + } + + [Fact] + public void DescriptionUsesTheActualProfileName() + { + Assert.Equal("P0", Engine.TryDescribe(Fixture())!.TrainerName); + } + + [Fact] + public void SwitchingProfilesAndListingTheirNamesDoesNotChangeTheFile() + { + var bytes = Fixture(); + using var session = Engine.OpenSession(bytes); + var profiles = Assert.IsAssignableFrom(session); + Assert.Equal(new[] { "P0", "P1", "P2", "P3" }, profiles.Profiles.Select(p => p.Name)); + foreach (var index in new[] { 3, 1, 0, 2 }) + { + profiles.SelectProfile(index); + Assert.Equal(index, session.Snapshot.ProfileIndex); + Assert.Equal($"P{index}", session.GetTrainer().Name); + Assert.True(session.Serialize().Span.SequenceEqual(bytes)); + } + Assert.Throws(() => profiles.SelectProfile(-1)); + Assert.Throws(() => profiles.SelectProfile(4)); + Assert.Equal(2, profiles.CurrentProfile); + Assert.True(session.Serialize().Span.SequenceEqual(bytes)); + } + + [Theory] + [InlineData(0)] + [InlineData(1)] + [InlineData(2)] + [InlineData(3)] + public void ExplicitProfileScopeAllowsOnlyItsTargetedSlot(int index) + { + var bytes = Fixture(); + var candidate = Rename(bytes, index); + Assert.Null(Engine.CheckWriteSafety(bytes, candidate, + WriteScope.Only(new SlotRef(0, 0)) with { ProfileIndex = index })); + Assert.NotNull(Engine.CheckWriteSafety(bytes, candidate, + WriteScope.Only(new SlotRef(0, 1)) with { ProfileIndex = index })); + var reopened = new SAV4BR(candidate.ToArray()); + for (var other = 0; other < 4; other++) + { + reopened.CurrentSlot = other; + Assert.Equal(other == index ? "CHANGED" : "PIKACHU", reopened.GetBoxSlotAtIndex(0, 0).Nickname); + } + Assert.True(bytes.AsSpan(SAV4BR.SIZE_HALF).SequenceEqual(candidate.AsSpan(SAV4BR.SIZE_HALF)), + "The inactive partition must stay byte-identical."); + } + + [Fact] + public void OtherProfileMetadataCannotEvadeTheSlotScope() + { + var bytes = Fixture(); + var save = new SAV4BR(bytes.ToArray()) { CurrentSlot = 2, CurrentOT = "NEW" }; + Assert.NotNull(Engine.CheckWriteSafety(bytes, save.Write(), WriteScope.Only(new SlotRef(0, 0)))); + } + + [Theory] + [InlineData(0)] + [InlineData(1)] + [InlineData(2)] + [InlineData(3)] + public void PartyScopeCannotAuthorizeTheSamePartySlotInAnotherProfile(int profile) + { + var original = Fixture(); + using var session = Engine.OpenSession(original); + ((IProfiledSaveSession)session).SelectProfile(profile); + session.ApplyEdit(-1, 0, new EntityEdit(Nickname: "PARTY")); + var candidate = session.Serialize(); + var scope = WriteScope.Only(new SlotRef(-1, 0)) with { ProfileIndex = profile }; + Assert.Null(Engine.CheckWriteSafety(original, candidate, scope)); + Assert.NotNull(Engine.CheckWriteSafety(original, candidate, + scope with { ProfileIndex = (profile + 1) % 4 })); + using var reopened = Engine.OpenSession(candidate); + var profiles = (IProfiledSaveSession)reopened; + for (var other = 0; other < 4; other++) + { + profiles.SelectProfile(other); + Assert.Equal(other == profile ? "PARTY" : "PIKACHU", reopened.ReadEntity(-1, 0).Nickname); + } + } + + [Fact] + public void TrainerRenamePersistsInTheSelectedProfile() + { + using var session = Engine.OpenSession(Fixture()); + var profiles = (IProfiledSaveSession)session; + profiles.SelectProfile(2); + session.SetTrainer(session.GetTrainer() with { Name = "NEW" }); + var bytes = session.Serialize(); + using var reopened = Engine.OpenSession(bytes); + ((IProfiledSaveSession)reopened).SelectProfile(2); + Assert.Equal("NEW", reopened.GetTrainer().Name); + Assert.Equal("NEW", profiles.Profiles[2].Name); + profiles.SelectProfile(0); + Assert.Equal("P0", session.GetTrainer().Name); + } + + [Fact] + public void UnrepresentableTrainerRenameLeavesTheSessionUnchanged() + { + var bytes = Fixture(); + using var session = Engine.OpenSession(bytes); + Assert.Throws(() => session.SetTrainer(session.GetTrainer() with { Name = "TOOLONG" })); + Assert.True(session.Serialize().Span.SequenceEqual(bytes)); + } + + [Theory] + [InlineData(1, "JA", "雪月", "テスト")] + [InlineData(2, "EN", "Jo", "TEST")] + [InlineData(3, "FR", "Été", "Été")] + [InlineData(4, "IT", "Più", "Caffè")] + [InlineData(5, "DE", "Öde", "MÄX")] + [InlineData(7, "ES", "Peña", "NIÑO")] + public void NativeLanguageAndUnicodeNamesSurviveProfileEdits(int language, string tag, string name, string nickname) + { + var original = Fixture(language); + Assert.Equal(tag, Engine.TryDescribe(original)!.Language); + using var session = Engine.OpenSession(original); + var profiles = (IProfiledSaveSession)session; + profiles.SelectProfile(2); + Assert.True(session.Serialize().Span.SequenceEqual(original)); + session.SetTrainer(session.GetTrainer() with { Name = name }); + session.ApplyEdit(0, 0, new EntityEdit(Nickname: nickname)); + var candidate = session.Serialize(); + Assert.Null(Engine.CheckWriteSafety(original, candidate, + WriteScope.Only(new SlotRef(0, 0)) with { ProfileIndex = 2 })); + using var reopened = Engine.OpenSession(candidate); + var selection = (IProfiledSaveSession)reopened; + selection.SelectProfile(2); + Assert.Equal(name, reopened.GetTrainer().Name); + Assert.Equal(name, selection.Profiles[2].Name); + Assert.Equal(nickname, reopened.ReadEntity(0, 0).Nickname); + var export = reopened.ExportSlot(0, 0); + Assert.Equal("BK4", export.Format); + Assert.Equal(nickname, EntityBytes.Parse(export.Data, export.Format)!.Nickname); + Assert.True(reopened.Serialize().Span.SequenceEqual(candidate.Span)); + selection.SelectProfile(0); + Assert.Equal("P0", reopened.GetTrainer().Name); + Assert.Equal("PIKACHU", reopened.ReadEntity(0, 0).Nickname); + Assert.Equal(tag, Engine.TryDescribe(candidate)!.Language); + } + + [Fact] + public async Task RevertAndSuccessfulWritesRetainSelectedProfileAndFullBaseline() + { + var original = Fixture(); + var service = new SaveSessionService(new MemoryAccess(original), Engine); + await service.OpenAsync(new PickedDocument("pbr", "PbrSaveData")); + service.SelectProfile(3); + service.CurrentSession!.ApplyEdit(0, 0, new EntityEdit(Nickname: "FIRST")); + var candidate = service.CurrentSession.Serialize(); + service.MarkWritten("pbr", candidate); + service.CurrentSession.ApplyEdit(0, 0, new EntityEdit(Nickname: "SECOND")); + service.RevertToBaseline(); + Assert.Equal(3, ((IProfiledSaveSession)service.CurrentSession!).CurrentProfile); + Assert.Equal(3, service.Current!.Snapshot.ProfileIndex); + Assert.Equal("FIRST", service.CurrentSession.ReadEntity(0, 0).Nickname); + Assert.True(service.Current.Snapshot.OriginalBytes.Span.SequenceEqual(candidate.Span)); + service.SelectProfile(0); + Assert.Equal("PIKACHU", service.CurrentSession.ReadEntity(0, 0).Nickname); + Assert.True(service.Current.Snapshot.OriginalBytes.Span.SequenceEqual(candidate.Span)); + } + + [Fact] + public async Task WriterBindsOrdinaryEditsToTheSelectedProfileBeforeBackingUp() + { + var original = Fixture(); + using var session = Engine.OpenSession(original); + ((IProfiledSaveSession)session).SelectProfile(2); + var access = new MemoryAccess(original); + var backups = new MemoryBackups(access); + var writer = new SafeSaveWriter(Engine, backups, access); + var snapshot = session.Snapshot; + var noop = await writer.WriteAsync("pbr", snapshot, original); + Assert.False(noop.Changed); + Assert.Equal(0, backups.Count); + Assert.Equal(0, access.Writes); + // An out-of-profile candidate must fail even on the general write path. + await Assert.ThrowsAsync(() => + writer.WriteAsync("pbr", snapshot, Rename(original, 1)).AsTask()); + Assert.Equal(0, backups.Count); + Assert.Equal(0, access.Writes); + await Assert.ThrowsAsync(() => + writer.WriteAsync("pbr", snapshot, new byte[20]).AsTask()); + Assert.Equal(0, backups.Count); + Assert.Equal(0, access.Writes); + await Assert.ThrowsAsync(() => + writer.WriteScopedAsync("pbr", snapshot, Rename(original, 2), + WriteScope.Only(new SlotRef(0, 0)) with { ProfileIndex = 1 }).AsTask()); + Assert.Equal(0, backups.Count); + Assert.Equal(0, access.Writes); + session.ApplyEdit(0, 0, new EntityEdit(Nickname: "SAVED")); + var candidate = session.Serialize(); + await writer.WriteScopedAsync("pbr", snapshot, candidate, WriteScope.Only(new SlotRef(0, 0))); + Assert.Equal(1, backups.Count); + Assert.Equal(1, access.Writes); + Assert.True(backups.Bytes!.AsSpan().SequenceEqual(original)); + Assert.True(access.Bytes.AsSpan().SequenceEqual(candidate.Span)); + } + + [Fact] + public void InvalidSizesAndBothDamagedPartitionsAreRejected() + { + Assert.False(Engine.Validate(new byte[0x380000 - 1])); + Assert.False(Engine.Validate(new byte[3732864])); // Wii data.bin archive size + var damaged = Fixture(); + damaged[0x1000] ^= 1; + damaged[SAV4BR.SIZE_HALF + 0x1000] ^= 1; + Assert.False(Engine.Validate(damaged)); + } + + [Fact] + public void SecondPartitionFallbackSupportsEveryProfileWithoutRepairingTheDamagedFirst() + { + var bytes = Fixture(); + bytes.AsSpan(0, SAV4BR.SIZE_HALF).CopyTo(bytes.AsSpan(SAV4BR.SIZE_HALF)); + bytes[0x1000] ^= 1; // a damaged first partition forces the valid second one + using var session = Engine.OpenSession(bytes); + var profiles = (IProfiledSaveSession)session; + foreach (var index in Enumerable.Range(0, 4)) + { + profiles.SelectProfile(index); + Assert.Equal($"P{index}", session.GetTrainer().Name); + Assert.True(session.Serialize().Span.SequenceEqual(bytes)); + } + session.ApplyEdit(0, 0, new EntityEdit(Nickname: "BACKUP")); + var candidate = session.Serialize(); + Assert.True(bytes.AsSpan(0, SAV4BR.SIZE_HALF).SequenceEqual(candidate.Span[..SAV4BR.SIZE_HALF])); + Assert.Null(Engine.CheckWriteSafety(bytes, candidate, + WriteScope.Only(new SlotRef(0, 0)) with { ProfileIndex = 3 })); + } + + [Fact] + public void EmptyProfilesKeepTheirIndicesWhenTheAutomaticDefaultChanges() + { + var save = new SAV4BR(Fixture()) { CurrentSlot = 0, CurrentOT = "" }; + var bytes = save.Write(); + using var session = Engine.OpenSession(bytes); + var profiles = (IProfiledSaveSession)session; + Assert.Equal(1, profiles.CurrentProfile); + Assert.True(profiles.Profiles[0].IsEmpty); + profiles.SelectProfile(0); + session.SetTrainer(session.GetTrainer() with { Name = "NEW" }); + Assert.Null(Engine.CheckWriteSafety(bytes, session.Serialize(), + WriteScope.Only() with { ProfileIndex = 0 })); + Assert.NotNull(Engine.CheckWriteSafety(bytes, session.Serialize(), + WriteScope.Only() with { ProfileIndex = 1 })); + } + + private sealed class MemoryAccess(byte[] bytes) : ISaveFileAccess + { + public byte[] Bytes = bytes.ToArray(); + public int Writes; + public ValueTask> ReadAsync(string documentId, CancellationToken cancellationToken = default) => + ValueTask.FromResult>(Bytes); + public ValueTask WriteAtomicallyAsync(string documentId, ReadOnlyMemory bytes, CancellationToken cancellationToken = default) + { + Bytes = bytes.ToArray(); + Writes++; + return ValueTask.CompletedTask; + } + } + + private sealed class MemoryBackups(MemoryAccess access) : IBackupService + { + public int Count; + public byte[]? Bytes; + public ValueTask CreateAsync(SaveSnapshot source, string? changeDescription = null, + string? documentId = null, CancellationToken cancellationToken = default) + { + Assert.Equal(0, access.Writes); + Count++; + Bytes = source.OriginalBytes.ToArray(); + return ValueTask.FromResult(new BackupReceipt("pbr-backup", DateTimeOffset.UtcNow, "hash")); + } + public ValueTask> ListAsync(CancellationToken cancellationToken = default) => + ValueTask.FromResult>([]); + public ValueTask> ReadAsync(string backupId, CancellationToken cancellationToken = default) => + ValueTask.FromResult>(Bytes ?? []); + } +}