diff --git a/VisualPinball.Engine.DOF.Test/DofInstanceTests.cs b/VisualPinball.Engine.DOF.Test/DofInstanceTests.cs index 0be75b8..b5b7398 100644 --- a/VisualPinball.Engine.DOF.Test/DofInstanceTests.cs +++ b/VisualPinball.Engine.DOF.Test/DofInstanceTests.cs @@ -171,7 +171,7 @@ private void BoundedCleanup(DofInstance dof) [Test] public void ReportsAbiAndLibdofVersion() { - Assert.That(DofLibrary.NativeAbiVersion, Is.EqualTo(6)); + Assert.That(DofLibrary.NativeAbiVersion, Is.EqualTo(7)); Assert.That(DofLibrary.LibdofVersion, Does.Match(@"^\d+\.\d+\.\d+")); } diff --git a/VisualPinball.Engine.DOF.Test/DofOutputWiringTests.cs b/VisualPinball.Engine.DOF.Test/DofOutputWiringTests.cs index 44766c6..36c0089 100644 --- a/VisualPinball.Engine.DOF.Test/DofOutputWiringTests.cs +++ b/VisualPinball.Engine.DOF.Test/DofOutputWiringTests.cs @@ -80,10 +80,102 @@ public void SavesAndLoads() public void LeavesOutLinesThatAreNoPermutation() { Directory.CreateDirectory(_root); - File.WriteAllText(Path.Combine(_root, DofOutputWiring.FileName), "1=2,1\n2=1,1\n3=3,1\nx=1\n0=1\n4=\n5=2,1,3\n6=2,,1\n"); + File.WriteAllText(Path.Combine(_root, DofOutputWiring.FileName), "1=2,1\n2=1,1\n3=3,1\nx=1\n0=1\n4=\n5=2,1,3\n6=2,,1\n7=0,1\n8=-1,1\n9=0,0\n"); var loaded = DofOutputWiring.Load(_root); - Assert.That(loaded.Devices, Is.EqualTo(new[] { 1, 5 })); + Assert.That(loaded.Devices, Is.EqualTo(new[] { 1, 5, 7, 9 })); Assert.That(loaded.MapOf(5), Is.EqualTo(new[] { 2, 1 }), "trailing ports that keep their own are left out"); + Assert.That(loaded.MapOf(7), Is.EqualTo(new[] { -1, 1 }), "0 is a port that drives nothing, which the native layer takes as -1"); + Assert.That(loaded.PortOn(9, 2), Is.EqualTo(DofOutputWiring.Nothing), "two ports may drive nothing"); + } + + [Test] + public void AnOutputWhosePortMovedAwayDrivesNothing() + { + var wiring = DofOutputWiring.None.Remove(1, new[] { 3 }); + Assert.That(wiring.OutputOf(1, 3), Is.EqualTo(DofOutputWiring.Nothing)); + Assert.That(wiring.PortOn(1, 3), Is.EqualTo(DofOutputWiring.Nothing)); + Assert.That(wiring.PortOn(1, 4), Is.EqualTo(4), "past the map, every port drives its own"); + Assert.That(wiring.Extent(1), Is.EqualTo(3), "the output stays on the board, to be given a toy again"); + + // swapping an output nothing drives leaves the other one driven by nothing + wiring = wiring.Swap(1, 3, 7, 1); + Assert.That(wiring.OutputOf(1, 7), Is.EqualTo(3)); + Assert.That(wiring.PortOn(1, 7), Is.EqualTo(DofOutputWiring.Nothing)); + Assert.That(wiring.Extent(1), Is.EqualTo(7)); + } + + [Test] + public void AssigningSwapsWithWhereTheToyWas() + { + // a toy on port 16 goes to output 14; what 14 had goes to 16 + var wiring = DofOutputWiring.None.Assign(1, new[] { 16 }, 14); + Assert.That(wiring.OutputOf(1, 16), Is.EqualTo(14)); + Assert.That(wiring.OutputOf(1, 14), Is.EqualTo(16)); + + // an RGB toy one output further: the output it leaves takes what it moved onto + wiring = DofOutputWiring.None.Assign(1, new[] { 3, 4, 5 }, 4); + Assert.That(Enumerable.Range(3, 3).Select(p => wiring.OutputOf(1, p)), Is.EqualTo(new[] { 4, 5, 6 })); + Assert.That(wiring.OutputOf(1, 6), Is.EqualTo(3)); + } + + [Test] + public void AssigningAToyOnNoOutputLeavesWhatItDisplacesOnNone() + { + var wiring = DofOutputWiring.None.Remove(1, new[] { 5 }).Assign(1, new[] { 5 }, 2); + Assert.That(wiring.OutputOf(1, 5), Is.EqualTo(2)); + Assert.That(wiring.OutputOf(1, 2), Is.EqualTo(DofOutputWiring.Nothing)); + Assert.That(wiring.PortOn(1, 5), Is.EqualTo(DofOutputWiring.Nothing), "output 5 lost its port"); + + // a new toy on a port past the board: what output 2 had drives nothing, the board is no longer for it + wiring = DofOutputWiring.None.Assign(1, new[] { 40 }, 2, true); + Assert.That(wiring.OutputOf(1, 40), Is.EqualTo(2)); + Assert.That(wiring.OutputOf(1, 2), Is.EqualTo(DofOutputWiring.Nothing)); + Assert.That(wiring.Extent(1), Is.EqualTo(40), "the ports in between keep their own; the output the port left stays on the board"); + Assert.That(wiring.PortOn(1, 33), Is.EqualTo(33)); + Assert.Throws(() => wiring.Assign(1, new[] { 2, 2 }, 1), "a port twice"); + } + + [Test] + public void SavesAndLoadsPortsThatDriveNothing() + { + var wiring = DofOutputWiring.None.Assign(1, new[] { 40 }, 2, true).Remove(1, new[] { 7 }); + wiring.Save(_root); + var loaded = DofOutputWiring.Load(_root); + Assert.That(loaded.MapOf(1), Is.EqualTo(wiring.MapOf(1))); + Assert.That(loaded.OutputOf(1, 2), Is.EqualTo(DofOutputWiring.Nothing)); + Assert.That(loaded.OutputOf(1, 40), Is.EqualTo(2)); + } + + [Test] + public void KeepsTheToysTheUserNamed() + { + var names = DofToyNames.None.With(1, 40, " Gear\nmotor ").With(2, 33, "Fan"); + Assert.That(names.NameOf(1, 40), Is.EqualTo("Gear motor"), "on one line, without the spaces around it"); + names.Save(_root); + var loaded = DofToyNames.Load(_root); + Assert.That(loaded.NameOf(1, 40), Is.EqualTo("Gear motor")); + Assert.That(loaded.PortsOf(2), Is.EqualTo(new[] { 33 })); + loaded.With(1, 40, " ").With(2, 33, "").Save(_root); + Assert.That(File.Exists(Path.Combine(_root, DofToyNames.FileName)), Is.False, "no file without a name"); + Assert.That(DofToyNames.Clean(new string('x', 100)).Length, Is.EqualTo(DofToyNames.MaxLength)); + + // cut before a character of two UTF-16 units, not inside it, so the name saved is the name shown + var target = new string('x', DofToyNames.MaxLength - 1) + char.ConvertFromUtf32(0x1F3AF); + Assert.That(DofToyNames.Clean(target), Is.EqualTo(new string('x', DofToyNames.MaxLength - 1))); + DofToyNames.None.With(1, 40, target).Save(_root); + Assert.That(DofToyNames.Load(_root).NameOf(1, 40), Is.EqualTo(DofToyNames.None.With(1, 40, target).NameOf(1, 40))); + } + + [Test] + public void KeepsAnOutputNothingDrivesOnTheBoard() + { + // swapped, then the output the port moved to cleared: that output stays on the board to be given a toy again + var wiring = DofOutputWiring.None.Swap(17, 2, 60, 1).Remove(17, new[] { 2 }); + Assert.That(wiring.PortOn(17, 60), Is.EqualTo(DofOutputWiring.Nothing)); + Assert.That(wiring.Extent(17), Is.EqualTo(60)); + // a toy the user added is on a port far past the board's: only the output it is on counts + var added = DofOutputWiring.None.Assign(17, new[] { DofToyNames.FirstPort }, 5, true); + Assert.That(added.Extent(17), Is.EqualTo(5)); } } } diff --git a/VisualPinball.Engine.DOF.Unity/Runtime/Player/DofHardware.cs b/VisualPinball.Engine.DOF.Unity/Runtime/Player/DofHardware.cs index 9b22fe8..b6c95d2 100644 --- a/VisualPinball.Engine.DOF.Unity/Runtime/Player/DofHardware.cs +++ b/VisualPinball.Engine.DOF.Unity/Runtime/Player/DofHardware.cs @@ -97,13 +97,16 @@ internal static class DofPortTest /// How long the controller units have to confirm that their outputs are off, once DOF has started. internal static readonly TimeSpan DefaultConfirmTimeout = TimeSpan.FromSeconds(3); - /// An output to test: the device (N of directoutputconfigN.ini) and its port, from 1. + /// + /// An output to test: the device (N of directoutputconfigN.ini) and its port, from 1; or the number of an output nothing + /// drives, as a negative port. + /// internal static bool TryParse(string id, out int device, out int port) { device = port = 0; var separator = id?.IndexOf(':') ?? -1; return separator > 0 && int.TryParse(id.Substring(0, separator), out device) && int.TryParse(id.Substring(separator + 1), out port) - && device > 0 && port > 0; + && device > 0 && port != 0; } internal static string Id(int device, int port) => device + ":" + port; diff --git a/VisualPinball.Engine.DOF.Unity/Runtime/Player/DofPluginFactory.cs b/VisualPinball.Engine.DOF.Unity/Runtime/Player/DofPluginFactory.cs index dea8912..2637d2f 100644 --- a/VisualPinball.Engine.DOF.Unity/Runtime/Player/DofPluginFactory.cs +++ b/VisualPinball.Engine.DOF.Unity/Runtime/Player/DofPluginFactory.cs @@ -27,7 +27,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, IPluginSystemDefaults + internal sealed class DofPluginFactory : IPlayerPluginFactory, IPluginSettingsProvider, IPluginSettingsInfoProvider, IPluginOutputMapProvider, IPluginOutputRearranger, IPluginOutputAssigner, IPluginSystemDefaults { internal const string Id = "org.visualpinball.dof"; private const string PinMameId = "org.visualpinball.pinmame"; @@ -203,7 +203,7 @@ internal static NLog.LogLevel LogLevelOf(DofLogLevel level) new PluginSettingsGroup("Import an existing installation", "A complete DOF configuration, such as the Config folder of DirectOutput. Importing it replaces the whole configuration; the folder is copied, never changed.", new PluginField("ImportFolder", "Configuration folder", SettingKind.Folder) { Default = "", FullWidth = true }, new PluginField("ImportFolderAction", "Import", SettingKind.Action) { Provider = "import-folder", AttachTo = "ImportFolder" }), - new PluginSettingsGroup("Hardware", "The connected boards DOF knows, found without opening them, and what the configuration wires to their outputs. Testing an output turns it on for a moment, outside a game; All off turns every output off, such as one a game that crashed left on. Where your cabling differs from the configuration, rearrange the outputs: games and tests use it at once, with every configuration you import.", + new PluginSettingsGroup("Hardware", "The connected boards DOF knows, found without opening them, and what the configuration wires to their outputs. Testing an output turns it on for a moment, outside a game; All off turns every output off, such as one a game that crashed left on. Where your cabling differs from the configuration, choose what an output drives or rearrange the outputs: games and tests use it at once, with every configuration you import.", new PluginField("Devices", "Connected boards", SettingKind.Info) { Provider = "devices" }, new PluginField("Detect", "Detect again", SettingKind.Action) { Provider = "detect", AttachTo = "Devices" }, new PluginField("AllOff", "All off", SettingKind.Action) { Provider = "all-off", AttachTo = "Devices" }, @@ -521,7 +521,8 @@ private PluginOutputMap DescribeOutputs(string provider, PluginOutputLeases leas var catalog = CatalogOf(revision); var detected = DetectedBoards(catalog); var wiring = ReadWiring(store.Root) ?? DofOutputWiring.None; - var boards = catalog.Devices.Select(device => Board(device, detected, Reach(catalog, detected, device.Number), wiring)).ToList(); + var names = ReadNames(store.Root) ?? DofToyNames.None; + var boards = catalog.Devices.Select(device => Board(device, detected, Reach(catalog, detected, device.Number), wiring, names)).ToList(); return new PluginOutputMap(boards, "The configuration has no ini files, so it assigns nothing to the outputs.", leases == null ? NoTestsYet : ""); } @@ -567,50 +568,160 @@ private static int FixedOutputs(string type) /// /// The outputs of an ini device: what its header names on each port, and the three ports of each RGB toy as its red, - /// green and blue, all named after the toy. Named after a board of its number when one is detected. + /// green and blue, all named after the toy. Named after a board of its number when one is detected. Lists the toys its + /// outputs can be given: the header's and the user's. /// /// The highest output DOF drives on the device with or without a row (). /// /// How the cabling differs from the configuration: each output shows the port that drives it, with a note where that is - /// another one. The ids stay the ports', so a test of an output pulses the port that drives it. + /// another one. The ids stay the ports', so a test of an output pulses the port that drives it; an output nothing drives + /// has its number as a negative port. /// - internal static PluginOutputBoard Board(DofCatalogDevice device, IReadOnlyList detected, int mapped = 0, DofOutputWiring wiring = null) + /// The toys the user added, on ports past the configuration's. + internal static PluginOutputBoard Board(DofCatalogDevice device, IReadOnlyList detected, int mapped = 0, DofOutputWiring wiring = null, + DofToyNames names = null) { wiring ??= DofOutputWiring.None; - var ports = Ports(device, mapped, wiring); - var outputs = new List(ports.Count); - for (var number = 1; number <= ports.Count; number++) { + var ports = new DevicePorts(device, mapped, wiring, names); + var outputs = new List(ports.Outputs); + for (var number = 1; number <= ports.Outputs; number++) { var port = wiring.PortOn(device.Number, number); - var (name, channel) = ports[port - 1]; + if (port == DofOutputWiring.Nothing) { + outputs.Add(new PluginOutput(DofPortTest.Id(device.Number, -number), number, "")); + continue; + } + var (name, channel) = ports.At(port); + var toy = ports.ToyOf(port); outputs.Add(new PluginOutput(DofPortTest.Id(device.Number, port), number, name, channel) { - Note = port != number ? $"Moved from {port}" : "", + // a toy the user added is on no output of the configuration's + Note = port == number || ports.Added(port) ? "" : $"Moved from {port}", + // an RGB toy the header doesn't name can't be picked, but still be swapped or emptied; nor a toy of a device + // the board lists no toys for + Toy = toy > 0 && ports.At(toy).Name.Length > 0 && device.Number <= DofOutputWiring.MaxDevice ? ToyId(toy) : "", }); } var board = detected.FirstOrDefault(d => d.Device == device.Number); - return board != null + var result = board != null ? new PluginOutputBoard($"{board.Type} {device.Number}", $"Device {device.Number} ยท {device.FileName}", outputs) { Rearrangeable = true } : new PluginOutputBoard($"Device {device.Number}", device.FileName, outputs) { Rearrangeable = true }; + if (device.Number <= DofOutputWiring.MaxDevice) { + result.Toys = ports.Toys.Where(t => t.Name.Length > 0).Select(t => new PluginOutputToy(ToyId(t.Port), t.Name, t.Rgb)).ToList(); + result.AcceptsNewToys = true; + } + return result; + } + + // A toy by its first port: the red one of an RGB toy. + private static string ToyId(int port) => "p" + port.ToString(CultureInfo.InvariantCulture); + + private static bool TryParseToy(string id, out int port) + { + port = 0; + return id != null && id.Length > 1 && id[0] == 'p' && int.TryParse(id.Substring(1), NumberStyles.None, CultureInfo.InvariantCulture, out port) && port > 0; } - /// What the configuration puts on each port of an ini device, from port 1: the header's name and the colour of an RGB toy's port. - private static IReadOnlyList<(string Name, PluginOutputChannel Channel)> Ports(DofCatalogDevice device, int mapped, DofOutputWiring wiring) + /// + /// What is on the ports of an ini device: the configuration's header names, the colours of its RGB toys and the names of + /// the toys the user added. Shows as many outputs as the board or the configuration has. + /// + private sealed class DevicePorts { - var count = System.Math.Max(device.Number >= 1 && device.Number <= 16 ? System.Math.Max(device.PortCount, LedWizOutputs) : device.PortCount, mapped); - count = System.Math.Max(count, wiring.Extent(device.Number)); - var rgb = new HashSet(device.RgbPorts); - var ports = new List<(string, PluginOutputChannel)>(count); - for (var port = 1; port <= count; port++) { - var name = port <= device.Ports.Count ? device.Ports[port - 1]?.Trim() ?? "" : ""; - if (rgb.Contains(port) && port + 2 <= count) { - ports.Add((name, PluginOutputChannel.Red)); - ports.Add((name, PluginOutputChannel.Green)); - ports.Add((name, PluginOutputChannel.Blue)); - port += 2; - } else { - ports.Add((name, PluginOutputChannel.None)); + private readonly int _device; + private readonly int _portCount; + private readonly DofToyNames _names; + // what the configuration puts on each port, from port 1: the header's name and the colour of an RGB toy's port + private readonly List<(string Name, PluginOutputChannel Channel)> _ports; + + internal DevicePorts(DofCatalogDevice device, int mapped, DofOutputWiring wiring, DofToyNames names) + { + _device = device.Number; + _portCount = device.PortCount; + _names = names ?? DofToyNames.None; + var count = System.Math.Max(device.Number >= 1 && device.Number <= 16 ? System.Math.Max(device.PortCount, LedWizOutputs) : device.PortCount, mapped); + count = System.Math.Max(count, wiring.Extent(device.Number)); + var rgb = new HashSet(device.RgbPorts); + _ports = new List<(string, PluginOutputChannel)>(count); + for (var port = 1; port <= count; port++) { + var name = port <= device.Ports.Count ? device.Ports[port - 1]?.Trim() ?? "" : ""; + if (rgb.Contains(port) && port + 2 <= count) { + _ports.Add((name, PluginOutputChannel.Red)); + _ports.Add((name, PluginOutputChannel.Green)); + _ports.Add((name, PluginOutputChannel.Blue)); + port += 2; + } else { + _ports.Add((name, PluginOutputChannel.None)); + } + } + } + + /// How many outputs the board shows. + internal int Outputs => _ports.Count; + + /// + /// What is on a port: the header's name, or the user's past every port the configuration uses (a configuration that + /// came to use the port takes it), and the colour of an RGB toy's port. + /// + internal (string Name, PluginOutputChannel Channel) At(int port) + { + var (name, channel) = port >= 1 && port <= _ports.Count ? _ports[port - 1] : ("", PluginOutputChannel.None); + return name.Length > 0 || channel != PluginOutputChannel.None || port <= _portCount ? (name, channel) : (_names.NameOf(_device, port) ?? "", channel); + } + + /// Whether the toy on these ports is on the board as a whole: each port on an output it shows, an RGB toy's in a row. + internal bool Placed(DofOutputWiring wiring, IReadOnlyList toy) + { + var first = wiring.OutputOf(_device, toy[0]); + return toy.Select((p, i) => wiring.OutputOf(_device, p) == first + i).All(on => on) && first >= 1 && first + toy.Count - 1 <= Outputs; + } + + /// Whether a port carries a toy the user added, past every port the configuration uses. + internal bool Added(int port) => port > _portCount && _names.NameOf(_device, port) != null; + + /// The first port of the toy on a port: the red of an RGB toy, itself for a named one, 0 for none. + internal int ToyOf(int port) + { + var (name, channel) = At(port); + return channel == PluginOutputChannel.None ? (name.Length > 0 ? port : 0) : port - (channel - PluginOutputChannel.Red); + } + + /// The ports of the toy on a port, all three of an RGB toy; empty for none. + internal IReadOnlyList PortsOf(int port) + { + var toy = ToyOf(port); + return toy == 0 ? Array.Empty() : At(toy).Channel == PluginOutputChannel.Red ? new[] { toy, toy + 1, toy + 2 } : new[] { toy }; + } + + /// The toys, by their first port: the configuration's in port order, then the user's. + internal IEnumerable<(int Port, string Name, bool Rgb)> Toys + { + get { + for (var port = 1; port <= _ports.Count; port++) { + var (name, channel) = At(port); + if (ToyOf(port) == port) { + yield return (port, name, channel == PluginOutputChannel.Red); + } + } + foreach (var port in _names.PortsOf(_device).Where(p => p > _ports.Count && p > _portCount)) { + yield return (port, _names.NameOf(_device, port), false); + } } } - return ports; + + /// + /// A port for a new toy: far past every port a configuration uses and every output the board shows + /// (), so no game drives it, a later configuration won't use it, and it drives no + /// output yet; and that no toy has. + /// + internal int FreePort(DofOutputWiring wiring) + { + for (var port = System.Math.Max(DofToyNames.FirstPort, System.Math.Max(_portCount, _ports.Count) + 1); port <= DofOutputWiring.MaxOutput; port++) { + var output = wiring.OutputOf(_device, port); + if (_names.NameOf(_device, port) == null && (output == port || output == DofOutputWiring.Nothing)) { + return port; + } + } + return 0; + } } public Task TestOutputAsync(string provider, string output, PluginChoiceRequest request, CancellationToken cancellation) @@ -682,6 +793,7 @@ private PluginActionResult SwapOutputs(string first, string second, int count, C if (!DofPortTest.TryParse(first, out var device, out var firstPort) || !DofPortTest.TryParse(second, out var other, out var secondPort)) { return new PluginActionResult(false, "Unknown output."); } + // an output nothing drives has its number as a negative port if (device != other) { return new PluginActionResult(false, "Outputs move within their board only."); } @@ -702,10 +814,10 @@ private PluginActionResult SwapOutputs(string first, string second, int count, C if (wiring == null) { return new PluginActionResult(false, "The output wiring could not be read, so nothing was changed. Try again."); } - var ports = Ports(entry, Reach(catalog, DetectedBoards(catalog), device), wiring); - var a = wiring.OutputOf(device, firstPort); - var b = wiring.OutputOf(device, secondPort); - if (count < 1 || firstPort > ports.Count || secondPort > ports.Count || a + count - 1 > ports.Count || b + count - 1 > ports.Count) { + var ports = new DevicePorts(entry, Reach(catalog, DetectedBoards(catalog), device), wiring, null); + var a = OutputAt(wiring, device, firstPort); + var b = OutputAt(wiring, device, secondPort); + if (count < 1 || a < 1 || b < 1 || a + count - 1 > ports.Outputs || b + count - 1 > ports.Outputs) { return new PluginActionResult(false, "The outputs are not all on the board."); } if (a < b + count && b < a + count) { @@ -713,20 +825,9 @@ private PluginActionResult SwapOutputs(string first, string second, int count, C } // An RGB toy on three outputs in a row: each run holds all three or none. One a new configuration put on outputs // apart moves an output at a time, so it can be put back together. - for (var port = 1; port + 2 <= ports.Count; port++) { - if (ports[port - 1].Channel != PluginOutputChannel.Red) { - continue; - } - var start = wiring.OutputOf(device, port); - if (wiring.OutputOf(device, port + 1) != start + 1 || wiring.OutputOf(device, port + 2) != start + 2) { - continue; - } - foreach (var run in new[] { a, b }) { - var inside = Enumerable.Range(start, 3).Count(o => o >= run && o < run + count); - if (inside != 0 && inside != 3) { - return new PluginActionResult(false, $"That would split {Toy(ports[port - 1].Name)}: its red, green and blue move together."); - } - } + var split = Split(ports, wiring, device, null, new[] { (a, count), (b, count) }); + if (split != null) { + return new PluginActionResult(false, $"That would split {Toy(split)}: its red, green and blue move together."); } try { wiring.Swap(device, a, b, count).Save(store.Root); @@ -749,6 +850,213 @@ private static string WhenItApplies() => DofOwnership.InUse private static string Toy(string name) => name.Length > 0 ? name : "an RGB toy"; + // The output a port drives, or the number of an output nothing drives, given as a negative port. + private static int OutputAt(DofOutputWiring wiring, int device, int port) => port < 0 ? -port : wiring.OutputOf(device, port); + + /// + /// The name of an RGB toy on three outputs in a row that a run of outputs would take one or two of, so it would come + /// apart; null for none. The toy that starts at is left out, as it moves itself. One a new + /// configuration put on outputs apart is free to move an output at a time, so it can be put back together. + /// + private static string Split(DevicePorts ports, DofOutputWiring wiring, int device, int? moving, IEnumerable<(int Start, int Count)> runs) + { + foreach (var toy in ports.Toys.Where(t => t.Rgb && t.Port != moving)) { + var start = wiring.OutputOf(device, toy.Port); + if (start == DofOutputWiring.Nothing || wiring.OutputOf(device, toy.Port + 1) != start + 1 || wiring.OutputOf(device, toy.Port + 2) != start + 2) { + continue; + } + foreach (var (run, count) in runs) { + var inside = Enumerable.Range(start, 3).Count(o => o >= run && o < run + count); + if (inside != 0 && inside != 3) { + return toy.Name; + } + } + } + return null; + } + + public Task AssignOutputAsync(string provider, string output, string toy, PluginChoiceRequest request, CancellationToken cancellation) + => Task.Run(() => provider != "outputs" ? new PluginActionResult(false, "Unknown DOF outputs.") : ChangeOutput(output, cancellation, (ports, wiring, names, device, number) => { + if (toy == null) { + return Empty(ports, wiring, names, device, number); + } + return TryParseToy(toy, out var port) && ports.ToyOf(port) == port && ports.At(port).Name.Length > 0 + ? Give(ports, wiring, names, device, number, port) + : (false, "That toy is not on this board any more.", null, null); + }), cancellation); + + public Task AddToyAsync(string provider, string output, string name, PluginChoiceRequest request, CancellationToken cancellation) + => Task.Run(() => provider != "outputs" ? new PluginActionResult(false, "Unknown DOF outputs.") + : ChangeOutput(output, cancellation, (ports, wiring, names, device, number) => Add(ports, wiring, names, device, number, name)), cancellation); + + /// + /// Changes what an output of a device drives, by where it shows, as works it out from the + /// ports, the wiring and the user's toys; and saves the wiring and toys it returns, the toys first, so a toy is never + /// on an output without its name. Null for one that stays as it is. + /// + private PluginActionResult ChangeOutput(string id, CancellationToken cancellation, + Func change) + { + cancellation.ThrowIfCancellationRequested(); + if (!DofPortTest.TryParse(id, out var device, out var port)) { + return new PluginActionResult(false, "Unknown output."); + } + if (device > DofOutputWiring.MaxDevice) { + return new PluginActionResult(false, $"Device {device} can't be changed: DOF takes devices 1 to {DofOutputWiring.MaxDevice}."); + } + // one folder for the whole change, should the host move the store meanwhile + var store = Store; + using var lease = store.AcquireForReading(); + var revision = lease?.Revision; + var catalog = revision != null ? CatalogOf(revision) : null; + var entry = catalog?.Devices.FirstOrDefault(d => d.Number == device); + if (entry == null) { + return new PluginActionResult(false, "The configuration has no device " + device + "."); + } + lock (WiringFileLock) { + var wiring = ReadWiring(store.Root); + var names = ReadNames(store.Root); + if (wiring == null || names == null) { + return new PluginActionResult(false, "The output wiring could not be read, so nothing was changed. Try again."); + } + var ports = new DevicePorts(entry, Reach(catalog, DetectedBoards(catalog), device), wiring, names); + var number = OutputAt(wiring, device, port); + if (number < 1 || number > ports.Outputs) { + return new PluginActionResult(false, "That output is not on the board any more."); + } + var (success, message, next, nextNames) = change(ports, wiring, names, device, number); + if (!success || next == null && nextNames == null) { + return new PluginActionResult(success, message); + } + var namesSaved = false; + try { + if (nextNames != null) { + nextNames.Save(store.Root); + namesSaved = true; + } + next?.Save(store.Root); + } catch (Exception e) when (e is IOException || e is UnauthorizedAccessException || e is ArgumentOutOfRangeException) { + Logger.Warn(e, "[DOF] Saving the output wiring failed."); + if (namesSaved) { + // a toy on no output would be left behind, and its name taken + try { + names.Save(store.Root); + } catch (Exception again) when (again is IOException || again is UnauthorizedAccessException) { + Logger.Warn(again, "[DOF] Putting the toys back failed."); + } + } + return new PluginActionResult(false, "Not changed: " + e.Message); + } finally { + ForgetWiring(); + } + Logger.Info($"[DOF] Output {number} of device {device}: {message}"); + return new PluginActionResult(true, $"{message} {WhenItApplies()}"); + } + } + + // Output `number` drives nothing: the toy on it is on no output then, all three outputs of an RGB toy. + private static (bool, string, DofOutputWiring, DofToyNames) Empty(DevicePorts ports, DofOutputWiring wiring, DofToyNames names, int device, int number) + { + var port = wiring.PortOn(device, number); + if (port == DofOutputWiring.Nothing) { + // what was asked for: nothing to change + return (true, $"Output {number} drives nothing already.", null, null); + } + var toy = ports.PortsOf(port); + var name = ports.At(port).Name; + if (toy.Count == 0) { + return (true, $"Output {number} drives nothing now.", wiring.Remove(device, new[] { port }), null); + } + var outputs = toy.Select(p => wiring.OutputOf(device, p)).Where(o => o != DofOutputWiring.Nothing).OrderBy(o => o).ToList(); + var on = outputs.Count == 1 ? $"Output {outputs[0]} drives" : $"Outputs {string.Join(", ", outputs)} drive"; + return (true, $"{on} nothing now: {Toy(name)} is on no output.", wiring.Remove(device, toy), null); + } + + // Output `number` drives the toy that starts on `toy`, an RGB toy the next two as well; what they drove goes where it was. + private static (bool, string, DofOutputWiring, DofToyNames) Give(DevicePorts ports, DofOutputWiring wiring, DofToyNames names, int device, int number, int toy) + { + var moving = ports.PortsOf(toy); + var name = ports.At(toy).Name; + if (number + moving.Count - 1 > ports.Outputs) { + return (false, $"{Toy(name)} takes three outputs in a row, and the board ends at {ports.Outputs}.", null, null); + } + if (moving.Select((p, i) => wiring.OutputOf(device, p) == number + i).All(on => on)) { + return (false, moving.Count == 1 ? $"Output {number} drives {name} already." : $"Outputs {number} to {number + 2} drive {Toy(name)} already.", null, null); + } + var split = Split(ports, wiring, device, toy, new[] { (number, moving.Count) }); + if (split != null) { + return (false, $"That would split {Toy(split)}: its red, green and blue move together. Swap them instead.", null, null); + } + // a toy on no output, off the board or apart has no place to give back: what it displaces is on no output then, + // rather than off the board or apart in its turn + var next = wiring.Assign(device, moving, number, !ports.Placed(wiring, moving)); + var where = moving.Count == 1 ? $"Output {number} drives {name} now." : $"Outputs {number} to {number + 2} drive {Toy(name)} now."; + return (true, where + Displaced(ports, wiring, next, device, number, moving), next, null); + } + + // Output `number` drives a new toy of the name the user typed; what it drove then drives nothing. + private static (bool, string, DofOutputWiring, DofToyNames) Add(DevicePorts ports, DofOutputWiring wiring, DofToyNames names, int device, int number, string name) + { + var clean = DofToyNames.Clean(name); + if (clean.Length == 0) { + return (false, "Type the toy's name.", null, null); + } + var same = ports.Toys.FirstOrDefault(t => string.Equals(t.Name, clean, StringComparison.OrdinalIgnoreCase)); + if (same.Port > 0) { + return (false, $"This board has {same.Name} already: choose it from the list.", null, null); + } + var split = Split(ports, wiring, device, null, new[] { (number, 1) }); + if (split != null) { + return (false, $"That would split {Toy(split)}: its red, green and blue move together. Choose Nothing for it first.", null, null); + } + var port = ports.FreePort(wiring); + if (port == 0) { + return (false, "This board has no port left for a new toy.", null, null); + } + var next = wiring.Assign(device, new[] { port }, number, true); + var withName = names.With(device, port, clean); + var message = $"Output {number} drives {clean} now; no configuration drives it yet."; + return (true, message + Displaced(ports, wiring, next, device, number, new[] { port }), next, withName); + } + + // Where the toys the outputs from `number` on had went: to the outputs the moved ones left, or to none. + private static string Displaced(DevicePorts ports, DofOutputWiring before, DofOutputWiring after, int device, int number, IReadOnlyList moving) + { + var text = new StringBuilder(); + var told = new HashSet(); + for (var output = number; output < number + moving.Count; output++) { + var port = before.PortOn(device, output); + var toy = port == DofOutputWiring.Nothing || moving.Contains(port) ? 0 : ports.ToyOf(port); + if (toy == 0 || !told.Add(toy)) { + continue; + } + // all of the toy's ports: one of an RGB toy may be driven where the others aren't + var now = ports.PortsOf(toy).Select(p => after.OutputOf(device, p)).ToList(); + var driven = now.Where(o => o != DofOutputWiring.Nothing).ToList(); + var name = ports.At(toy).Name; + text.Append(driven.Count == 0 ? $" {Toy(name)} is on no output now." + : driven.Count == now.Count && now.Select((o, i) => o - i).Distinct().Count() == 1 ? $" {Toy(name)} moved to output {now[0]}." + : $" {Toy(name)} is on output{(driven.Count > 1 ? "s" : "")} {string.Join(", ", driven)} now."); + } + return text.ToString(); + } + + /// The toys the user added, of a folder, or null when their file can't be read, after a few tries. + private static DofToyNames ReadNames(string root) + { + for (var attempt = 1; ; attempt++) { + try { + return DofToyNames.Load(root); + } catch (Exception e) when (e is IOException || e is UnauthorizedAccessException) { + if (attempt == 3) { + Logger.Warn(e, "[DOF] The toys you added could not be read."); + return null; + } + Thread.Sleep(20); + } + } + } + #endregion #region Actions @@ -880,6 +1188,9 @@ private PluginActionResult PulsePort(string id, PluginOutputLeases leases, Cance if (!DofPortTest.TryParse(id, out var device, out var port)) { return new PluginActionResult(false, "Unknown output " + id + "."); } + if (port < 0) { + return new PluginActionResult(false, $"Nothing drives output {-port} now: give it a toy to test it."); + } var store = Store; var (success, message) = DofPortTest.Pulse(store, leases, Id, ReadWiring(store.Root) ?? DofOutputWiring.None, device, port, PulseDuration, ConfirmTimeout, TestNativeFactory, cancellation); return new PluginActionResult(success, message); diff --git a/VisualPinball.Engine.DOF.Unity/Tests/DofPluginTests.cs b/VisualPinball.Engine.DOF.Unity/Tests/DofPluginTests.cs index f7bf812..f910d70 100644 --- a/VisualPinball.Engine.DOF.Unity/Tests/DofPluginTests.cs +++ b/VisualPinball.Engine.DOF.Unity/Tests/DofPluginTests.cs @@ -390,6 +390,112 @@ public void AnRgbToyANewConfigurationPutsApartMovesAnOutputAtATime() Assert.That(Outputs(host).Take(3).Select(o => o.Channel), Is.EqualTo(new[] { PluginOutputChannel.Red, PluginOutputChannel.Green, PluginOutputChannel.Blue })); } + private static PluginActionResult Assign(DofTestHost host, string output, string toy) + => host.Factory.AssignOutputAsync("outputs", output, toy, Request(), CancellationToken.None).Result; + + private static PluginActionResult AddToy(DofTestHost host, string output, string name) + => host.Factory.AddToyAsync("outputs", output, name, Request(), CancellationToken.None).Result; + + private static PluginOutputBoard Board(DofTestHost host) + => host.Factory.DescribeOutputsAsync("outputs", Request(), CancellationToken.None).Result.Boards.Single(); + + [Test] + public void AnOutputIsGivenAToyOrNothing() + { + var native = new RecordingTestNative(); + var host = Host(); + host.Factory.TestNativeFactory = _ => native; + host.Factory.PulseDuration = TimeSpan.FromMilliseconds(20); + host.Import(365, "vpetest,S1,0,E2 White,S2", null, "\"Rom\",\"Knocker\",\"\",\"Flasher\",\"\",\"\",\"Shaker\""); + var board = Board(host); + Assert.That(board.Toys.Select(t => (t.Id, t.Label, t.Rgb)), Is.EqualTo(new[] { ("p1", "Knocker", false), ("p3", "Flasher", true), ("p6", "Shaker", false) })); + Assert.That(board.AcceptsNewToys, Is.True); + Assert.That(board.Outputs.Take(6).Select(o => o.Toy), Is.EqualTo(new[] { "p1", "", "p3", "p3", "p3", "p6" })); + + // the knocker is cabled to output 14: what 14 had goes where the knocker was + var result = Assign(host, "1:14", "p1"); + Assert.That(result.Success, Is.True, result.Message); + Assert.That(result.Message, Does.StartWith("Output 14 drives Knocker now.")); + var outputs = Board(host).Outputs; + Assert.That((outputs[13].Label, outputs[13].Toy, outputs[13].Note), Is.EqualTo(("Knocker", "p1", "Moved from 1"))); + Assert.That(outputs[0].Id, Is.EqualTo("1:14")); + // the ids stay the ports': port 1 drives output 14 + Assert.That(Assign(host, "1:1", "p1").Success, Is.False, "it is there already"); + + // nothing: the shaker is on no output, still listed, and its output can't be tested + result = Assign(host, "1:6", null); + Assert.That(result.Success, Is.True, result.Message); + Assert.That(result.Message, Does.StartWith("Output 6 drives nothing now: Shaker is on no output.")); + board = Board(host); + Assert.That((board.Outputs[5].Id, board.Outputs[5].Label, board.Outputs[5].Toy), Is.EqualTo(("1:-6", "", ""))); + Assert.That(board.Toys.Select(t => t.Label), Does.Contain("Shaker"), "a toy on no output can be given one again"); + Assert.That(Pulse(host, "1:-6").Message, Does.Contain("Nothing drives output 6")); + Assert.That(native.Calls, Is.Empty, "nothing is opened for it"); + Assert.That(Assign(host, "1:-6", null).Message, Does.StartWith("Output 6 drives nothing already."), "nothing to change"); + + // a toy on no output: what its new output had drives nothing + result = Assign(host, "1:2", "p6"); + Assert.That(result.Success, Is.True, result.Message); + outputs = Board(host).Outputs; + Assert.That((outputs[1].Label, outputs[1].Id), Is.EqualTo(("Shaker", "1:6"))); + Assert.That(outputs[5].Id, Is.EqualTo("1:-6")); + + // an RGB toy takes three outputs, and splits none + Assert.That(Assign(host, "1:31", "p3").Message, Does.Contain("three outputs in a row")); + Assert.That(Assign(host, "1:4", "p6").Message, Does.Contain("would split Flasher")); + result = Assign(host, "1:20", "p3"); + Assert.That(result.Success, Is.True, result.Message); + outputs = Board(host).Outputs; + Assert.That(outputs.Skip(19).Take(3).Select(o => (o.Label, o.Channel)), Is.EqualTo(new[] { + ("Flasher", PluginOutputChannel.Red), ("Flasher", PluginOutputChannel.Green), ("Flasher", PluginOutputChannel.Blue) })); + Assert.That(Assign(host, "1:4", null).Message, Does.StartWith("Outputs 20, 21, 22 drive nothing now: Flasher is on no output.")); + Assert.That(Assign(host, "1:1", "p9").Success, Is.False, "no such toy"); + + // games get the outputs that drive nothing as -1 + Assert.That(Pulse(host, "1:6").Success, Is.True); + Assert.That(native.Calls.Single(c => c.StartsWith("map:1:")), Does.Contain("-1")); + + var reset = RunAction(host, "reset-wiring"); + Assert.That(reset.Success, Is.True, reset.Message); + Assert.That(Board(host).Outputs.Take(6).Select(o => o.Label), Is.EqualTo(new[] { "Knocker", "", "Flasher", "Flasher", "Flasher", "Shaker" })); + } + + [Test] + public void AnOutputIsGivenANewToy() + { + var host = Host(); + host.Import(366, "vpetest,S1", null, "\"Rom\",\"Knocker\",\"Shaker\""); + var result = AddToy(host, "1:2", " Gear motor "); + Assert.That(result.Success, Is.True, result.Message); + Assert.That(result.Message, Does.StartWith("Output 2 drives Gear motor now; no configuration drives it yet. Shaker is on no output now.")); + var board = Board(host); + Assert.That(board.Outputs.Count, Is.EqualTo(32), "the new toy's port stretches no board"); + Assert.That((board.Outputs[1].Label, board.Outputs[1].Note, board.Outputs[1].Id), Is.EqualTo(("Gear motor", "", "1:" + DofToyNames.FirstPort))); + Assert.That(board.Toys.Select(t => (t.Id, t.Label)), Is.EqualTo(new[] { ("p1", "Knocker"), ("p2", "Shaker"), ("p" + DofToyNames.FirstPort, "Gear motor") })); + Assert.That(File.Exists(Path.Combine(host.Factory.Store.Root, DofToyNames.FileName)), Is.True, "kept with the configurations"); + + Assert.That(AddToy(host, "1:5", "gear MOTOR").Message, Does.Contain("has Gear motor already")); + Assert.That(AddToy(host, "1:5", " ").Success, Is.False); + + // kept across imports, and on no output after the wiring is undone, where it drives nothing + host.Import(366, "vpetest,S1", null, "\"Rom\",\"Knocker\",\"Shaker\""); + Assert.That(Board(host).Outputs[1].Label, Is.EqualTo("Gear motor")); + Assert.That(RunAction(host, "reset-wiring").Success, Is.True); + board = Board(host); + Assert.That(board.Outputs[1].Label, Is.EqualTo("Shaker")); + Assert.That(board.Toys.Select(t => t.Label), Does.Contain("Gear motor")); + // back on an output; what it displaces goes on no output, not off the board where the toy was + var back = Assign(host, "1:5", "p" + DofToyNames.FirstPort); + Assert.That(back.Success, Is.True, back.Message); + Assert.That(Board(host).Outputs.Count, Is.EqualTo(32)); + Assert.That(Board(host).Toys.Select(t => t.Label), Does.Contain("Shaker")); + + // a configuration that came to use the toy's port takes it: its name is no longer the port's + var header = "\"Rom\",\"Knocker\",\"Shaker\"" + string.Concat(Enumerable.Repeat(",\"\"", DofToyNames.FirstPort - 3)) + ",\"Bell\""; + host.Import(366, "vpetest,S1", null, header); + Assert.That(Board(host).Toys.Select(t => t.Label), Does.Not.Contain("Gear motor")); + } + [Test] public void TheSerialPortsFollowTheCabinet() { diff --git a/VisualPinball.Engine.DOF/Configuration/DofOutputWiring.cs b/VisualPinball.Engine.DOF/Configuration/DofOutputWiring.cs index cd1f9d7..e666d98 100644 --- a/VisualPinball.Engine.DOF/Configuration/DofOutputWiring.cs +++ b/VisualPinball.Engine.DOF/Configuration/DofOutputWiring.cs @@ -15,11 +15,13 @@ namespace VisualPinball.Engine.DOF.Configuration /// /// How the cabinet's cabling differs from what the configuration says: for each ini device, the output each of its ports /// drives. Port p of device N (directoutputconfigN.ini) drives what port OutputOf(N, p) drives in the - /// cabinet file. Each device's map is a permutation, so every output stays reachable from exactly one port. + /// cabinet file, or nothing (). No two ports drive the same output; an output no port is moved to is + /// driven by its own port, unless that one is moved away, when nothing drives it. /// /// - /// Kept next to the revisions (<root>/output-wiring.txt, one device=output,output,... line per device), - /// for every configuration: it describes the cabinet, not one import. Immutable; changes return a new wiring. + /// Kept next to the revisions (<root>/output-wiring.txt, one device=output,output,... line per device, + /// 0 for a port that drives nothing), for every configuration: it describes the cabinet, not one import. Immutable; + /// changes return a new wiring. /// public sealed class DofOutputWiring { @@ -31,9 +33,16 @@ public sealed class DofOutputWiring /// The highest device a map can be for, as the native layer takes them. public const int MaxDevice = 999; + /// What gives for a port that drives nothing, and for an output nothing drives. + public const int Nothing = 0; + + // what the native layer takes for a port that drives nothing + private const int NativeNothing = -1; + public static readonly DofOutputWiring None = new DofOutputWiring(new Dictionary()); - // By device: the output of port i + 1 at index i; trailing ports that drive their own output are left out. + // By device: the output of port i + 1 at index i, or Nothing; trailing ports that drive their own output are left out. + // No output is named twice, nor beyond the map, where the ports drive their own. private readonly IReadOnlyDictionary _maps; private DofOutputWiring(IReadOnlyDictionary maps) { _maps = maps; } @@ -44,27 +53,48 @@ public sealed class DofOutputWiring /// The devices with a map, in order. public IEnumerable Devices => _maps.Keys.OrderBy(d => d); - /// The output port of the device drives. + /// The output port of the device drives, or . public int OutputOf(int device, int port) => _maps.TryGetValue(device, out var map) && port >= 1 && port <= map.Length ? map[port - 1] : port; - /// The port that drives output of the device. + /// The port that drives output of the device, or . public int PortOn(int device, int output) { - if (_maps.TryGetValue(device, out var map) && output >= 1 && output <= map.Length) { - var index = Array.IndexOf(map, output); - if (index >= 0) { - return index + 1; - } + if (!_maps.TryGetValue(device, out var map) || output > map.Length) { + return output; } - return output; + var index = Array.IndexOf(map, output); + return index >= 0 ? index + 1 : Nothing; } - /// The highest port or output the device's map names; 0 without a map. - public int Extent(int device) => _maps.TryGetValue(device, out var map) ? map.Length : 0; + /// + /// The highest output a port of the device is moved to or from; 0 without a map. A port moved off its output came from + /// an output the board shows, which stays shown when nothing drives it any more; not a port of a toy the user added + /// (), past every board's. + /// + public int Extent(int device) + { + if (!_maps.TryGetValue(device, out var map)) { + return 0; + } + var extent = 0; + for (var i = 0; i < map.Length; i++) { + if (map[i] != i + 1) { + extent = Math.Max(extent, map[i]); + if (i + 1 < DofToyNames.FirstPort) { + extent = Math.Max(extent, i + 1); + } + } + } + return extent; + } - /// The device's map for the native layer: the output of port i + 1 at index i; empty without a map. - public IReadOnlyList MapOf(int device) => _maps.TryGetValue(device, out var map) ? (int[])map.Clone() : Array.Empty(); + /// + /// The device's map for the native layer: the output of port i + 1 at index i, -1 for one that drives nothing; empty + /// without a map. + /// + public IReadOnlyList MapOf(int device) + => _maps.TryGetValue(device, out var map) ? map.Select(o => o == Nothing ? NativeNothing : o).ToArray() : Array.Empty(); /// Every device's map, as gives it. public IReadOnlyDictionary> Maps => Devices.ToDictionary(d => d, MapOf); @@ -72,32 +102,77 @@ public int PortOn(int device, int output) /// /// Swaps what drives two runs of outputs of a device: outputs from on /// with as many from on, so the ports that drove the first run drive the second, in order, and - /// the other way around. + /// the other way around. An output nothing drove leaves the other one driven by nothing. /// /// /// The runs overlap or leave 1 to , or the device is outside 1 to . /// public DofOutputWiring Swap(int device, int first, int second, int count) { - if (device < 1 || device > MaxDevice) { - throw new ArgumentOutOfRangeException(nameof(device), $"Device {device} can't be rearranged: DOF takes devices 1 to {MaxDevice}."); - } + CheckDevice(device); if (count < 1 || first < 1 || second < 1 || first + count - 1 > MaxOutput || second + count - 1 > MaxOutput) { throw new ArgumentOutOfRangeException(nameof(count), "The outputs are outside the board."); } if (first < second + count && second < first + count) { throw new ArgumentOutOfRangeException(nameof(count), "The outputs overlap."); } - var size = Math.Max(Extent(device), Math.Max(first, second) + count - 1); - var map = new int[size]; - for (var port = 1; port <= size; port++) { - map[port - 1] = OutputOf(device, port); - } + var map = Expanded(device, Math.Max(first, second) + count - 1); for (var k = 0; k < count; k++) { var a = PortOn(device, first + k); var b = PortOn(device, second + k); - map[a - 1] = second + k; - map[b - 1] = first + k; + if (a != Nothing) { + map[a - 1] = second + k; + } + if (b != Nothing) { + map[b - 1] = first + k; + } + } + return With(device, map); + } + + /// + /// Moves ports of a device onto the outputs from on, in order, such as a toy's or the three of + /// an RGB toy. The ports those outputs had go where the moved ports were, in order; with + /// , or where there is no such place, they drive nothing. + /// + /// + /// A port or output is outside 1 to , a port is named twice, or the device is outside 1 to + /// . + /// + public DofOutputWiring Assign(int device, IReadOnlyList ports, int output, bool displacedToNothing = false) + { + CheckDevice(device); + if (ports == null || ports.Count == 0 || ports.Any(p => p < 1 || p > MaxOutput) || ports.Distinct().Count() != ports.Count) { + throw new ArgumentOutOfRangeException(nameof(ports), "The ports are outside the board."); + } + if (output < 1 || output + ports.Count - 1 > MaxOutput) { + throw new ArgumentOutOfRangeException(nameof(output), "The outputs are outside the board."); + } + var targets = Enumerable.Range(output, ports.Count).ToList(); + var freed = ports.Select(p => OutputOf(device, p)).Where(o => o != Nothing && !targets.Contains(o)).ToList(); + var displaced = targets.Select(o => PortOn(device, o)).Where(p => p != Nothing && !ports.Contains(p)).ToList(); + var map = Expanded(device, Math.Max(ports.Max(), targets.Max())); + for (var i = 0; i < ports.Count; i++) { + map[ports[i] - 1] = targets[i]; + } + for (var i = 0; i < displaced.Count; i++) { + map[displaced[i] - 1] = !displacedToNothing && i < freed.Count ? freed[i] : Nothing; + } + // a freed output no port took is driven by nothing: the map reaches it, so its own port has an entry + return With(device, map); + } + + /// The wiring with the ports of a device driving nothing. + /// A port is outside 1 to , or the device outside 1 to . + public DofOutputWiring Remove(int device, IReadOnlyList ports) + { + CheckDevice(device); + if (ports == null || ports.Any(p => p < 1 || p > MaxOutput)) { + throw new ArgumentOutOfRangeException(nameof(ports), "The ports are outside the board."); + } + var map = Expanded(device, ports.DefaultIfEmpty(0).Max()); + foreach (var port in ports) { + map[port - 1] = Nothing; } return With(device, map); } @@ -105,11 +180,36 @@ public DofOutputWiring Swap(int device, int first, int second, int count) /// The wiring without the device's map, so its ports drive their own outputs again. public DofOutputWiring Without(int device) => With(device, Array.Empty()); + private static void CheckDevice(int device) + { + if (device < 1 || device > MaxDevice) { + throw new ArgumentOutOfRangeException(nameof(device), $"Device {device} can't be rearranged: DOF takes devices 1 to {MaxDevice}."); + } + } + + // The device's map as long as the given port at least, every port with its output: an output the map reaches but no + // port names is driven by nothing. + private int[] Expanded(int device, int length) + { + var size = Math.Max(_maps.TryGetValue(device, out var current) ? current.Length : 0, length); + var map = new int[size]; + for (var port = 1; port <= size; port++) { + map[port - 1] = OutputOf(device, port); + } + return map; + } + private DofOutputWiring With(int device, int[] map) { var maps = _maps.ToDictionary(e => e.Key, e => e.Value); + // the highest output the ports before each one name + var before = new int[map.Length + 1]; + for (var i = 0; i < map.Length; i++) { + before[i + 1] = Math.Max(before[i], map[i]); + } + // a trailing port that drives its own output is left out, while no earlier one is moved past it var length = map.Length; - while (length > 0 && map[length - 1] == length) { + while (length > 0 && map[length - 1] == length && before[length - 1] < length) { length--; } if (length == 0) { @@ -121,8 +221,8 @@ private DofOutputWiring With(int device, int[] map) } /// - /// Reads the wiring of a store's folder; none when it has no file. A line that is not a device's permutation is left - /// out, so its device drives its own outputs. + /// Reads the wiring of a store's folder; none when it has no file. A line that does not give each port its own output + /// or none is left out, so its device drives its own outputs. /// public static DofOutputWiring Load(string root) { @@ -152,7 +252,7 @@ public static DofOutputWiring Load(string root) return wiring; } - // A permutation of 1 to its length, or null. + // Outputs from 1 to its length, or 0 for none, no output twice; or null. private static int[] Parse(string text) { // an empty entry is no output, and leaves the line out @@ -164,7 +264,7 @@ private static int[] Parse(string text) var seen = new bool[parts.Length + 1]; for (var i = 0; i < parts.Length; i++) { if (!int.TryParse(parts[i].Trim(), NumberStyles.Integer, CultureInfo.InvariantCulture, out var output) - || output < 1 || output > parts.Length || seen[output]) { + || output < 0 || output > parts.Length || output != Nothing && seen[output]) { return null; } seen[output] = true; diff --git a/VisualPinball.Engine.DOF/Configuration/DofToyNames.cs b/VisualPinball.Engine.DOF/Configuration/DofToyNames.cs new file mode 100644 index 0000000..f7ce5e4 --- /dev/null +++ b/VisualPinball.Engine.DOF/Configuration/DofToyNames.cs @@ -0,0 +1,134 @@ +// 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 +{ + /// + /// The toys the user added to the cabinet that no configuration names, such as a gear motor: a name for a port of an ini + /// device far past every port a configuration uses (from on), so no game drives it unless told + /// to, nor will one of a later configuration. + /// + /// + /// Kept next to the revisions and the output wiring (<root>/toy-names.txt, one device:port=name line + /// per toy), for every configuration. Immutable; changes return new names. + /// + public sealed class DofToyNames + { + public const string FileName = "toy-names.txt"; + + /// The longest name kept. + public const int MaxLength = 64; + + /// The first port a toy is added on: half of what the native layer takes, far past any board's. + public const int FirstPort = DofOutputWiring.MaxOutput / 2 + 1; + + public static readonly DofToyNames None = new DofToyNames(new Dictionary<(int, int), string>()); + + private readonly IReadOnlyDictionary<(int Device, int Port), string> _names; + + private DofToyNames(IReadOnlyDictionary<(int, int), string> names) { _names = names; } + + /// Whether the user named no toy. + public bool IsEmpty => _names.Count == 0; + + /// The name the user gave a port, or null. + public string NameOf(int device, int port) => _names.TryGetValue((device, port), out var name) ? name : null; + + /// The ports of a device the user named, in order. + public IReadOnlyList PortsOf(int device) => _names.Keys.Where(k => k.Device == device).Select(k => k.Port).OrderBy(p => p).ToList(); + + /// A name made fit to keep: on one line, without the spaces around it, and not too long; empty for none. + public static string Clean(string name) + { + var text = new string((name ?? "").Select(c => char.IsControl(c) ? ' ' : c).ToArray()).Trim(); + return Truncate(text, MaxLength); + } + + /// The text cut to a length, never inside a surrogate pair, without the spaces it then ends with. + internal static string Truncate(string text, int length) + { + if (text.Length <= length) { + return text; + } + if (length > 0 && char.IsHighSurrogate(text[length - 1])) { + length--; + } + return text.Substring(0, length).TrimEnd(); + } + + /// The names with a port of a device named, or its name removed for an empty one. + public DofToyNames With(int device, int port, string name) + { + var names = _names.ToDictionary(e => e.Key, e => e.Value); + var clean = Clean(name); + if (clean.Length == 0) { + names.Remove((device, port)); + } else { + names[(device, port)] = clean; + } + return new DofToyNames(names); + } + + /// Reads the names of a store's folder; none when it has no file. A line that names no port is left out. + public static DofToyNames Load(string root) + { + var path = Path.Combine(root, FileName); + if (Directory.Exists(path)) { + throw new IOException(path + " is a folder, not the toy names."); + } + if (!File.Exists(path)) { + return None; + } + var names = new Dictionary<(int, int), string>(); + foreach (var line in File.ReadAllLines(path, Encoding.UTF8)) { + var colon = line.IndexOf(':'); + var equals = line.IndexOf('='); + if (colon <= 0 || equals <= colon + 1 + || !int.TryParse(line.Substring(0, colon).Trim(), NumberStyles.Integer, CultureInfo.InvariantCulture, out var device) + || !int.TryParse(line.Substring(colon + 1, equals - colon - 1).Trim(), NumberStyles.Integer, CultureInfo.InvariantCulture, out var port) + || device < 1 || device > DofOutputWiring.MaxDevice || port < 1 || port > DofOutputWiring.MaxOutput) { + continue; + } + var name = Clean(line.Substring(equals + 1)); + if (name.Length > 0) { + names[(device, port)] = name; + } + } + return new DofToyNames(names); + } + + /// Replaces the names file of a store's folder in one step; deletes it when no toy is named. + 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 _names.OrderBy(e => e.Key.Device).ThenBy(e => e.Key.Port)) { + text.Append(entry.Key.Device.ToString(CultureInfo.InvariantCulture)).Append(':') + .Append(entry.Key.Port.ToString(CultureInfo.InvariantCulture)).Append('=').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); + } + } + } +} diff --git a/VisualPinball.Engine.DOF/Native/DofNative.cs b/VisualPinball.Engine.DOF/Native/DofNative.cs index 905fcaf..4b8e4ba 100644 --- a/VisualPinball.Engine.DOF/Native/DofNative.cs +++ b/VisualPinball.Engine.DOF/Native/DofNative.cs @@ -15,7 +15,7 @@ namespace VisualPinball.Engine.DOF.Native internal static class DofNative { public const string Library = "VpeDof"; - public const int AbiVersion = 6; + public const int AbiVersion = 7; [UnmanagedFunctionPointer(CallingConvention.Cdecl)] public delegate void LogCallback(int level, IntPtr message, IntPtr user); diff --git a/native/include/vpe_dof.h b/native/include/vpe_dof.h index b6f06b4..b8f0879 100644 --- a/native/include/vpe_dof.h +++ b/native/include/vpe_dof.h @@ -36,7 +36,7 @@ extern "C" { #endif /// Version of this ABI. Bumped on every incompatible change; the managed binding refuses a library with another one. -#define VPE_DOF_ABI_VERSION 6 +#define VPE_DOF_ABI_VERSION 7 enum vpe_dof_status { @@ -152,10 +152,11 @@ VPE_DOF_API int32_t VPE_DOF_CALL vpe_dof_test_output(vpe_dof* dof, int32_t devic /// Routes the ports of an ini device (the N of directoutputconfigN.ini) to other outputs of its LedWiz equivalent, for /// cabling that differs from the configuration: port i + 1 drives the output port targets[i] drives in the cabinet, its -/// own for 0 or i + 1. A port whose target the equivalent has no output for drives nothing. Applied when init sets up -/// the cabinet, before the table config makes its toys, so games and port tests follow it. Call before vpe_dof_init; a -/// later call for the device replaces its map, a count of 0 removes it. VPE_DOF_INVALID_ARGUMENT for a device outside -/// 1..999, a count outside 0..4096, or no targets for a count; VPE_DOF_INVALID_STATE after init. +/// own for 0 or i + 1, and nothing for a negative target. A port whose target the equivalent has no output for drives +/// nothing too. Applied when init sets up the cabinet, before the table config makes its toys, so games and port tests +/// follow it. Call before vpe_dof_init; a later call for the device replaces its map, a count of 0 removes it. +/// VPE_DOF_INVALID_ARGUMENT for a device outside 1..999, a count outside 0..4096, or no targets for a count; +/// VPE_DOF_INVALID_STATE after init. VPE_DOF_API int32_t VPE_DOF_CALL vpe_dof_set_output_map(vpe_dof* dof, int32_t device, const int32_t* targets, int32_t count); /// After init: lists "controller|||" and "toy||" lines describing the cabinet. diff --git a/native/src/vpe_dof.cpp b/native/src/vpe_dof.cpp index f69821a..642533e 100644 --- a/native/src/vpe_dof.cpp +++ b/native/src/vpe_dof.cpp @@ -316,9 +316,10 @@ void ApplyOutputMaps(const std::map>& maps, DOF::C { const int port = static_cast(i) + 1; const int target = map->second[i]; - if (target <= 0 || target == port) + if (target == 0 || target == port) continue; - auto name = names.find(target); + // a negative target drives nothing: the port loses its output's name + auto name = target > 0 ? names.find(target) : names.end(); const std::string targetName = name != names.end() ? name->second : std::string(); if (DOF::LedWizEquivalentOutput* output = outputs.FindByNumber(port)) output->SetOutputName(targetName);