From f50bee318170e53bf3e90328f7fe828a3e0a2fda Mon Sep 17 00:00:00 2001 From: freezy Date: Sat, 7 Nov 2026 16:25:32 +0100 Subject: [PATCH 1/2] pinmame: back up and reset per-ROM memory --- VisualPinball.Engine.PinMAME.Unity/README.md | 2 + .../Runtime/PinMameFolders.cs | 27 ++++++++++++++ .../Runtime/PinMameGamelogicEngine.cs | 17 +++++++++ .../Runtime/PinMamePluginFactory.cs | 37 +++++++++++++++++-- 4 files changed, 79 insertions(+), 4 deletions(-) diff --git a/VisualPinball.Engine.PinMAME.Unity/README.md b/VisualPinball.Engine.PinMAME.Unity/README.md index 6cc8386..a0ce176 100644 --- a/VisualPinball.Engine.PinMAME.Unity/README.md +++ b/VisualPinball.Engine.PinMAME.Unity/README.md @@ -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/` 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/.nv`. + ## Developer Setup This UPM package gets build and published via CI. If you want to use it locally, diff --git a/VisualPinball.Engine.PinMAME.Unity/Runtime/PinMameFolders.cs b/VisualPinball.Engine.PinMAME.Unity/Runtime/PinMameFolders.cs index 29e1358..b1d8d0e 100644 --- a/VisualPinball.Engine.PinMAME.Unity/Runtime/PinMameFolders.cs +++ b/VisualPinball.Engine.PinMAME.Unity/Runtime/PinMameFolders.cs @@ -86,6 +86,30 @@ public static bool HasRomZip(string romFolder, string romId) .Any(folder => folder.Length > 0 && File.Exists(Path.Combine(folder, romId + ".zip"))); } + /// Backs up a stopped ROM's NVRAM so the next run starts with fresh memory. + 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); + } 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"); + /// /// 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 @@ -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; diff --git a/VisualPinball.Engine.PinMAME.Unity/Runtime/PinMameGamelogicEngine.cs b/VisualPinball.Engine.PinMAME.Unity/Runtime/PinMameGamelogicEngine.cs index 9bb1d3b..ed240a5 100644 --- a/VisualPinball.Engine.PinMAME.Unity/Runtime/PinMameGamelogicEngine.cs +++ b/VisualPinball.Engine.PinMAME.Unity/Runtime/PinMameGamelogicEngine.cs @@ -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; diff --git a/VisualPinball.Engine.PinMAME.Unity/Runtime/PinMamePluginFactory.cs b/VisualPinball.Engine.PinMAME.Unity/Runtime/PinMamePluginFactory.cs index 3be5576..d6c35c4 100644 --- a/VisualPinball.Engine.PinMAME.Unity/Runtime/PinMamePluginFactory.cs +++ b/VisualPinball.Engine.PinMAME.Unity/Runtime/PinMamePluginFactory.cs @@ -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; @@ -14,9 +15,12 @@ namespace VisualPinball.Engine.PinMAME { /// Configures the selected engine's audio; emulation remains owned by the table. - 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 } }), @@ -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 DiscoverAsync(string provider, PluginChoiceRequest request, CancellationToken cancellation) + => Task.FromResult(new PluginChoiceCatalog(provider, Array.Empty())); + + public IReadOnlyList Validate(PluginChoiceRequest request) => Array.Empty(); + + public Task 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()); From fbdce5c2cce2d8ad074de3c980bc46745323f288 Mon Sep 17 00:00:00 2001 From: freezy Date: Sat, 14 Nov 2026 10:36:38 +0100 Subject: [PATCH 2/2] packaging: read the game's identity through the packer The identity reader looked the game up by its key name in the packed JSON, and VPE now writes package keys in camelCase. It unpacks the component's packable instead, so it reads whatever names the packer writes. --- .../Runtime/PinMamePackageIdentityReader.cs | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/VisualPinball.Engine.PinMAME.Unity/Runtime/PinMamePackageIdentityReader.cs b/VisualPinball.Engine.PinMAME.Unity/Runtime/PinMamePackageIdentityReader.cs index 1fe1496..cc80f90 100644 --- a/VisualPinball.Engine.PinMAME.Unity/Runtime/PinMamePackageIdentityReader.cs +++ b/VisualPinball.Engine.PinMAME.Unity/Runtime/PinMamePackageIdentityReader.cs @@ -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 { @@ -17,9 +16,10 @@ internal sealed class PinMamePackageIdentityReader : IPackagedGameIdentityReader public string ComponentType => "PinMameGamelogicEngine"; public GameIdentity? Read(ReadOnlyMemory payload) { - var values = JObject.Parse(Encoding.UTF8.GetString(payload.Span)); - string rom = values.Value("RomId"); - if (string.IsNullOrWhiteSpace(rom)) rom = values.Value("GameId"); + // read as the packer wrote it, so the key names are the packer's + var data = PackageApi.Packer.Unpack(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)]