Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
18 changes: 17 additions & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -146,14 +146,30 @@ 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:

- **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

Expand Down
6 changes: 4 additions & 2 deletions src/PKForge.App/Platforms/Android/AndroidEmulatorScanner.cs
Original file line number Diff line number Diff line change
Expand Up @@ -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();
Expand Down
2 changes: 2 additions & 0 deletions src/PKForge.App/Services/TransferService.cs
Original file line number Diff line number Diff line change
Expand Up @@ -87,6 +87,8 @@ public TransferPreviewOutcome PreviewIntoConnected(ReadOnlyMemory<byte> 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));
Expand Down
30 changes: 30 additions & 0 deletions src/PKForge.App/ViewModels/BoxBrowserViewModel.cs
Original file line number Diff line number Diff line change
Expand Up @@ -319,6 +319,36 @@ public void RefreshFromCurrentSession()
Status = "READY";
}

public IReadOnlyList<SaveProfile> SaveProfiles =>
_sessions.CurrentSession is IProfiledSaveSession profiles ? profiles.Profiles : [];

public int CurrentProfile =>
_sessions.CurrentSession is IProfiledSaveSession profiles ? profiles.CurrentProfile : 0;

public async Task<bool> 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 ──

/// <summary>The last sweep's verdicts while they still match the save's write
Expand Down
20 changes: 20 additions & 0 deletions src/PKForge.App/Views/BoxBrowserPage.cs
Original file line number Diff line number Diff line change
Expand Up @@ -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);
Expand Down Expand Up @@ -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();
Expand All @@ -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.")),
Expand Down Expand Up @@ -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;
Expand Down
6 changes: 3 additions & 3 deletions src/PKForge.App/Views/HomePage.cs
Original file line number Diff line number Diff line change
Expand Up @@ -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"));
Expand All @@ -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"),
Expand All @@ -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.",
Expand Down
11 changes: 10 additions & 1 deletion src/PKForge.Domain/Contracts.cs
Original file line number Diff line number Diff line change
Expand Up @@ -119,6 +119,9 @@ public interface ISaveSessionService
/// </summary>
void MarkWritten(string documentId, ReadOnlyMemory<byte> written);

/// <summary>Changes the viewed profile without changing the whole-file backup baseline.</summary>
void SelectProfile(int index) => throw new NotSupportedException("This session has no profiles.");

/// <summary>
/// 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
Expand Down Expand Up @@ -176,6 +179,8 @@ void RevokeLayoutRisk(string documentId) { }
/// </summary>
public sealed record WriteScope(IReadOnlyCollection<SlotRef> Slots, bool Unrestricted = false)
{
/// <summary>The profile these slot coordinates address; null uses the session's profile.</summary>
public int? ProfileIndex { get; init; }
public static WriteScope Everything { get; } = new([], Unrestricted: true);
public static WriteScope Only(params SlotRef[] slots) => new(slots);
}
Expand Down Expand Up @@ -277,7 +282,11 @@ public sealed record SaveSnapshot(
int Generation,
ReadOnlyMemory<byte> OriginalBytes,
IReadOnlyList<SlotSummary> Slots,
string? DisplayName);
string? DisplayName)
{
/// <summary>Selected profile in a multi-profile file; null for a single-profile save.</summary>
public int? ProfileIndex { get; init; }
}

/// <param name="HeldItem">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.</param>
Expand Down
12 changes: 12 additions & 0 deletions src/PKForge.Domain/SaveProfiles.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
namespace PKForge.Domain;

/// <summary>A named profile within one save file. Indices are stable even for empty profiles.</summary>
public sealed record SaveProfile(int Index, string Name, bool IsEmpty);

/// <summary>Optional profile selection. All profiles share one whole-file restore point.</summary>
public interface IProfiledSaveSession
{
IReadOnlyList<SaveProfile> Profiles { get; }
int CurrentProfile { get; }
void SelectProfile(int index);
}
6 changes: 5 additions & 1 deletion src/PKForge.Engine/SaveEngine.cs
Original file line number Diff line number Diff line change
Expand Up @@ -63,7 +63,8 @@ public SaveSnapshot Open(ReadOnlyMemory<byte> 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<byte> bytes, string? displayName = null)
Expand Down Expand Up @@ -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));

Expand Down
59 changes: 54 additions & 5 deletions src/PKForge.Engine/SaveEngineSession.cs
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@
namespace PKForge.Engine;

/// <summary>Holds a pinned PKHeX <see cref="SaveFile"/> and exposes entity access without leaking engine types.</summary>
public sealed class SaveEngineSession : ISaveEngineSession
public sealed class SaveEngineSession : ISaveEngineSession, IProfiledSaveSession
{
private readonly SaveFile _save;
static SaveEngineSession() => LegalityRules.Apply();
Expand Down Expand Up @@ -59,6 +59,40 @@ internal SaveEngineSession(SaveFile save, string? displayName)
/// session (generate, import, move), not the state of the file at open time.</summary>
public SaveSnapshot Snapshot => BuildSnapshot(_displayName);

public IReadOnlyList<SaveProfile> 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();
Expand Down Expand Up @@ -1530,16 +1564,30 @@ 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)
{
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<byte> 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);
Expand Down Expand Up @@ -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)
Expand Down
Loading