diff --git a/VisualPinball.Engine.DOF.Test/DofGameTriggersTests.cs b/VisualPinball.Engine.DOF.Test/DofGameTriggersTests.cs new file mode 100644 index 0000000..b994663 --- /dev/null +++ b/VisualPinball.Engine.DOF.Test/DofGameTriggersTests.cs @@ -0,0 +1,149 @@ +// Visual Pinball Engine +// Copyright (C) 2026 freezy and VPE Team +// +// SPDX-License-Identifier: GPL-3.0-or-later + +using System; +using System.IO; +using NUnit.Framework; +using VisualPinball.Engine.DOF.Configuration; + +namespace VisualPinball.Engine.DOF.Test +{ + public class DofGameTriggersTests + { + // Combo1 and Combo2 are RGB toys on 1-3 and 4-6, the knocker is on 7, as the Config Tool writes them. + private const string Ini = "[version]\r\nversion=5302\r\n\r\n[Colors DOF]\r\nRed=#FF0000FF\r\n\r\n[Variables DOF]\r\n@flash@=W30 500\r\n@wide@=shape Red\r\n\r\n" + + "[Config DOF]\r\n# \"Rom\",\"Combo1\",\"\",\"\",\"Combo2\",\"\",\"\",\"Knocker\"\r\n" + + "afm,E101 Red,0,0,0,S5\r\n" + + "t2,0,0,0,L12 Blue/S3 Red,@flash@\r\n" + + "afm,S9\r\n" + + "fh,S1\r\n"; + + private string _root; + + [SetUp] + public void SetUp() => _root = Path.Combine(Path.GetTempPath(), "vpe-dof-triggers-" + Guid.NewGuid().ToString("N")); + + [TearDown] + public void TearDown() + { + if (Directory.Exists(_root)) { + Directory.Delete(_root, true); + } + } + + [Test] + public void ReadsWhatFiresEachToyOfARow() + { + var afm = DofIniRow.Parse(Ini, "AFM"); + Assert.That(afm.Rom, Is.EqualTo("afm"), "the first row of a ROM, as libdof keeps it"); + Assert.That(afm.SettingOf(1, 3), Is.EqualTo("E101 Red")); + Assert.That(afm.SettingOf(4, 3), Is.EqualTo(""), "three 0s for an RGB toy without effects"); + Assert.That(afm.SettingOf(7, 1), Is.EqualTo("S5")); + Assert.That(afm.SettingOf(8, 1), Is.EqualTo(""), "past the row"); + Assert.That(afm.SettingOf(2, 1), Is.Null, "inside the colour column of another toy"); + + var t2 = DofIniRow.Parse(Ini, "t2"); + Assert.That(t2.SettingOf(4, 3), Is.EqualTo("L12 Blue/S3 Red")); + Assert.That(t2.SettingOf(7, 1), Is.EqualTo("@flash@"), "as written, its variable kept"); + Assert.That(t2.Extent, Is.EqualTo(7)); + Assert.That(DofIniRow.Parse(Ini, "gnr"), Is.Null); + } + + [Test] + public void ChangesAToyAndKeepsTheOthersOnTheirPorts() + { + var afm = DofIniRow.Parse(Ini, "afm"); + var combo2 = afm.With(4, 3, "S28 Red", out var problem); + Assert.That(problem, Is.Null); + Assert.That(combo2.Line, Is.EqualTo("afm,E101 Red,S28 Red,S5"), "one colour column for the three 0s"); + Assert.That(combo2.SettingOf(7, 1), Is.EqualTo("S5"), "the knocker stays on its port"); + + var cleared = combo2.With(1, 3, "", out problem); + Assert.That(cleared.Line, Is.EqualTo("afm,0,0,0,S28 Red,S5"), "nothing takes the RGB toy's three ports"); + Assert.That(cleared.SettingOf(4, 3), Is.EqualTo("S28 Red")); + + var knocker = afm.With(7, 1, "W25 500", out problem); + Assert.That(knocker.Line, Is.EqualTo("afm,E101 Red,0,0,0,W25 500")); + + var added = afm.With(10, 1, "S40", out problem); + Assert.That(added.Line, Is.EqualTo("afm,E101 Red,0,0,0,S5,0,0,S40"), "0s up to a toy past the row"); + Assert.That(added.SettingOf(10, 1), Is.EqualTo("S40")); + Assert.That(afm.With(10, 1, "", out problem), Is.SameAs(afm), "nothing past the row is nothing to write"); + + Assert.That(afm.With(2, 1, "S1", out problem), Is.Null); + Assert.That(problem, Does.Contain("colour")); + Assert.That(afm.With(10, 1, "S40 Red", out problem), Is.Null, "past the row too, a colour would drive the ports after the toy"); + Assert.That(problem, Does.Contain("takes one output")); + Assert.That(afm.With(10, 3, "S40", out problem), Is.Null); + Assert.That(problem, Does.Contain("RGB toy")); + Assert.That(afm.With(4, 1, "S7 SHPshape,", out problem), Is.Null, "a comma would move the knocker to port 8"); + Assert.That(problem, Does.Contain("move the toys after it")); + Assert.That(afm.With(4, 1, "S7 SHP@wide@", out problem), Is.Null, "a variable with a colour takes three ports as libdof reads it"); + Assert.That(problem, Does.Contain("move the toys after it")); + Assert.That(DofIniRow.Parse(Ini, "t2").With(1, 3, "S1 Red", out problem).Line, Is.EqualTo("t2,S1 Red,L12 Blue/S3 Red,@flash@"), + "a row with a variable in a column of its own stays editable"); + } + + [Test] + public void FitsWhatTheUserWrites() + { + Assert.That(DofIniRow.Fit(" S28 Blink ", false, out var problem), Is.EqualTo("S28 Blink")); + Assert.That(DofIniRow.Fit("S28", true, out problem), Is.EqualTo("S28 #FFFFFF"), "an RGB toy takes a colour, in one every configuration knows"); + Assert.That(DofIniRow.Fit("S28/L5 Red", true, out problem), Is.EqualTo("S28 #FFFFFF/L5 Red")); + Assert.That(DofIniRow.Fit("0", false, out problem), Is.EqualTo("")); + Assert.That(DofIniRow.Fit("", true, out problem), Is.EqualTo("")); + Assert.That(DofIniRow.Fit("S28 Red", false, out problem), Is.Null); + Assert.That(problem, Does.Contain("leave out the colour")); + Assert.That(DofIniRow.Fit("S28,S29", false, out problem), Is.Null); + Assert.That(problem, Does.Contain("comma")); + Assert.That(DofIniRow.Fit("Q12", false, out problem), Is.Null); + Assert.That(problem, Does.Contain("Q12")); + Assert.That(DofIniRow.Fit("S28 RougeƩ", true, out problem), Is.Null); + Assert.That(DofIniRow.Fit("S7 SHP(", false, out problem), Is.Null, "libdof would read the rest of the row as the column"); + Assert.That(problem, Does.Contain("brackets")); + Assert.That(DofIniRow.Fit("(S7 or S8) Red", true, out problem), Is.EqualTo("(S7 or S8) Red")); + Assert.That(DofIniRow.Fit("S7 SHPshape,", false, out problem), Is.Null, "a comma at the end is a column too"); + Assert.That(problem, Does.Contain("comma")); + Assert.That(DofIniRow.Fit("S7 SHP@wide@", false, out problem), Is.Null, "a variable may stand for columns of its own"); + Assert.That(problem, Does.Contain("variables")); + } + + [Test] + public void ReplacesTheRowInTheText() + { + var row = DofIniRow.Parse(Ini, "afm").With(7, 1, "S6", out _); + var text = row.ReplaceIn(Ini); + Assert.That(text, Does.Contain("\r\nafm,E101 Red,0,0,0,S6\r\nt2,"), "the row in place, its line ending kept"); + Assert.That(text, Does.Contain("\r\nafm,S9\r\n"), "the second row of the ROM, which libdof skips, as it was"); + Assert.That(DofIniRow.Parse(text, "afm").SettingOf(7, 1), Is.EqualTo("S6")); + + const string old = "[Config DOF]\rafm,S1\rt2,S2\r"; + var mac = DofIniRow.Parse(old, "afm"); + Assert.That(mac.SettingOf(1, 1), Is.EqualTo("S1"), "lines that end with \\r alone, as libdof reads them"); + Assert.That(mac.With(1, 1, "S7", out _).ReplaceIn(old), Is.EqualTo("[Config DOF]\rafm,S7\rt2,S2\r")); + } + + [Test] + public void KeepsTriggersPerRowDeviceAndPort() + { + var triggers = DofGameTriggers.None.With("afm", 30, 7, "S6\t").With("AFM", 30, 1, "").With("t2", 30, 7, "S8"); + Assert.That(triggers.SettingOf("afm", 30, 7), Is.EqualTo("S6")); + Assert.That(triggers.SettingOf("afm", 30, 1), Is.EqualTo(""), "nothing fires it"); + Assert.That(triggers.SettingOf("afm", 30, 4), Is.Null, "unchanged"); + Assert.That(triggers.SettingOf("afm", 31, 7), Is.Null); + Assert.That(triggers.Of("Afm", 30), Is.EqualTo(new[] { (1, ""), (7, "S6") }), "ROMs as libdof compares them"); + + triggers.Save(_root); + var loaded = DofGameTriggers.Load(_root); + Assert.That(loaded.Of("afm", 30), Is.EqualTo(new[] { (1, ""), (7, "S6") })); + Assert.That(loaded.SettingOf("t2", 30, 7), Is.EqualTo("S8")); + + var reset = loaded.With("afm", 30, 7, null).With("afm", 30, 1, null).With("t2", 30, 7, null); + Assert.That(reset.IsEmpty, Is.True); + reset.Save(_root); + Assert.That(File.Exists(Path.Combine(_root, DofGameTriggers.FileName)), Is.False, "no file for nothing changed"); + } + } +} diff --git a/VisualPinball.Engine.DOF.Test/DofImporterTests.cs b/VisualPinball.Engine.DOF.Test/DofImporterTests.cs index 70e354e..fe4e014 100644 --- a/VisualPinball.Engine.DOF.Test/DofImporterTests.cs +++ b/VisualPinball.Engine.DOF.Test/DofImporterTests.cs @@ -751,5 +751,53 @@ public void GlobalConfigUsesPathsLibdofCanOpen() Assert.That(DofPaths.IsAscii(global.Element(element).Value), Is.True, global.Element(element).Value); } } + + [Test] + public void BuildsAGameCopyWithTheUsersTriggers() + { + Accepted(_importer.Import(Zip("config.zip", ("directoutputconfig.ini", MainIni), ("directoutputconfig51.ini", SecondIni), + ("DirectOutputShapes.xml", Shapes), ("DirectOutputShapes.png", "png")))); + var revision = _store.Active; + var catalog = DofCatalog.Load(revision); + var problems = new List(); + Assert.That(DofGameConfig.Build(revision, catalog, _store.Root, catalog.Match("afm_113b"), DofGameTriggers.None.With("t2", 1, 2, "S9"), problems), + Is.Null, "another game's triggers leave the revision to the game"); + + var triggers = DofGameTriggers.None.With("afm", 1, 2, "S7 500").With("afm", 51, 3, "L9").With("afm", 1, 1, ""); + var basePath = DofGameConfig.Build(revision, catalog, _store.Root, catalog.Match("afm_113b"), triggers, problems); + Assert.That(problems, Is.Empty); + var config = Path.Combine(basePath, DofRevision.ConfigFolder); + Assert.That(File.ReadAllText(Path.Combine(config, "directoutputconfig.ini")), Does.Contain("\r\nafm,0,S7 500\r\nt2,S3,0\r\n")); + Assert.That(File.ReadAllText(Path.Combine(config, "directoutputconfig51.ini")), Does.Contain("\r\nafm,L5,0,L9\r\n"), "0s up to the toy"); + Assert.That(File.ReadAllText(Path.Combine(revision.ConfigDir, "directoutputconfig.ini")), Does.Contain("afm,S1,S2"), "the revision as it was imported"); + Assert.That(File.Exists(Path.Combine(config, "DirectOutputShapes.png")), Is.True); + var global = XDocument.Load(Path.Combine(config, DofGlobalConfig.FileName)).Root; + Assert.That(global.Element("IniFilesPath").Value, Is.EqualTo(DofPaths.ToNative(config))); + Assert.That(global.Element("ShapeDefinitionFilePattern").Value, Is.EqualTo(Path.Combine(DofPaths.ToNative(config), "DirectOutputShapes.xml"))); + + // libdof runs with it, confined to the copy + using (var dof = DofInstance.Create(basePath)) { + dof.Init(null, "afm_113b"); + dof.Finish(); + } + + // a row that changed since: what can't be made is said, the rest is made + triggers = DofGameTriggers.None.With("afm", 1, 2, "S7").With("afm", 51, 2, "L1"); + File.WriteAllText(Path.Combine(revision.ConfigDir, "directoutputconfig51.ini"), Header + "afm,L5 Red\r\n"); + basePath = DofGameConfig.Build(revision, DofCatalog.Load(revision), _store.Root, catalog.Match("afm"), triggers, problems); + Assert.That(problems, NUnit.Framework.Has.Count.EqualTo(1)); + Assert.That(problems[0], Does.Contain("Device 51, port 2")); + Assert.That(File.ReadAllText(Path.Combine(basePath, DofRevision.ConfigFolder, "directoutputconfig.ini")), Does.Contain("afm,S1,S7")); + // a toy an import made an RGB one fires in white; a colour on a toy of one output is said and left out + triggers = DofGameTriggers.None.With("afm", 51, 1, "L1").With("afm", 1, 2, "S7 Red").With("afm", 51, 2, "L2"); + problems.Clear(); + basePath = DofGameConfig.Build(revision, DofCatalog.Load(revision), _store.Root, catalog.Match("afm"), triggers, problems); + Assert.That(File.ReadAllText(Path.Combine(basePath, DofRevision.ConfigFolder, "directoutputconfig51.ini")), Does.Contain("\r\nafm,L1 #FFFFFF\r\n")); + Assert.That(problems, NUnit.Framework.Has.Count.EqualTo(2), string.Join("\n", problems)); + Assert.That(problems, NUnit.Framework.Has.Some.Contains("Device 1, port 2").And.Some.Contains("takes one output")); + Assert.That(problems, NUnit.Framework.Has.Some.Contains("Device 51, port 2").And.Some.Contains("part of an RGB toy"), "its green is changed with the toy"); + DofGameConfig.Delete(_store.Root); + Assert.That(Directory.Exists(basePath), Is.False); + } } } diff --git a/VisualPinball.Engine.DOF.Unity/Runtime/Player/DofPlugin.cs b/VisualPinball.Engine.DOF.Unity/Runtime/Player/DofPlugin.cs index ade2e75..beebe75 100644 --- a/VisualPinball.Engine.DOF.Unity/Runtime/Player/DofPlugin.cs +++ b/VisualPinball.Engine.DOF.Unity/Runtime/Player/DofPlugin.cs @@ -151,8 +151,10 @@ public override async Task PrepareGameAsync(PluginGameContext game, Cancellation var selection = new PluginResourceSelection(ResourceKind.RealtimeOutputs) { Controller = game.ControllerId, Session = game.Session }; var outputs = activity.Own(game.Resources.Bind(selection)); var feed = FeedOf(outputs); + // what the user changed of the game's rows, in a copy only this game uses: the previous game's is done with it + var basePath = (_rom != null ? GameConfig(revision, catalog, game) : null) ?? revision.BasePath; session = new DofGameSession(new DofSessionOptions { - BasePath = revision.BasePath, + BasePath = basePath, RomName = _rom, GameSession = unchecked((int)game.Session), // Without a feed only the triggers drive DOF; there is no initial state to wait for. @@ -403,6 +405,59 @@ private void SessionLog(DofLogLevel level, string message) } } + /// + /// The base path of a copy of the configuration with what the user changed of the game's rows; null when nothing is + /// changed or the copy can't be made, so the game uses the configuration as it is. The log says what wasn't applied. + /// + private string GameConfig(DofRevision revision, DofCatalog catalog, PluginGameContext game) + { + var root = _factory.Store.Root; + try { + var rows = catalog.Match(_rom); + var triggers = DofGameTriggers.Load(root); + // The settings page changes the rows of the ROM it finds without a running game. The game may play a compatible + // ROM, or have a name for DOF, with rows of their own: on a port where the user's trigger of those doesn't apply, + // the page's does, where it applies on the page. + var problems = new List(); + var (pageRom, _) = DofGameSetup.ResolveRom(game.Settings.String("Rom", DofGameSetup.Auto), game.Identity, null, null, catalog); + foreach (var pageRow in pageRom != null ? catalog.Match(pageRom) : Array.Empty()) { + var device = catalog.Devices.FirstOrDefault(d => d.Number == pageRow.Device); + // the files are large: read only for a device the user changed + if (triggers.Of(pageRow.Rom, pageRow.Device).Count == 0) { + continue; + } + foreach (var row in rows.Where(r => device != null && r.Device == pageRow.Device && !string.Equals(r.Rom, pageRow.Rom, StringComparison.OrdinalIgnoreCase)).Take(1)) { + var path = Path.Combine(revision.ConfigDir, device.FileName); + var (own, page) = (DofIniRow.Read(path, row.Rom), DofIniRow.Read(path, pageRow.Rom)); + var rgb = DofGameConfig.RgbStarts(device); + foreach (var (port, setting) in triggers.Of(pageRow.Rom, pageRow.Device)) { + var mine = triggers.SettingOf(row.Rom, row.Device, port); + if (own == null || page == null || mine != null && DofGameConfig.Change(own, rgb, port, mine, out _) != null) { + continue; + } + // the page shows it doesn't fit; the log says so too, as it does for one of the running rows + if (DofGameConfig.Change(page, rgb, port, setting, out var problem) == null) { + problems.Add($"Device {pageRow.Device}, port {port}: {problem}"); + continue; + } + triggers = triggers.With(row.Rom, row.Device, port, setting); + } + } + } + var basePath = DofGameConfig.Build(revision, catalog, root, rows, triggers, problems); + foreach (var problem in problems) { + _application.Logger.Warn("A trigger you changed for this game is not applied: " + problem); + } + if (basePath != null) { + _application.Logger.Info("DOF fires the toys with the triggers you changed for this game."); + } + return basePath; + } catch (Exception e) when (e is IOException || e is UnauthorizedAccessException || e is System.Xml.XmlException || e is FormatException || e is DofException) { + _application.Logger.Warn("The triggers you changed for this game could not be applied; DOF uses the configuration as it is.", e); + return null; + } + } + /// The ROM the gamelogic engine plays, which PinMAME prepares first; null for other engines. private static string RunningRom(IUnityGameScene scene, GameIdentity game) { diff --git a/VisualPinball.Engine.DOF.Unity/Runtime/Player/DofPluginFactory.cs b/VisualPinball.Engine.DOF.Unity/Runtime/Player/DofPluginFactory.cs index 2637d2f..640deff 100644 --- a/VisualPinball.Engine.DOF.Unity/Runtime/Player/DofPluginFactory.cs +++ b/VisualPinball.Engine.DOF.Unity/Runtime/Player/DofPluginFactory.cs @@ -17,6 +17,7 @@ using UnityEngine; using VisualPinball.Engine.DOF.Configuration; using VisualPinball.Engine.DOF.Detection; +using LampSource = VisualPinball.Engine.Game.Engines.LampSource; using VisualPinball.Plugins; using VisualPinball.Unity; using Logger = NLog.Logger; @@ -27,7 +28,7 @@ namespace VisualPinball.Engine.DOF.Player /// The DOF plugin: imports DOF configurations, runs DOF for each game and publishes the cabinet triggers, and /// describes the settings the Player renders. /// - internal sealed class DofPluginFactory : IPlayerPluginFactory, IPluginSettingsProvider, IPluginSettingsInfoProvider, IPluginOutputMapProvider, IPluginOutputRearranger, IPluginOutputAssigner, IPluginSystemDefaults + internal sealed class DofPluginFactory : IPlayerPluginFactory, IPluginSettingsProvider, IPluginSettingsInfoProvider, IPluginOutputMapProvider, IPluginOutputRearranger, IPluginOutputAssigner, IPluginOutputTriggerEditor, IPluginSystemDefaults { internal const string Id = "org.visualpinball.dof"; private const string PinMameId = "org.visualpinball.pinmame"; @@ -218,9 +219,11 @@ internal static NLog.LogLevel LogLevelOf(DofLogLevel level) new PluginField("Port", "Port", SettingKind.Choice) { Default = "", Provider = "serial-port-names", Row = "port" }, } }, new PluginField("ApplySerialOverrides", "Apply ports", SettingKind.Action) { Provider = "apply-serial-overrides", AttachTo = "SerialOverrides" }), - new PluginSettingsGroup("This game", "Which configuration rows the game uses.", + new PluginSettingsGroup("This game", "Which configuration rows the game uses, and what of the game fires each toy.", new PluginField("Rom", "Game name", SettingKind.Choice) { Default = DofGameSetup.Auto, Scope = ConfigurationScope.GameOnly, Provider = "roms", FullWidth = true, - Description = "Automatic uses the ROM the game plays, or the name the table sets for DOF. A table mapping for the table's name is offered here." })); + Description = "Automatic uses the ROM the game plays, or the name the table sets for DOF. A table mapping for the table's name is offered here." }, + new PluginField("GameOutputs", "What fires the toys", SettingKind.Outputs) { Scope = ConfigurationScope.GameOnly, Provider = GameOutputsProvider, FullWidth = true, + Description = "What the configuration's rows fire each toy with in this game. Choose a toy to fire it with something else: it applies to this game only, and stays when you import a configuration again." })); #endregion @@ -501,9 +504,253 @@ private PluginOutputLeases LeasesFor(PluginChoiceRequest request) public Task DescribeOutputsAsync(string provider, PluginChoiceRequest request, CancellationToken cancellation) { var leases = LeasesFor(request); - return Task.Run(() => DescribeOutputs(provider, leases, cancellation), cancellation); + return provider == GameOutputsProvider + ? DescribeGameOutputsAsync(request, leases, cancellation) + : Task.Run(() => DescribeOutputs(provider, leases, cancellation), cancellation); } + /// The field that shows what fires the toys in a game. + internal const string GameOutputsProvider = "game-outputs"; + + /// + /// The boards a game has rows on, each toy with what fires it in the game; and for a PinMAME game, its solenoids, lamps + /// and switches by the names the table gives them, to pick from. + /// + private async Task DescribeGameOutputsAsync(PluginChoiceRequest request, PluginOutputLeases leases, CancellationToken cancellation) + { + var map = await Task.Run(() => DescribeGameOutputs(request, leases, cancellation), cancellation).ConfigureAwait(false); + var path = request?.Package?.Path; + if (map.TriggersEditable && request.Game?.Provider == "pinmame" && !string.IsNullOrEmpty(path)) { + try { + map.GameOutputs = GameOutputsOf(await PackagedGameInformation.ReadMappingsAsync(path, cancellation).ConfigureAwait(false)); + } catch (Exception e) when (!(e is OperationCanceledException)) { + Logger.Warn(e, "[DOF] The switches, coils and lamps of " + path + " could not be read."); + } + } + return map; + } + + private PluginOutputMap DescribeGameOutputs(PluginChoiceRequest request, PluginOutputLeases leases, CancellationToken cancellation) + { + cancellation.ThrowIfCancellationRequested(); + var store = Store; + using var lease = store.AcquireForReading(); + var revision = lease?.Revision; + if (revision == null) { + return new PluginOutputMap(Array.Empty(), "Import a DOF configuration to see what fires the toys in this game."); + } + var catalog = CatalogOf(revision); + var (_, rows, problem) = GameRows(request, catalog); + if (rows.Count == 0) { + return new PluginOutputMap(Array.Empty(), problem); + } + var detected = DetectedBoards(catalog); + var wiring = ReadWiring(store.Root) ?? DofOutputWiring.None; + var names = ReadNames(store.Root) ?? DofToyNames.None; + var triggers = ReadTriggers(store.Root) ?? DofGameTriggers.None; + var boards = new List(); + foreach (var row in rows) { + var device = catalog.Devices.FirstOrDefault(d => d.Number == row.Device); + if (device == null) { + continue; + } + DofIniRow ini; + try { + ini = DofIniRow.Read(Path.Combine(revision.ConfigDir, device.FileName), row.Rom); + } catch (Exception e) when (e is IOException || e is UnauthorizedAccessException) { + Logger.Warn(e, "[DOF] The row of " + row.Rom + " could not be read from " + device.FileName + "."); + ini = null; + } + var board = Board(device, detected, Reach(catalog, detected, device.Number), wiring, names); + var rgb = DofGameConfig.RgbStarts(device); + foreach (var output in board.Outputs) { + // what drives the output is chosen and shown on the global page; here only what fires it, a note saying when + // the user's trigger doesn't + output.Toy = ""; + output.Note = ""; + if (!DofPortTest.TryParse(output.Id, out _, out var port) || port < 1 + || output.Channel != PluginOutputChannel.None && output.Channel != PluginOutputChannel.Red) { + continue; + } + // What fires it as the game runs: the user's trigger, unless a configuration imported since makes it not fit; kept + // for one that fits it again, and changed like one that fits. + var width = rgb.Contains(port) ? 3 : 1; + var saved = triggers.SettingOf(row.Rom, device.Number, port); + var applies = saved != null && ini != null && DofGameConfig.Change(ini, rgb, port, saved, out _) != null; + // one saved on the green or blue of an RGB toy, from before an import made one of it, is reset with the toy + var inside = width == 3 && (triggers.SettingOf(row.Rom, device.Number, port + 1) != null || triggers.SettingOf(row.Rom, device.Number, port + 2) != null); + output.Trigger = applies ? DofIniRow.Fit(saved, width == 3, out _) : ini?.SettingOf(port, width) ?? ""; + output.TriggerChanged = saved != null || inside; + if (saved != null && !applies || inside) { + output.Note = "Yours doesn't fit"; + } + } + board.Rearrangeable = false; + board.Toys = Array.Empty(); + board.AcceptsNewToys = false; + boards.Add(board); + } + return new PluginOutputMap(boards, problem, leases == null ? NoTestsYet : "") { TriggersEditable = boards.Count > 0 }; + } + + /// + /// The ROM a game uses as its settings choose it, and the configuration's rows for it, one per device; with why it has + /// none. + /// + private static (string Rom, IReadOnlyList Rows, string Problem) GameRows(PluginChoiceRequest request, DofCatalog catalog) + { + var game = request?.Game; + if (game == null) { + return (null, Array.Empty(), "Choose a game to see what fires the toys in it."); + } + var setting = request.Settings?.String("Rom", DofGameSetup.Auto) ?? DofGameSetup.Auto; + var (rom, problem) = DofGameSetup.ResolveRom(setting, game.Value, null, null, catalog); + if (rom == null) { + return (null, Array.Empty(), problem ?? "The game has no name DOF knows: choose one under Game name."); + } + var rows = catalog.Match(rom); + return (rom, rows, rows.Count == 0 ? $"The configuration has no rows for {rom}, so nothing fires the toys in this game." : ""); + } + + + /// + /// What of a game can fire a toy, from the table's mappings of a PinMAME game: its solenoids, flashers on solenoids, + /// lamps, GI strings and switches, by number, each with the first name the table gives it. + /// + internal static IReadOnlyList GameOutputsOf(MappingConfig mappings) + { + var outputs = new List<(char Letter, int Number, string Label)>(); + void Add(char letter, string id, string description) + { + if (int.TryParse(id?.Trim(), NumberStyles.None, CultureInfo.InvariantCulture, out var number)) { + outputs.Add((letter, number, description?.Trim() ?? "")); + } + } + foreach (var coil in mappings?.Coils ?? new List()) { + Add('S', coil.Id, coil.Description); + } + foreach (var lamp in mappings?.Lamps ?? new List()) { + Add(lamp.IsCoil ? 'S' : lamp.Source == LampSource.GI ? 'G' : 'L', lamp.Id, lamp.Description); + } + foreach (var sw in mappings?.Switches ?? new List()) { + Add('W', sw.Id, sw.Description); + } + const string order = "SLGW"; + return outputs + .GroupBy(o => (o.Letter, o.Number)) + .Select(g => (g.Key.Letter, g.Key.Number, Label: g.Select(o => o.Label).FirstOrDefault(l => l.Length > 0) ?? "")) + .OrderBy(o => order.IndexOf(o.Letter)).ThenBy(o => o.Number) + .Select(o => new PluginGameOutput(o.Letter + o.Number.ToString(CultureInfo.InvariantCulture), o.Label)) + .ToList(); + } + + /// What the user changed of the games' rows, of a folder; null when its file can't be read, after a few tries. + private static DofGameTriggers ReadTriggers(string root) + { + for (var attempt = 1; ; attempt++) { + try { + return DofGameTriggers.Load(root); + } catch (Exception e) when (e is IOException || e is UnauthorizedAccessException) { + if (attempt == 3) { + Logger.Warn(e, "[DOF] What you changed of the games' triggers could not be read."); + return null; + } + Thread.Sleep(20); + } + } + } + + public Task SetTriggerAsync(string provider, string output, string trigger, PluginChoiceRequest request, CancellationToken cancellation) + => Task.Run(() => provider != GameOutputsProvider ? new PluginActionResult(false, "Unknown DOF outputs.") : SetTrigger(output, trigger, request, cancellation), cancellation); + + /// + /// Changes what fires the toy on a port in the game's row of its device: a trigger as libdof takes it, empty for nothing, + /// null for the configuration's. Kept beside the configuration, for every configuration imported later. + /// + private PluginActionResult SetTrigger(string id, string trigger, PluginChoiceRequest request, CancellationToken cancellation) + { + cancellation.ThrowIfCancellationRequested(); + if (!DofPortTest.TryParse(id, out var device, out var port)) { + return new PluginActionResult(false, "Unknown output."); + } + // an output nothing drives has its number as a negative port + if (port < 1) { + return new PluginActionResult(false, "Nothing is on that output, so nothing can fire it."); + } + var store = Store; + using var lease = store.AcquireForReading(); + var revision = lease?.Revision; + if (revision == null) { + return new PluginActionResult(false, "Import a DOF configuration first."); + } + var catalog = CatalogOf(revision); + var (rom, rows, problem) = GameRows(request, catalog); + var matching = rows.Where(r => r.Device == device).ToList(); + var entry = catalog.Devices.FirstOrDefault(d => d.Number == device); + if (matching.Count == 0 || entry == null) { + return new PluginActionResult(false, rows.Count == 0 ? problem : $"The configuration has no row for {rom} on device {device}."); + } + var row = matching[0]; + DofIniRow ini; + try { + ini = DofIniRow.Read(Path.Combine(revision.ConfigDir, entry.FileName), row.Rom); + } catch (Exception e) when (e is IOException || e is UnauthorizedAccessException) { + return new PluginActionResult(false, $"The row of {row.Rom} could not be read: {e.Message}"); + } + if (ini == null) { + return new PluginActionResult(false, $"{entry.FileName} has no row for {row.Rom} any more."); + } + var rgb = DofGameConfig.RgbStarts(entry); + var width = rgb.Contains(port) ? 3 : 1; + string setting = null; + if (trigger != null) { + setting = DofIniRow.Fit(trigger, width == 3, out var invalid); + if (setting == null) { + return new PluginActionResult(false, invalid); + } + if (setting.Length > DofGameTriggers.MaxLength) { + return new PluginActionResult(false, $"A trigger can have {DofGameTriggers.MaxLength} characters at most."); + } + if (DofGameConfig.Change(ini, rgb, port, setting, out var unfit) == null) { + return new PluginActionResult(false, unfit); + } + // what the configuration says is no change + if (string.Equals(setting, ini.SettingOf(port, width), StringComparison.Ordinal)) { + setting = null; + } + } + var header = port <= entry.Ports.Count ? entry.Ports[port - 1]?.Trim() ?? "" : ""; + var name = header.Length > 0 ? header : ReadNames(store.Root)?.NameOf(device, port) ?? ""; + var toy = name.Length > 0 ? name : $"port {port} of device {device}"; + lock (WiringFileLock) { + // a page left meanwhile changes nothing + cancellation.ThrowIfCancellationRequested(); + var triggers = ReadTriggers(store.Root); + if (triggers == null) { + return new PluginActionResult(false, "What you changed of the games' triggers could not be read, so nothing was changed. Try again."); + } + try { + cancellation.ThrowIfCancellationRequested(); + var next = triggers.With(row.Rom, device, port, setting); + // what was saved on the green and blue goes with the toy (see DescribeGameOutputs) + if (width == 3) { + next = next.With(row.Rom, device, port + 1, null).With(row.Rom, device, port + 2, null); + } + next.Save(store.Root); + } catch (Exception e) when (e is IOException || e is UnauthorizedAccessException) { + Logger.Warn(e, "[DOF] Saving the game triggers failed."); + return new PluginActionResult(false, "Not changed: " + e.Message); + } + } + Logger.Info($"[DOF] {toy} of {row.Rom} fires on {(setting == null ? "what the configuration says" : setting.Length == 0 ? "nothing" : setting)}."); + var fires = setting == null ? $"{Capital(toy)} fires as the configuration says in {row.Rom}." + : setting.Length == 0 ? $"Nothing fires {toy} in {row.Rom} now." + : $"{setting} fires {toy} in {row.Rom} now."; + return new PluginActionResult(true, DofOwnership.InUse ? fires + " A running game keeps what it started with: it applies from the next game." : fires); + } + + private static string Capital(string text) => text.Length > 0 ? char.ToUpperInvariant(text[0]) + text.Substring(1) : text; + private PluginOutputMap DescribeOutputs(string provider, PluginOutputLeases leases, CancellationToken cancellation) { cancellation.ThrowIfCancellationRequested(); @@ -728,7 +975,7 @@ public Task TestOutputAsync(string provider, string output, { var leases = LeasesFor(request); return Task.Run(() => { - if (provider != "outputs") { + if (provider != "outputs" && provider != GameOutputsProvider) { return new PluginActionResult(false, "Unknown DOF outputs."); } try { diff --git a/VisualPinball.Engine.DOF.Unity/Runtime/Player/VisualPinball.Engine.DOF.Player.asmdef b/VisualPinball.Engine.DOF.Unity/Runtime/Player/VisualPinball.Engine.DOF.Player.asmdef index 66d45ff..0223a46 100644 --- a/VisualPinball.Engine.DOF.Unity/Runtime/Player/VisualPinball.Engine.DOF.Player.asmdef +++ b/VisualPinball.Engine.DOF.Unity/Runtime/Player/VisualPinball.Engine.DOF.Player.asmdef @@ -4,6 +4,7 @@ "references": [ "VisualPinball.Plugins", "VisualPinball.Unity", + "VisualPinball.Engine", "VisualPinball.Engine.DOF.Unity", "Newtonsoft.Json" ], diff --git a/VisualPinball.Engine.DOF.Unity/Tests/DofPluginTests.cs b/VisualPinball.Engine.DOF.Unity/Tests/DofPluginTests.cs index f910d70..e18b579 100644 --- a/VisualPinball.Engine.DOF.Unity/Tests/DofPluginTests.cs +++ b/VisualPinball.Engine.DOF.Unity/Tests/DofPluginTests.cs @@ -836,6 +836,137 @@ public IEnumerator FollowsOnlyTheTriggersOfAFeedItCannotRead() yield return host.Await(host.Plugin.Quiescence, "quiescence"); } + private static PluginChoiceRequest GameRequest(string rom = "vpetest_l1") + => new PluginChoiceRequest(new GameIdentity("pinmame", rom), new PluginSettingsSnapshot(1), "windows"); + + private static PluginOutputMap GameOutputs(DofTestHost host, string rom = "vpetest_l1") + => host.Factory.DescribeOutputsAsync(DofPluginFactory.GameOutputsProvider, GameRequest(rom), CancellationToken.None).Result; + + private static PluginActionResult SetTrigger(DofTestHost host, string output, string trigger, string rom = "vpetest_l1") + => host.Factory.SetTriggerAsync(DofPluginFactory.GameOutputsProvider, output, trigger, GameRequest(rom), CancellationToken.None).Result; + + [Test] + public void ShowsWhatFiresTheToysInAGame() + { + var host = Host(); + host.Import(367, "vpetest,S1,0,E2 White", null, "\"Rom\",\"Knocker\",\"\",\"Flasher\""); + var map = GameOutputs(host); + Assert.That(map.TriggersEditable, Is.True); + var board = map.Boards.Single(); + Assert.That((board.Rearrangeable, board.Toys.Count, board.AcceptsNewToys), Is.EqualTo((false, 0, false)), "what drives an output is chosen for every game"); + Assert.That(board.Outputs.All(o => o.Toy.Length == 0), Is.True); + Assert.That(board.Outputs.Take(5).Select(o => o.Trigger), Is.EqualTo(new[] { "S1", "", "E2 White", "", "" }), "an RGB toy's on its red"); + Assert.That(board.Outputs.Any(o => o.TriggerChanged), Is.False); + + var none = GameOutputs(host, "other_l1"); + Assert.That(none.Boards, Is.Empty); + Assert.That(none.EmptyMessage, Does.Contain("no rows for other_l1")); + Assert.That(none.TriggersEditable, Is.False); + } + + [Test] + public void ChangesWhatFiresAToyInAGame() + { + var host = Host(); + host.Import(368, "vpetest,S1,0,E2 White", null, "\"Rom\",\"Knocker\",\"\",\"Flasher\""); + var result = SetTrigger(host, "1:1", " S28 Blink "); + Assert.That(result.Success, Is.True, result.Message); + Assert.That(result.Message, Does.StartWith("S28 Blink fires Knocker in vpetest now.")); + Assert.That(SetTrigger(host, "1:3", "L5").Success, Is.True, "an RGB toy fires in white without a colour"); + var outputs = GameOutputs(host).Boards.Single().Outputs; + Assert.That(outputs.Take(3).Select(o => (o.Trigger, o.TriggerChanged)), Is.EqualTo(new[] { ("S28 Blink", true), ("", false), ("L5 #FFFFFF", true) })); + Assert.That(GameOutputs(host, "vpetest_l2").Boards.Single().Outputs[0].Trigger, Is.EqualTo("S28 Blink"), "kept for the row, which other versions of the game share"); + + Assert.That(SetTrigger(host, "1:1", "S1,S2").Message, Does.Contain("comma")); + Assert.That(SetTrigger(host, "1:1", "S1 Red").Success, Is.False, "a colour fires an RGB toy only"); + Assert.That(SetTrigger(host, "1:-2", "S3").Success, Is.False, "nothing is on an output nothing drives"); + Assert.That(SetTrigger(host, "1:1", "S3", "other_l1").Message, Does.Contain("no rows for other_l1")); + + result = SetTrigger(host, "1:1", ""); + Assert.That(result.Message, Does.StartWith("Nothing fires Knocker in vpetest now.")); + Assert.That(GameOutputs(host).Boards.Single().Outputs[0].Trigger, Is.Empty); + result = SetTrigger(host, "1:1", null); + Assert.That(result.Message, Does.StartWith("Knocker fires as the configuration says in vpetest.")); + Assert.That(SetTrigger(host, "1:3", "E2 White").Success, Is.True); + outputs = GameOutputs(host).Boards.Single().Outputs; + Assert.That(outputs.Take(3).Select(o => (o.Trigger, o.TriggerChanged)), Is.EqualTo(new[] { ("S1", false), ("", false), ("E2 White", false) }), + "what the configuration says is no change"); + Assert.That(File.Exists(Path.Combine(host.Factory.Store.Root, DofGameTriggers.FileName)), Is.False, "nothing is left changed"); + + host.Import(368, "vpetest,S1,0,E2 White,S4", null, "\"Rom\",\"Knocker\",\"\",\"Flasher\",\"\",\"\",\"Shaker\""); + Assert.That(SetTrigger(host, "1:6", "S9").Success, Is.True); + host.Import(368, "vpetest,S1,0,E2 White,S5", null, "\"Rom\",\"Knocker\",\"\",\"Flasher\",\"\",\"\",\"Shaker\""); + Assert.That(GameOutputs(host).Boards.Single().Outputs[5].Trigger, Is.EqualTo("S9"), "kept across imports"); + + // a colour on a toy an import made a single one: the configuration's fires it, and the user's stays to reset + Assert.That(SetTrigger(host, "1:3", "L5").Success, Is.True); + host.Import(368, "vpetest,S1,0,S7", null, "\"Rom\",\"Knocker\",\"\",\"Flasher\""); + var flasher = GameOutputs(host).Boards.Single().Outputs[2]; + Assert.That((flasher.Trigger, flasher.TriggerChanged, flasher.Note), Is.EqualTo(("S7", true, "Yours doesn't fit"))); + Assert.That(SetTrigger(host, "1:3", null).Success, Is.True); + flasher = GameOutputs(host).Boards.Single().Outputs[2]; + Assert.That((flasher.Trigger, flasher.TriggerChanged, flasher.Note), Is.EqualTo(("S7", false, ""))); + + // one on a port that became the green of an RGB toy goes with the toy's reset + Assert.That(SetTrigger(host, "1:4", "S8").Success, Is.True); + host.Import(368, "vpetest,S1,0,E2 White", null, "\"Rom\",\"Knocker\",\"\",\"Flasher\""); + flasher = GameOutputs(host).Boards.Single().Outputs[2]; + Assert.That((flasher.Trigger, flasher.TriggerChanged, flasher.Note), Is.EqualTo(("E2 White", true, "Yours doesn't fit"))); + Assert.That(SetTrigger(host, "1:3", null).Success, Is.True); + Assert.That(SetTrigger(host, "1:6", null).Success, Is.True); + Assert.That(File.Exists(Path.Combine(host.Factory.Store.Root, DofGameTriggers.FileName)), Is.False, "nothing is left of it"); + } + + [Test] + public void OffersTheSolenoidsLampsAndSwitchesOfAPinMameGame() + { + var mappings = new VisualPinball.Unity.MappingConfig { + Coils = new List { + new VisualPinball.Unity.CoilMapping { Id = "28", Description = "" }, + new VisualPinball.Unity.CoilMapping { Id = "28", Description = "Shaker" }, + new VisualPinball.Unity.CoilMapping { Id = "c_name", Description = "Not PinMAME's" }, + }, + Lamps = new List { + new VisualPinball.Unity.LampMapping { Id = "12", Description = "Shoot again" }, + new VisualPinball.Unity.LampMapping { Id = "3", Source = VisualPinball.Engine.Game.Engines.LampSource.GI, Description = "Playfield" }, + new VisualPinball.Unity.LampMapping { Id = "5", IsCoil = true, Description = "Flasher" }, + }, + Switches = new List { + new VisualPinball.Unity.SwitchMapping { Id = "25", Description = "Left outlane" }, + }, + }; + var outputs = DofPluginFactory.GameOutputsOf(mappings); + Assert.That(outputs.Select(o => (o.Trigger, o.Label)), Is.EqualTo(new[] { + ("S5", "Flasher"), ("S28", "Shaker"), ("L12", "Shoot again"), ("G3", "Playfield"), ("W25", "Left outlane"), + })); + Assert.That(DofPluginFactory.GameOutputsOf(new VisualPinball.Unity.MappingConfig()), Is.Empty); + } + + [UnityTest] + public IEnumerator FiresAToyWithWhatTheUserChoseForTheGame() + { + const int universe = 369; + var host = Host(); + host.Import(universe, "vpetest,S1,S2", null, "\"Rom\",\"Knocker\",\"Shaker\""); + Assert.That(SetTrigger(host, "1:1", "S7").Success, Is.True); + var feed = host.PublishFeed(); + yield return host.Await(host.Plugin.PrepareGameAsync(host.Game(), CancellationToken.None), "prepare"); + Assert.That(Directory.Exists(Path.Combine(host.Factory.Store.Root, DofGameConfig.FolderName)), Is.True, "the game runs a copy"); + yield return host.Await(host.Plugin.StartGameAsync(CancellationToken.None), "start"); + Assert.That(feed.BeginSnapshot(), Is.True); + feed.PublishSnapshot(RealtimeOutputKind.Solenoid, 1, 255); + feed.PublishSnapshot(RealtimeOutputKind.Solenoid, 2, 255); + feed.EndSnapshot(); + Expect(universe, f => f[0] == 0 && f[1] == 255, "S1 fires the knocker no more; S2 still fires the shaker"); + var mark = _capture.Count(universe); + feed.Publish(RealtimeOutputKind.Solenoid, 7, 255); + Expect(universe, f => f[0] == 255, "S7 fires the knocker", mark); + yield return host.Await(host.Plugin.StopGameAsync(CancellationToken.None), "stop"); + yield return host.Await(host.Plugin.Quiescence, "quiescence"); + Assert.That(File.ReadAllText(Path.Combine(host.Factory.Store.Active.ConfigDir, "directoutputconfig.ini")), Does.Contain("vpetest,S1,S2"), + "the configuration itself is as imported"); + } + [Test] public void ListsTheRomsOfTheConfiguration() { diff --git a/VisualPinball.Engine.DOF/Configuration/DofGameConfig.cs b/VisualPinball.Engine.DOF/Configuration/DofGameConfig.cs new file mode 100644 index 0000000..3a541ff --- /dev/null +++ b/VisualPinball.Engine.DOF/Configuration/DofGameConfig.cs @@ -0,0 +1,157 @@ +// Visual Pinball Engine +// Copyright (C) 2026 freezy and VPE Team +// +// SPDX-License-Identifier: GPL-3.0-or-later + +using System; +using System.Collections.Generic; +using System.IO; +using System.Linq; +using System.Text; +using System.Xml.Linq; + +namespace VisualPinball.Engine.DOF.Configuration +{ + /// + /// The configuration a game runs with when the user changed what fires its toys (): a copy of + /// the revision's configuration folder whose rows of the game have the user's settings, in <root>/game-config. + /// libdof reads nothing outside the folder it gets, so the copy has all of it; the revision stays as it was imported. + /// + public static class DofGameConfig + { + public const string FolderName = "game-config"; + + // byte for byte: a configuration may have bytes that aren't UTF-8, in names of other rows + private static readonly Encoding Bytes = Encoding.GetEncoding(28591); + + /// + /// Builds the copy for the rows a game uses, when the user changed any of them; replaces the copy of a previous game. + /// + /// The configuration. + /// The revision's catalog: its devices tell the RGB toys. + /// The store's folder, next to the revisions. + /// The rows the game uses, one per device (). + /// What the user changed. + /// Gets a line per change that could not be made, such as a row that changed since. + /// The base path for libdof, or null when the user changed none of the rows, so the game uses the revision. + /// The copy can't be written, such as when another game still uses it. + public static string Build(DofRevision revision, DofCatalog catalog, string root, IEnumerable rows, DofGameTriggers triggers, List problems) + { + var changes = (rows ?? Enumerable.Empty()) + .Select(r => (Row: r, Settings: (triggers ?? DofGameTriggers.None).Of(r.Rom, r.Device))) + .Where(c => c.Settings.Count > 0) + .ToList(); + if (changes.Count == 0) { + return null; + } + var basePath = Path.Combine(root, FolderName); + var configDir = Path.Combine(basePath, DofRevision.ConfigFolder); + if (Directory.Exists(basePath)) { + Directory.Delete(basePath, true); + } + Copy(revision.ConfigDir, configDir); + + foreach (var (row, settings) in changes) { + var device = catalog.Devices.FirstOrDefault(d => d.Number == row.Device); + if (device == null) { + continue; + } + var path = Path.Combine(configDir, device.FileName); + var text = Bytes.GetString(File.ReadAllBytes(path)); + var changed = DofIniRow.Parse(text, row.Rom); + if (changed == null) { + continue; + } + var rgb = RgbStarts(device); + foreach (var (port, setting) in settings) { + var next = Change(changed, rgb, port, setting, out var problem); + if (next == null) { + problems?.Add($"Device {row.Device}, port {port}: {problem}"); + } else { + changed = next; + } + } + File.WriteAllBytes(path, Bytes.GetBytes(changed.ReplaceIn(text))); + } + + // the global config names the folder it is in + var global = Path.Combine(configDir, DofGlobalConfig.FileName); + if (File.Exists(global)) { + var document = XDocument.Load(global); + var native = DofPaths.ToNative(configDir); + foreach (var element in document.Root?.Elements() ?? Enumerable.Empty()) { + switch (element.Name.LocalName) { + case "IniFilesPath": + element.Value = native; + break; + case "CabinetConfigFilePattern": + case "ShapeDefinitionFilePattern": + if (!string.IsNullOrWhiteSpace(element.Value)) { + element.Value = Path.Combine(native, Path.GetFileName(element.Value.Trim())); + } + break; + } + } + DofXml.Save(document, global); + } + return basePath; + } + + /// + /// The first ports of a device's RGB toys, as the settings show its outputs: from port 1 up, a port a colour column + /// starts on and the two after it, unless an earlier toy takes it. + /// + public static ISet RgbStarts(DofCatalogDevice device) + { + var starts = new HashSet(); + var next = 1; + foreach (var port in device.RgbPorts.OrderBy(p => p)) { + if (port >= next) { + starts.Add(port); + next = port + 3; + } + } + return starts; + } + + /// + /// A row with the toy on a port fired by the user's setting, made fit for the toy as the configuration has it now: an + /// import may have made an RGB toy of a single one, or put the green or blue of one on the port. Null with why not. + /// + /// The game's row. + /// The first ports of the device's RGB toys (). + /// The toy's first port. + /// The user's setting, empty for nothing. + /// Why it can't be, or null. + public static DofIniRow Change(DofIniRow row, ISet rgb, int port, string setting, out string problem) + { + if (rgb.Any(start => port > start && port <= start + 2)) { + problem = "The port is part of an RGB toy now, which is changed on its first port."; + return null; + } + var width = rgb.Contains(port) ? 3 : 1; + var fit = DofIniRow.Fit(setting, width == 3, out problem); + return fit == null ? null : row.With(port, width, fit, out problem); + } + + /// Deletes the copy of a previous game, if any. + public static void Delete(string root) + { + var basePath = Path.Combine(root, FolderName); + if (Directory.Exists(basePath)) { + Directory.Delete(basePath, true); + } + } + + private static void Copy(string from, string to) + { + Directory.CreateDirectory(to); + foreach (var file in Directory.GetFiles(from)) { + File.Copy(file, Path.Combine(to, Path.GetFileName(file))); + } + foreach (var folder in Directory.GetDirectories(from)) { + Copy(folder, Path.Combine(to, Path.GetFileName(folder))); + } + } + } +} diff --git a/VisualPinball.Engine.DOF/Configuration/DofGameTriggers.cs b/VisualPinball.Engine.DOF/Configuration/DofGameTriggers.cs new file mode 100644 index 0000000..a5cbe76 --- /dev/null +++ b/VisualPinball.Engine.DOF/Configuration/DofGameTriggers.cs @@ -0,0 +1,132 @@ +// Visual Pinball Engine +// Copyright (C) 2026 freezy and VPE Team +// +// SPDX-License-Identifier: GPL-3.0-or-later + +using System; +using System.Collections.Generic; +using System.Globalization; +using System.IO; +using System.Linq; +using System.Text; + +namespace VisualPinball.Engine.DOF.Configuration +{ + /// + /// What the user changed of what fires the toys in a game: per row of an ini device, the setting of the toy that starts at a + /// port, such as S28 Blink for the shaker, or nothing. A game gets them in a copy of the configuration + /// (). + /// + /// + /// Kept next to the revisions and the output wiring (<root>/game-triggers.txt, one + /// row device port setting line per toy, the setting empty for nothing), for every configuration: the + /// rows go by the ROM they name, and the ports by the configuration's toys, so they survive a new import. Immutable; + /// changes return new triggers. + /// + public sealed class DofGameTriggers + { + public const string FileName = "game-triggers.txt"; + + /// The longest setting kept. + public const int MaxLength = 512; + + public static readonly DofGameTriggers None = new DofGameTriggers(new Dictionary()); + + private readonly IReadOnlyDictionary _settings; + + private DofGameTriggers(IReadOnlyDictionary settings) { _settings = settings; } + + /// Whether the user changed nothing. + public bool IsEmpty => _settings.Count == 0; + + /// The setting the user gave the toy at a port of a row of a device, empty for nothing; null when unchanged. + public string SettingOf(string row, int device, int port) => _settings.TryGetValue(new Key(row, device, port), out var setting) ? setting : null; + + /// The toys the user changed of a row of a device, by their first port. + public IReadOnlyList<(int Port, string Setting)> Of(string row, int device) + => _settings.Where(e => e.Key.Device == device && Key.Rows.Equals(e.Key.Row, (row ?? "").Trim())) + .OrderBy(e => e.Key.Port).Select(e => (e.Key.Port, e.Value)).ToList(); + + /// The triggers with a toy's setting changed, or given back to the configuration for null. + public DofGameTriggers With(string row, int device, int port, string setting) + { + var settings = _settings.ToDictionary(e => e.Key, e => e.Value); + var key = new Key(row, device, port); + if (setting == null) { + settings.Remove(key); + } else { + settings[key] = Clean(setting); + } + return new DofGameTriggers(settings); + } + + /// Reads the triggers of a store's folder; none when it has no file. A line that names no toy is left out. + public static DofGameTriggers Load(string root) + { + var path = Path.Combine(root, FileName); + if (Directory.Exists(path)) { + throw new IOException(path + " is a folder, not the game triggers."); + } + if (!File.Exists(path)) { + return None; + } + var settings = new Dictionary(); + foreach (var line in File.ReadAllLines(path, Encoding.UTF8)) { + var parts = line.Split('\t'); + if (parts.Length != 4 || parts[0].Trim().Length == 0 + || !int.TryParse(parts[1].Trim(), NumberStyles.Integer, CultureInfo.InvariantCulture, out var device) + || !int.TryParse(parts[2].Trim(), NumberStyles.Integer, CultureInfo.InvariantCulture, out var port) + || device < 1 || device > DofOutputWiring.MaxDevice || port < 1 || port > DofOutputWiring.MaxOutput) { + continue; + } + settings[new Key(parts[0], device, port)] = Clean(parts[3]); + } + return new DofGameTriggers(settings); + } + + /// Replaces the triggers file of a store's folder in one step; deletes it when nothing is changed. + public void Save(string root) + { + var path = Path.Combine(root, FileName); + if (IsEmpty) { + if (File.Exists(path)) { + File.Delete(path); + } + return; + } + Directory.CreateDirectory(root); + var text = new StringBuilder(); + foreach (var entry in _settings.OrderBy(e => e.Key.Row, StringComparer.OrdinalIgnoreCase).ThenBy(e => e.Key.Device).ThenBy(e => e.Key.Port)) { + text.Append(entry.Key.Row).Append('\t').Append(entry.Key.Device.ToString(CultureInfo.InvariantCulture)).Append('\t') + .Append(entry.Key.Port.ToString(CultureInfo.InvariantCulture)).Append('\t').Append(entry.Value).Append('\n'); + } + var temp = path + ".tmp"; + File.WriteAllText(temp, text.ToString(), new UTF8Encoding(false)); + if (File.Exists(path)) { + File.Replace(temp, path, null); + } else { + File.Move(temp, path); + } + } + + // on one line, without tabs, and not too long + private static string Clean(string setting) + { + var text = new string((setting ?? "").Select(c => char.IsControl(c) ? ' ' : c).ToArray()).Trim(); + return DofToyNames.Truncate(text, MaxLength); + } + + private readonly struct Key : IEquatable + { + // ROM names as libdof compares them + internal static readonly StringComparer Rows = StringComparer.OrdinalIgnoreCase; + internal readonly string Row; + internal readonly int Device; + internal readonly int Port; + internal Key(string row, int device, int port) { Row = (row ?? "").Trim(); Device = device; Port = port; } + public bool Equals(Key other) => Rows.Equals(Row, other.Row) && Device == other.Device && Port == other.Port; + public override bool Equals(object obj) => obj is Key other && Equals(other); + public override int GetHashCode() => (Rows.GetHashCode(Row) * 397 ^ Device) * 397 ^ Port; + } + } +} diff --git a/VisualPinball.Engine.DOF/Configuration/DofIniFile.cs b/VisualPinball.Engine.DOF/Configuration/DofIniFile.cs index 2453d7e..057e992 100644 --- a/VisualPinball.Engine.DOF/Configuration/DofIniFile.cs +++ b/VisualPinball.Engine.DOF/Configuration/DofIniFile.cs @@ -281,7 +281,7 @@ private void ReadPorts(IEnumerable rows, IReadOnlyListThe [Variables DOF] section: name=value per line, the last of a name counting. - private static IReadOnlyList> Variables(IEnumerable lines) + internal static IReadOnlyList> Variables(IEnumerable lines) { var variables = new List>(); foreach (var line in lines) { @@ -299,7 +299,7 @@ private static IReadOnlyList> Variables(IEnumerable /// The [TableVariables] section: rom,name=value/name={value with /} per line, the first of a name counting /// (libdof's TableVariablesDictionary). /// - private static IReadOnlyDictionary>> TableVariables(IEnumerable lines) + internal static IReadOnlyDictionary>> TableVariables(IEnumerable lines) { var tables = new Dictionary>>(StringComparer.Ordinal); foreach (var line in lines) { @@ -354,7 +354,7 @@ private static IReadOnlyDictionary>> T } /// The row with the variables of its ROM replaced, then the global ones, each named with or without its @s. - private static string Resolve(string row, IReadOnlyList> variables, + internal static string Resolve(string row, IReadOnlyList> variables, IReadOnlyDictionary>> tableVariables) { var d = row.Trim(); @@ -408,7 +408,7 @@ private static string Delimited(string name) => (name.StartsWith("@", StringComparison.Ordinal) ? "" : "@") + name + (name.EndsWith("@", StringComparison.Ordinal) ? "" : "@"); /// Splits at a separator outside of brackets, as libdof splits a row into columns and a column into settings. - private static List Split(string data, char separator) + internal static List Split(string data, char separator) { var parts = new List(); int brackets = 0, start = 0; diff --git a/VisualPinball.Engine.DOF/Configuration/DofIniRow.cs b/VisualPinball.Engine.DOF/Configuration/DofIniRow.cs new file mode 100644 index 0000000..387b17c --- /dev/null +++ b/VisualPinball.Engine.DOF/Configuration/DofIniRow.cs @@ -0,0 +1,348 @@ +// Visual Pinball Engine +// Copyright (C) 2026 freezy and VPE Team +// +// SPDX-License-Identifier: GPL-3.0-or-later + +using System; +using System.Collections.Generic; +using System.IO; +using System.Linq; +using System.Text; + +namespace VisualPinball.Engine.DOF.Configuration +{ + /// + /// The row of an ini file a game uses, column by column as libdof numbers the ports: what fires a toy in the game, and a + /// change of it. + /// + /// + /// libdof starts each column at the port after the previous one's: three ports for a column with a colour, one for any + /// other, a 0 included. So the Config Tool writes three 0s for an RGB toy without effects, and one column + /// with a colour for one with effects. A change replaces the columns of a toy's ports as a whole and keeps the ports of the + /// columns after them. Immutable; a change returns a new row. + /// + public sealed class DofIniRow + { + /// What is written for a toy nothing fires. + public const string Nothing = "0"; + + /// The colour gives an RGB toy's setting without one. + public const string White = "#FFFFFF"; + + /// The ROM, as the row writes it. + public string Rom { get; } + /// The row as written, its variables kept. + public string Line => string.Join(",", _columns); + /// + /// Whether its columns can be changed: false when its variables take up columns of their own, so the ports of the + /// columns as written aren't known. + /// + public bool Editable { get; } + /// The last port the row reaches, 0 for none. + public int Extent => _starts.Count == 0 ? 0 : _starts[_starts.Count - 1] + _widths[_widths.Count - 1] - 1; + + // the columns as written (index 0 the ROM's), and as libdof reads them, their variables replaced + private readonly IReadOnlyList _columns; + private readonly IReadOnlyList _shown; + private readonly IReadOnlyList _resolved; + // from column 1 up to the last with data: the first port of each, and how many it takes + private readonly IReadOnlyList _starts; + private readonly IReadOnlyList _widths; + // the row's variables replaced, as libdof does before it reads the columns + private readonly Func _resolve; + + private DofIniRow(IReadOnlyList columns, Func resolve) + { + _columns = columns; + _resolve = resolve; + var resolved = DofIniFile.Split(resolve(string.Join(",", columns)), ','); + Rom = columns.Count > 0 ? columns[0].Trim() : ""; + Editable = columns.Count == resolved.Count; + _shown = Editable ? columns : resolved; + _resolved = resolved; + var last = resolved.Count - 1; + while (last > 0 && string.IsNullOrWhiteSpace(resolved[last])) { + last--; + } + var starts = new List(); + var widths = new List(); + var port = 1; + for (var i = 1; i <= last; i++) { + starts.Add(port); + widths.Add(Width(resolved[i])); + port += widths[widths.Count - 1]; + } + _starts = starts; + _widths = widths; + } + + /// Reads the row of a ROM of an ini file, the first one as libdof keeps it; null when the file has none. + /// The file can't be read. + /// The file is not a text file. + public static DofIniRow Read(string path, string rom) => Parse(DofIniFile.ReadText(path), rom); + + /// The row of a ROM of an ini file's text, the first one as libdof keeps it; null when the text has none. + public static DofIniRow Parse(string text, string rom) + { + var scan = Scan(text ?? ""); + var line = Find(text ?? "", scan.Rows, rom); + if (line == null) { + return null; + } + var variables = DofIniFile.Variables(scan.Variables); + var tableVariables = DofIniFile.TableVariables(scan.TableVariables); + return new DofIniRow(DofIniFile.Split(line.Trim(), ','), row => DofIniFile.Resolve(row, variables, tableVariables)); + } + + /// An ini file's text with the row of its ROM replaced by this one; the text as it was when it has none. + public string ReplaceIn(string text) + { + text ??= ""; + foreach (var (start, length) in Scan(text).Rows) { + if (string.Equals(RomOf(text.Substring(start, length)), Rom, StringComparison.OrdinalIgnoreCase)) { + return text.Substring(0, start) + Line + text.Substring(start + length); + } + } + return text; + } + + /// + /// What fires the toy on the ports from on: its column's settings as written; empty for nothing, + /// past the row's end or for 0s; null when the row's columns don't line up with the toy, such as a column with a + /// colour across two toys. + /// + /// The toy's first port. + /// How many ports it takes: 3 for an RGB toy, else 1. + public string SettingOf(int port, int width) + { + if (!TryCover(port, width, out var first, out var count)) { + return null; + } + if (count == 0 || Enumerable.Range(first, count).All(i => IsNothing(_shown[i]))) { + return ""; + } + return count == 1 ? _shown[first].Trim() : null; + } + + /// + /// The row with a toy's columns replaced by one with the setting, or by 0s for nothing; the columns after it keep + /// their ports. A toy past the row's end gets 0s up to it. + /// + /// The toy's first port. + /// How many ports it takes: 3 for an RGB toy, else 1. + /// The setting as libdof takes it (see ), empty for nothing. + /// Why the row can't be changed, or null. + /// The changed row, or null with a problem. + public DofIniRow With(int port, int width, string setting, out string problem) + { + problem = null; + if (!Editable) { + problem = $"The row of {Rom} uses variables that take up columns of their own, so VPE can't change its columns."; + return null; + } + if (port < 1 || port > DofOutputWiring.MaxOutput) { + problem = $"There is no port {port}."; + return null; + } + if (!TryCover(port, width, out var first, out var count)) { + problem = $"In the row of {Rom}, a column with a colour takes in port {port} or the ports next to it, so it can't change on its own."; + return null; + } + // a setting with a colour takes three ports: on another toy it would drive the ones next to it, or move the columns after it + if (!string.IsNullOrEmpty(setting) && Width(setting) != width) { + problem = width == 3 + ? $"\"{setting}\" has no colour, but the toy on port {port} is an RGB toy." + : $"\"{setting}\" has a colour, but the toy on port {port} takes one output."; + return null; + } + var replacement = string.IsNullOrEmpty(setting) ? Enumerable.Repeat(Nothing, width).ToList() : new List { setting }; + var columns = _columns.ToList(); + if (count == 0) { + if (string.IsNullOrEmpty(setting)) { + return this; + } + // up to the toy: the row's columns with data, then a 0 per port + columns = columns.Take(_starts.Count + 1).ToList(); + for (var next = Extent + 1; next < port; next++) { + columns.Add(Nothing); + } + columns.AddRange(replacement); + } else { + var before = Enumerable.Range(first, count).Sum(i => _widths[i - 1]); + var after = replacement.Sum(Width); + if (first + count - 1 < _starts.Count && before != after) { + problem = $"The setting takes {after} ports where the row has {before}, so the toys after it would move."; + return null; + } + columns.RemoveRange(first, count); + columns.InsertRange(first, replacement); + } + // as libdof reads it, its variables replaced: the setting on the toy's ports alone, every other toy where it was + var changed = new DofIniRow(columns, _resolve); + if (!changed.Editable || !changed.Others(port, width).SequenceEqual(Others(port, width)) + || !string.IsNullOrEmpty(setting) && !(changed.TryCover(port, width, out var at, out var taken) && taken == 1 && changed._widths[at - 1] == width)) { + problem = $"\"{setting}\" would move the toys after it in the row of {Rom}: write a single trigger, without commas or the configuration's variables."; + return null; + } + return changed; + } + + // The columns libdof reads off the toy's ports, with something on them: their first port, width and setting. + private IEnumerable<(int Start, int Width, string Setting)> Others(int port, int width) + => Enumerable.Range(0, _starts.Count) + .Where(i => (_starts[i] + _widths[i] - 1 < port || _starts[i] > port + width - 1) && !IsNothing(_resolved[i + 1])) + .Select(i => (_starts[i], _widths[i], _resolved[i + 1].Trim())); + + /// + /// A setting as the user wrote it, made fit for a toy: on one line, an RGB toy's parts without a colour in white; empty + /// for nothing. + /// + /// Settings such as S28 Blink, several separated by /. + /// Whether the toy is an RGB toy, which takes a colour. + /// Why libdof can't take it, or null. + /// The setting, or null with a problem. + public static string Fit(string setting, bool rgb, out string problem) + { + problem = null; + var text = new string((setting ?? "").Select(c => char.IsControl(c) ? ' ' : c).ToArray()).Trim(); + if (text.Length == 0 || text == Nothing) { + return ""; + } + if (text.Any(c => c > '~')) { + problem = "Use the letters, digits and signs of a DOF trigger only."; + return null; + } + if (text.Contains(',')) { + problem = "A trigger can't have a comma: separate several with a slash."; + return null; + } + if (text.Contains('@')) { + problem = "A trigger can't use the configuration's variables: write what they stand for."; + return null; + } + // libdof reads an open bracket to its close, past the column's end + var depth = 0; + foreach (var c in text) { + depth += c == '(' ? 1 : c == ')' ? -1 : 0; + if (depth < 0) { + break; + } + } + if (depth != 0) { + problem = "The brackets of the trigger don't match."; + return null; + } + var parts = new List(); + foreach (var part in DofIniFile.Split(text, '/').Select(p => p.Trim()).Where(p => p.Length > 0)) { + var colour = DofIniFile.Colour(part); + if (colour == null) { + problem = $"DOF doesn't understand \"{part}\": write a trigger such as S28, L12 Blink or W25 500."; + return null; + } + if (colour == true && !rgb) { + problem = $"\"{part}\" has a colour, but the toy takes one output: leave out the colour."; + return null; + } + // in a colour every configuration knows, whatever colours its file names + parts.Add(colour == false && rgb ? part + " " + White : part); + } + return string.Join("/", parts); + } + + // The columns that take the toy's ports: from one that starts at its first port to one that ends at its last, or at the + // row's end; none past the row's end. False when a column takes ports inside and outside of it. + private bool TryCover(int port, int width, out int first, out int count) + { + first = -1; + count = 0; + var end = port + width - 1; + for (var i = 0; i < _starts.Count; i++) { + var start = _starts[i]; + var last = start + _widths[i] - 1; + if (last < port || start > end) { + continue; + } + if (start < port || last > end) { + return false; + } + if (first < 0) { + first = i + 1; + } + count++; + } + // a toy's ports are in a row: a toy that ends past the row's end ends with it + return count == 0 || _starts[first - 1] == port; + } + + private static bool IsNothing(string column) + { + var text = column.Trim(); + return text.Length == 0 || text == Nothing; + } + + private static int Width(string column) + => DofIniFile.Split(column, '/').Where(s => !string.IsNullOrWhiteSpace(s)).Any(s => DofIniFile.Colour(s) == true) ? 3 : 1; + + private static string RomOf(string line) => DofIniFile.Split(line.Trim(), ',').FirstOrDefault()?.Trim() ?? ""; + + private static string Find(string text, IEnumerable<(int Start, int Length)> rows, string rom) + { + foreach (var (start, length) in rows) { + var line = text.Substring(start, length); + if (string.Equals(RomOf(line), rom?.Trim(), StringComparison.OrdinalIgnoreCase)) { + return line; + } + } + return null; + } + + /// + /// Where the rows libdof reads are in the text, those of the first [Config DOF] section or else of the first + /// [Config outs] one, and the lines of the variable sections; as reads them. + /// + private static readonly char[] LineEnds = { '\r', '\n' }; + + private static (List<(int Start, int Length)> Rows, List Variables, List TableVariables) Scan(string text) + { + List<(int, int)> dof = null, outs = null, rows = null; + var variables = new List(); + var tableVariables = new List(); + string section = null; + var position = 0; + while (position < text.Length) { + // a line ends as libdof's reader ends it: at \r\n, \n or \r alone + var end = text.IndexOfAny(LineEnds, position); + var next = end < 0 ? text.Length : end + (text[end] == '\r' && end + 1 < text.Length && text[end + 1] == '\n' ? 2 : 1); + var length = (end < 0 ? text.Length : end) - position; + var raw = text.Substring(position, length); + var line = raw.Trim(); + var start = position; + position = next; + if (line.Length == 0) { + continue; + } + if (line.Length > 2 && line[0] == '[' && line[line.Length - 1] == ']') { + section = line; + rows = null; + if (string.Equals(line, "[Config DOF]", StringComparison.OrdinalIgnoreCase) && dof == null) { + rows = dof = new List<(int, int)>(); + } else if (string.Equals(line, "[Config outs]", StringComparison.OrdinalIgnoreCase) && outs == null) { + rows = outs = new List<(int, int)>(); + } + continue; + } + if (section == null || line[0] == '#') { + continue; + } + if (string.Equals(section, "[Variables DOF]", StringComparison.OrdinalIgnoreCase)) { + variables.Add(line); + } else if (string.Equals(section, "[TableVariables]", StringComparison.OrdinalIgnoreCase)) { + tableVariables.Add(line); + } else if (rows != null && !line.StartsWith("//", StringComparison.Ordinal)) { + rows.Add((start, length)); + } + } + return (dof ?? outs ?? new List<(int, int)>(), variables, tableVariables); + } + } +}