Skip to content
Merged
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
2 changes: 2 additions & 0 deletions VisualPinball.Engine.PinMAME.Unity/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,8 @@ Desktop builds use the ROM folder configured by the player or host. If neither s

NVRAM, configuration and high scores stay in VPE's own shared data folder (`%LOCALAPPDATA%\Visual Pinball Engine\PinMAME` on Windows). Existing game state is copied from Visual PinMAME on the first run only; VPE subsequently maintains its own copy.

To reset a ROM's saved memory, exit the table in all VPE windows, select it in the library and open **Settings › Plugins › PinMAME › Selected game › Back up and reset ROM memory**. VPE moves the ROM's `.nv` file to `nvram-backups/<rom>` and skips importing that ROM's NVRAM from Visual PinMAME. The reset applies to every VPE table using the same ROM. To restore the backup, exit the table again and copy the backed-up file to `nvram/<rom>.nv`.

## Developer Setup

This UPM package gets build and published via CI. If you want to use it locally,
Expand Down
27 changes: 27 additions & 0 deletions VisualPinball.Engine.PinMAME.Unity/Runtime/PinMameFolders.cs
Original file line number Diff line number Diff line change
Expand Up @@ -86,6 +86,30 @@ public static bool HasRomZip(string romFolder, string romId)
.Any(folder => folder.Length > 0 && File.Exists(Path.Combine(folder, romId + ".zip")));
}

/// <summary>Backs up a stopped ROM's NVRAM so the next run starts with fresh memory.</summary>
internal static string ResetNvram(string romId)
{
if (string.IsNullOrEmpty(romId) || romId.Any(c => !(c is >= 'a' and <= 'z' or >= '0' and <= '9' or '_'))) {
throw new ArgumentException("The selected table has an invalid PinMAME ROM name.", nameof(romId));
}
var dataFolder = DataFolder;
var backupFolder = Path.Combine(dataFolder, "nvram-backups", romId);
Directory.CreateDirectory(backupFolder);
// Keep the import opt-out beside the active save so clearing backups does not re-enable import.
using (File.Open(NvramImportOptOut(dataFolder, romId), FileMode.OpenOrCreate, FileAccess.Write)) { }
var backup = Path.Combine(backupFolder, $"{DateTime.UtcNow:yyyyMMdd-HHmmss}-{Guid.NewGuid():N}.nv");
try {
File.Move(Path.Combine(dataFolder, "nvram", romId + ".nv"), backup);
Comment on lines +90 to +102

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Save resets lack tests

ResetNvram changes saved game files but has no automated tests. Add temporary-folder tests for backup bytes, repeated resets, a missing save, and the import opt-out. Also check that resetting one ROM leaves another ROM's files alone. These checks would catch changes that silently lose a backup or bring back memory the user just cleared.

Note: If this suggestion doesn't match your team's coding style, reply to this and let me know. I'll remember it for next time!

} catch (FileNotFoundException) {
return null;
}
Logger.Info("[PinMAME] Backed up {Rom:l} NVRAM to {Backup:l}.", romId, backup);
return backup;
}

private static string NvramImportOptOut(string dataFolder, string romId)
=> Path.Combine(dataFolder, "nvram", romId.ToLowerInvariant() + ".skip-vpm-import");

/// <summary>
/// Copies the game's NVRAM, high scores and config from VPM's folders, for each of them
/// that VPE doesn't have yet. Existing files are never overwritten, so after the first run
Expand All @@ -98,6 +122,9 @@ public static void ImportFromVpm(string romId)
}
var dataFolder = DataFolder;
foreach (var (type, folder, extension) in VpmImports) {
if (type == PinMameFileType.Nvram && File.Exists(NvramImportOptOut(dataFolder, romId))) {
continue;
}
var target = Path.Combine(dataFolder, folder, romId + extension);
if (File.Exists(target)) {
continue;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -926,6 +926,23 @@ public void StopForPlayModeExit()
}
}

internal static bool TryResetNvram(string romId, out string backup)
{
backup = null;
if (!PinMameStartStopGate.Wait(0)) {
return false;
}
try {
if (PinMame.PinMame.IsStopInProgress || PinMame.PinMame.IsRunning) {
return false;
}
backup = PinMameFolders.ResetNvram(romId);
return true;
} finally {
PinMameStartStopGate.Release();
}
}

private void RequestStopGame(string reason)
{
_romStarting = false;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -5,10 +5,9 @@
// Licensed under MIT. See https://opensource.org/license/mit.

using System;
using System.Text;
using Newtonsoft.Json.Linq;
using UnityEngine;
using VisualPinball.Plugins;
using VisualPinball.Unity;

namespace VisualPinball.Engine.PinMAME
{
Expand All @@ -17,9 +16,10 @@ internal sealed class PinMamePackageIdentityReader : IPackagedGameIdentityReader
public string ComponentType => "PinMameGamelogicEngine";
public GameIdentity? Read(ReadOnlyMemory<byte> payload)
{
var values = JObject.Parse(Encoding.UTF8.GetString(payload.Span));
string rom = values.Value<string>("RomId");
if (string.IsNullOrWhiteSpace(rom)) rom = values.Value<string>("GameId");
// read as the packer wrote it, so the key names are the packer's
var data = PackageApi.Packer.Unpack<PinMameGamelogicEnginePackable>(payload.ToArray());
var rom = data.RomId;
if (string.IsNullOrWhiteSpace(rom)) rom = data.GameId;
return string.IsNullOrWhiteSpace(rom) ? null : new GameIdentity("pinmame", rom);
}
[RuntimeInitializeOnLoadMethod(RuntimeInitializeLoadType.BeforeSceneLoad)]
Expand Down
37 changes: 33 additions & 4 deletions VisualPinball.Engine.PinMAME.Unity/Runtime/PinMamePluginFactory.cs
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@
// Licensed under MIT. See https://opensource.org/license/mit.

using System;
using System.Collections.Generic;
using System.Threading;
using System.Threading.Tasks;
using UnityEngine;
Expand All @@ -14,9 +15,12 @@
namespace VisualPinball.Engine.PinMAME
{
/// <summary>Configures the selected engine's audio; emulation remains owned by the table.</summary>
internal sealed partial class PinMamePluginFactory : IPlayerPluginFactory, IPluginSystemDefaults
internal sealed partial class PinMamePluginFactory : IPlayerPluginFactory, IPluginSystemDefaults, IPluginSettingsProvider
{
public PluginDescriptor Descriptor { get; } = new PluginDescriptor("org.visualpinball.pinmame", "PinMAME", "ROM audio for tables using the PinMAME engine.") { EnabledByDefault = true, CanDisable = false, Category = "Gamelogic", Order = 5 };
private const string ResetRomMemory = "reset-rom-memory";
private const string CloseTableMessage = "Exit the running table before resetting ROM memory.";

public PluginDescriptor Descriptor { get; } = new PluginDescriptor("org.visualpinball.pinmame", "PinMAME", "ROM audio and saved memory for tables using the PinMAME engine.") { EnabledByDefault = true, CanDisable = false, Category = "Gamelogic", Order = 5 };
public PluginSettingsSchema Schema { get; } = new PluginSettingsSchema(1, new PluginSettingsGroup("ROM audio", "Controls PinMAME playback without changing ROM settings.",
new PluginField("Volume", "Volume", SettingKind.Integer) { Default = 100, Minimum = 0, Maximum = 100, Change = ConfigurationChange.Live,
Presentation = PluginFieldPresentation.Slider, Unit = "%", GlobalSetting = new PluginGlobalSetting(PluginGlobalSections.VolumeMixer) { Order = 20 } }),
Expand All @@ -33,8 +37,33 @@ internal sealed partial class PinMamePluginFactory : IPlayerPluginFactory, IPlug
Description = "Lets the volume set in the game's own menu scale the pack too, as in Visual PinMAME. Packs are often much quieter then." },
new PluginField("AltSoundRomVolume", "ROM sound under AltSound", SettingKind.Integer) { Default = 0, Minimum = 0, Maximum = 100, Change = ConfigurationChange.Live,
Presentation = PluginFieldPresentation.Slider, Unit = "%", Scope = ConfigurationScope.GlobalAndGame, VisibleWhen = "AltSound",
Description = "How much of the ROM's own sound still plays, for packs that don't replace all of it. Off, like Visual PinMAME." }));
public IPluginSettingsProvider SettingsProvider => null;
Description = "How much of the ROM's own sound still plays, for packs that don't replace all of it. Off, like Visual PinMAME." }),
new PluginSettingsGroup("ROM memory", "Tables using the same ROM share its saved memory.",
new PluginField("ResetRomMemory", "Back up and reset ROM memory", SettingKind.Action) { Scope = ConfigurationScope.GameOnly, Provider = ResetRomMemory,
Description = "Takes effect immediately. The ROM starts fresh next time, clearing saved adjustments, audits and any scores stored in its memory. Exit the table in every VPE window first." }));
public IPluginSettingsProvider SettingsProvider => this;

public Task<PluginChoiceCatalog> DiscoverAsync(string provider, PluginChoiceRequest request, CancellationToken cancellation)
=> Task.FromResult(new PluginChoiceCatalog(provider, Array.Empty<PluginChoice>()));

public IReadOnlyList<PluginValidationIssue> Validate(PluginChoiceRequest request) => Array.Empty<PluginValidationIssue>();

public Task<PluginActionResult> RunActionAsync(string action, PluginChoiceRequest request, CancellationToken cancellation)
{
cancellation.ThrowIfCancellationRequested();
if (action != ResetRomMemory || Application.isMobilePlatform) {
return Task.FromResult(new PluginActionResult(false, "This action is unavailable."));
}
if (!(request.Game is GameIdentity game) || game.Provider != "pinmame") {
return Task.FromResult(new PluginActionResult(false, "Select a table that uses PinMAME."));
}
if (!PinMameGamelogicEngine.TryResetNvram(game.Key, out var backup)) {
return Task.FromResult(new PluginActionResult(false, CloseTableMessage));
}
var message = $"{game.Key} will start with fresh ROM memory.";
return Task.FromResult(new PluginActionResult(true, backup == null ? message : $"{message} Backup saved to {backup}"));
}

public IPlayerPlugin Create(PluginApplicationContext context) => new SettingsAdapter(context);
[RuntimeInitializeOnLoadMethod(RuntimeInitializeLoadType.BeforeSceneLoad)]
private static void Register() => PlayerPluginRegistry.Register(new PinMamePluginFactory());
Expand Down
Loading