From 3b90260c80038276bbb616812c126d2a3c92393f Mon Sep 17 00:00:00 2001 From: freezy Date: Tue, 17 Nov 2026 14:35:40 +0100 Subject: [PATCH 1/2] pinmame: offer compatible ROMs when the table's ROM is missing The component now keeps the other ROMs of its machine that can run the table, taken from the games catalog (identical, compatible or unverified; ROMs marked "different" are left out both ways), and writes them into the .vpe package. Export refreshes the list from the catalog. In the player, the PinMAME plugin checks before a launch whether the table's ROM is in the ROM folder. When it's missing and at least one compatible ROM is there, the launch asks which one to play with and saves the choice for the table. The engine then starts that ROM, and its NVRAM, AltSound, diagnostics and ROM name follow it, while the table's settings stay with its own ROM. Resetting ROM memory resets the ROM that plays. Package format: case 1 of "Versioning the items schema" in Packaging/FORMAT.md, an optional field older readers ignore, so no schema bump. --- .../Editor/PinMameCompatibleRomsExport.cs | 59 +++++++ .../PinMameCompatibleRomsExport.cs.meta | 2 + .../Editor/PinMameGameDefinition.cs | 8 +- .../Editor/PinMameGameDefinitionConverter.cs | 59 ++++++- .../PinMameGameDefinitionEditorService.cs | 1 + .../Editor/PinMameGamelogicEngineInspector.cs | 23 +++ .../Runtime/PinMameCompatibleRoms.cs | 153 ++++++++++++++++++ .../Runtime/PinMameCompatibleRoms.cs.meta | 2 + .../Runtime/PinMameGamelogicEngine.cs | 147 +++++++++++++---- .../Runtime/PinMamePluginFactory.cs | 136 ++++++++++++++-- 10 files changed, 549 insertions(+), 41 deletions(-) create mode 100644 VisualPinball.Engine.PinMAME.Unity/Editor/PinMameCompatibleRomsExport.cs create mode 100644 VisualPinball.Engine.PinMAME.Unity/Editor/PinMameCompatibleRomsExport.cs.meta create mode 100644 VisualPinball.Engine.PinMAME.Unity/Runtime/PinMameCompatibleRoms.cs create mode 100644 VisualPinball.Engine.PinMAME.Unity/Runtime/PinMameCompatibleRoms.cs.meta diff --git a/VisualPinball.Engine.PinMAME.Unity/Editor/PinMameCompatibleRomsExport.cs b/VisualPinball.Engine.PinMAME.Unity/Editor/PinMameCompatibleRomsExport.cs new file mode 100644 index 0000000..c8bff76 --- /dev/null +++ b/VisualPinball.Engine.PinMAME.Unity/Editor/PinMameCompatibleRomsExport.cs @@ -0,0 +1,59 @@ +// Visual Pinball Engine +// Copyright (C) 2026 freezy and VPE Team +// +// This program is free software: you can redistribute it and/or modify +// it under the terms of the GNU General Public License as published by +// the Free Software Foundation, either version 3 of the License, or +// (at your option) any later version. + +// ReSharper disable CheckNamespace + +using System; +using System.Linq; +using System.Threading; +using UnityEditor; +using UnityEngine; + +namespace VisualPinball.Engine.PinMAME.Editor +{ + /// + /// Looks up the ROMs compatible with a table's ROM in the machine catalog when the table is + /// exported, so the player can offer them when the table's ROM isn't there. + /// + [InitializeOnLoad] + internal static class PinMameCompatibleRomsExport + { + // the export waits for it; a cached catalog answers at once + private static readonly TimeSpan Timeout = TimeSpan.FromSeconds(15); + + static PinMameCompatibleRomsExport() + { + PinMameGamelogicEngine.ResolveCompatibleRoms = Resolve; + } + + private static PinMameCompatibleRom[] Resolve(PinMameGamelogicEngine engine) + { + if (!engine || string.IsNullOrWhiteSpace(engine.machineId) || string.IsNullOrWhiteSpace(engine.romId)) { + return null; + } + try { + using var cancellation = new CancellationTokenSource(Timeout); + PinMameGameDefinitionCatalogClient.EnsureCacheRoot(); + var catalog = PinMameGameDefinitionCatalogClient.GetCatalogAsync(false, cancellation.Token) + .ConfigureAwait(false).GetAwaiter().GetResult().Value; + var machine = catalog.Machines.FirstOrDefault(entry => string.Equals(entry.Id, engine.machineId, StringComparison.Ordinal)); + if (machine == null || string.IsNullOrWhiteSpace(machine.Detail)) { + return null; + } + var definition = PinMameGameDefinitionCatalogClient.GetDefinitionAsync(machine, false, cancellation.Token) + .ConfigureAwait(false).GetAwaiter().GetResult(); + var roms = PinMameGameDefinitionConverter.ReadCompatibleRoms(definition.Value, engine.romId); + Debug.Log($"[PinMAME] Exporting {roms.Length} ROM(s) compatible with {engine.romId}: {string.Join(", ", roms.Select(rom => rom.Id))}."); + return roms; + } catch (Exception exception) { + Debug.LogWarning($"[PinMAME] Could not look up the ROMs compatible with {engine.romId} in the machine catalog; exporting the {engine.CompatibleRoms.Count} saved with the table. {exception.Message}"); + return null; + } + } + } +} diff --git a/VisualPinball.Engine.PinMAME.Unity/Editor/PinMameCompatibleRomsExport.cs.meta b/VisualPinball.Engine.PinMAME.Unity/Editor/PinMameCompatibleRomsExport.cs.meta new file mode 100644 index 0000000..f5c4e2c --- /dev/null +++ b/VisualPinball.Engine.PinMAME.Unity/Editor/PinMameCompatibleRomsExport.cs.meta @@ -0,0 +1,2 @@ +fileFormatVersion: 2 +guid: 0806d80e8e70442c87667fe3e2dccca4 diff --git a/VisualPinball.Engine.PinMAME.Unity/Editor/PinMameGameDefinition.cs b/VisualPinball.Engine.PinMAME.Unity/Editor/PinMameGameDefinition.cs index a56a630..3adaa43 100644 --- a/VisualPinball.Engine.PinMAME.Unity/Editor/PinMameGameDefinition.cs +++ b/VisualPinball.Engine.PinMAME.Unity/Editor/PinMameGameDefinition.cs @@ -33,11 +33,16 @@ public sealed class PinMameGameDefinition public PinMameSpatialPlacement[] SpatialCoils { get; } public PinMameSpatialPlacement[] SpatialLamps { get; } public string[] Diagnostics { get; } + /// + /// The machine's other ROMs that run a table made for the selected ROM, best match first. + /// + public PinMameCompatibleRom[] CompatibleRoms { get; } public PinMameGameDefinition(string machineId, string name, string coverageStatus, int completionScore, PinMameRomDefinition[] roms, string defaultRomId, GamelogicEngineSwitch[] switches, GamelogicEngineCoil[] coils, GamelogicEngineLamp[] lamps, GamelogicEngineWire[] wires, PinMameSpatialPlacement[] spatialSwitches, - PinMameSpatialPlacement[] spatialCoils, PinMameSpatialPlacement[] spatialLamps, string[] diagnostics) + PinMameSpatialPlacement[] spatialCoils, PinMameSpatialPlacement[] spatialLamps, string[] diagnostics, + PinMameCompatibleRom[] compatibleRoms = null) { MachineId = machineId; Name = name; @@ -53,6 +58,7 @@ public PinMameGameDefinition(string machineId, string name, string coverageStatu SpatialCoils = spatialCoils ?? Array.Empty(); SpatialLamps = spatialLamps ?? Array.Empty(); Diagnostics = diagnostics ?? Array.Empty(); + CompatibleRoms = compatibleRoms ?? Array.Empty(); } } diff --git a/VisualPinball.Engine.PinMAME.Unity/Editor/PinMameGameDefinitionConverter.cs b/VisualPinball.Engine.PinMAME.Unity/Editor/PinMameGameDefinitionConverter.cs index 8551aca..262e610 100644 --- a/VisualPinball.Engine.PinMAME.Unity/Editor/PinMameGameDefinitionConverter.cs +++ b/VisualPinball.Engine.PinMAME.Unity/Editor/PinMameGameDefinitionConverter.cs @@ -86,9 +86,66 @@ public static PinMameGameDefinition Convert(string json, string selectedRomId = ConvertOutputs(root["outputs"] as JArray, overrides, coils, lamps, spatialCoils, spatialLamps, diagnostics); var wires = ConvertFlipperWires(root["inputs"] as JArray, root["outputs"] as JArray, overrides, diagnostics); + var compatibleRoms = CompatibleRoms(sourceDrivers, roms, string.IsNullOrWhiteSpace(selectedRomId) ? defaultRomId : selectedRomId); + return new PinMameGameDefinition(machineId, name, coverageStatus, completionScore, roms, defaultRomId, switches.ToArray(), coils.ToArray(), lamps.ToArray(), wires, spatialSwitches.ToArray(), - spatialCoils.ToArray(), spatialLamps.ToArray(), diagnostics.ToArray()); + spatialCoils.ToArray(), spatialLamps.ToArray(), diagnostics.ToArray(), compatibleRoms); + } + + /// + /// The machine's other ROMs that run a table made for , best match + /// first, read from a machine definition of the catalog. + /// + public static PinMameCompatibleRom[] ReadCompatibleRoms(string json, string romId) + { + if (string.IsNullOrWhiteSpace(json) || string.IsNullOrWhiteSpace(romId)) { + return Array.Empty(); + } + var root = JObject.Parse(json); + if (!string.Equals(root.Value("format"), ExpectedFormat, StringComparison.Ordinal)) { + throw new InvalidDataException($"Expected {ExpectedFormat}, got {root.Value("format") ?? "no format"}."); + } + var sourceDrivers = (root["drivers"] as JArray)?.OfType().ToArray() ?? Array.Empty(); + return CompatibleRoms(sourceDrivers, ReadRoms(root, sourceDrivers), romId); + } + + /// + /// The catalog marks how each curated ROM relates to the physical machine. Two ROMs both + /// "identical" to it are revisions of each other; "identical" or "compatible" ones run the + /// same machine; "different" ones need modified hardware, so they don't run a table made for + /// another ROM, and nothing else runs a table made for them. ROMs without a mark, or marked + /// "unknown", are offered as unverified. + /// + private static PinMameCompatibleRom[] CompatibleRoms(IEnumerable sourceDrivers, PinMameRomDefinition[] roms, string selectedRomId) + { + // a ROM the machine doesn't list may not even run it + if (string.IsNullOrWhiteSpace(selectedRomId) || !roms.Any(rom => string.Equals(rom.Id, selectedRomId, StringComparison.OrdinalIgnoreCase))) { + return Array.Empty(); + } + var marks = new Dictionary(StringComparer.OrdinalIgnoreCase); + foreach (var driver in sourceDrivers) { + var id = driver.Value("id"); + if (!string.IsNullOrWhiteSpace(id)) marks[id] = driver.Value("physical_compatibility"); + } + string Mark(string id) => marks.TryGetValue(id, out var mark) ? mark : null; + static bool RunsMachine(string mark) => mark is "identical" or "compatible"; + + var selected = Mark(selectedRomId); + if (selected == "different") { + return Array.Empty(); + } + return roms + .Where(rom => !string.Equals(rom.Id, selectedRomId, StringComparison.OrdinalIgnoreCase)) + .Select(rom => (rom, mark: Mark(rom.Id))) + .Where(entry => entry.mark != "different") + .Select(entry => new PinMameCompatibleRom(entry.rom.Id, entry.rom.Description, + selected == "identical" && entry.mark == "identical" ? PinMameRomCompatibility.Identical + : RunsMachine(selected) && RunsMachine(entry.mark) ? PinMameRomCompatibility.Compatible + : PinMameRomCompatibility.Unverified)) + .OrderBy(rom => rom.Compatibility) + .ThenBy(rom => rom.Id, StringComparer.OrdinalIgnoreCase) + .ToArray(); } private static GamelogicEngineWire[] ConvertFlipperWires(JArray inputs, JArray outputs, IReadOnlyDictionary overrides, diff --git a/VisualPinball.Engine.PinMAME.Unity/Editor/PinMameGameDefinitionEditorService.cs b/VisualPinball.Engine.PinMAME.Unity/Editor/PinMameGameDefinitionEditorService.cs index 2da8aac..a4187f4 100644 --- a/VisualPinball.Engine.PinMAME.Unity/Editor/PinMameGameDefinitionEditorService.cs +++ b/VisualPinball.Engine.PinMAME.Unity/Editor/PinMameGameDefinitionEditorService.cs @@ -85,6 +85,7 @@ private static PinMameGameDefinition Apply(PinMameGamelogicEngine gle, TableComp Undo.RecordObject(tableComponent, "Populate PinMAME hardware"); gle.SetMachineSelection(machineId, !string.IsNullOrWhiteSpace(romId) ? romId : definition.DefaultRomId); gle.SetAvailableHardware(definition.Switches, definition.Coils, definition.Lamps, definition.Wires); + gle.SetCompatibleRoms(definition.CompatibleRoms); tableComponent.RepopulateHardware(gle); gle.MarkMappingsPopulated(); EditorUtility.SetDirty(gle); diff --git a/VisualPinball.Engine.PinMAME.Unity/Editor/PinMameGamelogicEngineInspector.cs b/VisualPinball.Engine.PinMAME.Unity/Editor/PinMameGamelogicEngineInspector.cs index d993b79..3df8fe1 100644 --- a/VisualPinball.Engine.PinMAME.Unity/Editor/PinMameGamelogicEngineInspector.cs +++ b/VisualPinball.Engine.PinMAME.Unity/Editor/PinMameGamelogicEngineInspector.cs @@ -220,6 +220,7 @@ private async System.Threading.Tasks.Task SelectMachine(int selectedGameIndex, s } // candidates for the manager dropdowns; the table's mappings stay until Populate Hardware _gle.SetAvailableHardware(_definition.Switches, _definition.Coils, _definition.Lamps, _definition.Wires); + _gle.SetCompatibleRoms(_definition.CompatibleRoms); EditorUtility.SetDirty(_gle); } else if (!string.IsNullOrWhiteSpace(preferredRomId) && selectedRomId == null) { _loadWarning = CombineWarnings(_loadWarning, $"The saved ROM '{preferredRomId}' is not listed for {selectedMachine.Name}; the saved component value was left unchanged."); @@ -229,8 +230,28 @@ private async System.Threading.Tasks.Task SelectMachine(int selectedGameIndex, s // The selection and the table's mappings stay as they are. if (forceRefresh) Undo.RecordObject(_gle, "Refresh PinMAME hardware candidates"); _gle.SetAvailableHardware(_definition.Switches, _definition.Coils, _definition.Lamps, _definition.Wires); + _gle.SetCompatibleRoms(CompatibleRomsOf(selectedRomId)); EditorUtility.SetDirty(_gle); + } else if (fillCandidates && selectedRomId != null && !SameCompatibleRoms(_gle.CompatibleRoms, CompatibleRomsOf(selectedRomId))) { + // tables saved before the compatible ROMs were kept, or the catalog learned more since + Undo.RecordObject(_gle, "Update compatible PinMAME ROMs"); + _gle.SetCompatibleRoms(CompatibleRomsOf(selectedRomId)); + EditorUtility.SetDirty(_gle); + } + } + + private PinMameCompatibleRom[] CompatibleRomsOf(string romId) + => string.IsNullOrWhiteSpace(_definitionJson) ? Array.Empty() : PinMameGameDefinitionConverter.ReadCompatibleRoms(_definitionJson, romId); + + private static bool SameCompatibleRoms(IReadOnlyList current, IReadOnlyList updated) + { + if (current.Count != updated.Count) return false; + for (var i = 0; i < current.Count; i++) { + if (!string.Equals(current[i].Id, updated[i].Id, StringComparison.OrdinalIgnoreCase) + || !string.Equals(current[i].Description ?? string.Empty, updated[i].Description ?? string.Empty, StringComparison.Ordinal) + || current[i].Compatibility != updated[i].Compatibility) return false; } + return true; } private static string CombineWarnings(string first, string second) @@ -383,6 +404,7 @@ public override void OnInspectorGUI() Undo.RecordObject(_tableComponent, "Populate PinMAME hardware"); _gle.SetMachineSelection(_definition.MachineId, _roms[_selectedRomIndex].Id); _gle.SetAvailableHardware(_definition.Switches, _definition.Coils, _definition.Lamps, _definition.Wires); + _gle.SetCompatibleRoms(_definition.CompatibleRoms); _tableComponent.RepopulateHardware(_gle); _gle.MarkMappingsPopulated(); EditorUtility.SetDirty(_gle); @@ -502,6 +524,7 @@ private void ChangeRom(int selectedRomIndex) _gle.SetMachineSelection(definition.MachineId, selectedRomId); // a ROM of the same machine: refresh the dropdown candidates, keep the mappings _gle.SetAvailableHardware(definition.Switches, definition.Coils, definition.Lamps, definition.Wires); + _gle.SetCompatibleRoms(definition.CompatibleRoms); _loadError = null; _spatialAssignmentMessage = null; EditorUtility.SetDirty(_gle); diff --git a/VisualPinball.Engine.PinMAME.Unity/Runtime/PinMameCompatibleRoms.cs b/VisualPinball.Engine.PinMAME.Unity/Runtime/PinMameCompatibleRoms.cs new file mode 100644 index 0000000..c066278 --- /dev/null +++ b/VisualPinball.Engine.PinMAME.Unity/Runtime/PinMameCompatibleRoms.cs @@ -0,0 +1,153 @@ +// Visual Pinball Engine +// Copyright (C) 2026 freezy and VPE Team +// +// SPDX-License-Identifier: MIT +// Licensed under MIT. See https://opensource.org/license/mit. + +using System; +using System.Collections.Generic; +using System.IO; +using System.Linq; +using System.Threading; +using PinMame; +using VisualPinball.Unity; + +namespace VisualPinball.Engine.PinMAME +{ + /// + /// How closely a ROM matches the physical machine a table was made for, as the machine catalog + /// at games.visualpinball.org tells. + /// + public enum PinMameRomCompatibility + { + /// + /// Another revision of the same game: switches, coils, lamps and displays are wired the same. + /// + Identical = 0, + + /// + /// Runs on the same machine, but isn't just a revision of the table's ROM, e.g. a community + /// fix or alternative firmware. + /// + Compatible = 1, + + /// + /// A ROM of the same machine that nobody has confirmed runs it the same way. + /// + Unverified = 2, + } + + /// + /// A ROM that can run a table in place of the one its author chose. + /// + [Serializable] + public struct PinMameCompatibleRom + { + public string Id; + public string Description; + public PinMameRomCompatibility Compatibility; + + public PinMameCompatibleRom(string id, string description, PinMameRomCompatibility compatibility) + { + Id = id; + Description = description ?? string.Empty; + Compatibility = compatibility; + } + + public override string ToString() => string.IsNullOrWhiteSpace(Description) ? Id : $"{Id} ({Description})"; + } + + /// + /// Finds the ROM a table package needs and the compatible ones it lists, and whether they are + /// in the ROM folder, without loading the table or PinMAME. + /// + internal static class PinMameRomAvailability + { + private const string ComponentType = "PinMameGamelogicEngine"; + + private sealed class Cached + { + internal long Size; + internal DateTime Modified; + internal PackagedRoms Roms; + } + + private static readonly Dictionary Cache = new(StringComparer.Ordinal); + + internal sealed class PackagedRoms + { + public string Rom { get; } + public IReadOnlyList Compatible { get; } + + public PackagedRoms(string rom, IEnumerable compatible) + { + Rom = rom; + // best match first, keeping the catalog's order within each kind + Compatible = (compatible ?? Enumerable.Empty()) + .Where(candidate => IsSafeRomName(candidate.Id) && !string.Equals(candidate.Id, rom, StringComparison.OrdinalIgnoreCase)) + .GroupBy(candidate => candidate.Id, StringComparer.OrdinalIgnoreCase) + .Select(group => group.First()) + .OrderBy(candidate => candidate.Compatibility) + .ToArray(); + } + + public bool Lists(string rom) => Compatible.Any(candidate => string.Equals(candidate.Id, rom, StringComparison.OrdinalIgnoreCase)); + } + + /// + /// The ';'-separated folders PinMAME looks for ROMs in, as + /// sets them: the player's or editor's ROM folder, else VPM's, else "roms" in VPE's data folder. + /// + internal static string RomFolders => GamelogicPaths.RomFolder + ?? PinMame.PinMame.FindVpmPath(PinMameFileType.Roms) + ?? Path.Combine(PinMameFolders.DataFolderPath, "roms"); + + /// + /// Whether the ROM's zip is in the ROM folder. Clones also need their parent's zip, which + /// isn't checked: PinMAME reports it when the game doesn't start. + /// + internal static bool IsAvailable(string rom, string romFolders) => IsSafeRomName(rom) && PinMameFolders.HasRomZip(romFolders, rom); + + /// + /// Reads the ROM of the package's PinMAME engine and its compatible ROMs. Null when the + /// package has no PinMAME engine with a ROM, or more than one. Runs on any thread. + /// + internal static PackagedRoms Read(string packagePath, CancellationToken cancellation) + { + if (string.IsNullOrWhiteSpace(packagePath)) return null; + var path = Path.GetFullPath(packagePath); + var file = new FileInfo(path); + if (!file.Exists) return null; + lock (Cache) { + if (Cache.TryGetValue(path, out var cached) && cached.Size == file.Length && cached.Modified == file.LastWriteTimeUtc) { + return cached.Roms; + } + } + + PackagedRoms found = null; + var ambiguous = false; + using (var storage = PackageApi.StorageManager.OpenStorage(path)) { + var table = storage.GetFolder(PackageApi.TableFolder); + foreach (var node in PackagedItems.Read(table)) { + cancellation.ThrowIfCancellationRequested(); + foreach (var component in node.Components) { + if (!string.Equals(component.Type, ComponentType, StringComparison.Ordinal) || component.Data == null) continue; + // read as the packer wrote it, so the key names are the packer's + var data = PackageApi.Packer.Unpack(component.Data); + var rom = string.IsNullOrWhiteSpace(data.RomId) ? data.GameId : data.RomId; + if (string.IsNullOrWhiteSpace(rom)) continue; + if (found != null && !string.Equals(found.Rom, rom, StringComparison.OrdinalIgnoreCase)) ambiguous = true; + found ??= new PackagedRoms(rom.Trim(), data.CompatibleRoms); + } + } + } + var result = ambiguous ? null : found; + lock (Cache) Cache[path] = new Cached { Size = file.Length, Modified = file.LastWriteTimeUtc, Roms = result }; + return result; + } + + // ROM names go into file paths; PinMAME's are lower case letters, digits and underscores + private static bool IsSafeRomName(string rom) => !string.IsNullOrWhiteSpace(rom) + && rom.All(c => c is >= 'a' and <= 'z' or >= 'A' and <= 'Z' or >= '0' and <= '9' or '_' or '-'); + } +} diff --git a/VisualPinball.Engine.PinMAME.Unity/Runtime/PinMameCompatibleRoms.cs.meta b/VisualPinball.Engine.PinMAME.Unity/Runtime/PinMameCompatibleRoms.cs.meta new file mode 100644 index 0000000..829733a --- /dev/null +++ b/VisualPinball.Engine.PinMAME.Unity/Runtime/PinMameCompatibleRoms.cs.meta @@ -0,0 +1,2 @@ +fileFormatVersion: 2 +guid: a435fd0ee0744a719357e838fa9f0bed diff --git a/VisualPinball.Engine.PinMAME.Unity/Runtime/PinMameGamelogicEngine.cs b/VisualPinball.Engine.PinMAME.Unity/Runtime/PinMameGamelogicEngine.cs index ed240a5..fad4652 100644 --- a/VisualPinball.Engine.PinMAME.Unity/Runtime/PinMameGamelogicEngine.cs +++ b/VisualPinball.Engine.PinMAME.Unity/Runtime/PinMameGamelogicEngine.cs @@ -83,7 +83,43 @@ public class PinMameGamelogicEngine : MonoBehaviour, IGamelogicEngine, IDisplayF [SerializeField, HideInInspector] private string _legacyGameId; - string IRomNameProvider.RomName => romId; + // ROMs that run this table in place of romId, exported so the player can offer them when romId is missing + [SerializeField, HideInInspector] + private PinMameCompatibleRom[] _compatibleRoms = Array.Empty(); + + // the ROM started, which is romId unless the player substituted a compatible one + private string _runningRomId; + private string _romSubstitute; + // the compatible ROM chosen in place of the table's one counts from the moment it's chosen, so the plugins prepared + // after PinMAME's (the DMD's colorization) see it before OnInit + private string RunningRom => !string.IsNullOrEmpty(_runningRomId) ? _runningRomId : !string.IsNullOrWhiteSpace(_romSubstitute) ? _romSubstitute : romId; + + /// + /// The ROMs that can run this table in place of , as of when the ROM was + /// selected or the table was last exported. + /// + public IReadOnlyList CompatibleRoms => _compatibleRoms ?? Array.Empty(); + + /// + /// Starts in place of the table's ROM, or the table's own ROM again + /// when null. Only before the game starts. + /// + /// + /// The compatible ROM that plays in place of the table's, or null. + /// + internal string RomSubstitute => _romSubstitute; + + internal void UseCompatibleRom(string rom) + { + if (Volatile.Read(ref _onInitCalled) != 0) { + throw new InvalidOperationException("The ROM can only be changed before the game starts."); + } + _romSubstitute = string.IsNullOrWhiteSpace(rom) || string.Equals(rom, romId, StringComparison.OrdinalIgnoreCase) ? null : rom.Trim(); + } + + // the ROM that runs, whose files colorizations and the like belong to + string IRomNameProvider.RomName => RunningRom; + // always the table's own ROM, so per-game settings don't change with the ROM that happens to be there GameIdentity? IGameIdentityProvider.GameIdentity => string.IsNullOrWhiteSpace(romId) ? null : new GameIdentity("pinmame", romId); DisplayEncoding IDisplayResourceMetadata.DisplayFormats => DisplayEncoding.Gray2 | DisplayEncoding.Gray4 | DisplayEncoding.Luminance8; DisplayEncoding IDisplayResourceMetadata.DefaultDisplayFormat => DisplayEncoding.Luminance8; @@ -122,12 +158,29 @@ public byte[] Pack() MachineId = machineId, GameId = _legacyGameId, RomId = romId, + CompatibleRoms = CompatibleRomsForPack(), DisableMechs = DisableMechs, SolenoidDelay = SolenoidDelay }; return PackageApi.Packer.Pack(data); } + private PinMameCompatibleRom[] CompatibleRomsForPack() + { + #if UNITY_EDITOR + // the machine catalog may know more ROMs, or know them better, than when the ROM was selected + try { + var resolved = ResolveCompatibleRoms?.Invoke(this); + if (resolved != null) { + return resolved.Where(rom => !string.IsNullOrWhiteSpace(rom.Id)).ToArray(); + } + } catch (Exception e) { + Logger.Warn(e, "[PinMAME] Could not look up the ROMs compatible with {Rom}; exporting the ones saved with the table.", romId); + } + #endif + return _compatibleRoms?.Where(rom => !string.IsNullOrWhiteSpace(rom.Id)).ToArray() ?? Array.Empty(); + } + public byte[] PackReferences(Transform root, PackagedRefs refs, PackagedFiles files) => Array.Empty(); public void Unpack(byte[] bytes) @@ -136,6 +189,7 @@ public void Unpack(byte[] bytes) machineId = data.MachineId ?? string.Empty; _legacyGameId = data.GameId; romId = data.RomId; + _compatibleRoms = data.CompatibleRoms ?? Array.Empty(); DisableMechs = data.DisableMechs; SolenoidDelay = data.SolenoidDelay; // Playback preferences belong to the player; ignore legacy package mute settings. @@ -226,11 +280,32 @@ public void SetMachineSelection(string selectedMachineId, string selectedRomId, _mappedMachineId = currentMachineId; } machineId = selectedMachineId; - romId = selectedRomId ?? string.Empty; + var newRomId = selectedRomId ?? string.Empty; + if (!string.Equals(romId, newRomId, StringComparison.OrdinalIgnoreCase)) { + // they were compatible with the ROM selected until now + _compatibleRoms = Array.Empty(); + } + romId = newRomId; _legacyGameId = null; ClearAvailableHardware(); } + /// + /// Sets the ROMs that can run this table in place of . + /// + public void SetCompatibleRoms(IEnumerable roms) + { + _compatibleRoms = roms?.Where(rom => !string.IsNullOrWhiteSpace(rom.Id) + && !string.Equals(rom.Id, romId, StringComparison.OrdinalIgnoreCase)).ToArray() ?? Array.Empty(); + } + + /// + /// Set by the editor to look up the ROMs compatible with a component's ROM in the machine + /// catalog when the table is exported. Returns null when it can't tell, in which case the + /// ones saved with the component are exported. + /// + public static Func ResolveCompatibleRoms; + private void ClearAvailableHardware() { _runtimeCachesBuilt = false; @@ -514,7 +589,7 @@ private void StartAltSound() _altSoundStatus = "Off"; return; } - var altSound = PinMameAltSound.Start(_altSoundFolder, romId, AudioSettings.outputSampleRate, out _altSoundStatus); + var altSound = PinMameAltSound.Start(_altSoundFolder, RunningRom, AudioSettings.outputSampleRate, out _altSoundStatus); // Published with a full fence, as the game start publishes the hardware generation, so one side sees the other // even when the ROM starts meanwhile. Setting it twice is harmless. Interlocked.Exchange(ref _altSound, altSound); @@ -732,7 +807,7 @@ private void Update() /// private void ReportRomMissing() { - var rom = romId; + var rom = RunningRom; var folders = _romFolder; EnqueueMainThreadDispatch(() => GamelogicPaths.ReportRomMissing(rom, folders)); } @@ -980,7 +1055,7 @@ private void RequestStopGame(string reason) // Never block the Unity main thread during playmode exit. // PinMAME shutdown is best-effort here; OnInit() and the editor lifecycle hook // will recover/ensure shutdown before starting a new ROM. - Logger.Info("[PinMAME] Stopping ROM {Rom} ({Reason}).", _pinMame?.RunningGame ?? romId, reason); + Logger.Info("[PinMAME] Stopping ROM {Rom} ({Reason}).", _pinMame?.RunningGame ?? RunningRom, reason); try { if (_pinMame != null) { @@ -1023,6 +1098,12 @@ public async Task OnInit(Player player, TableApi tableApi, BallManager ballManag return; } + // the player may run a compatible ROM when the table's own isn't there + _runningRomId = string.IsNullOrWhiteSpace(_romSubstitute) ? romId : _romSubstitute; + if (!string.Equals(_runningRomId, romId, StringComparison.OrdinalIgnoreCase)) { + Logger.Info("[PinMAME] Running ROM {Rom} in place of the table's ROM {TableRom}.", _runningRomId, romId); + } + string vpmPath = null; _ballManager = ballManager; _playfieldComponent = GetComponentInChildren(); @@ -1034,9 +1115,9 @@ public async Task OnInit(Player player, TableApi tableApi, BallManager ballManag byte[] data = null; #if UNITY_IOS - data = File.ReadAllBytes(Path.Combine(Application.streamingAssetsPath, $"{romId}.zip")); + data = File.ReadAllBytes(Path.Combine(Application.streamingAssetsPath, $"{RunningRom}.zip")); #else - UnityWebRequest webRequest = new UnityWebRequest(Path.Combine(Application.streamingAssetsPath, $"{romId}.zip")); + UnityWebRequest webRequest = new UnityWebRequest(Path.Combine(Application.streamingAssetsPath, $"{RunningRom}.zip")); webRequest.downloadHandler = new DownloadHandlerBuffer(); webRequest.SendWebRequest(); @@ -1046,14 +1127,14 @@ public async Task OnInit(Player player, TableApi tableApi, BallManager ballManag data = webRequest.downloadHandler.data; #endif - File.WriteAllBytes(Path.Combine(vpmPath, "roms", $"{romId}.zip"), data); + File.WriteAllBytes(Path.Combine(vpmPath, "roms", $"{RunningRom}.zip"), data); #else vpmPath = PinMameFolders.DataFolder; #endif await PinMameStartStopGate.WaitAsync(ct); try { - Logger.Info("[PinMAME] Starting ROM {Rom} of machine {Machine} on {Name:l} (audio {SampleRate} Hz).", romId, machineId, name, AudioSettings.outputSampleRate); + Logger.Info("[PinMAME] Starting ROM {Rom} of machine {Machine} on {Name:l} (audio {SampleRate} Hz).", RunningRom, machineId, name, AudioSettings.outputSampleRate); #if UNITY_EDITOR // With Domain Reload disabled, PinMAME (native + managed singleton) persists across play sessions. @@ -1074,7 +1155,7 @@ public async Task OnInit(Player player, TableApi tableApi, BallManager ballManag Logger.Debug($"[PinMAME] Editor pre-stop: initialRunState={preStopState}, stopCallMs={preStopSw.ElapsedMilliseconds}, waitMs={preStopWaitSw.ElapsedMilliseconds}, finalRunState={PinMame.PinMame.RunState}"); if (PinMame.PinMame.RunState != 0) { _startFailure = "previous game did not stop"; - Logger.Error("[PinMAME] Cannot start ROM {Rom}, the previous game did not stop within {TimeoutMs} ms (run state {RunState}).", romId, StopTimeoutMs, PinMame.PinMame.RunState); + Logger.Error("[PinMAME] Cannot start ROM {Rom}, the previous game did not stop within {TimeoutMs} ms (run state {RunState}).", RunningRom, StopTimeoutMs, PinMame.PinMame.RunState); return; } @@ -1173,7 +1254,7 @@ public async Task OnInit(Player player, TableApi tableApi, BallManager ballManag try { _awaitingGameStart = true; Interlocked.Increment(ref _romRun); - _pinMame.StartGame(romId); + _pinMame.StartGame(RunningRom); Logger.Debug($"[PinMAME] StartGame returned. RunState={PinMame.PinMame.RunState}"); } catch (InvalidOperationException e) when (e.Message != null && e.Message.Contains("status=GAME_ALREADY_RUNNING")) @@ -1191,7 +1272,7 @@ public async Task OnInit(Player player, TableApi tableApi, BallManager ballManag Interlocked.Increment(ref _romRun); _romStarting = true; StartAltSound(); - _pinMame.StartGame(romId); + _pinMame.StartGame(RunningRom); Logger.Debug($"[PinMAME] StartGame retry returned. RunState={PinMame.PinMame.RunState}"); } catch (OperationCanceledException) { @@ -1201,7 +1282,7 @@ public async Task OnInit(Player player, TableApi tableApi, BallManager ballManag catch (Exception retryEx) { _awaitingGameStart = false; _startFailure = "start failed after stopping the running game"; - Logger.Error(retryEx, "[PinMAME] Cannot start ROM {Rom} after stopping the game that was still running.", romId); + Logger.Error(retryEx, "[PinMAME] Cannot start ROM {Rom} after stopping the game that was still running.", RunningRom); } } catch (InvalidOperationException e) when (e.Message != null && e.Message.Contains("status=GAME_NOT_FOUND")) @@ -1209,12 +1290,12 @@ public async Task OnInit(Player player, TableApi tableApi, BallManager ballManag // a typo in the table, or a ROM newer than this PinMAME _awaitingGameStart = false; _startFailure = "unknown ROM"; - Logger.Warn(e, "[PinMAME] Cannot start ROM {Rom}, libpinmame {Version} doesn't know it. Check the ROM name of the table.", romId, _nativeVersion ?? "unknown"); + Logger.Warn(e, "[PinMAME] Cannot start ROM {Rom}, libpinmame {Version} doesn't know it. Check the ROM name of the table.", RunningRom, _nativeVersion ?? "unknown"); } catch (Exception e) { _awaitingGameStart = false; _startFailure = "start failed: " + e.Message; - Logger.Error(e, "[PinMAME] Cannot start ROM {Rom}.", romId); + Logger.Error(e, "[PinMAME] Cannot start ROM {Rom}.", RunningRom); } } catch (Exception e) when (e is DllNotFoundException || e is EntryPointNotFoundException || e is BadImageFormatException) { @@ -1222,7 +1303,7 @@ public async Task OnInit(Player player, TableApi tableApi, BallManager ballManag _awaitingGameStart = false; _startFailure = "native library not loaded"; // a broken local install, a missing runtime dependency, or no build for this platform - Logger.Warn(e, "[PinMAME] Cannot start ROM {Rom}, PinMAME's native library could not be loaded.", romId); + Logger.Warn(e, "[PinMAME] Cannot start ROM {Rom}, PinMAME's native library could not be loaded.", RunningRom); } finally { if (_startFailure != null) EndAltSound(Volatile.Read(ref _romRun), "the ROM didn't start"); @@ -1240,7 +1321,7 @@ private void PrepareDesktopFolders() } catch (InvalidOperationException e) { Logger.Error(e, "[PinMAME] Could not set the ROM folder."); } - PinMameFolders.ImportFromVpm(romId); + PinMameFolders.ImportFromVpm(RunningRom); try { _romFolder = _pinMame.RomPath; @@ -1254,17 +1335,17 @@ private void PrepareDesktopFolders() // missing, although they run. So only a failed audit without a zip is reported here. // StartGame reports unknown ROMs, OnGameEnded ROMs that fail to load. try { - _romAuditPassed = _pinMame.GetGame(romId).RomFound; + _romAuditPassed = _pinMame.GetGame(RunningRom).RomFound; } catch (InvalidOperationException e) { _romKnown = false; - Logger.Debug(e, "[PinMAME] PinMAME doesn't know ROM {Rom}.", romId); + Logger.Debug(e, "[PinMAME] PinMAME doesn't know ROM {Rom}.", RunningRom); } if (_romAuditPassed == false) { - if (!PinMameFolders.HasRomZip(_romFolder, romId)) { + if (!PinMameFolders.HasRomZip(_romFolder, RunningRom)) { _romMissingReported = true; - Logger.Warn("[PinMAME] ROM {Rom} not found, there is no zip file of that name in {RomFolders:l}. Put the ROM there, or set the ROM folder to where your ROMs are.", romId, _romFolder ?? ""); + Logger.Warn("[PinMAME] ROM {Rom} not found, there is no zip file of that name in {RomFolders:l}. Put the ROM there, or set the ROM folder to where your ROMs are.", RunningRom, _romFolder ?? ""); } else { - Logger.Debug("[PinMAME] PinMAME's audit reports ROM {Rom} as incomplete in {RomFolders:l}. Clones often do and still run.", romId, _romFolder); + Logger.Debug("[PinMAME] PinMAME's audit reports ROM {Rom} as incomplete in {RomFolders:l}. Clones often do and still run.", RunningRom, _romFolder); } } } @@ -1298,7 +1379,7 @@ private void HandleGameStarted() } Interlocked.Exchange(ref _hardwareGen, hardwareGen); // a full fence, see StartAltSound Volatile.Read(ref _altSound)?.SetHardwareGen(hardwareGen); - Logger.Info("[PinMAME] Game {Rom} started (hardware {HardwareGen}, libpinmame {Version}).", romId, ((PinMameHardwareGen)(ulong)hardwareGen).ToString(), _nativeVersion ?? "unknown"); + Logger.Info("[PinMAME] Game {Rom} started (hardware {HardwareGen}, libpinmame {Version}).", RunningRom, ((PinMameHardwareGen)(ulong)hardwareGen).ToString(), _nativeVersion ?? "unknown"); _isRunning = true; _solenoidDelayStartTimestampUsec = TimestampUsec; @@ -1310,7 +1391,7 @@ private void HandleGameStarted() } catch(Exception e) { - Logger.Error(e, "[PinMAME] Could not send the initial switches and mechs to ROM {Rom}.", romId); + Logger.Error(e, "[PinMAME] Could not send the initial switches and mechs to ROM {Rom}.", RunningRom); } EnqueueMainThreadDispatch(() => { @@ -1339,7 +1420,7 @@ private void HandleGameEnded() } // Native can report ended more than once during teardown; keep it idempotent. if (_isRunning) { - Logger.Info("[PinMAME] Game {Rom} ended.", romId); + Logger.Info("[PinMAME] Game {Rom} ended.", RunningRom); var run = Volatile.Read(ref _romRun); EnqueueMainThreadDispatch(() => EndAltSound(run, "the ROM stopped")); @@ -1348,7 +1429,7 @@ private void HandleGameEnded() _awaitingGameStart = false; _startFailure = "stopped before it started"; if (!_romMissingReported) { - Logger.Warn("[PinMAME] PinMAME stopped ROM {Rom} before it started. The ROM is probably missing or incomplete in {RomFolders:l}.", romId, _romFolder ?? ""); + Logger.Warn("[PinMAME] PinMAME stopped ROM {Rom} before it started. The ROM is probably missing or incomplete in {RomFolders:l}.", RunningRom, _romFolder ?? ""); } // only now: the audit before the start can't tell a missing ROM from a clone that // runs from its parent's zip @@ -2464,10 +2545,14 @@ public void Describe(DiagnosticsWriter writer) writer.Add("hardware", ((PinMameHardwareGen)(ulong)hardwareGen).ToString()); } + if (!string.Equals(RunningRom, romId, StringComparison.OrdinalIgnoreCase)) { + writer.Add("running-rom", RunningRom); + writer.Add("table-rom", romId); + } var romFolder = _romFolder ?? GamelogicPaths.RomFolder; writer.Add("rom-folder", romFolder ?? ""); - if (!string.IsNullOrWhiteSpace(romFolder) && !string.IsNullOrWhiteSpace(romId)) { - writer.Add("rom-zip-found", PinMameFolders.HasRomZip(romFolder, romId)); + if (!string.IsNullOrWhiteSpace(romFolder) && !string.IsNullOrWhiteSpace(RunningRom)) { + writer.Add("rom-zip-found", PinMameFolders.HasRomZip(romFolder, RunningRom)); } if (!_romKnown) { writer.Add("rom-known", false); @@ -2477,8 +2562,8 @@ public void Describe(DiagnosticsWriter writer) } if (_nvramFolder != null) { writer.Add("nvram-folder", _nvramFolder); - if (!string.IsNullOrWhiteSpace(romId)) { - writer.Add("nvram-found", System.IO.File.Exists(System.IO.Path.Combine(_nvramFolder, romId + ".nv"))); + if (!string.IsNullOrWhiteSpace(RunningRom)) { + writer.Add("nvram-found", System.IO.File.Exists(System.IO.Path.Combine(_nvramFolder, RunningRom + ".nv"))); } } if (_configFolder != null) { @@ -2516,6 +2601,8 @@ public struct PinMameGamelogicEnginePackable public string GameType; public string GameId; public string RomId; + // ROMs that can run the table in place of RomId; missing in packages written before they were exported + public PinMameCompatibleRom[] CompatibleRoms; public bool DisableMechs; public float SolenoidDelay; } diff --git a/VisualPinball.Engine.PinMAME.Unity/Runtime/PinMamePluginFactory.cs b/VisualPinball.Engine.PinMAME.Unity/Runtime/PinMamePluginFactory.cs index d6c35c4..03a20e6 100644 --- a/VisualPinball.Engine.PinMAME.Unity/Runtime/PinMamePluginFactory.cs +++ b/VisualPinball.Engine.PinMAME.Unity/Runtime/PinMamePluginFactory.cs @@ -6,6 +6,7 @@ using System; using System.Collections.Generic; +using System.Linq; using System.Threading; using System.Threading.Tasks; using UnityEngine; @@ -15,9 +16,12 @@ namespace VisualPinball.Engine.PinMAME { /// Configures the selected engine's audio; emulation remains owned by the table. - internal sealed partial class PinMamePluginFactory : IPlayerPluginFactory, IPluginSystemDefaults, IPluginSettingsProvider + internal sealed partial class PinMamePluginFactory : IPlayerPluginFactory, IPluginSystemDefaults, IPluginSettingsProvider, IPluginLaunchCheck { + private static readonly NLog.Logger Logger = NLog.LogManager.GetCurrentClassLogger(); private const string ResetRomMemory = "reset-rom-memory"; + private const string CompatibleRomField = "CompatibleRom"; + private const string CompatibleRomsProvider = "compatible-roms"; 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 }; @@ -38,30 +42,138 @@ internal sealed partial class PinMamePluginFactory : IPlayerPluginFactory, IPlug 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." }), + new PluginSettingsGroup("ROM", "", + new PluginField(CompatibleRomField, "Compatible ROM", SettingKind.Choice) { Scope = ConfigurationScope.GameOnly, Provider = CompatibleRomsProvider, Default = "", + Description = "The ROM to play when the one this table was made for isn't in your ROM folder. The table lists the ROMs that run the same machine." }), 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())); + { + if (provider != CompatibleRomsProvider) { + return Task.FromResult(new PluginChoiceCatalog(provider, Array.Empty())); + } + var package = request.Package?.Path; + return Task.Run(() => CompatibleRomCatalog(package, cancellation), cancellation); + } + + /// + /// The compatible ROMs the table lists that are in the ROM folder, best match first. + /// + private static PluginChoiceCatalog CompatibleRomCatalog(string package, CancellationToken cancellation) + { + cancellation.ThrowIfCancellationRequested(); + // incomplete: a saved choice stays when its zip is gone or another table is selected + if (string.IsNullOrWhiteSpace(package)) { + return new PluginChoiceCatalog("", Array.Empty(), isComplete: false) { EmptyMessage = "Select a table to see its compatible ROMs." }; + } + var roms = PinMameRomAvailability.Read(package, cancellation); + if (roms == null || roms.Compatible.Count == 0) { + return new PluginChoiceCatalog("", Array.Empty(), isComplete: false) { + EmptyMessage = "This table lists no compatible ROMs. Export it again with a current VPE to add them.", + }; + } + var folders = PinMameRomAvailability.RomFolders; + var choices = roms.Compatible + .Where(rom => PinMameRomAvailability.IsAvailable(rom.Id, folders)) + .Select(rom => new PluginChoice(rom.Id, ChoiceLabel(rom), Explain(rom))) + .ToArray(); + var listed = string.Join(", ", roms.Compatible.Select(rom => rom.Id)); + var folderList = folders.Replace(";", "\n"); + return new PluginChoiceCatalog(string.Join("|", choices.Select(choice => choice.Id)), choices, isComplete: false) { + AvailableMessage = PinMameRomAvailability.IsAvailable(roms.Rom, folders) + ? $"This table was made for {roms.Rom}, which is in your ROM folder, so it plays with {roms.Rom}. The ROM chosen here plays when {roms.Rom} is missing." + : $"This table was made for the ROM {roms.Rom}, which isn't in your ROM folder. Play it with one of these compatible ROMs you have, or put {roms.Rom}.zip into:\n{folderList}", + EmptyMessage = $"None of the ROMs compatible with this table are in your ROM folder:\n{folderList}\n\nCompatible ROMs: {listed}", + }; + } + + private static string ChoiceLabel(PinMameCompatibleRom rom) + { + var label = string.IsNullOrWhiteSpace(rom.Description) ? rom.Id : $"{rom.Description} ยท {rom.Id}"; + return rom.Compatibility == PinMameRomCompatibility.Unverified ? label + " (unverified)" : label; + } + + private static string Explain(PinMameCompatibleRom rom) => rom.Compatibility switch { + PinMameRomCompatibility.Identical => "Another revision of the same game, for the same machine.", + PinMameRomCompatibility.Compatible => "Runs on the same machine, but may play differently, like a community fix or alternative firmware.", + _ => "A ROM of the same machine whose compatibility hasn't been confirmed. Switches, lamps or coils may not all work.", + }; + + public bool AppliesTo(GameIdentity game) => game.Provider == "pinmame"; + + /// + /// Stops the launch when the table's ROM isn't there but a compatible one is, so the player + /// asks which one to play. Without a compatible ROM it lets the launch go on, and the + /// missing ROM is reported as before. + /// + public Task> CheckLaunchAsync(PluginLaunchContext context, CancellationToken cancellation) + { + var package = context.Package?.Path; + var chosen = context.Settings.String(CompatibleRomField); + var mobile = Application.isMobilePlatform; + return Task.Run>(() => { + cancellation.ThrowIfCancellationRequested(); + if (mobile || string.IsNullOrWhiteSpace(package)) return Array.Empty(); + var roms = PinMameRomAvailability.Read(package, cancellation); + if (roms == null || roms.Compatible.Count == 0) return Array.Empty(); + var folders = PinMameRomAvailability.RomFolders; + if (PinMameRomAvailability.IsAvailable(roms.Rom, folders)) return Array.Empty(); + if (roms.Lists(chosen) && PinMameRomAvailability.IsAvailable(chosen, folders)) return Array.Empty(); + if (!roms.Compatible.Any(rom => PinMameRomAvailability.IsAvailable(rom.Id, folders))) return Array.Empty(); + return new[] { new PluginValidationIssue(CompatibleRomField, $"This table was made for the ROM {roms.Rom}, which isn't in your ROM folder. Choose a compatible ROM to play it with.") }; + }, cancellation); + } + + /// + /// The ROM to play in place of the table's own, or null to play the table's own. + /// + private static string SubstituteRom(PinMameGamelogicEngine engine, string chosen) + { + if (engine == null || string.IsNullOrWhiteSpace(chosen) || string.IsNullOrWhiteSpace(engine.romId)) return null; + return SubstituteRom(engine.romId, chosen, rom => engine.CompatibleRoms.Any(compatible => string.Equals(compatible.Id, rom, StringComparison.OrdinalIgnoreCase))); + } + + private static string SubstituteRom(string tableRom, string chosen, Func lists) + { + if (string.IsNullOrWhiteSpace(tableRom) || string.IsNullOrWhiteSpace(chosen) || !lists(chosen)) return null; + var folders = PinMameRomAvailability.RomFolders; + return !PinMameRomAvailability.IsAvailable(tableRom, folders) && PinMameRomAvailability.IsAvailable(chosen, folders) ? chosen : null; + } + + /// + /// The ROM the selected table plays: the compatible one chosen for it when its own is missing, else its own. + /// + private static string PlayedRom(string tableRom, string chosen, string package, CancellationToken cancellation) + { + if (string.IsNullOrWhiteSpace(chosen) || string.IsNullOrWhiteSpace(package)) return tableRom; + var roms = PinMameRomAvailability.Read(package, cancellation); + if (roms == null || !string.Equals(roms.Rom, tableRom, StringComparison.OrdinalIgnoreCase)) return tableRom; + return SubstituteRom(tableRom, chosen, roms.Lists) ?? tableRom; + } public IReadOnlyList Validate(PluginChoiceRequest request) => Array.Empty(); - public Task RunActionAsync(string action, PluginChoiceRequest request, CancellationToken cancellation) + public async 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.")); + return 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.")); + return new PluginActionResult(false, "Select a table that uses PinMAME."); } - if (!PinMameGamelogicEngine.TryResetNvram(game.Key, out var backup)) { - return Task.FromResult(new PluginActionResult(false, CloseTableMessage)); + // the memory of the ROM the table plays, which is the compatible one chosen when the table's own is missing + var chosen = request.Settings.String(CompatibleRomField); + var package = request.Package?.Path; + var rom = await Task.Run(() => PlayedRom(game.Key, chosen, package, cancellation), cancellation); + if (!PinMameGamelogicEngine.TryResetNvram(rom, out var backup)) { + return 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}")); + var message = $"{rom} will start with fresh ROM memory."; + return new PluginActionResult(true, backup == null ? message : $"{message} Backup saved to {backup}"); } public IPlayerPlugin Create(PluginApplicationContext context) => new SettingsAdapter(context); @@ -79,6 +191,11 @@ public override Task PrepareGameAsync(PluginGameContext game, CancellationToken var scene = game.Capabilities.Require(UnityPluginCapability.GameScene); _engine = scene.Table.GetComponentInChildren(true); if (_engine != null) { + if (!Application.isMobilePlatform) { + var substitute = SubstituteRom(_engine, game.Settings.String(CompatibleRomField)); + _engine.UseCompatibleRom(substitute); + if (substitute != null) Logger.Info("[PinMAME] ROM {Rom} isn't in the ROM folder; playing {Substitute}, the compatible ROM chosen for it.", _engine.romId, substitute); + } _original = _engine.OutputGain; _engine.ConfigureAltSound(game.Settings.Boolean("AltSound"), game.Settings.String("AltSoundFolder")); Apply(game.Settings); @@ -100,6 +217,7 @@ public void DescribeStatus(PluginStatusWriter writer) { if (_engine == null) return; writer.Add("ROM", string.IsNullOrEmpty(_engine.romId) ? "not set" : _engine.romId); + if (_engine.RomSubstitute is { } substitute) writer.Add("Playing", substitute + ", a compatible ROM"); writer.Add("Volume", Mathf.RoundToInt(_engine.OutputGain * 100f) + "%"); writer.Add("AltSound", _engine.AltSoundStatus); } From 2dfe5a824f32ff8af67ff78265e3c7de10f43088 Mon Sep 17 00:00:00 2001 From: freezy Date: Tue, 17 Nov 2026 15:35:18 +0100 Subject: [PATCH 2/2] pinmame: let the definition tests build with the compatible ROM types The test project links the definition and its converter, which now use the compatible ROM types, so these move to a file without Unity dependencies that the project links too. Adds tests for the compatibility rules. --- .../PinMameGameDefinitionConverterTests.cs | 41 ++++++++++++++ .../VisualPinball.Engine.PinMAME.Test.csproj | 1 + .../Runtime/PinMameCompatibleRom.cs | 53 +++++++++++++++++++ .../Runtime/PinMameCompatibleRom.cs.meta | 2 + ...tibleRoms.cs => PinMameRomAvailability.cs} | 43 --------------- ...cs.meta => PinMameRomAvailability.cs.meta} | 0 6 files changed, 97 insertions(+), 43 deletions(-) create mode 100644 VisualPinball.Engine.PinMAME.Unity/Runtime/PinMameCompatibleRom.cs create mode 100644 VisualPinball.Engine.PinMAME.Unity/Runtime/PinMameCompatibleRom.cs.meta rename VisualPinball.Engine.PinMAME.Unity/Runtime/{PinMameCompatibleRoms.cs => PinMameRomAvailability.cs} (78%) rename VisualPinball.Engine.PinMAME.Unity/Runtime/{PinMameCompatibleRoms.cs.meta => PinMameRomAvailability.cs.meta} (100%) diff --git a/VisualPinball.Engine.PinMAME.Test/PinMameGameDefinitionConverterTests.cs b/VisualPinball.Engine.PinMAME.Test/PinMameGameDefinitionConverterTests.cs index e2f3367..7a0140b 100644 --- a/VisualPinball.Engine.PinMAME.Test/PinMameGameDefinitionConverterTests.cs +++ b/VisualPinball.Engine.PinMAME.Test/PinMameGameDefinitionConverterTests.cs @@ -111,6 +111,47 @@ public void ConvertsTransportBindingsAndDriverOverrides() Assert.That(catalogOnlyDefinition.Diagnostics, Has.Exactly(1).Contains("no curated driver override")); } + private const string CompatibilityJson = @"{ + 'format': 'pinmame-machine-definition', + 'schema_version': 2, + 'machine': { 'id': 'test.compatibility.2026', 'name': 'Test Compatibility' }, + 'coverage': { 'status': 'partial', 'completion_score': 50 }, + 'drivers': [ + { 'id': 'test_l1', 'description': 'Test (L-1)', 'physical_compatibility': 'identical' }, + { 'id': 'test_l2', 'description': 'Test (L-2)', 'physical_compatibility': 'identical' }, + { 'id': 'test_f1', 'description': 'Test (Fix 1)', 'physical_compatibility': 'compatible' }, + { 'id': 'test_x1', 'description': 'Test (Other hardware)', 'physical_compatibility': 'different' }, + { 'id': 'test_u1', 'description': 'Test (Unknown)', 'physical_compatibility': 'unknown' } + ], + 'catalogDrivers': [ + { 'id': 'test_p1', 'description': 'Test (Prototype)' } + ] + }"; + + [Test] + public void ListsCompatibleRomsBestMatchFirst() + { + var roms = PinMameGameDefinitionConverter.ReadCompatibleRoms(CompatibilityJson, "test_l2"); + + Assert.That(roms.Select(rom => rom.Id), Is.EqualTo(new[] { "test_l1", "test_f1", "test_p1", "test_u1" })); + Assert.That(roms.Select(rom => rom.Compatibility), Is.EqualTo(new[] { + PinMameRomCompatibility.Identical, PinMameRomCompatibility.Compatible, PinMameRomCompatibility.Unverified, PinMameRomCompatibility.Unverified + })); + Assert.That(roms[0].Description, Is.EqualTo("Test (L-1)")); + Assert.That(PinMameGameDefinitionConverter.Convert(CompatibilityJson, "test_l2").CompatibleRoms.Select(rom => rom.Id), Is.EqualTo(roms.Select(rom => rom.Id))); + } + + [Test] + public void KeepsDifferentRomsApartFromCompatibleOnes() + { + Assert.That(PinMameGameDefinitionConverter.ReadCompatibleRoms(CompatibilityJson, "test_x1"), Is.Empty); + Assert.That(PinMameGameDefinitionConverter.ReadCompatibleRoms(CompatibilityJson, "test_f1").Select(rom => rom.Compatibility), + Has.None.EqualTo(PinMameRomCompatibility.Identical)); + Assert.That(PinMameGameDefinitionConverter.ReadCompatibleRoms(CompatibilityJson, "test_u1").Select(rom => rom.Compatibility), + Is.All.EqualTo(PinMameRomCompatibility.Unverified)); + Assert.That(PinMameGameDefinitionConverter.ReadCompatibleRoms(CompatibilityJson, "other_l1"), Is.Empty); + } + [Test] public void SkipsAmbiguousOrDuplicateDevicesWithDiagnostics() { diff --git a/VisualPinball.Engine.PinMAME.Test/VisualPinball.Engine.PinMAME.Test.csproj b/VisualPinball.Engine.PinMAME.Test/VisualPinball.Engine.PinMAME.Test.csproj index 58a6434..8bee8f0 100644 --- a/VisualPinball.Engine.PinMAME.Test/VisualPinball.Engine.PinMAME.Test.csproj +++ b/VisualPinball.Engine.PinMAME.Test/VisualPinball.Engine.PinMAME.Test.csproj @@ -16,6 +16,7 @@ + diff --git a/VisualPinball.Engine.PinMAME.Unity/Runtime/PinMameCompatibleRom.cs b/VisualPinball.Engine.PinMAME.Unity/Runtime/PinMameCompatibleRom.cs new file mode 100644 index 0000000..a18b7e6 --- /dev/null +++ b/VisualPinball.Engine.PinMAME.Unity/Runtime/PinMameCompatibleRom.cs @@ -0,0 +1,53 @@ +// Visual Pinball Engine +// Copyright (C) 2026 freezy and VPE Team +// +// SPDX-License-Identifier: MIT +// Licensed under MIT. See https://opensource.org/license/mit. + +using System; + +namespace VisualPinball.Engine.PinMAME +{ + /// + /// How closely a ROM matches the physical machine a table was made for, as the machine catalog + /// at games.visualpinball.org tells. + /// + public enum PinMameRomCompatibility + { + /// + /// Another revision of the same game: switches, coils, lamps and displays are wired the same. + /// + Identical = 0, + + /// + /// Runs on the same machine, but isn't just a revision of the table's ROM, e.g. a community + /// fix or alternative firmware. + /// + Compatible = 1, + + /// + /// A ROM of the same machine that nobody has confirmed runs it the same way. + /// + Unverified = 2, + } + + /// + /// A ROM that can run a table in place of the one its author chose. + /// + [Serializable] + public struct PinMameCompatibleRom + { + public string Id; + public string Description; + public PinMameRomCompatibility Compatibility; + + public PinMameCompatibleRom(string id, string description, PinMameRomCompatibility compatibility) + { + Id = id; + Description = description ?? string.Empty; + Compatibility = compatibility; + } + + public override string ToString() => string.IsNullOrWhiteSpace(Description) ? Id : $"{Id} ({Description})"; + } +} diff --git a/VisualPinball.Engine.PinMAME.Unity/Runtime/PinMameCompatibleRom.cs.meta b/VisualPinball.Engine.PinMAME.Unity/Runtime/PinMameCompatibleRom.cs.meta new file mode 100644 index 0000000..da39fa2 --- /dev/null +++ b/VisualPinball.Engine.PinMAME.Unity/Runtime/PinMameCompatibleRom.cs.meta @@ -0,0 +1,2 @@ +fileFormatVersion: 2 +guid: 98d7f2fba74f469bb9a9bcdcb22d2157 diff --git a/VisualPinball.Engine.PinMAME.Unity/Runtime/PinMameCompatibleRoms.cs b/VisualPinball.Engine.PinMAME.Unity/Runtime/PinMameRomAvailability.cs similarity index 78% rename from VisualPinball.Engine.PinMAME.Unity/Runtime/PinMameCompatibleRoms.cs rename to VisualPinball.Engine.PinMAME.Unity/Runtime/PinMameRomAvailability.cs index c066278..b84d0b0 100644 --- a/VisualPinball.Engine.PinMAME.Unity/Runtime/PinMameCompatibleRoms.cs +++ b/VisualPinball.Engine.PinMAME.Unity/Runtime/PinMameRomAvailability.cs @@ -14,49 +14,6 @@ namespace VisualPinball.Engine.PinMAME { - /// - /// How closely a ROM matches the physical machine a table was made for, as the machine catalog - /// at games.visualpinball.org tells. - /// - public enum PinMameRomCompatibility - { - /// - /// Another revision of the same game: switches, coils, lamps and displays are wired the same. - /// - Identical = 0, - - /// - /// Runs on the same machine, but isn't just a revision of the table's ROM, e.g. a community - /// fix or alternative firmware. - /// - Compatible = 1, - - /// - /// A ROM of the same machine that nobody has confirmed runs it the same way. - /// - Unverified = 2, - } - - /// - /// A ROM that can run a table in place of the one its author chose. - /// - [Serializable] - public struct PinMameCompatibleRom - { - public string Id; - public string Description; - public PinMameRomCompatibility Compatibility; - - public PinMameCompatibleRom(string id, string description, PinMameRomCompatibility compatibility) - { - Id = id; - Description = description ?? string.Empty; - Compatibility = compatibility; - } - - public override string ToString() => string.IsNullOrWhiteSpace(Description) ? Id : $"{Id} ({Description})"; - } - /// /// Finds the ROM a table package needs and the compatible ones it lists, and whether they are /// in the ROM folder, without loading the table or PinMAME. diff --git a/VisualPinball.Engine.PinMAME.Unity/Runtime/PinMameCompatibleRoms.cs.meta b/VisualPinball.Engine.PinMAME.Unity/Runtime/PinMameRomAvailability.cs.meta similarity index 100% rename from VisualPinball.Engine.PinMAME.Unity/Runtime/PinMameCompatibleRoms.cs.meta rename to VisualPinball.Engine.PinMAME.Unity/Runtime/PinMameRomAvailability.cs.meta