From ae82a71f8df667b1fead6c5867022b42f07a2f24 Mon Sep 17 00:00:00 2001 From: freezy Date: Thu, 26 Nov 2026 05:08:35 +0100 Subject: [PATCH 1/3] pinmame: publish the game's outputs on the real-time feed PinMAME's solenoids, mechs and applied switches go through a lock-free ring, and lamps and GI strings are read by a single owner (the 1 kHz poll while a receiver listens, the main thread otherwise), so the feed keeps their order and the main thread still gets every lamp change. Each game is a session that turns everything off when it ends; a soft reset starts from what PinMAME reported before. Switches inside the matrix are read back, the others are reported as the engine applied them, and the start-up replay no longer overwrites a switch the game changed meanwhile. --- .../PinMameRealtimeOutputsTests.cs | 996 ++++++++++++ .../VisualPinball.Engine.PinMAME.Test.csproj | 1 + .../Runtime/PinMameGamelogicEngine.cs | 254 +++- .../Runtime/PinMameRealtimeOutputs.cs | 1332 +++++++++++++++++ .../Runtime/PinMameRealtimeOutputs.cs.meta | 2 + 5 files changed, 2568 insertions(+), 17 deletions(-) create mode 100644 VisualPinball.Engine.PinMAME.Test/PinMameRealtimeOutputsTests.cs create mode 100644 VisualPinball.Engine.PinMAME.Unity/Runtime/PinMameRealtimeOutputs.cs create mode 100644 VisualPinball.Engine.PinMAME.Unity/Runtime/PinMameRealtimeOutputs.cs.meta diff --git a/VisualPinball.Engine.PinMAME.Test/PinMameRealtimeOutputsTests.cs b/VisualPinball.Engine.PinMAME.Test/PinMameRealtimeOutputsTests.cs new file mode 100644 index 0000000..243f6ee --- /dev/null +++ b/VisualPinball.Engine.PinMAME.Test/PinMameRealtimeOutputsTests.cs @@ -0,0 +1,996 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Reflection; +using System.Threading; +using NUnit.Framework; + +namespace VisualPinball.Engine.PinMAME.Test +{ + public class PinMameRealtimeOutputsTests + { + private FakeReader _reader; + private RecordingSink _sink; + private PinMameRealtimeOutputs _outputs; + + [SetUp] + public void SetUp() + { + _reader = new FakeReader(); + _sink = new RecordingSink(); + _outputs = new PinMameRealtimeOutputs(_reader); + _outputs.BeginSession(PinMameSwitchNumbering.Wpc); + _outputs.Prepare(Array.Empty(), Array.Empty()); + } + + [Test] + public void UnmappedOutputsReachTheFeed() + { + Subscribe(); + _outputs.Solenoid(40, 1); + _reader.Lamps.Enqueue((77, 1)); + _outputs.Poll(true); + Assert.That(_sink.Changes, Is.EqualTo(new[] { (PinMameOutputKind.Solenoid, 40, 1), (PinMameOutputKind.Lamp, 77, 1) })); + } + + [Test] + public void SwitchesPinMameChangesItselfAreReadOnEveryPoll() + { + _outputs.Prepare(new[] { 33, 15 }, Array.Empty()); + Subscribe(); + // a mech switch: PinMAME closes and opens it, the engine never applies it + _reader.SetSwitch(33, true); + _outputs.Poll(true); + _reader.SetSwitch(33, false); + _outputs.Poll(true); + // an applied switch arrives through the ring, so its read back does not repeat it + _outputs.Switch(15, true); + _reader.SetSwitch(15, true); + _outputs.Poll(true); + Assert.That(_sink.Changes, Is.EqualTo(new[] { (PinMameOutputKind.Switch, 33, 1), (PinMameOutputKind.Switch, 33, 0), (PinMameOutputKind.Switch, 15, 1) })); + } + + [Test] + public void TheRestOfTheMatrixIsReadAColumnPerPoll() + { + // a Whitestar game whose built-in mech drives switches the table doesn't map, and a cabinet switch + _outputs.BeginSession(PinMameSwitchNumbering.Sequential); + _outputs.Prepare(new[] { 17 }, Array.Empty()); + Subscribe(); + _reader.SetSwitch(45, true); + _reader.SetSwitch(-3, true); + for (var i = 0; i < PinMameSwitchMatrix.Columns; i++) { + _outputs.Poll(true); + } + Assert.That(_sink.Changes, Is.EquivalentTo(new[] { (PinMameOutputKind.Switch, 45, 1), (PinMameOutputKind.Switch, -3, 1) })); + + // a poll reads the mapped switches and 8 of the matrix, not all of it (unless it came late, which a busy machine may do) + var reads = new List(); + for (var i = 0; i < 20; i++) { + _reader.SwitchReads = 0; + _outputs.Poll(true); + reads.Add(_reader.SwitchReads); + } + Assert.That(reads.Min(), Is.EqualTo(1 + PinMameSwitchMatrix.Rows)); + } + + [Test] + public void APollThatComesLateReadsTheWholeMatrix() + { + Subscribe(); + // the frame update polls when no simulation thread does + _reader.SetSwitch(45, true); + _reader.SetSwitch(158, true); + Thread.Sleep(5); + _outputs.Poll(true); + Assert.That(_sink.Changes, Is.EquivalentTo(new[] { (PinMameOutputKind.Switch, 45, 1), (PinMameOutputKind.Switch, 158, 1) })); + } + + [Test] + public void OnlySwitchesInsideTheMatrixAreRead() + { + // row 9, row 0, nothing, negative, row 9 of column 15, column 16, far out + var outside = _outputs.Prepare(new[] { 9, 10, 0, -1, 159, 161, 2047, 33 }, Array.Empty()); + Assert.That(outside, Is.EqualTo(7)); + _reader.Validate = PinMameSwitchNumbering.Wpc; + Subscribe(); + for (var i = 0; i < 40; i++) { + _sink.Requested = i % 10 == 0; + _outputs.Poll(true); + } + Assert.That(_reader.Invalid, Is.Empty); + Assert.That(_reader.SwitchReads, Is.GreaterThan(PinMameSwitchMatrix.Size)); + } + + [Test] + public void WithAnUnknownNumberingNoSwitchIsReadButAppliedOnesAreReported() + { + _outputs.BeginSession(PinMameSwitchNumbering.Unknown); + Assert.That(_outputs.Prepare(new[] { 5, 77 }, Array.Empty()), Is.EqualTo(0)); + _outputs.SetSink(_sink); + _outputs.Switch(77, true); + _sink.Requested = true; + _reader.SwitchReads = 0; + _outputs.Poll(true); + _outputs.Poll(true); + Assert.That(_reader.SwitchReads, Is.EqualTo(0)); + Assert.That(_sink.Snapshot.Where(e => e.Item1 == PinMameOutputKind.Switch), Is.EqualTo(new[] { (PinMameOutputKind.Switch, 5, 0), (PinMameOutputKind.Switch, 77, 1) })); + } + + [Test] + public void AppliedSwitchesAreKeptBeforeAnybodySubscribes() + { + // a system whose switches can't be read back: the trough switch closed at start-up, another closed and opened later + _outputs.BeginSession(PinMameSwitchNumbering.Unknown); + _outputs.Switch(77, true); + _outputs.Prepare(new[] { 5, 77, 12 }, Array.Empty()); + _outputs.Switch(12, true); + _outputs.Switch(12, false); + _outputs.Switch(5, true); + _outputs.SetSink(_sink); + _sink.Requested = true; + _outputs.Poll(true); + Assert.That(_sink.Snapshot.Where(e => e.Item1 == PinMameOutputKind.Switch), Is.EqualTo(new[] { (PinMameOutputKind.Switch, 5, 1), (PinMameOutputKind.Switch, 12, 0), (PinMameOutputKind.Switch, 77, 1) })); + } + + [Test] + public void SwitchesAreNotReadWhileTheRomIsStopped() + { + _outputs.Prepare(new[] { 33 }, Array.Empty()); + Subscribe(); + _reader.SwitchReads = 0; + _reader.SetSwitch(33, true); + _outputs.Poll(false); + Assert.That(_reader.SwitchReads, Is.EqualTo(0)); + Assert.That(_sink.Changes, Is.Empty); + } + + [Test] + public void AReadBetweenPinMameClearingAndSettingASwitchIsNotPublished() + { + _outputs.Prepare(new[] { 33 }, Array.Empty()); + Subscribe(); + _reader.SetSwitch(33, true); + _outputs.Poll(true); + // core_setSw clears the bit and sets it again; one read sees it open + _reader.GlitchOnce(33); + _outputs.Poll(true); + _outputs.Poll(true); + Assert.That(_sink.Changes, Is.EqualTo(new[] { (PinMameOutputKind.Switch, 33, 1) })); + } + + [Test] + public void TheSnapshotCoversEveryElementThenTheBoundaryThenOnlyChanges() + { + _outputs.Prepare(new[] { 21, 33 }, new[] { 95 }); + _outputs.MarkUserMechRegistered(1); + _outputs.SetSink(_sink); + _outputs.Solenoid(28, 1); + _reader.Lamps.Enqueue((45, 1)); + _reader.Lamps.Enqueue((101, 1)); + _reader.GIs.Enqueue((2, 8)); + _reader.SetSwitch(33, true); + _reader.SetSwitch(-3, true); + _sink.Requested = true; + _outputs.Poll(true); + + var snapshot = _sink.Snapshot; + Assert.That(snapshot.Where(e => e.Item1 == PinMameOutputKind.Solenoid).Select(e => e.Item2), Is.EqualTo(Enumerable.Range(1, 72))); + Assert.That(snapshot, Does.Contain((PinMameOutputKind.Solenoid, 28, 1))); + Assert.That(snapshot.Where(e => e.Item1 == PinMameOutputKind.GeneralIllumination), Is.EqualTo(Enumerable.Range(0, 8).Select(n => (PinMameOutputKind.GeneralIllumination, n, n == 2 ? 8 : 0)))); + // the standard lamps, the ones the table maps and the ones PinMAME reported, off ones included + var lamps = Enumerable.Range(0, 64).Select(i => PinMameSwitchMatrix.LampNumber(PinMameSwitchNumbering.Wpc, i)).Concat(new[] { 95, 101 }).OrderBy(n => n); + Assert.That(snapshot.Where(e => e.Item1 == PinMameOutputKind.Lamp), Is.EqualTo(lamps.Select(n => (PinMameOutputKind.Lamp, n, n == 45 || n == 101 ? 1 : 0)))); + // the whole matrix, as read + var switches = snapshot.Where(e => e.Item1 == PinMameOutputKind.Switch).ToArray(); + Assert.That(switches.Select(e => e.Item2), Is.EqualTo(Enumerable.Range(0, PinMameSwitchMatrix.Size).Select(i => PinMameSwitchMatrix.SwitchNumber(PinMameSwitchNumbering.Wpc, i)).OrderBy(n => n))); + Assert.That(switches.Where(e => e.Item3 == 1).Select(e => e.Item2), Is.EqualTo(new[] { 33 }), "-3 isn't a WPC switch"); + Assert.That(snapshot.Where(e => e.Item1 == PinMameOutputKind.Mech), Is.EqualTo(new[] { (PinMameOutputKind.Mech, 1, 0), (PinMameOutputKind.Mech, -1, 0) })); + Assert.That(_sink.Boundaries, Is.EqualTo(1)); + _sink.Changes.Clear(); + + _outputs.Solenoid(28, 1); + _outputs.Solenoid(28, 0); + _outputs.Poll(true); + Assert.That(_sink.Changes, Is.EqualTo(new[] { (PinMameOutputKind.Solenoid, 28, 0) })); + Assert.That(_sink.Boundaries, Is.EqualTo(1)); + } + + [Test] + public void AReceiverBoundBeforeTheRomStartsWaitsUntilTheGameIsPrepared() + { + _outputs = new PinMameRealtimeOutputs(_reader); + _outputs.SetSink(_sink); + _sink.Requested = true; + _outputs.Poll(false); + _outputs.Poll(true); + Assert.That(_sink.Boundaries, Is.EqualTo(0), "no game yet"); + + _outputs.BeginSession(PinMameSwitchNumbering.Wpc); + _outputs.Solenoid(12, 1); + _outputs.Poll(true); + Assert.That(_sink.Boundaries, Is.EqualTo(0), "the ROM runs, but its outputs aren't known yet"); + Assert.That(_sink.BeginCalls, Is.EqualTo(0)); + + _reader.SetSwitch(33, true); + _outputs.Prepare(new[] { 33 }, new[] { 95 }); + _outputs.Poll(false); + Assert.That(_sink.Boundaries, Is.EqualTo(0), "stopped again"); + _outputs.Poll(true); + Assert.That(_sink.Boundaries, Is.EqualTo(1)); + Assert.That(_sink.Snapshot, Does.Contain((PinMameOutputKind.Solenoid, 12, 1))); + Assert.That(_sink.Snapshot, Does.Contain((PinMameOutputKind.Switch, 33, 1))); + Assert.That(_sink.Snapshot, Does.Contain((PinMameOutputKind.Lamp, 95, 0))); + Assert.That(_sink.Snapshot.Count(e => e.Item1 == PinMameOutputKind.Switch), Is.EqualTo(PinMameSwitchMatrix.Size)); + } + + [Test] + public void ASnapshotThatFailsIsAbortedAndSentAgain() + { + _outputs.SetSink(_sink); + _sink.Requested = true; + _sink.ThrowOnSnapshotValue = 10; + Assert.Throws(() => _outputs.Poll(true)); + Assert.That(_sink.Aborts, Is.EqualTo(1)); + Assert.That(_sink.Boundaries, Is.EqualTo(0)); + + _sink.Snapshot.Clear(); + _sink.Requested = true; + _outputs.Poll(true); + Assert.That(_sink.Boundaries, Is.EqualTo(1)); + Assert.That(_sink.Snapshot.Count(e => e.Item1 == PinMameOutputKind.Solenoid), Is.EqualTo(72)); + } + + [Test] + public void ASnapshotThatTheEndOfItsGameInterruptsIsAborted() + { + _outputs.SetSink(_sink); + _sink.Requested = true; + _sink.OnSnapshotValue = () => { + _sink.OnSnapshotValue = null; + _outputs.EndSession(); + }; + _outputs.Poll(true); + Assert.That(_sink.Aborts, Is.EqualTo(1)); + Assert.That(_sink.Boundaries, Is.EqualTo(0)); + + // the next game's snapshot + _outputs.BeginSession(PinMameSwitchNumbering.Wpc); + _outputs.Prepare(Array.Empty(), Array.Empty()); + _sink.Requested = true; + _outputs.Poll(true); + Assert.That(_sink.Boundaries, Is.EqualTo(1)); + } + + [Test] + public void AReceiverThatJoinsLaterGetsTheStateTheOthersSaw() + { + Subscribe(); + _outputs.Solenoid(9, 255); + _reader.Lamps.Enqueue((61, 1)); + _outputs.Poll(true); + _sink.Requested = true; + _outputs.Poll(true); + Assert.That(_sink.Snapshot, Does.Contain((PinMameOutputKind.Solenoid, 9, 255))); + Assert.That(_sink.Snapshot, Does.Contain((PinMameOutputKind.Lamp, 61, 1))); + } + + [Test] + public void MechPositionAndSpeedAreSeparateElements() + { + Subscribe(); + _outputs.Mech(1, 100, 5); + _outputs.Mech(1, 120, 5); + _outputs.Mech(1, 120, 0); + // not a user mech + _outputs.Mech(6, 50, 1); + _outputs.Poll(true); + Assert.That(_sink.Changes, Is.EqualTo(new[] { + (PinMameOutputKind.Mech, 1, 100), (PinMameOutputKind.Mech, -1, 5), (PinMameOutputKind.Mech, 1, 120), (PinMameOutputKind.Mech, -1, 0), + })); + } + + [Test] + public void AFirstReceiverGetsTheLatestMechStateButNotTheLastGames() + { + // nobody listens while the mech moves + _outputs.Mech(1, 100, 5); + _outputs.SetSink(_sink); + _sink.Requested = true; + _outputs.Poll(true); + Assert.That(_sink.Snapshot.Where(e => e.Item1 == PinMameOutputKind.Mech), Is.EqualTo(new[] { (PinMameOutputKind.Mech, 1, 100), (PinMameOutputKind.Mech, -1, 5) })); + + _outputs.SetSink(null); + _outputs.BeginSession(PinMameSwitchNumbering.Wpc); + _outputs.Prepare(Array.Empty(), Array.Empty()); + _sink.Snapshot.Clear(); + _outputs.SetSink(_sink); + _sink.Requested = true; + _outputs.Poll(true); + Assert.That(_sink.Snapshot.Where(e => e.Item1 == PinMameOutputKind.Mech), Is.Empty); + } + + [Test] + public void ModulatedValuesKeepTheirOrderAcrossSolenoidsAndMechs() + { + Subscribe(); + _outputs.Solenoid(9, 255); + _outputs.Mech(2, 10, 1); + _outputs.Solenoid(9, 128); + _outputs.Solenoid(9, 128); + _outputs.Solenoid(9, 0); + _outputs.Solenoid(9, 255); + _outputs.Poll(true); + Assert.That(_sink.Changes, Is.EqualTo(new[] { + (PinMameOutputKind.Solenoid, 9, 255), (PinMameOutputKind.Mech, 2, 10), (PinMameOutputKind.Mech, -2, 1), + (PinMameOutputKind.Solenoid, 9, 128), (PinMameOutputKind.Solenoid, 9, 0), (PinMameOutputKind.Solenoid, 9, 255), + })); + } + + [Test] + public void ConcurrentProducersKeepTheirOrderAndLoseNothing() + { + Subscribe(); + const int producers = 4, values = 1500; + var done = 0; + var poller = new Thread(() => { + while (Volatile.Read(ref done) == 0) { + _outputs.Poll(false); + } + }); + poller.Start(); + var threads = Enumerable.Range(0, producers).Select(p => new Thread(() => { + for (var i = 0; i < values; i++) { + // unknown to the matrix, so only the ring reports them + _outputs.Switch(1000 + p, (i & 1) == 0); + } + })).ToArray(); + foreach (var thread in threads) thread.Start(); + foreach (var thread in threads) thread.Join(); + Volatile.Write(ref done, 1); + poller.Join(); + _outputs.Poll(false); + + Assert.That(_sink.Changes.Any(e => e.Item1 == PinMameOutputKind.Overflow), Is.False); + for (var p = 0; p < producers; p++) { + var number = 1000 + p; + Assert.That(_sink.Changes.Where(e => e.Item2 == number).Select(e => e.Item3), Is.EqualTo(Enumerable.Range(0, values).Select(i => (i & 1) == 0 ? 1 : 0)), $"producer {p}"); + } + } + + [Test] + public void GiIsNotReplayedAcrossPolls() + { + Subscribe(); + _reader.GIs.Enqueue((2, 8)); + _outputs.Poll(true); + _outputs.Poll(true); + var lamps = new List(); + var gis = new List(); + _outputs.ReadOnMainThread(lamps, gis); + _outputs.ReadOnMainThread(lamps, gis); + Assert.That(_sink.Changes, Is.EqualTo(new[] { (PinMameOutputKind.GeneralIllumination, 2, 8) })); + Assert.That(gis, Is.Empty); + Assert.That(_reader.LampReads, Is.EqualTo(3), "the poll owns the reads"); + } + + [Test] + public void TheMainThreadDispatchesWhatWasReadWithOrWithoutTheFeed() + { + // without a sink the main thread reads, and dispatches every change in PinMAME's order + var lamps = new List(); + var gis = new List(); + _reader.Lamps.Enqueue((13, 1)); + _reader.Lamps.Enqueue((11, 1)); + _reader.GIs.Enqueue((0, 8)); + _outputs.ReadOnMainThread(lamps, gis); + Assert.That(Pairs(lamps), Is.EqualTo(new[] { (13, 1), (11, 1) })); + Assert.That(Pairs(gis), Is.EqualTo(new[] { (0, 8) })); + + // with one, the poll reads; the main thread gets the same changes, one per lamp per frame + Subscribe(); + _reader.Lamps.Enqueue((11, 0)); + _reader.Lamps.Enqueue((12, 1)); + _reader.Lamps.Enqueue((13, 0)); + _outputs.Poll(true); + _reader.Lamps.Enqueue((12, 0)); + _reader.Lamps.Enqueue((14, 1)); + _reader.Lamps.Enqueue((11, 1)); + _reader.GIs.Enqueue((0, 4)); + _outputs.Poll(true); + _reader.Lamps.Enqueue((12, 1)); + _outputs.Poll(true); + var reads = _reader.LampReads; + _outputs.ReadOnMainThread(lamps, gis); + Assert.That(_reader.LampReads, Is.EqualTo(reads)); + Assert.That(Pairs(lamps), Is.EqualTo(new[] { (12, 1), (13, 0), (14, 1) }), "11 is back on, as dispatched before"); + Assert.That(Pairs(gis), Is.EqualTo(new[] { (0, 4) })); + Assert.That(_sink.Changes.Where(e => e.Item1 == PinMameOutputKind.Lamp && e.Item2 == 12).Select(e => e.Item3), Is.EqualTo(new[] { 1, 0, 1 })); + } + + [Test] + public void WhatTheMainThreadReadsWhileThePollStallsReachesTheFeedInOrder() + { + Subscribe(); + _outputs.Poll(true); + Thread.Sleep(300); + var lamps = new List(); + var gis = new List(); + // a flash across two frames + _reader.Lamps.Enqueue((11, 1)); + _reader.GIs.Enqueue((3, 8)); + _outputs.ReadOnMainThread(lamps, gis); + Assert.That(Pairs(lamps), Is.EqualTo(new[] { (11, 1) })); + _reader.Lamps.Enqueue((11, 0)); + _reader.GIs.Enqueue((3, 0)); + _outputs.ReadOnMainThread(lamps, gis); + Assert.That(Pairs(lamps), Is.EqualTo(new[] { (11, 0) })); + + _outputs.Poll(true); + Assert.That(_sink.Changes, Is.EqualTo(new[] { + (PinMameOutputKind.Lamp, 11, 1), (PinMameOutputKind.GeneralIllumination, 3, 8), (PinMameOutputKind.Lamp, 11, 0), (PinMameOutputKind.GeneralIllumination, 3, 0), + })); + } + + [Test] + public void LampsReadWhileThePollStallsKeepTheirOrderWithTheCoils() + { + Subscribe(); + _outputs.Poll(true); + Thread.Sleep(300); + var lamps = new List(); + var gis = new List(); + _reader.Lamps.Enqueue((11, 1)); + _outputs.ReadOnMainThread(lamps, gis); + _outputs.Solenoid(28, 1); + _reader.Lamps.Enqueue((11, 0)); + _outputs.ReadOnMainThread(lamps, gis); + _outputs.Solenoid(28, 0); + + _outputs.Poll(true); + Assert.That(_sink.Changes, Is.EqualTo(new[] { + (PinMameOutputKind.Lamp, 11, 1), (PinMameOutputKind.Solenoid, 28, 1), (PinMameOutputKind.Lamp, 11, 0), (PinMameOutputKind.Solenoid, 28, 0), + })); + } + + [Test] + public void LampReadsWaitBehindAnEntryAProducerIsStillWriting() + { + Subscribe(); + var stalled = ReserveSlot(); + _reader.Lamps.Enqueue((11, 1)); + _outputs.Poll(true); + Assert.That(_sink.Changes, Is.Empty, "the lamp came after the stalled coil"); + + FinishSlot(stalled, PinMameOutputKind.Solenoid, 28, 1); + _outputs.Poll(true); + Assert.That(_sink.Changes, Is.EqualTo(new[] { (PinMameOutputKind.Solenoid, 28, 1), (PinMameOutputKind.Lamp, 11, 1) })); + } + + [Test] + public void ASwitchPulseQueuedBehindAnEntryStillBeingWrittenIsNotHiddenByTheRead() + { + _outputs.Prepare(new[] { 15 }, Array.Empty()); + Subscribe(); + var stalled = ReserveSlot(); + _reader.SetSwitch(15, true); + _outputs.Switch(15, true); + _reader.SetSwitch(15, false); + _outputs.Switch(15, false); + _reader.SetSwitch(15, true); + _outputs.Switch(15, true); + _outputs.Poll(true); + Assert.That(_sink.Changes, Is.Empty, "the read waits for the ring"); + + FinishSlot(stalled, PinMameOutputKind.Solenoid, 28, 1); + _outputs.Poll(true); + Assert.That(_sink.Changes, Is.EqualTo(new[] { + (PinMameOutputKind.Solenoid, 28, 1), (PinMameOutputKind.Switch, 15, 1), (PinMameOutputKind.Switch, 15, 0), (PinMameOutputKind.Switch, 15, 1), + })); + } + + [Test] + public void AnEntryStillBeingWrittenWhenTheRingOverflowedIsNotPublishedAfterTheResync() + { + Subscribe(); + // a producer stalls writing "coil on", the coil goes off, and the ring fills up behind it + var stalled = ReserveSlot(); + _outputs.Solenoid(28, 0); + _outputs.Solenoid(28, 1); + _outputs.Solenoid(28, 0); + for (var i = 0; i < PinMameRealtimeOutputs.EmulationRingSize; i++) { + _outputs.Solenoid(40, i & 1); + } + _outputs.Poll(true); + Assert.That(_sink.Changes.Single(e => e.Item1 == PinMameOutputKind.Overflow).Item2, Is.EqualTo(PinMameRealtimeOutputs.OverflowOutputs)); + _sink.Changes.Clear(); + + FinishSlot(stalled, PinMameOutputKind.Solenoid, 28, 1); + _outputs.Poll(true); + _outputs.Poll(true); + Assert.That(_sink.Changes.Where(e => e.Item2 == 28), Is.Empty, "the old coil-on stays history"); + } + + [Test] + public void AStallTooLongForTheBacklogIsReportedAsAnOverflow() + { + Subscribe(); + _outputs.Poll(true); + Thread.Sleep(300); + var lamps = new List(); + var gis = new List(); + for (var round = 0; round < 10; round++) { + for (var number = 0; number < 2000; number++) _reader.Lamps.Enqueue((number, (round + number) & 1)); + _outputs.ReadOnMainThread(lamps, gis); + } + _outputs.Poll(true); + + var overflow = _sink.Changes.FindIndex(e => e.Item1 == PinMameOutputKind.Overflow); + Assert.That(overflow, Is.EqualTo(PinMameRealtimeOutputs.FeedBacklogSize - 1000), "everything up to the loss in order (the first round's even lamps were off already), then the loss"); + Assert.That(_sink.Changes[overflow], Is.EqualTo((PinMameOutputKind.Overflow, PinMameRealtimeOutputs.OverflowLamps, 20000 - PinMameRealtimeOutputs.FeedBacklogSize))); + var last = new Dictionary(); + foreach (var (kind, number, value) in _sink.Changes) { + if (kind == PinMameOutputKind.Lamp) last[number] = value; + } + for (var number = 0; number < 2000; number++) { + Assert.That(last.TryGetValue(number, out var value) ? value : 0, Is.EqualTo((9 + number) & 1), $"lamp {number}"); + } + } + + [Test] + public void AnEndedSessionTurnsTheFeedOffAndTheMainThreadForgetsSilently() + { + Subscribe(); + _outputs.Solenoid(28, 1); + _reader.Lamps.Enqueue((11, 1)); + _reader.GIs.Enqueue((1, 8)); + _outputs.Poll(true); + var lamps = new List(); + var gis = new List(); + _outputs.ReadOnMainThread(lamps, gis); + _sink.Changes.Clear(); + + _outputs.EndSession(); + _outputs.Poll(false); + Assert.That(_sink.Changes, Is.EquivalentTo(new[] { (PinMameOutputKind.Solenoid, 28, 0), (PinMameOutputKind.Lamp, 11, 0), (PinMameOutputKind.GeneralIllumination, 1, 0) })); + Assert.That(_outputs.IsReady, Is.False); + + // the next game turns lamp 11 on again, which the main thread dispatches + _outputs.BeginRun(); + _outputs.BeginSession(PinMameSwitchNumbering.Wpc); + _outputs.Prepare(Array.Empty(), Array.Empty()); + _reader.Lamps.Enqueue((11, 1)); + _outputs.Poll(true); + _outputs.ReadOnMainThread(lamps, gis); + Assert.That(Pairs(lamps), Is.EqualTo(new[] { (11, 1) })); + Assert.That(gis, Is.Empty); + } + + [Test] + public void ASoftResetStartsFromWhatPinMameReportedBefore() + { + Subscribe(); + _reader.Lamps.Enqueue((11, 1)); + _reader.GIs.Enqueue((1, 8)); + _outputs.Poll(true); + var lamps = new List(); + var gis = new List(); + _outputs.ReadOnMainThread(lamps, gis); + + // PinMAME resets without a new run: it keeps what it reported, so it won't report lamp 11 and GI 1 again + _outputs.EndSession(); + _outputs.Poll(false); + _outputs.ReadOnMainThread(lamps, gis); + _sink.Changes.Clear(); + _outputs.BeginSession(PinMameSwitchNumbering.Wpc); + _outputs.Prepare(Array.Empty(), Array.Empty()); + _outputs.Poll(true); + Assert.That(_sink.Changes, Is.EquivalentTo(new[] { (PinMameOutputKind.Lamp, 11, 1), (PinMameOutputKind.GeneralIllumination, 1, 8) })); + _outputs.ReadOnMainThread(lamps, gis); + Assert.That(Pairs(lamps), Is.EqualTo(new[] { (11, 1) })); + Assert.That(Pairs(gis), Is.EqualTo(new[] { (1, 8) })); + } + + [Test] + public void AnEndedSessionDropsWhatItQueuedAndItsMechs() + { + _outputs.MarkUserMechRegistered(2); + Subscribe(); + _outputs.Mech(1, 100, 5); + _outputs.Poll(true); + // queued, but the game ends before the poll + _outputs.Solenoid(28, 1); + _outputs.Mech(1, 110, 5); + _outputs.EndSession(); + _sink.Changes.Clear(); + _outputs.Poll(false); + Assert.That(_sink.Changes.Where(e => e.Item1 != PinMameOutputKind.Lamp), Is.Empty, "no old pulse, no old mech"); + + // a restart while values were queued, without the end in between + _outputs.BeginSession(PinMameSwitchNumbering.Wpc); + _outputs.Solenoid(28, 1); + _outputs.BeginSession(PinMameSwitchNumbering.Wpc); + _outputs.Prepare(Array.Empty(), Array.Empty()); + _sink.Changes.Clear(); + _sink.Snapshot.Clear(); + _sink.Requested = true; + _outputs.Poll(true); + Assert.That(_sink.Changes.Where(e => e.Item1 == PinMameOutputKind.Solenoid), Is.Empty); + Assert.That(_sink.Snapshot.Where(e => e.Item1 == PinMameOutputKind.Mech), Is.Empty, "the last game's mechs"); + Assert.That(_sink.Snapshot, Does.Contain((PinMameOutputKind.Solenoid, 28, 0))); + } + + [Test] + public void ARestartReplaysTheNewGamesValuesFromItsStart() + { + Subscribe(); + _outputs.Solenoid(9, 128); + _outputs.Poll(true); + _sink.Changes.Clear(); + + _outputs.BeginSession(PinMameSwitchNumbering.Wpc); + _outputs.Solenoid(9, 64); + _outputs.Solenoid(9, 128); + _outputs.Poll(true); + Assert.That(_sink.Changes.Where(e => e.Item1 == PinMameOutputKind.Solenoid), Is.EqualTo(new[] { + (PinMameOutputKind.Solenoid, 9, 0), (PinMameOutputKind.Solenoid, 9, 64), (PinMameOutputKind.Solenoid, 9, 128), + })); + } + + [Test] + public void ASnapshotIsNotTakenWhenTheGameRestartsDuringThePoll() + { + Subscribe(); + _outputs.Solenoid(9, 255); + _sink.Requested = true; + // the ROM restarts and is prepared while the poll publishes the old game's coil + _sink.OnChange = () => { + _sink.OnChange = null; + _outputs.BeginSession(PinMameSwitchNumbering.Wpc); + _outputs.Prepare(Array.Empty(), Array.Empty()); + }; + _outputs.Poll(true); + Assert.That(_sink.Boundaries, Is.EqualTo(0), "the old game's values are no snapshot of the new one"); + + _outputs.Poll(true); + Assert.That(_sink.Boundaries, Is.EqualTo(1)); + Assert.That(_sink.Snapshot, Does.Contain((PinMameOutputKind.Solenoid, 9, 0))); + } + + [Test] + public void AFullRingTheLastGameLeftDoesNotDropTheNewGamesFirstPulse() + { + Subscribe(); + for (var i = 0; i < PinMameRealtimeOutputs.EmulationRingSize + 10; i++) { + _outputs.Solenoid(1 + i % 10, i / 10 & 1); + } + _outputs.BeginSession(PinMameSwitchNumbering.Wpc); + _outputs.Solenoid(20, 1); + _outputs.Solenoid(20, 0); + _outputs.Prepare(Array.Empty(), Array.Empty()); + _outputs.Poll(true); + Assert.That(_sink.Changes.Where(e => e.Item1 == PinMameOutputKind.Solenoid && e.Item2 == 20), Is.EqualTo(new[] { (PinMameOutputKind.Solenoid, 20, 1), (PinMameOutputKind.Solenoid, 20, 0) })); + Assert.That(_sink.Changes, Does.Contain((PinMameOutputKind.Overflow, PinMameRealtimeOutputs.OverflowOutputs, 10)), "the last game's loss is still reported"); + } + + [Test] + public void ANewSinkAndANewGameTogetherForgetTheLastGamesMechs() + { + _outputs.MarkUserMechRegistered(1); + Subscribe(); + _outputs.Mech(1, 100, 5); + _outputs.Poll(true); + + // the game restarts while the receivers bind again, and the table registers the mech again + _outputs.BeginSession(PinMameSwitchNumbering.Wpc); + _outputs.SetSink(_sink); + _outputs.Prepare(Array.Empty(), Array.Empty()); + _outputs.MarkUserMechRegistered(1); + _sink.Snapshot.Clear(); + _sink.Requested = true; + _outputs.Poll(true); + Assert.That(_sink.Snapshot.Where(e => e.Item1 == PinMameOutputKind.Mech), Is.EqualTo(new[] { (PinMameOutputKind.Mech, 1, 0), (PinMameOutputKind.Mech, -1, 0) })); + } + + [Test] + public void LampsTheEndedGameStillHadWaitingAreDiscarded() + { + Subscribe(); + _outputs.Poll(true); + Thread.Sleep(300); + var lamps = new List(); + var gis = new List(); + _reader.Lamps.Enqueue((11, 1)); + _outputs.ReadOnMainThread(lamps, gis); + _outputs.EndSession(); + _outputs.ReadOnMainThread(lamps, gis); + _outputs.Poll(false); + Assert.That(_sink.Changes.Where(e => e.Item1 == PinMameOutputKind.Lamp), Is.Empty); + } + + [Test] + public void AFullEmulationRingIsReportedAndResynchronisesToTheLatestValues() + { + Subscribe(); + for (var i = 0; i < PinMameRealtimeOutputs.EmulationRingSize + 100; i++) { + _outputs.Solenoid(1 + i % 10, i / 10 & 1); + } + // a pulse that doesn't fit + _outputs.Solenoid(20, 1); + _outputs.Solenoid(20, 0); + _outputs.Solenoid(5, 200); + _outputs.Poll(true); + + var overflow = _sink.Changes.FindIndex(e => e.Item1 == PinMameOutputKind.Overflow); + Assert.That(overflow, Is.EqualTo(PinMameRealtimeOutputs.EmulationRingSize - 10), "the ring's entries in order (the first round was off already), then the loss"); + Assert.That(_sink.Changes[overflow], Is.EqualTo((PinMameOutputKind.Overflow, PinMameRealtimeOutputs.OverflowOutputs, 103))); + var expected = new Dictionary(); + for (var i = 0; i < PinMameRealtimeOutputs.EmulationRingSize + 100; i++) expected[1 + i % 10] = i / 10 & 1; + expected[5] = 200; + expected[20] = 0; + var last = new Dictionary(); + foreach (var (kind, number, value) in _sink.Changes) { + if (kind == PinMameOutputKind.Solenoid) last[number] = value; + } + foreach (var (number, value) in expected) { + Assert.That(last.TryGetValue(number, out var published) ? published : 0, Is.EqualTo(value), $"solenoid {number}"); + } + + // recording again + _sink.Changes.Clear(); + _outputs.Solenoid(20, 1); + _outputs.Poll(true); + Assert.That(_sink.Changes, Is.EqualTo(new[] { (PinMameOutputKind.Solenoid, 20, 1) })); + } + + [Test] + public void AFullMainRingResynchronisesFromTheStateTable() + { + Subscribe(); + var lamps = new List(); + var gis = new List(); + for (var round = 0; round < 40; round++) { + for (var number = 0; number < 1000; number++) _reader.Lamps.Enqueue((number, (round + number) & 1)); + _outputs.Poll(true); + } + _outputs.ReadOnMainThread(lamps, gis); + // the last round left the even lamps on and the odd ones off; the main thread had dispatched nothing yet + Assert.That(lamps, Has.Count.EqualTo(500)); + Assert.That(lamps.All(lamp => lamp.Value == 1 && lamp.Id % 2 == 0), Is.True); + } + + [Test] + public void WithoutASinkThePollDoesNothing() + { + _outputs.Solenoid(28, 1); + _reader.Lamps.Enqueue((11, 1)); + _outputs.Poll(true); + Assert.That(_reader.LampReads, Is.EqualTo(0)); + _outputs.SetSink(_sink); + _outputs.Poll(true); + // the solenoid's state is not lost: a new sink starts from the latest values + Assert.That(_sink.Changes, Is.EqualTo(new[] { (PinMameOutputKind.Solenoid, 28, 1), (PinMameOutputKind.Lamp, 11, 1) })); + } + + [Test] + public void PollingDoesNotAllocate() + { + var sink = new CountingSink(); + _outputs.Prepare(Enumerable.Range(0, PinMameSwitchMatrix.Size).Select(i => PinMameSwitchMatrix.SwitchNumber(PinMameSwitchNumbering.Wpc, i)).ToArray(), Array.Empty()); + _outputs.SetSink(sink); + for (var i = 0; i < 3; i++) { + _outputs.Poll(true); + } + var lamps = new List(PinMameRealtimeOutputs.TableSize); + var gis = new List(PinMameRealtimeOutputs.MaxGIs); + _reader.Repeat = true; + + var before = GC.GetAllocatedBytesForCurrentThread(); + for (var i = 0; i < 2000; i++) { + _outputs.Solenoid(1 + i % 72, i & 255); + _outputs.Mech(1, i, i & 7); + _outputs.Switch(15, (i & 1) == 0); + _reader.SetSwitch(33, (i & 2) == 0); + sink.Requested = i % 500 == 0; + _outputs.Poll(true); + if (i % 16 == 0) { + _outputs.ReadOnMainThread(lamps, gis); + } + } + // an overflow and its resync + for (var i = 0; i < PinMameRealtimeOutputs.EmulationRingSize + 10; i++) { + _outputs.Solenoid(1 + i % 72, i & 1); + } + _outputs.Poll(true); + var allocated = GC.GetAllocatedBytesForCurrentThread() - before; + Assert.That(allocated, Is.EqualTo(0)); + Assert.That(sink.Count, Is.GreaterThan(2000)); + } + + [Test] + public void TheNumberingFollowsTheHardwareGeneration() + { + Assert.That(PinMameSwitchMatrix.NumberingOf(0x4), Is.EqualTo(PinMameSwitchNumbering.Wpc), "WPC DMD"); + Assert.That(PinMameSwitchMatrix.NumberingOf(0x80), Is.EqualTo(PinMameSwitchNumbering.Wpc), "WPC-95"); + Assert.That(PinMameSwitchMatrix.NumberingOf(0x0004000000000), Is.EqualTo(PinMameSwitchNumbering.Sequential), "Whitestar"); + Assert.That(PinMameSwitchMatrix.NumberingOf(0x0100000000000), Is.EqualTo(PinMameSwitchNumbering.Sequential), "SAM"); + Assert.That(PinMameSwitchMatrix.NumberingOf(0x0000000000100), Is.EqualTo(PinMameSwitchNumbering.Sequential), "System 11"); + Assert.That(PinMameSwitchMatrix.NumberingOf(0x0000000400000), Is.EqualTo(PinMameSwitchNumbering.Sequential), "Bally 35"); + Assert.That(PinMameSwitchMatrix.NumberingOf(0x0020000000000), Is.EqualTo(PinMameSwitchNumbering.Unknown), "GTS3 converts its own way"); + Assert.That(PinMameSwitchMatrix.NumberingOf(0x0000200000000), Is.EqualTo(PinMameSwitchNumbering.Unknown), "GTS80 converts its own way"); + Assert.That(PinMameSwitchMatrix.NumberingOf(0), Is.EqualTo(PinMameSwitchNumbering.Unknown)); + } + + [Test] + public void SwitchNumbersAndMatrixPositionsConvertBothWays() + { + foreach (var numbering in new[] { PinMameSwitchNumbering.Wpc, PinMameSwitchNumbering.Sequential }) { + for (var index = 0; index < PinMameSwitchMatrix.Size; index++) { + var number = PinMameSwitchMatrix.SwitchNumber(numbering, index); + Assert.That(PinMameSwitchMatrix.TryIndex(numbering, number, out var back), Is.True, $"{numbering} {number}"); + Assert.That(back, Is.EqualTo(index)); + } + } + // as PinMAME converts them: wpc_m2sw and core_m2swSeq + Assert.That(PinMameSwitchMatrix.SwitchNumber(PinMameSwitchNumbering.Wpc, 0), Is.EqualTo(1)); + Assert.That(PinMameSwitchMatrix.SwitchNumber(PinMameSwitchNumbering.Wpc, 8), Is.EqualTo(11)); + Assert.That(PinMameSwitchMatrix.SwitchNumber(PinMameSwitchNumbering.Wpc, 127), Is.EqualTo(158)); + Assert.That(PinMameSwitchMatrix.SwitchNumber(PinMameSwitchNumbering.Sequential, 0), Is.EqualTo(-7)); + Assert.That(PinMameSwitchMatrix.SwitchNumber(PinMameSwitchNumbering.Sequential, 8), Is.EqualTo(1)); + Assert.That(PinMameSwitchMatrix.LampNumber(PinMameSwitchNumbering.Wpc, 0), Is.EqualTo(11)); + Assert.That(PinMameSwitchMatrix.LampNumber(PinMameSwitchNumbering.Wpc, 63), Is.EqualTo(88)); + Assert.That(PinMameSwitchMatrix.LampNumber(PinMameSwitchNumbering.Sequential, 0), Is.EqualTo(1)); + Assert.That(PinMameSwitchMatrix.LampNumber(PinMameSwitchNumbering.Sequential, 63), Is.EqualTo(64)); + Assert.That(PinMameSwitchMatrix.TryIndex(PinMameSwitchNumbering.Sequential, 121, out _), Is.False); + Assert.That(PinMameSwitchMatrix.TryIndex(PinMameSwitchNumbering.Sequential, -8, out _), Is.False); + Assert.That(PinMameSwitchMatrix.TryIndex(PinMameSwitchNumbering.Unknown, 11, out _), Is.False); + } + + private void Subscribe() + { + _outputs.SetSink(_sink); + _sink.Requested = true; + _outputs.Poll(true); + Assert.That(_sink.Boundaries, Is.EqualTo(1)); + _sink.Snapshot.Clear(); + _sink.Changes.Clear(); + _sink.Boundaries = 0; + } + + /// Takes the next ring slot like a producer that is preempted before it writes the entry. + private (long position, int order) ReserveSlot() + { + var enqueue = Field("_enqueuePosition"); + var position = (long)enqueue.GetValue(_outputs); + enqueue.SetValue(_outputs, position + 1); + // the order the slot's position gives the entry + return (position, (int)(position * 2 + 1)); + } + + /// The stalled producer writes its entry. + private void FinishSlot((long position, int order) stalled, PinMameOutputKind kind, int number, int value) + { + var ring = (Array)Field("_ring").GetValue(_outputs); + var index = (int)(stalled.position % ring.Length); + var slot = ring.GetValue(index); + var type = slot.GetType(); + type.GetField("Epoch").SetValue(slot, Field("_epoch").GetValue(_outputs)); + type.GetField("Order").SetValue(slot, stalled.order); + type.GetField("Kind").SetValue(slot, (int)kind); + type.GetField("Number").SetValue(slot, number); + type.GetField("Value").SetValue(slot, value); + type.GetField("Sequence").SetValue(slot, stalled.position + 1); + ring.SetValue(slot, index); + } + + private static FieldInfo Field(string name) => typeof(PinMameRealtimeOutputs).GetField(name, BindingFlags.Instance | BindingFlags.NonPublic); + + private static IEnumerable<(int, int)> Pairs(IEnumerable changes) => changes.Select(change => (change.Id, change.Value)); + + private sealed class FakeReader : IPinMameOutputReader + { + private const int Offset = 8; + public readonly Queue<(int number, int value)> Lamps = new Queue<(int, int)>(); + public readonly Queue<(int number, int value)> GIs = new Queue<(int, int)>(); + public readonly HashSet Invalid = new HashSet(); + public PinMameSwitchNumbering? Validate; + public int LampReads, SwitchReads; + public bool Repeat; + private readonly bool[] _switches = new bool[2048 + Offset]; + private readonly bool[] _glitch = new bool[2048 + Offset]; + private int _tick; + + public void SetSwitch(int number, bool isClosed) => _switches[number + Offset] = isClosed; + public void GlitchOnce(int number) => _glitch[number + Offset] = true; + + public int ReadChangedLamps(int[] numbers, int[] values) + { + LampReads++; + if (Repeat) { + // lamp 11 blinks, lamp 12 dims, with no queue involved + _tick++; + numbers[0] = 11; values[0] = _tick & 1; + numbers[1] = 12; values[1] = _tick & 255; + return 2; + } + return Drain(Lamps, numbers, values); + } + + public int ReadChangedGIs(int[] numbers, int[] values) => Repeat ? 0 : Drain(GIs, numbers, values); + + public bool ReadSwitch(int number) + { + SwitchReads++; + if (Validate.HasValue && !PinMameSwitchMatrix.TryIndex(Validate.Value, number, out _)) { + Invalid.Add(number); + return false; + } + if (_glitch[number + Offset]) { + _glitch[number + Offset] = false; + return !_switches[number + Offset]; + } + return _switches[number + Offset]; + } + + private static int Drain(Queue<(int number, int value)> queue, int[] numbers, int[] values) + { + var count = 0; + while (queue.Count > 0 && count < numbers.Length) { + var (number, value) = queue.Dequeue(); + numbers[count] = number; + values[count] = value; + count++; + } + return count; + } + } + + private sealed class RecordingSink : IPinMameOutputSink + { + public readonly List<(PinMameOutputKind, int, int)> Snapshot = new List<(PinMameOutputKind, int, int)>(); + public readonly List<(PinMameOutputKind, int, int)> Changes = new List<(PinMameOutputKind, int, int)>(); + public int Boundaries, Aborts, BeginCalls; + public bool Requested; + /// Throws on this snapshot value (counted from 1), once. + public int ThrowOnSnapshotValue; + public Action OnSnapshotValue; + public Action OnChange; + + public bool BeginSnapshot() + { + BeginCalls++; + var requested = Requested; + Requested = false; + return requested; + } + + public void SnapshotValue(PinMameOutputKind kind, int number, int value) + { + Snapshot.Add((kind, number, value)); + OnSnapshotValue?.Invoke(); + if (ThrowOnSnapshotValue > 0 && --ThrowOnSnapshotValue == 0) { + throw new InvalidOperationException("receiver failed"); + } + } + + public void EndSnapshot() => Boundaries++; + public void AbortSnapshot() => Aborts++; + public void OutputChanged(PinMameOutputKind kind, int number, int value) + { + Changes.Add((kind, number, value)); + OnChange?.Invoke(); + } + } + + private sealed class CountingSink : IPinMameOutputSink + { + public int Count; + public bool Requested; + public bool BeginSnapshot() => Requested; + public void SnapshotValue(PinMameOutputKind kind, int number, int value) => Count++; + public void EndSnapshot() { } + public void AbortSnapshot() { } + public void OutputChanged(PinMameOutputKind kind, int number, int value) => Count++; + } + } +} diff --git a/VisualPinball.Engine.PinMAME.Test/VisualPinball.Engine.PinMAME.Test.csproj b/VisualPinball.Engine.PinMAME.Test/VisualPinball.Engine.PinMAME.Test.csproj index 8bee8f0..9346d9e 100644 --- a/VisualPinball.Engine.PinMAME.Test/VisualPinball.Engine.PinMAME.Test.csproj +++ b/VisualPinball.Engine.PinMAME.Test/VisualPinball.Engine.PinMAME.Test.csproj @@ -19,6 +19,7 @@ + diff --git a/VisualPinball.Engine.PinMAME.Unity/Runtime/PinMameGamelogicEngine.cs b/VisualPinball.Engine.PinMAME.Unity/Runtime/PinMameGamelogicEngine.cs index 09a6731..b508c1e 100644 --- a/VisualPinball.Engine.PinMAME.Unity/Runtime/PinMameGamelogicEngine.cs +++ b/VisualPinball.Engine.PinMAME.Unity/Runtime/PinMameGamelogicEngine.cs @@ -45,7 +45,7 @@ namespace VisualPinball.Engine.PinMAME [RequireComponent(typeof(AudioSource))] [PackAs("PinMameGamelogicEngine")] [AddComponentMenu("Pinball/Gamelogic Engine/PinMAME")] - public class PinMameGamelogicEngine : MonoBehaviour, IGamelogicEngine, IDisplayFrameFormatPreference, IDisplayResourceMetadata, IGamelogicAudioResourceProvider, IGameIdentityProvider, IRomNameProvider, IGamelogicInputThreading, IGamelogicTimeFence, IGamelogicCoilOutputFeed, IGamelogicSharedStateWriter, IGamelogicSharedStateApplier, IGamelogicPerformanceStats, IGamelogicNativeOutputs, ISegmentDisplayMetadata, IPackable, IDiagnosticsSource, IGamelogicStartupStatus + public class PinMameGamelogicEngine : MonoBehaviour, IGamelogicEngine, IDisplayFrameFormatPreference, IDisplayResourceMetadata, IGamelogicAudioResourceProvider, IGameIdentityProvider, IRomNameProvider, IGamelogicInputThreading, IGamelogicTimeFence, IGamelogicCoilOutputFeed, IGamelogicSharedStateWriter, IGamelogicSharedStateApplier, IGamelogicPerformanceStats, IGamelogicNativeOutputs, IGamelogicRealtimeOutputs, ISegmentDisplayMetadata, IPackable, IDiagnosticsSource, IGamelogicStartupStatus { public string Name { get; } = "PinMAME Gamelogic Engine"; public GamelogicInputDispatchMode SwitchDispatchMode => GamelogicInputDispatchMode.SimulationThread; @@ -472,8 +472,9 @@ public void ApplySharedState(in SimulationState.Snapshot snapshot) [NonSerialized] private BallManager _ballManager; [NonSerialized] private PlayfieldComponent _playfieldComponent; - [NonSerialized] private readonly List _changedLamps = new(); - [NonSerialized] private readonly List _changedGIs = new(); + // this frame's lamp and GI changes, coalesced from what the reader (the real-time poll or Update) read + [NonSerialized] private readonly List _changedLamps = new(PinMameRealtimeOutputs.TableSize); + [NonSerialized] private readonly List _changedGIs = new(PinMameRealtimeOutputs.MaxGIs); private Dictionary _switches = new(); private volatile GamelogicEngineSwitch[] _requestedSwitches = Array.Empty(); @@ -492,6 +493,10 @@ public void ApplySharedState(in SimulationState.Snapshot snapshot) private volatile bool _runtimeCachesBuilt; private volatile bool _isRunning; + // The switches the engine sent while the game ran, by PinMAME number plus the feed's offset: a write count, and the + // value (1 closed, 0 open) when the count is not zero. Cleared before a game runs, so the start-up replay can tell. + private readonly int[] _liveSwitchWrites = new int[PinMameRealtimeOutputs.TableSize]; + private readonly int[] _liveSwitchValues = new int[PinMameRealtimeOutputs.TableSize]; private int _numMechs; private Dictionary _frameBuffer = new(); private volatile DisplayFrameFormat _requestedDmdFrameFormat = DisplayFrameFormat.Dmd8; @@ -758,8 +763,8 @@ private void Update() return; } - // lamps - _pinMame.GetChangedLamps(_changedLamps); + // lamps and gi, read here unless the real-time poll owns the reads + RealtimeOutputs.ReadOnMainThread(_changedLamps, _changedGIs); foreach (var changedLamp in _changedLamps) { lock (_outputStateLock) { _sharedLampStates[changedLamp.Id] = changedLamp.Value; @@ -774,9 +779,7 @@ private void Update() } } - // gi (pinmame-dotnet's list overload appends without clearing, unlike the lamp one, which would replay every change so far) - _changedGIs.Clear(); - _pinMame.GetChangedGIs(_changedGIs); + // gi foreach (var changedGi in _changedGIs) { lock (_outputStateLock) { _sharedGiStates[changedGi.Id] = changedGi.Value; @@ -1253,6 +1256,7 @@ public async Task OnInit(Player player, TableApi tableApi, BallManager ballManag try { _awaitingGameStart = true; Interlocked.Increment(ref _romRun); + RealtimeOutputs.BeginRun(); _pinMame.StartGame(RunningRom); Logger.Debug($"[PinMAME] StartGame returned. RunState={PinMame.PinMame.RunState}"); } @@ -1271,6 +1275,7 @@ public async Task OnInit(Player player, TableApi tableApi, BallManager ballManag Interlocked.Increment(ref _romRun); _romStarting = true; StartAltSound(); + RealtimeOutputs.BeginRun(); _pinMame.StartGame(RunningRom); Logger.Debug($"[PinMAME] StartGame retry returned. RunState={PinMame.PinMame.RunState}"); } @@ -1379,6 +1384,9 @@ private void HandleGameStarted() Interlocked.Exchange(ref _hardwareGen, hardwareGen); // a full fence, see StartAltSound Volatile.Read(ref _altSound)?.SetHardwareGen(hardwareGen); Logger.Info("[PinMAME] Game {Rom} started (hardware {HardwareGen}, libpinmame {Version}).", RunningRom, ((PinMameHardwareGen)(ulong)hardwareGen).ToString(), _nativeVersion ?? "unknown"); + // before the game counts as running: the feed drops what the last game left and holds receivers back until it's prepared + RealtimeOutputs.BeginSession(PinMameSwitchMatrix.NumberingOf((ulong)hardwareGen)); + System.Array.Clear(_liveSwitchWrites, 0, _liveSwitchWrites.Length); _isRunning = true; _solenoidDelayStartTimestampUsec = TimestampUsec; @@ -1386,13 +1394,23 @@ private void HandleGameStarted() try { SendInitialSwitches(); + } + + catch(Exception e) { + Logger.Error(e, "[PinMAME] Could not send the initial switches to ROM {Rom}.", RunningRom); + } + + try { SendMechs(); } catch(Exception e) { - Logger.Error(e, "[PinMAME] Could not send the initial switches and mechs to ROM {Rom}.", RunningRom); + Logger.Error(e, "[PinMAME] Could not send the mechs to ROM {Rom}.", RunningRom); } + // whether or not the mechs could be sent + PrepareRealtimeOutputs(hardwareGen); + EnqueueMainThreadDispatch(() => { OnStarted?.Invoke(this, EventArgs.Empty); // the run state and hardware generation are known now @@ -1439,6 +1457,8 @@ private void HandleGameEnded() EnqueueMainThreadDispatch(() => _player?.RefreshGamelogicDiagnostics()); } _isRunning = false; + // the feed turns everything off and drops what the game still queued; mapped lamps keep what they show, as before + RealtimeOutputs.EndSession(); while (_simulationCoilDispatchQueue.TryDequeue(out _)) { if (Interlocked.Decrement(ref _simulationCoilDispatchQueueSize) < 0) { Interlocked.Exchange(ref _simulationCoilDispatchQueueSize, 0); @@ -2086,6 +2106,8 @@ private void OnSolenoidUpdated(int id, int value) private void HandleSolenoidUpdated(int id, int value) { MarkPinMameCallbackActivity(); + // raw, before the mapping and the start-up delay + RealtimeOutputs.Solenoid(id, value); if (_nativeOutputs != null) { _nativeSolenoids.Enqueue((id, value)); } @@ -2182,22 +2204,60 @@ public void SendInitialSwitches() { var switches = _player.SwitchStatuses; Logger.Info("[PinMAME] Sending initial switch statuses..."); + var applied = new Dictionary(); foreach (var id in switches.Keys) { - var isClosed = switches[id].IsSwitchClosed; - // skip open switches - if (!isClosed) { - continue; - } if (_switches.TryGetValue(id, out var @switch) && _switchIdToPinMameIdMappings.TryGetValue(@switch.Id, out var pinMameId) && !_mechSwitches.Contains(pinMameId)) { - if (Logger.IsDebugEnabled) { - Logger.Debug("[PinMAME] => initial sw {SwitchId} ({MappingId}): closed | {Description}", id, @switch.Id, @switch.Description); + // with several switches on one number, a closed one is sent + if (applied.TryGetValue(pinMameId, out var other) && other.Status.IsSwitchClosed) { + continue; } + applied[pinMameId] = (id, switches[id]); + } + } + // The feed keeps every applied switch, since it can't read them back on every system. The open ones are reported + // too: one released while the game was stopped wasn't applied, and the feed would still have it closed. + foreach (var entry in applied) { + SendInitialSwitch(entry.Key, entry.Value.Id, entry.Value.Status); + } + } - _pinMame.SetSwitch(pinMameId, true); + /// + /// The game already runs here, so the engine can send a switch while it's replayed, and the replay would overwrite + /// it. Not every change updates the switch's status first (scheduled ones don't), so the engine's own writes win: + /// once it wrote a switch in this game, that value is sent, and sent again until no write came in between. Each try + /// takes microseconds and needs a new write to fail, so the limit is only there against a switch that never rests. + /// + private void SendInitialSwitch(int pinMameId, string id, IApiSwitchStatus status) + { + var slot = pinMameId + PinMameRealtimeOutputs.SwitchOffset; + var tracked = (uint)slot < (uint)_liveSwitchWrites.Length; + var writes = tracked ? Volatile.Read(ref _liveSwitchWrites[slot]) : 0; + var isClosed = writes != 0 ? Volatile.Read(ref _liveSwitchValues[slot]) != 0 : status.IsSwitchClosed; + // PinMAME starts with every switch open + var setNative = isClosed; + for (var attempt = 0; attempt < 1000; attempt++) { + if (setNative) { + if (Logger.IsDebugEnabled) { + Logger.Debug("[PinMAME] => initial sw {SwitchId} ({PinMameId}): {IsClosed}", id, pinMameId, isClosed); + } + _pinMame.SetSwitch(pinMameId, isClosed); } + RealtimeOutputs.Switch(pinMameId, isClosed); + if (!tracked) { + return; + } + var now = Volatile.Read(ref _liveSwitchWrites[slot]); + if (now == writes) { + return; + } + // a write came in while this one was sent, and may have gone first + writes = now; + isClosed = Volatile.Read(ref _liveSwitchValues[slot]) != 0; + setNative = true; } + Logger.Warn("[PinMAME] Switch {SwitchId} ({PinMameId}) kept changing while it was sent at start-up; it may be off until it changes again.", id, pinMameId); } public void Switch(string id, bool isClosed) @@ -2212,7 +2272,14 @@ public void Switch(string id, bool isClosed) Logger.Trace("[PinMAME] => sw {SwitchId}: {IsClosed} | {Description}", id, isClosed, sw.Description); } if (_switchIdToPinMameIdMappings.TryGetValue(sw.Id, out pinMameId)) { + var slot = pinMameId + PinMameRealtimeOutputs.SwitchOffset; + if ((uint)slot < (uint)_liveSwitchWrites.Length) { + // the value before the count, so the replay that sees the count sees the value + Volatile.Write(ref _liveSwitchValues[slot], isClosed ? 1 : 0); + Interlocked.Increment(ref _liveSwitchWrites[slot]); + } _pinMame.SetSwitch(pinMameId, isClosed); + RealtimeOutputs.Switch(pinMameId, isClosed); } } } else if (id == "s_spawn_ball") { @@ -2304,6 +2371,156 @@ private static string SegmentLayout(PinMameDisplayType type) #endregion + #region Real-time outputs + + /// + /// The real-time feed and the lamp and GI reads. Created on first use, since the emulation, simulation and main + /// threads all reach it. + /// + private PinMameRealtimeOutputs RealtimeOutputs + { + get { + var outputs = Volatile.Read(ref _realtimeOutputs); + if (outputs != null) { + return outputs; + } + Interlocked.CompareExchange(ref _realtimeOutputs, new PinMameRealtimeOutputs(new OutputReader(this)), null); + return Volatile.Read(ref _realtimeOutputs); + } + } + [NonSerialized] private PinMameRealtimeOutputs _realtimeOutputs; + + public string RealtimeNumbering => RealtimeOutputNumbering.PinMame; + + /// + /// While a listener is set, the poll reads the lamps and GI strings (on the simulation thread), and + /// dispatches what it read. + /// + public void SetRealtimeOutputListener(IRealtimeOutputListener listener) + => RealtimeOutputs.SetSink(listener == null ? null : new RealtimeSink(listener)); + + public void PollRealtimeOutputs() => RealtimeOutputs.Poll(_isRunning); + + /// + /// Tells the feed what this game has once the ROM runs, which lets receivers have their snapshot: the switches it + /// reads on every poll (the mapped ones and the mech switches PinMAME drives itself; the rest of the matrix is read + /// a column per poll), and the lamps the snapshot includes before they report. The feed reads only switches inside + /// the game's matrix, since libpinmame doesn't check the numbers it's given. + /// + private void PrepareRealtimeOutputs(long hardwareGen) + { + try { + var switches = new HashSet(_switchIdToPinMameIdMappings.Values); + switches.UnionWith(_mechSwitches); + var outside = RealtimeOutputs.Prepare(switches, _pinMameIdToLampIdMapping.Keys); + if (RealtimeOutputs.Numbering == PinMameSwitchNumbering.Unknown) { + Logger.Info("[PinMAME] The switch numbering of hardware {HardwareGen} is unknown, so the real-time feed reports the switches VPE applies but reads none from PinMAME.", ((PinMameHardwareGen)(ulong)hardwareGen).ToString()); + + } else if (outside > 0) { + Logger.Warn("[PinMAME] {Count} mapped switch number(s) are outside the switch matrix of ROM {Rom}; the real-time feed doesn't read them.", outside, RunningRom); + } + + } catch (Exception e) { + Logger.Error(e, "[PinMAME] Could not prepare the real-time outputs of ROM {Rom}, so their receivers get no snapshot.", RunningRom); + } + } + + /// + /// User mechs go to the feed as VPinMAME reports them (position as number n, speed as -n). With PinMAME's own + /// mechanics on, the reported numbers aren't the user mechs, so nothing is sent; their switches still are. + /// + private void RecordRealtimeMech(int mechNo, PinMameMechInfo mechInfo) + { + if (DisableMechs) { + RealtimeOutputs.Mech(mechNo, mechInfo.Pos, mechInfo.Speed); + } + } + + /// Reads lamps, GI strings and switches from libpinmame into preallocated buffers. + private sealed class OutputReader : IPinMameOutputReader + { + private readonly PinMameGamelogicEngine _engine; + private readonly List _lamps = new(PinMameRealtimeOutputs.TableSize); + private readonly List _gis = new(16); + + public OutputReader(PinMameGamelogicEngine engine) => _engine = engine; + + public int ReadChangedLamps(int[] numbers, int[] values) + { + var pinMame = _engine._pinMame; + if (pinMame == null) { + return 0; + } + pinMame.GetChangedLamps(_lamps); + return Copy(_lamps, numbers, values); + } + + public int ReadChangedGIs(int[] numbers, int[] values) + { + var pinMame = _engine._pinMame; + if (pinMame == null) { + return 0; + } + // pinmame-dotnet's list overload appends without clearing, unlike the lamp one, which would replay every change so far + _gis.Clear(); + pinMame.GetChangedGIs(_gis); + return Copy(_gis, numbers, values); + } + + public bool ReadSwitch(int number) + { + var pinMame = _engine._pinMame; + return pinMame != null && pinMame.GetSwitch(number); + } + + private static int Copy(List changes, int[] numbers, int[] values) + { + var count = System.Math.Min(changes.Count, numbers.Length); + for (var i = 0; i < count; i++) { + numbers[i] = changes[i].Id; + values[i] = changes[i].Value; + } + return count; + } + } + + /// Hands the feed to VPE's real-time listener. + private sealed class RealtimeSink : IPinMameOutputSink + { + private readonly IRealtimeOutputListener _listener; + + public RealtimeSink(IRealtimeOutputListener listener) => _listener = listener; + + public bool BeginSnapshot() => _listener.BeginSnapshot(); + public void SnapshotValue(PinMameOutputKind kind, int number, int value) => _listener.SnapshotValue(Kind(kind), number, value); + public void EndSnapshot() => _listener.EndSnapshot(); + public void AbortSnapshot() => _listener.AbortSnapshot(); + + public void OutputChanged(PinMameOutputKind kind, int number, int value) + { + if (kind == PinMameOutputKind.Overflow) { + var queue = number == PinMameRealtimeOutputs.OverflowLamps ? RealtimeOutputOverflow.Lamps : RealtimeOutputOverflow.Outputs; + _listener.OutputChanged(RealtimeOutputKind.Overflow, queue, value); + return; + } + _listener.OutputChanged(Kind(kind), number, value); + } + + private static RealtimeOutputKind Kind(PinMameOutputKind kind) + { + switch (kind) { + case PinMameOutputKind.Solenoid: return RealtimeOutputKind.Solenoid; + case PinMameOutputKind.Switch: return RealtimeOutputKind.Switch; + case PinMameOutputKind.Lamp: return RealtimeOutputKind.Lamp; + case PinMameOutputKind.GeneralIllumination: return RealtimeOutputKind.GeneralIllumination; + case PinMameOutputKind.Overflow: return RealtimeOutputKind.Overflow; + default: return RealtimeOutputKind.Mech; + } + } + } + + #endregion + #region Mechs public void RegisterMech(PinMameMechComponent mechComponent) @@ -2319,6 +2536,7 @@ private void OnMechAvailable(int mechNo, PinMameMechInfo mechInfo) NameCallbackThread(); try { Logger.Info("[PinMAME] <= mech available: mechNo={MechNo}, mechInfo={MechInfo}", mechNo, mechInfo.ToString()); + RecordRealtimeMech(mechNo, mechInfo); } catch (Exception e) { LogCallbackFailure(MechCallbackThrottle, "mech available", e); } @@ -2339,6 +2557,7 @@ private void HandleMechUpdated(int mechNo, PinMameMechInfo mechInfo) if (_nativeOutputs != null) { _nativeMechs.Enqueue((mechNo, mechInfo.Pos)); } + RecordRealtimeMech(mechNo, mechInfo); if (_registeredMechs.ContainsKey(mechNo)) { EnqueueMainThreadDispatch(() => _registeredMechs[mechNo].UpdateMech(mechInfo)); @@ -2359,6 +2578,7 @@ private void SendMechs() } var mechConfig = mech.Config(_player.SwitchMapping, _player.CoilMapping, _switchIdToPinMameIdMappings, _coilIdToPinMameIdMapping); _pinMame.SetMech(id, mechConfig); + RealtimeOutputs.MarkUserMechRegistered(id); foreach (var c in mechConfig.SwitchList) { _mechSwitches.Add(c.SwNo); } diff --git a/VisualPinball.Engine.PinMAME.Unity/Runtime/PinMameRealtimeOutputs.cs b/VisualPinball.Engine.PinMAME.Unity/Runtime/PinMameRealtimeOutputs.cs new file mode 100644 index 0000000..310e6b1 --- /dev/null +++ b/VisualPinball.Engine.PinMAME.Unity/Runtime/PinMameRealtimeOutputs.cs @@ -0,0 +1,1332 @@ +// Visual Pinball Engine +// Copyright (C) 2026 freezy and VPE Team +// +// This program is free software: you can redistribute it and/or modify +// it under the terms of the GNU General Public License as published by +// the Free Software Foundation, either version 3 of the License, or +// (at your option) any later version. + +// ReSharper disable CheckNamespace + +using System.Collections.Generic; +using System.Diagnostics; +using System.Threading; + +namespace VisualPinball.Engine.PinMAME +{ + /// The element types of PinMAME's real-time feed, mapped one to one onto the plugin contract's kinds. + internal enum PinMameOutputKind + { + Solenoid, + Switch, + Lamp, + GeneralIllumination, + /// A user mech: number n is mech n's position, number -n its speed. + Mech, + /// + /// The feed lost values: number is or + /// , value how many. The latest values that differ follow. + /// + Overflow, + } + + /// How a game numbers its switches and lamps, which decides where a number sits in PinMAME's matrix. + internal enum PinMameSwitchNumbering + { + /// The driver converts numbers its own way, which VPE does not know: nothing is read from the matrix. + Unknown, + /// Williams WPC: column * 10 + row, such as 11..88, with the cabinet switches in column 0 (1..8). + Wpc, + /// + /// PinMAME's default, used by Williams System 3 to 11, Data East, Whitestar, SAM, Bally and Wico: column * 8 + row + /// - 7, so 1..64 for the matrix and -7..0 for the cabinet switches. + /// + Sequential, + } + + /// + /// PinMAME's switch matrix and standard lamp matrix, and the conversions between their positions and the numbers the + /// API takes (pinmame/src/wpc/core.c, core_swSeq2m and wpc.c, wpc_sw2m). + /// + internal static class PinMameSwitchMatrix + { + /// Switch columns in PinMAME's matrix (CORE_MAXSWCOL), cabinet, flipper and custom columns included. + public const int Columns = 16; + /// Switches per column. + public const int Rows = 8; + /// Positions in the switch matrix. libpinmame does not check the numbers it is given, so only these are read. + public const int Size = Columns * Rows; + /// Lamps of the standard lamp matrix (CORE_STDLAMPCOLS columns of 8). + public const int StandardLamps = 64; + + /// The hardware generations whose drivers keep PinMAME's default conversion (gen.h). + private const ulong SequentialGenerations = + 0x000008000ff00 // GEN_ALLS11: System 9 and 11, Data East + | 0x00000001f0000 // GEN_S7, GEN_S6, GEN_S4, GEN_S3C, GEN_S3 + | 0x0000047e00000 // GEN_ALLBY35: Bally 17 and 35, Stern MPU, Astro, Hankin, Bowling + | 0x0000030000000 // GEN_BY6803, GEN_BY6803A + | 0x001c000000000 // GEN_ALLWS: Whitestar + | 0x0100000000000 // GEN_SAM + | 0x2000000000000; // GEN_WICO + + /// The numbering of a hardware generation. + public static PinMameSwitchNumbering NumberingOf(ulong generation) + { + if ((generation & PinMameOutputModel.GenAllWpc) != 0) { + return PinMameSwitchNumbering.Wpc; + } + return (generation & SequentialGenerations) != 0 ? PinMameSwitchNumbering.Sequential : PinMameSwitchNumbering.Unknown; + } + + /// Where a switch number sits in the matrix, if it sits in it at all. + /// False when the number is outside the matrix or the numbering is unknown. + public static bool TryIndex(PinMameSwitchNumbering numbering, int number, out int index) + { + switch (numbering) { + case PinMameSwitchNumbering.Wpc: { + var row = number % 10; + index = number / 10 * Rows + row - 1; + return number > 0 && row >= 1 && row <= Rows && index < Size; + } + case PinMameSwitchNumbering.Sequential: + index = number + 7; + return index >= 0 && index < Size; + default: + index = -1; + return false; + } + } + + /// The switch number of a matrix position, 0 to - 1, of a known numbering. + public static int SwitchNumber(PinMameSwitchNumbering numbering, int index) + => numbering == PinMameSwitchNumbering.Wpc ? index / Rows * 10 + index % Rows + 1 : index - 7; + + /// The lamp number of a standard lamp, 0 to - 1, of a known numbering. + public static int LampNumber(PinMameSwitchNumbering numbering, int index) + => numbering == PinMameSwitchNumbering.Wpc ? (index / Rows + 1) * 10 + index % Rows + 1 : index + 1; + } + + /// A lamp or GI change for the main thread, by PinMAME number. + internal readonly struct PinMameOutputChange + { + public readonly int Id; + public readonly int Value; + + public PinMameOutputChange(int id, int value) + { + Id = id; + Value = value; + } + + public override string ToString() => $"{Id}: {Value}"; + } + + /// Reads PinMAME's state. The lamp and GI reads are destructive: each change is returned once. + internal interface IPinMameOutputReader + { + /// Copies the lamps that changed since the last call, at most as many as the arrays hold. + /// How many changes were copied. + int ReadChangedLamps(int[] numbers, int[] values); + /// Copies the GI strings that changed since the last call, at most as many as the arrays hold. + /// How many changes were copied. + int ReadChangedGIs(int[] numbers, int[] values); + /// Returns whether a switch is closed. Only called with numbers inside the game's switch matrix. + bool ReadSwitch(int number); + } + + /// Where the real-time feed goes; the engine forwards it to VPE's real-time listener. + internal interface IPinMameOutputSink + { + bool BeginSnapshot(); + void SnapshotValue(PinMameOutputKind kind, int number, int value); + void EndSnapshot(); + void AbortSnapshot(); + void OutputChanged(PinMameOutputKind kind, int number, int value); + } + + /// + /// PinMAME's real-time output feed (DOF) and the main thread's lamp and GI changes, read from PinMAME by one owner. + /// + /// + /// + /// + /// Three producers feed it. PinMAME's emulation thread reports solenoids and user mechs through + /// and , and the engine reports the switches it applies through + /// ; these go into a lock-free ring with their raw values, before VPE's mapping and the coil + /// start-up delay, so modulated values survive. Lamps and GI strings are read from PinMAME destructively, so exactly + /// one owner reads them: while a sink is set, otherwise, or when the + /// poll stopped coming. Every read is recorded, for the feed (which the next poll publishes, so a read on the main + /// thread loses nothing) and for the main thread, which coalesces them with into + /// the changes it dispatches to the mapped lamps. + /// + /// + /// Every event takes the next order number, and the latest value of each solenoid, mech and applied switch is kept + /// with its number, whether or not a sink is set. The poll publishes the ring and the lamp reads merged by that number, + /// so a lamp read between two coil changes is published between them. It publishes a value only when it is newer than + /// what it published for the element, and only when it differs from it. So when a queue overflows, the feed publishes + /// , then the latest values that differ, and an older entry that a producer was + /// still writing is skipped when it comes. The main thread dispatches the lamps that differ from what it dispatched. + /// + /// + /// A game is a session, from to . Either one turns the solenoids, + /// lamps and GI strings off, discards what the ring and the lamp reads still hold, and forgets the mechs; a new + /// session's entries are then published in order, starting from that state. Receivers get their snapshot only once + /// told the feed what the game has: solenoids 1 to 72, GI strings 0 to 7, the standard lamps and + /// those the table maps or PinMAME reported, the user mechs that reported or are registered, and the whole switch + /// matrix (or, with an unknown numbering, the mapped switches as the engine applied them). A snapshot that the end of + /// its session interrupts is aborted. + /// + /// + /// The poll never waits. Producers and the poll share no lock, and the locks between the poll and the main thread are + /// only tried. Each poll reads the switches PinMAME may change itself (mapped and mech switches) and one more matrix + /// column, so the whole matrix every 16 polls; a poll that comes late (the frame update's, when no simulation thread + /// polls) reads the whole matrix. Nothing here allocates after construction, except at session start and in + /// main-thread lists that grow past their capacity. + /// + /// + internal sealed class PinMameRealtimeOutputs + { + /// Solenoid numbers are 1 to 72 (CORE_MODOUT_SOL_MAX). + public const int MaxSolenoids = 72; + /// GI strings are 0 to 7 (CORE_MODOUT_GI_MAX). + public const int MaxGIs = 8; + /// User mechs are 1 to 5, as libpinmame reports them. + public const int MaxUserMechs = 5; + /// Lamp numbers below this keep a state; others pass through without one. + public const int TableSize = 2048; + /// Entries of the emulation-to-poll ring: solenoids, mechs and applied switches. A power of two. + public const int EmulationRingSize = 8192; + /// Lamp and GI reads the feed keeps until the poll publishes them. + public const int FeedBacklogSize = 16384; + /// Entries of the read-to-main-thread ring: lamps and GI strings. + public const int MainRingSize = 16384; + + /// The of the emulation ring: solenoids, mechs and switches. + public const int OverflowOutputs = 1; + /// The of the lamp and GI reads. + public const int OverflowLamps = 2; + + /// After this long without a poll, the main thread reads the lamps itself. + private static readonly long StalePollTicks = Stopwatch.Frequency / 4; + /// A poll this long after the previous one reads the whole switch matrix, not just one column. + private static readonly long SlowPollTicks = Stopwatch.Frequency / 500; + + private const int RingMask = EmulationRingSize - 1; + private const int RingFull = 1; + private const int RingFullBefore = 2; + private const int ResetMarker = -1; + // switch numbers go down to -7 (sequential cabinet switches) + internal const int SwitchOffset = 8; + // order numbers wrap; the poll keeps the ones it compares within this distance of the current one + private const int OrderWindow = 1 << 29; + private const int PollsPerOrderRefresh = 1024; + + private struct Slot + { + public long Sequence; + public int Epoch; + public int Order; + public int Kind; + public int Number; + public int Value; + } + + private struct Entry + { + public int Kind; + public int Number; + public int Value; + public int Order; + } + + /// What the feed knows of the running game. Replaced as a whole. + private sealed class Session + { + public static readonly Session None = new(PinMameSwitchNumbering.Unknown, System.Array.Empty(), System.Array.Empty(), false); + + public readonly PinMameSwitchNumbering Numbering; + /// Matrix positions read on every poll. + public readonly int[] Polled; + /// Switch numbers in the snapshot. + public readonly int[] Snapshot; + /// Whether receivers may get their snapshot. + public readonly bool Ready; + + public Session(PinMameSwitchNumbering numbering, int[] polled, int[] snapshot, bool ready) + { + Numbering = numbering; + Polled = polled; + Snapshot = snapshot; + Ready = ready; + } + } + + private readonly IPinMameOutputReader _reader; + private IPinMameOutputSink _sink; + private Session _session = Session.None; + + // ---- emulation-to-poll ring: bounded, lock-free, any number of producers, the poll consumes + private readonly Slot[] _ring = new Slot[EmulationRingSize]; + private long _enqueuePosition; + private long _dequeuePosition; + private int _ringEnabled; + // RingFull while producers drop, RingFullBefore when an earlier session's loss is still to be published + private int _ringOverflowed; + private int _ringDropped; + // a new session or sink: entries stamped with an earlier one are discarded + private int _epoch; + private int _sinks; + private int _sessions; + private int _sessionOrder; + // the latest value of each element with its order number (packed, see Pack), whether a sink is set or not + private readonly long[] _latestSolenoids = new long[MaxSolenoids + 1]; + private readonly long[] _latestMechPositions = new long[MaxUserMechs + 1]; + private readonly long[] _latestMechSpeeds = new long[MaxUserMechs + 1]; + private readonly bool[] _latestMechKnown = new bool[MaxUserMechs + 1]; + private readonly long[] _latestSwitches = new long[TableSize]; + // a packed open switch can be 0, so whether a switch was ever applied is kept apart + private readonly bool[] _latestSwitchKnown = new bool[TableSize]; + private readonly bool[] _userMechRegistered = new bool[MaxUserMechs + 1]; + + // ---- the feed's tables: what the live receivers saw, and the order of the value. Poll only. + private readonly object _pollLock = new(); + private int _pollEpoch; + private int _pollSinks; + private int _pollSessions; + private int _polls; + private readonly int[] _feedSolenoids = new int[MaxSolenoids + 1]; + private readonly int[] _feedSolenoidOrders = new int[MaxSolenoids + 1]; + private readonly int[] _feedMechPositions = new int[MaxUserMechs + 1]; + private readonly int[] _feedMechPositionOrders = new int[MaxUserMechs + 1]; + private readonly int[] _feedMechSpeeds = new int[MaxUserMechs + 1]; + private readonly int[] _feedMechSpeedOrders = new int[MaxUserMechs + 1]; + private readonly bool[] _feedMechKnown = new bool[MaxUserMechs + 1]; + private readonly int[] _feedLamps = new int[TableSize]; + private readonly int[] _feedGIs = new int[MaxGIs]; + private readonly byte[] _feedSwitches = new byte[TableSize]; + private readonly int[] _feedSwitchOrders = new int[TableSize]; + private int _feedResync; + private int _fullScan; + private int _scanColumn; + private long _lastPollTimestamp; + + // ---- PinMAME's lamp and GI state, the feed's backlog and the main-thread ring, under _readLock + private readonly object _readLock = new(); + private readonly int[] _readNumbers = new int[TableSize]; + private readonly int[] _readValues = new int[TableSize]; + private readonly int[] _lamps = new int[TableSize]; + private readonly int[] _gis = new int[MaxGIs]; + private readonly bool[] _lampKnown = new bool[TableSize]; + private int _resetPending; + // what PinMAME last reported for each lamp and GI string, which is what it compares the next read with: a session + // that starts without a new run (a soft reset) gets no change for what stayed, so these are its starting values + private readonly int[] _reportedLamps = new int[TableSize]; + private readonly int[] _reportedGis = new int[MaxGIs]; + private bool _resetReseeds; + private readonly Entry[] _backlog = new Entry[FeedBacklogSize]; + private int _backlogCount; + private int _backlogLost; + private readonly Entry[] _mainRing = new Entry[MainRingSize]; + private int _mainCount; + private bool _mainOverflow; + + // ---- main thread's view: what it dispatched. Under _readLock. + private readonly int[] _mainLamps = new int[TableSize]; + private readonly int[] _mainGIs = new int[MaxGIs]; + private readonly int[] _pendingLamps = new int[TableSize]; + private readonly int[] _pendingGIs = new int[MaxGIs]; + private readonly bool[] _lampDirty = new bool[TableSize]; + private readonly bool[] _giDirty = new bool[MaxGIs]; + private readonly int[] _lampOrder = new int[TableSize]; + private readonly int[] _giOrder = new int[MaxGIs]; + + public PinMameRealtimeOutputs(IPinMameOutputReader reader) + { + _reader = reader; + for (var i = 0; i < EmulationRingSize; i++) { + _ring[i].Sequence = i; + } + } + + /// Whether a sink is set, so the poll owns the lamp and GI reads. + public bool HasSink => Volatile.Read(ref _sink) != null; + + /// Whether receivers get their snapshot: a session runs and was called for it. + public bool IsReady => Volatile.Read(ref _session).Ready; + + /// The switch numbering of the running session. + public PinMameSwitchNumbering Numbering => Volatile.Read(ref _session).Numbering; + + /// + /// Sets the sink, or null, on the main thread. A new sink starts from a resync of the latest values and discards + /// what the ring holds; without one the ring stops recording and the main thread reads the lamps again. + /// + public void SetSink(IPinMameOutputSink sink) + { + lock (_readLock) { + _backlogCount = 0; + _backlogLost = 0; + Volatile.Write(ref _sink, sink); + } + Volatile.Write(ref _ringEnabled, sink != null ? 1 : 0); + Interlocked.Increment(ref _sinks); + Interlocked.Increment(ref _epoch); + if (sink != null) { + Volatile.Write(ref _feedResync, 1); + } + } + + #region Order numbers + + private static long Pack(int value, int order) => (long)order << 32 | (uint)value; + private static int ValueOf(long packed) => (int)packed; + private static int OrderOf(long packed) => (int)(packed >> 32); + private static bool IsNewer(int order, int than) => order - than > 0; + + // An entry's order number comes from its ring position, so the order is the order of the reservations. A value + // recorded outside the ring (a lamp read, a value without a sink or while the ring is full) is ordered before the + // next entry: an even number between two odd ones. Values outside the ring can share a number; the later one wins, + // so the feed publishes a value whose order is at least the one it has. + private static int EntryOrder(long position) => (int)(position * 2 + 1); + private int CurrentOrder => (int)(Volatile.Read(ref _enqueuePosition) * 2); + // what a switch scan sees comes after everything the poll took from the ring and before everything it did not + private int ScanOrder => (int)(Volatile.Read(ref _dequeuePosition) * 2); + + /// Keeps the newer of two values of an element that two threads may report at once; the later one of equals. + private static void StoreLatest(ref long latest, int value, int order) + { + while (true) { + var current = Interlocked.Read(ref latest); + if (current != 0 && IsNewer(OrderOf(current), order)) { + // a fence like the exchange's, before the producer looks at the ring's state + Thread.MemoryBarrier(); + return; + } + if (Interlocked.CompareExchange(ref latest, Pack(value, order), current) == current) { + return; + } + } + } + + /// Raises the orders the poll compares against to the window below the current one, so they never wrap past it. + private void KeepOrdersRecent() + { + var floor = CurrentOrder - OrderWindow; + Raise(_feedSolenoidOrders, floor); + Raise(_feedMechPositionOrders, floor); + Raise(_feedMechSpeedOrders, floor); + Raise(_feedSwitchOrders, floor); + } + + private static void Raise(int[] orders, int floor) + { + for (var i = 0; i < orders.Length; i++) { + if (IsNewer(floor, orders[i])) { + orders[i] = floor; + } + } + } + + #endregion + + #region Producers + + /// A solenoid's raw value, from the emulation thread. + public void Solenoid(int number, int value) + => Record(PinMameOutputKind.Solenoid, number, value, (uint)number <= MaxSolenoids ? _latestSolenoids : null, number); + + /// A user mech's position and speed as VPinMAME integers, from the emulation thread. + public void Mech(int number, int position, int speed) + { + if (number < 1 || number > MaxUserMechs) { + return; + } + // known before the values, so a resync that sees them sees the mech + Volatile.Write(ref _latestMechKnown[number], true); + Record(PinMameOutputKind.Mech, number, position, _latestMechPositions, number); + Record(PinMameOutputKind.Mech, -number, speed, _latestMechSpeeds, number); + } + + /// + /// A switch the engine applied to PinMAME, from the thread that applied it, the initial ones at game start included. + /// Kept whether a sink is set or not, so a snapshot has it even where the switches can't be read back. + /// + public void Switch(int number, bool isClosed) + { + var slot = number + SwitchOffset; + if ((uint)slot < TableSize) { + Volatile.Write(ref _latestSwitchKnown[slot], true); + } + Record(PinMameOutputKind.Switch, number, isClosed ? 1 : 0, (uint)slot < TableSize ? _latestSwitches : null, slot); + } + + /// + /// Records a value without waiting: into the ring, where it takes its order number from the slot it reserves, and + /// into its latest-value table. Without a sink, or while the ring is full, only the table gets it, ordered before the + /// next slot; a full ring drops everything until the poll published the overflow and resynchronised. + /// + private void Record(PinMameOutputKind kind, int number, int value, long[] latest, int index) + { + while (true) { + if (Volatile.Read(ref _ringEnabled) != 0 && Volatile.Read(ref _ringOverflowed) != RingFull) { + if (TryEnqueue(kind, number, value, latest, index)) { + return; + } + Interlocked.Exchange(ref _ringOverflowed, RingFull); + } + if (latest != null) { + StoreLatest(ref latest[index], value, CurrentOrder); + } else { + Thread.MemoryBarrier(); + } + if (Volatile.Read(ref _ringEnabled) == 0) { + return; + } + if (Volatile.Read(ref _ringOverflowed) == RingFull) { + Interlocked.Increment(ref _ringDropped); + return; + } + // the poll resynchronised in between, maybe without this value: record it after all + } + } + + /// Adds an entry to the ring (Vyukov's bounded queue), or returns false when the ring is full. + private bool TryEnqueue(PinMameOutputKind kind, int number, int value, long[] latest, int index) + { + var epoch = Volatile.Read(ref _epoch); + var position = Volatile.Read(ref _enqueuePosition); + while (true) { + ref var slot = ref _ring[position & RingMask]; + var difference = Volatile.Read(ref slot.Sequence) - position; + if (difference == 0) { + var observed = Interlocked.CompareExchange(ref _enqueuePosition, position + 1, position); + if (observed == position) { + var order = EntryOrder(position); + if (latest != null) { + StoreLatest(ref latest[index], value, order); + } + slot.Epoch = epoch; + slot.Order = order; + slot.Kind = (int)kind; + slot.Number = number; + slot.Value = value; + Volatile.Write(ref slot.Sequence, position + 1); + return true; + } + position = observed; + + } else if (difference < 0) { + // full; entries of an earlier session or sink are discarded anyway, so they make room for this one + if (!TryDiscardStaleHead(epoch)) { + return false; + } + position = Volatile.Read(ref _enqueuePosition); + + } else { + position = Volatile.Read(ref _enqueuePosition); + } + } + } + + /// A producer takes the oldest entry off a full ring when it belongs to an earlier session or sink. + private bool TryDiscardStaleHead(int epoch) + { + var position = Volatile.Read(ref _dequeuePosition); + ref var slot = ref _ring[position & RingMask]; + if (Volatile.Read(ref slot.Sequence) != position + 1 || slot.Epoch - epoch >= 0) { + return false; + } + if (Interlocked.CompareExchange(ref _dequeuePosition, position + 1, position) == position) { + Volatile.Write(ref slot.Sequence, position + EmulationRingSize); + } + return true; + } + + private bool TryPeek(out Slot entry, out long position) + { + position = Volatile.Read(ref _dequeuePosition); + ref var slot = ref _ring[position & RingMask]; + if (Volatile.Read(ref slot.Sequence) != position + 1) { + entry = default; + return false; + } + entry = slot; + return true; + } + + /// Takes the entry the poll peeked at; false when a producer discarded it first, as stale. + private bool TryTake(long position) + { + if (Interlocked.CompareExchange(ref _dequeuePosition, position + 1, position) != position) { + return false; + } + Volatile.Write(ref _ring[position & RingMask].Sequence, position + EmulationRingSize); + return true; + } + + /// Whether the ring holds entries the poll did not take, a producer may still be writing the first. + private bool IsHeadPending => Volatile.Read(ref _dequeuePosition) != Volatile.Read(ref _enqueuePosition); + + #endregion + + #region Game session + + /// + /// A game starts, on the emulation thread and before the engine marks it running. Discards what earlier sessions + /// queued, forgets their mechs, turns solenoids, lamps and GI off as does, and holds back + /// snapshots until . + /// + /// How the game numbers switches and lamps, from its hardware generation. + public void BeginSession(PinMameSwitchNumbering numbering) + { + Volatile.Write(ref _session, new Session(numbering, System.Array.Empty(), System.Array.Empty(), false)); + Forget(true); + if (numbering != PinMameSwitchNumbering.Unknown) { + for (var index = 0; index < PinMameSwitchMatrix.StandardLamps; index++) { + MarkLampKnown(PinMameSwitchMatrix.LampNumber(numbering, index)); + } + } + } + + /// + /// Tells the feed what the game has, once the engine initialized it, and lets receivers have their snapshot. A + /// receiver that subscribed before waits for this. + /// + /// + /// The switches PinMAME may change itself or the table maps. Those inside the matrix are read on every poll; with an + /// unknown numbering none are read, and the snapshot reports them as the engine applied them. + /// + /// The lamps the table maps, which the snapshot includes before PinMAME reports them. + /// How many distinct switches are outside the game's matrix and are not read. + public int Prepare(IEnumerable switches, IEnumerable lamps) + { + var numbering = Volatile.Read(ref _session).Numbering; + var polled = new SortedSet(); + var snapshot = new SortedSet(); + var outside = new HashSet(); + foreach (var number in switches) { + if (numbering == PinMameSwitchNumbering.Unknown) { + if ((uint)(number + SwitchOffset) < TableSize) { + snapshot.Add(number); + } + } else if (PinMameSwitchMatrix.TryIndex(numbering, number, out var index)) { + polled.Add(index); + } else { + outside.Add(number); + } + } + if (numbering != PinMameSwitchNumbering.Unknown) { + for (var index = 0; index < PinMameSwitchMatrix.Size; index++) { + snapshot.Add(PinMameSwitchMatrix.SwitchNumber(numbering, index)); + } + } + foreach (var lamp in lamps) { + MarkLampKnown(lamp); + } + var polledArray = new int[polled.Count]; + polled.CopyTo(polledArray); + var snapshotArray = new int[snapshot.Count]; + snapshot.CopyTo(snapshotArray); + + Volatile.Write(ref _fullScan, 1); + Volatile.Write(ref _session, new Session(numbering, polledArray, snapshotArray, true)); + return outside.Count; + } + + /// A user mech the table registered, which the snapshot includes even before it reported. + public void MarkUserMechRegistered(int number) + { + if (number >= 1 && number <= MaxUserMechs) { + Volatile.Write(ref _userMechRegistered[number], true); + } + } + + /// + /// The ROM stopped, on the emulation thread: solenoids, lamps and GI strings are off from PinMAME's point of view, + /// and the feed publishes the zeros; the main thread forgets what it dispatched without dispatching anything. What + /// the ring and the lamp reads still hold is discarded, mechs are forgotten, and no snapshot is sent until the next + /// session is prepared. Switches keep their state, since the machine still has it. + /// + public void EndSession() + { + var session = Volatile.Read(ref _session); + Volatile.Write(ref _session, new Session(session.Numbering, session.Polled, System.Array.Empty(), false)); + Forget(false); + } + + private void Forget(bool starts) + { + // newer than every earlier entry, and the new session's values are at least as new + var order = CurrentOrder; + for (var number = 0; number <= MaxSolenoids; number++) { + Interlocked.Exchange(ref _latestSolenoids[number], Pack(0, order)); + } + for (var number = 0; number <= MaxUserMechs; number++) { + Volatile.Write(ref _latestMechKnown[number], false); + Interlocked.Exchange(ref _latestMechPositions[number], Pack(0, order)); + Interlocked.Exchange(ref _latestMechSpeeds[number], Pack(0, order)); + Volatile.Write(ref _userMechRegistered[number], false); + } + // the poll that sees the new epoch starts the session from this order + Volatile.Write(ref _sessionOrder, order); + Interlocked.Increment(ref _sessions); + Interlocked.Increment(ref _epoch); + // a ring the earlier session filled takes the new one's values again; its entries make room for them, and the + // poll still publishes the loss + Interlocked.CompareExchange(ref _ringOverflowed, RingFullBefore, RingFull); + // Applied now rather than by the next read: a read between that read's check and its own lamp read would take the + // new game's first changes, and the reset after it would turn them off. PinMAME reports a state change before the + // ROM runs and without holding its own lock, so nothing new is read yet and the readers can't wait on this thread. + lock (_readLock) { + _resetPending = 1; + _resetReseeds = starts; + ApplyPendingReset(); + _resetReseeds = false; + } + } + + /// + /// PinMAME is about to start a new run, which forgets what it reported: its next reads report every lamp and GI string + /// that is on. Called before the engine starts the game, unlike a soft reset, which keeps them. + /// + public void BeginRun() + { + lock (_readLock) { + System.Array.Clear(_reportedLamps, 0, _reportedLamps.Length); + System.Array.Clear(_reportedGis, 0, _reportedGis.Length); + } + } + + private void MarkLampKnown(int number) + { + if ((uint)number < TableSize) { + Volatile.Write(ref _lampKnown[number], true); + } + } + + #endregion + + #region Poll + + /// + /// Publishes what changed since the last poll to the sink, and the snapshot a new receiver asked for. Returns at once + /// without a sink or while another poll runs; never waits for another thread. + /// + /// + /// A game that ends or restarts in the middle of a poll can still lose a change of that moment: a coil queued behind + /// one delivered as the game ends, or the first pulse of a new game behind a slot the old game reserved but did not + /// finish in a full ring, which the receiver sees as an overflow. The element's next change puts its state right, a + /// missed pulse stays lost, and a receiver that is already live gets no new snapshot. A stopped receiver's gate turns + /// the outputs off either way. + /// + /// Whether the ROM runs, so lamps, GI and switches can be read. + public void Poll(bool running) + { + var sink = Volatile.Read(ref _sink); + if (sink == null || !Monitor.TryEnter(_pollLock)) { + return; + } + try { + var now = Stopwatch.GetTimestamp(); + var late = now - Volatile.Read(ref _lastPollTimestamp) > SlowPollTicks; + Volatile.Write(ref _lastPollTimestamp, now); + + if (!Monitor.TryEnter(_readLock)) { + // the main thread is coalescing; the ring waits with the lamps, so they stay in order + return; + } + try { + // taken before the drain: a session that starts later has values this poll may not have published + var session = Volatile.Read(ref _session); + ApplyPendingReset(); + if (running) { + Read(); + } + // switches are read once the ring is empty, so what a read sees is newer than every entry published + var drained = Drain(sink); + if (Interlocked.Exchange(ref _feedResync, 0) != 0) { + ResyncLamps(sink); + } + var current = drained && Volatile.Read(ref _session) == session; + if (running && current) { + ReadSwitches(sink, session, late); + } + if (running && current && session.Ready && sink.BeginSnapshot()) { + try { + ReadAllSwitches(sink, session.Numbering); + Snapshot(sink, session); + } catch { + // the receivers must not go live on half a snapshot; they get another one + sink.AbortSnapshot(); + throw; + } + if (Volatile.Read(ref _session) == session) { + sink.EndSnapshot(); + } else { + // the game ended or restarted meanwhile: the receivers get the next one's snapshot + sink.AbortSnapshot(); + } + } + if (++_polls % PollsPerOrderRefresh == 0) { + KeepOrdersRecent(); + } + } finally { + Monitor.Exit(_readLock); + } + } finally { + Monitor.Exit(_pollLock); + } + } + + /// + /// Publishes the ring and the lamp reads, merged by order number, then what an overflow requires. Returns whether it + /// emptied the ring, rather than stopping at an entry a producer is still writing or after a ring's worth. + /// + private bool Drain(IPinMameOutputSink sink) + { + var epoch = Volatile.Read(ref _epoch); + if (epoch != _pollEpoch) { + ChangeEpoch(sink, epoch); + } + // read before draining: what is in the ring now came before the values that were dropped + var overflowed = Volatile.Read(ref _ringOverflowed) != 0; + + var next = 0; + var drained = 0; + bool emptied; + while (true) { + var entry = default(Slot); + var position = 0L; + var hasEntry = drained < EmulationRingSize && TryPeek(out entry, out position); + emptied = !hasEntry && drained < EmulationRingSize && !IsHeadPending; + if (next < _backlogCount) { + ref var read = ref _backlog[next]; + // without an entry, a lamp read goes first unless a producer is still writing an older entry + if (hasEntry ? IsNewer(entry.Order, read.Order) : emptied) { + PublishRead(sink, ref read); + next++; + continue; + } + } + if (!hasEntry) { + break; + } + drained++; + if (!TryTake(position)) { + // a producer discarded it, as one of an earlier session or sink + continue; + } + if (entry.Epoch != _pollEpoch) { + if (entry.Epoch - _pollEpoch < 0) { + continue; + } + // a session started or a sink was set while this poll drains + ChangeEpoch(sink, entry.Epoch); + } + switch ((PinMameOutputKind)entry.Kind) { + case PinMameOutputKind.Solenoid: + PublishSolenoid(sink, entry.Number, entry.Value, entry.Order); + break; + case PinMameOutputKind.Mech: + PublishMech(sink, entry.Number, entry.Value, entry.Order); + break; + case PinMameOutputKind.Switch: + PublishSwitch(sink, entry.Number, entry.Value, entry.Order); + break; + } + } + + // what waits behind an entry that is still being written goes out with the next poll + if (next > 0) { + var rest = _backlogCount - next; + if (rest > 0) { + System.Array.Copy(_backlog, next, _backlog, 0, rest); + } + _backlogCount = rest; + } + if (_backlogCount == 0 && _backlogLost > 0) { + sink.OutputChanged(PinMameOutputKind.Overflow, OverflowLamps, _backlogLost); + _backlogLost = 0; + ResyncLamps(sink); + } + + if (overflowed) { + // producers record again from here. The resync covers what they reported meanwhile, and an entry that was + // still being written is older than what it publishes, so it is skipped when it comes. + Interlocked.Exchange(ref _ringOverflowed, 0); + var lost = Interlocked.Exchange(ref _ringDropped, 0); + sink.OutputChanged(PinMameOutputKind.Overflow, OverflowOutputs, lost > 0 ? lost : 1); + ResyncFromLatest(sink); + // switches PinMAME changed itself may be lost too + Volatile.Write(ref _fullScan, 1); + } + return emptied; + } + + /// + /// A new session starts from its beginning, solenoids off and no mechs, and its own entries follow in order. A new + /// sink then catches up with the latest values (nobody has its snapshot yet). Both can happen between two polls. + /// + private void ChangeEpoch(IPinMameOutputSink sink, int epoch) + { + _pollEpoch = epoch; + var sinks = Volatile.Read(ref _sinks); + var sessions = Volatile.Read(ref _sessions); + if (sessions != _pollSessions) { + _pollSessions = sessions; + var order = Volatile.Read(ref _sessionOrder); + for (var number = 1; number <= MaxSolenoids; number++) { + PublishSolenoid(sink, number, 0, order); + } + for (var number = 1; number <= MaxUserMechs; number++) { + _feedMechKnown[number] = false; + _feedMechPositions[number] = _feedMechSpeeds[number] = 0; + _feedMechPositionOrders[number] = _feedMechSpeedOrders[number] = order; + } + } + if (sinks != _pollSinks) { + _pollSinks = sinks; + ResyncFromLatest(sink); + } + } + + /// Publishes each element's latest value that is at least as new as what the feed has and differs from it. + private void ResyncFromLatest(IPinMameOutputSink sink) + { + for (var number = 1; number <= MaxSolenoids; number++) { + var latest = Interlocked.Read(ref _latestSolenoids[number]); + PublishSolenoid(sink, number, ValueOf(latest), OrderOf(latest)); + } + for (var number = 1; number <= MaxUserMechs; number++) { + if (!Volatile.Read(ref _latestMechKnown[number])) { + // a mech the table registers again starts from zero, not from what an earlier game left + _feedMechKnown[number] = false; + _feedMechPositions[number] = _feedMechSpeeds[number] = 0; + continue; + } + var position = Interlocked.Read(ref _latestMechPositions[number]); + var speed = Interlocked.Read(ref _latestMechSpeeds[number]); + PublishMech(sink, number, ValueOf(position), OrderOf(position)); + PublishMech(sink, -number, ValueOf(speed), OrderOf(speed)); + } + for (var slot = 0; slot < TableSize; slot++) { + if (Volatile.Read(ref _latestSwitchKnown[slot])) { + var latest = Interlocked.Read(ref _latestSwitches[slot]); + PublishSwitch(sink, slot - SwitchOffset, ValueOf(latest), OrderOf(latest)); + } + } + } + + private void PublishSolenoid(IPinMameOutputSink sink, int number, int value, int order) + { + if ((uint)number <= MaxSolenoids) { + if (IsNewer(_feedSolenoidOrders[number], order)) { + return; + } + _feedSolenoidOrders[number] = order; + if (_feedSolenoids[number] == value) { + return; + } + _feedSolenoids[number] = value; + } + sink.OutputChanged(PinMameOutputKind.Solenoid, number, value); + } + + private void PublishMech(IPinMameOutputSink sink, int number, int value, int order) + { + var mech = number < 0 ? -number : number; + var values = number < 0 ? _feedMechSpeeds : _feedMechPositions; + var orders = number < 0 ? _feedMechSpeedOrders : _feedMechPositionOrders; + if (IsNewer(orders[mech], order)) { + return; + } + orders[mech] = order; + if (_feedMechKnown[mech] && values[mech] == value) { + return; + } + values[mech] = value; + if (number < 0) { + // the position comes first, so both are known from the speed on + _feedMechKnown[mech] = true; + } + sink.OutputChanged(PinMameOutputKind.Mech, number, value); + } + + private void PublishSwitch(IPinMameOutputSink sink, int number, int value, int order) + { + var slot = number + SwitchOffset; + if ((uint)slot < TableSize) { + if (IsNewer(_feedSwitchOrders[slot], order)) { + return; + } + _feedSwitchOrders[slot] = order; + if (_feedSwitches[slot] == value) { + return; + } + _feedSwitches[slot] = (byte)value; + } + sink.OutputChanged(PinMameOutputKind.Switch, number, value); + } + + /// + /// The switches PinMAME may change itself, and one more column of the matrix. All of it after a session started, + /// after a loss, and when the poll comes late (then it is the frame update's, so a column each would take long). + /// + private void ReadSwitches(IPinMameOutputSink sink, Session session, bool late) + { + var numbering = session.Numbering; + if (numbering == PinMameSwitchNumbering.Unknown) { + return; + } + if (Interlocked.Exchange(ref _fullScan, 0) != 0 | late) { + ReadAllSwitches(sink, numbering); + return; + } + var polled = session.Polled; + for (var i = 0; i < polled.Length; i++) { + ReadSwitch(sink, numbering, polled[i]); + } + var first = _scanColumn * PinMameSwitchMatrix.Rows; + for (var row = 0; row < PinMameSwitchMatrix.Rows; row++) { + ReadSwitch(sink, numbering, first + row); + } + _scanColumn = (_scanColumn + 1) % PinMameSwitchMatrix.Columns; + } + + private void ReadAllSwitches(IPinMameOutputSink sink, PinMameSwitchNumbering numbering) + { + if (numbering == PinMameSwitchNumbering.Unknown) { + return; + } + for (var index = 0; index < PinMameSwitchMatrix.Size; index++) { + ReadSwitch(sink, numbering, index); + } + } + + private void ReadSwitch(IPinMameOutputSink sink, PinMameSwitchNumbering numbering, int index) + { + var number = PinMameSwitchMatrix.SwitchNumber(numbering, index); + var slot = number + SwitchOffset; + // taken before the read, with the ring drained: what the ring took before is older than what the read sees, and + // what it takes from here, the read's value included, is newer + var order = ScanOrder; + var value = _reader.ReadSwitch(number) ? 1 : 0; + if (_feedSwitches[slot] == value) { + return; + } + // PinMAME's core_setSw clears a switch's bit before it sets it again, so a read can see a closed switch open: + // a change only counts when a second read agrees. Both reads can still land in that window when the emulation + // thread is preempted between the two writes; only a coherent read of the matrix would rule that out, which + // libpinmame doesn't export (PinmameGetSwitch reads one bit, without the emulation's lock). + if ((_reader.ReadSwitch(number) ? 1 : 0) != value) { + return; + } + // a read is the newest thing known about the switch, whatever the feed published last + if (IsNewer(order, _feedSwitchOrders[slot])) { + _feedSwitchOrders[slot] = order; + } + _feedSwitches[slot] = (byte)value; + sink.OutputChanged(PinMameOutputKind.Switch, number, value); + } + + private void PublishRead(IPinMameOutputSink sink, ref Entry read) + { + switch (read.Kind) { + case ResetMarker: + PublishLampsOff(sink); + break; + case (int)PinMameOutputKind.Lamp: + PublishLamp(sink, read.Number, read.Value); + break; + default: + PublishGI(sink, read.Number, read.Value); + break; + } + } + + private void PublishLamp(IPinMameOutputSink sink, int number, int value) + { + if ((uint)number < TableSize) { + if (_feedLamps[number] == value) { + return; + } + _feedLamps[number] = value; + } + sink.OutputChanged(PinMameOutputKind.Lamp, number, value); + } + + private void PublishGI(IPinMameOutputSink sink, int number, int value) + { + if ((uint)number < MaxGIs) { + if (_feedGIs[number] == value) { + return; + } + _feedGIs[number] = value; + } + sink.OutputChanged(PinMameOutputKind.GeneralIllumination, number, value); + } + + private void PublishLampsOff(IPinMameOutputSink sink) + { + for (var number = 0; number < TableSize; number++) { + PublishLamp(sink, number, 0); + } + for (var number = 0; number < MaxGIs; number++) { + PublishGI(sink, number, 0); + } + } + + private void ResyncLamps(IPinMameOutputSink sink) + { + for (var number = 0; number < TableSize; number++) { + if (_lampKnown[number]) { + PublishLamp(sink, number, _lamps[number]); + } + } + for (var number = 0; number < MaxGIs; number++) { + PublishGI(sink, number, _gis[number]); + } + } + + private void Snapshot(IPinMameOutputSink sink, Session session) + { + for (var number = 1; number <= MaxSolenoids; number++) { + sink.SnapshotValue(PinMameOutputKind.Solenoid, number, _feedSolenoids[number]); + } + var switches = session.Snapshot; + for (var i = 0; i < switches.Length; i++) { + sink.SnapshotValue(PinMameOutputKind.Switch, switches[i], _feedSwitches[switches[i] + SwitchOffset]); + } + for (var number = 0; number < TableSize; number++) { + if (Volatile.Read(ref _lampKnown[number])) { + sink.SnapshotValue(PinMameOutputKind.Lamp, number, _feedLamps[number]); + } + } + for (var number = 0; number < MaxGIs; number++) { + sink.SnapshotValue(PinMameOutputKind.GeneralIllumination, number, _feedGIs[number]); + } + for (var number = 1; number <= MaxUserMechs; number++) { + if (_feedMechKnown[number] || Volatile.Read(ref _userMechRegistered[number])) { + sink.SnapshotValue(PinMameOutputKind.Mech, number, _feedMechPositions[number]); + sink.SnapshotValue(PinMameOutputKind.Mech, -number, _feedMechSpeeds[number]); + } + } + } + + #endregion + + #region Lamp and GI reads + + /// + /// Reads the lamps and GI strings on the main thread when the poll does not own the reads (no sink, or no poll for a + /// quarter of a second), then coalesces everything read since the last call into the changes to dispatch. With a + /// sink, what it reads waits for the next poll, which publishes it in order with the coils. + /// + /// Cleared and filled with the lamps whose value differs from what was dispatched. + /// Cleared and filled with the GI strings whose value differs from what was dispatched. + public void ReadOnMainThread(List lamps, List gis) + { + lock (_readLock) { + ApplyPendingReset(); + if (Volatile.Read(ref _sink) == null || Stopwatch.GetTimestamp() - Volatile.Read(ref _lastPollTimestamp) > StalePollTicks) { + Read(); + } + DrainMainThreadChanges(lamps, gis); + } + } + + private void Read() + { + var feed = Volatile.Read(ref _sink) != null; + // after the entries reserved before the read, before the ones reserved during it + var order = CurrentOrder; + var count = _reader.ReadChangedLamps(_readNumbers, _readValues); + for (var i = 0; i < count; i++) { + var number = _readNumbers[i]; + var value = _readValues[i]; + RecordMain(PinMameOutputKind.Lamp, number, value); + if ((uint)number < TableSize) { + _lampKnown[number] = true; + _lamps[number] = value; + _reportedLamps[number] = value; + } + if (feed) { + RecordBacklog((int)PinMameOutputKind.Lamp, number, value, order); + } + } + + // the GI read is a read of its own, so its changes come after what was reserved before it + order = CurrentOrder; + count = _reader.ReadChangedGIs(_readNumbers, _readValues); + for (var i = 0; i < count; i++) { + var number = _readNumbers[i]; + var value = _readValues[i]; + RecordMain(PinMameOutputKind.GeneralIllumination, number, value); + if ((uint)number < MaxGIs) { + _gis[number] = value; + _reportedGis[number] = value; + } + if (feed) { + RecordBacklog((int)PinMameOutputKind.GeneralIllumination, number, value, order); + } + } + } + + private void ApplyPendingReset() + { + if (Interlocked.Exchange(ref _resetPending, 0) == 0) { + return; + } + System.Array.Clear(_lamps, 0, _lamps.Length); + System.Array.Clear(_gis, 0, _gis.Length); + RecordMain((PinMameOutputKind)ResetMarker, 0, 0); + var feed = Volatile.Read(ref _sink) != null; + var order = Volatile.Read(ref _sessionOrder); + if (feed) { + // what the ended game still had waiting is history; the lamps go off where the session changed + _backlogCount = 0; + _backlogLost = 0; + RecordBacklog(ResetMarker, 0, 0, order); + } + if (!_resetReseeds) { + return; + } + // a soft reset: PinMAME won't report again what it reported before and still has + for (var number = 0; number < TableSize; number++) { + var value = _reportedLamps[number]; + if (value != 0) { + _lampKnown[number] = true; + _lamps[number] = value; + RecordMain(PinMameOutputKind.Lamp, number, value); + if (feed) { + RecordBacklog((int)PinMameOutputKind.Lamp, number, value, order); + } + } + } + for (var number = 0; number < MaxGIs; number++) { + var value = _reportedGis[number]; + if (value != 0) { + _gis[number] = value; + RecordMain(PinMameOutputKind.GeneralIllumination, number, value); + if (feed) { + RecordBacklog((int)PinMameOutputKind.GeneralIllumination, number, value, order); + } + } + } + } + + private void RecordBacklog(int kind, int number, int value, int order) + { + if (_backlogLost > 0 || _backlogCount == FeedBacklogSize) { + // the poll publishes the loss and resynchronises from the state table + _backlogLost++; + return; + } + ref var entry = ref _backlog[_backlogCount++]; + entry.Kind = kind; + entry.Number = number; + entry.Value = value; + entry.Order = order; + } + + private void RecordMain(PinMameOutputKind kind, int number, int value) + { + if (_mainOverflow) { + return; + } + if (_mainCount == MainRingSize) { + _mainOverflow = true; + return; + } + ref var entry = ref _mainRing[_mainCount++]; + entry.Kind = (int)kind; + entry.Number = number; + entry.Value = value; + } + + private void DrainMainThreadChanges(List lamps, List gis) + { + lamps.Clear(); + gis.Clear(); + + if (_mainOverflow) { + // too much to replay: dispatch what differs from the state table + for (var number = 0; number < TableSize; number++) { + if (_lampKnown[number] && _mainLamps[number] != _lamps[number]) { + _mainLamps[number] = _lamps[number]; + lamps.Add(new PinMameOutputChange(number, _lamps[number])); + } + } + for (var number = 0; number < MaxGIs; number++) { + if (_mainGIs[number] != _gis[number]) { + _mainGIs[number] = _gis[number]; + gis.Add(new PinMameOutputChange(number, _gis[number])); + } + } + _mainCount = 0; + _mainOverflow = false; + return; + } + + var lampCount = 0; + var giCount = 0; + for (var i = 0; i < _mainCount; i++) { + ref var entry = ref _mainRing[i]; + if (entry.Kind == ResetMarker) { + // what was read before the reset is history; nothing is dispatched for it + for (var j = 0; j < lampCount; j++) _lampDirty[_lampOrder[j]] = false; + for (var j = 0; j < giCount; j++) _giDirty[_giOrder[j]] = false; + lampCount = giCount = 0; + lamps.Clear(); + gis.Clear(); + System.Array.Clear(_mainLamps, 0, _mainLamps.Length); + System.Array.Clear(_mainGIs, 0, _mainGIs.Length); + continue; + } + var number = entry.Number; + if (entry.Kind == (int)PinMameOutputKind.Lamp) { + if ((uint)number >= TableSize) { + lamps.Add(new PinMameOutputChange(number, entry.Value)); + continue; + } + if (!_lampDirty[number]) { + _lampDirty[number] = true; + _lampOrder[lampCount++] = number; + } + _pendingLamps[number] = entry.Value; + + } else { + if ((uint)number >= MaxGIs) { + gis.Add(new PinMameOutputChange(number, entry.Value)); + continue; + } + if (!_giDirty[number]) { + _giDirty[number] = true; + _giOrder[giCount++] = number; + } + _pendingGIs[number] = entry.Value; + } + } + _mainCount = 0; + + for (var i = 0; i < lampCount; i++) { + var number = _lampOrder[i]; + _lampDirty[number] = false; + if (_mainLamps[number] != _pendingLamps[number]) { + _mainLamps[number] = _pendingLamps[number]; + lamps.Add(new PinMameOutputChange(number, _pendingLamps[number])); + } + } + for (var i = 0; i < giCount; i++) { + var number = _giOrder[i]; + _giDirty[number] = false; + if (_mainGIs[number] != _pendingGIs[number]) { + _mainGIs[number] = _pendingGIs[number]; + gis.Add(new PinMameOutputChange(number, _pendingGIs[number])); + } + } + } + + #endregion + } +} diff --git a/VisualPinball.Engine.PinMAME.Unity/Runtime/PinMameRealtimeOutputs.cs.meta b/VisualPinball.Engine.PinMAME.Unity/Runtime/PinMameRealtimeOutputs.cs.meta new file mode 100644 index 0000000..eb5e7d9 --- /dev/null +++ b/VisualPinball.Engine.PinMAME.Unity/Runtime/PinMameRealtimeOutputs.cs.meta @@ -0,0 +1,2 @@ +fileFormatVersion: 2 +guid: 238f739dd7a142079514394f40666599 \ No newline at end of file From b2f92793dc63c3ea8e5b5775fa149ba0b469ad9d Mon Sep 17 00:00:00 2001 From: freezy Date: Mon, 30 Nov 2026 11:17:47 +0100 Subject: [PATCH 2/3] pinmame: end the feed's session on every stop, and keep its orders from wrapping Stopping the game in the player or leaving play mode unsubscribes the game ended callback before PinMAME stops, so the feed's session never ended and the last coils, lamps and GI stayed on for its receivers. Both stops now end it, and end it again once PinMAME stopped, for what a callback still running recorded meanwhile. The poll refreshed only the feed's order numbers. The ones kept with each element's latest value kept aging, so after a long run a fresh value could be taken for an older one and a later resync published a stale one. They are refreshed too now, to just below the feed's. Also: the poll takes its sink under the lock the sink is set under, a game reset reaches the main thread's lamp dispatch when its ring overflowed, and the timing tests use their own clock. --- .../PinMameRealtimeOutputsTests.cs | 178 +++++++++++++++++- .../Editor/PinMamePlayModeLifecycle.cs | 11 ++ .../Runtime/PinMameGamelogicEngine.cs | 19 ++ .../Runtime/PinMameRealtimeOutputs.cs | 89 +++++++-- 4 files changed, 278 insertions(+), 19 deletions(-) diff --git a/VisualPinball.Engine.PinMAME.Test/PinMameRealtimeOutputsTests.cs b/VisualPinball.Engine.PinMAME.Test/PinMameRealtimeOutputsTests.cs index 243f6ee..e6c6a61 100644 --- a/VisualPinball.Engine.PinMAME.Test/PinMameRealtimeOutputsTests.cs +++ b/VisualPinball.Engine.PinMAME.Test/PinMameRealtimeOutputsTests.cs @@ -2,6 +2,7 @@ using System.Collections.Generic; using System.Linq; using System.Reflection; +using System.Diagnostics; using System.Threading; using NUnit.Framework; @@ -12,6 +13,7 @@ public class PinMameRealtimeOutputsTests private FakeReader _reader; private RecordingSink _sink; private PinMameRealtimeOutputs _outputs; + private long _now; [SetUp] public void SetUp() @@ -54,6 +56,7 @@ public void SwitchesPinMameChangesItselfAreReadOnEveryPoll() public void TheRestOfTheMatrixIsReadAColumnPerPoll() { // a Whitestar game whose built-in mech drives switches the table doesn't map, and a cabinet switch + UseClock(); _outputs.BeginSession(PinMameSwitchNumbering.Sequential); _outputs.Prepare(new[] { 17 }, Array.Empty()); Subscribe(); @@ -64,24 +67,27 @@ public void TheRestOfTheMatrixIsReadAColumnPerPoll() } Assert.That(_sink.Changes, Is.EquivalentTo(new[] { (PinMameOutputKind.Switch, 45, 1), (PinMameOutputKind.Switch, -3, 1) })); - // a poll reads the mapped switches and 8 of the matrix, not all of it (unless it came late, which a busy machine may do) - var reads = new List(); + // a poll on time reads the mapped switches and 8 of the matrix, not all of it for (var i = 0; i < 20; i++) { _reader.SwitchReads = 0; _outputs.Poll(true); - reads.Add(_reader.SwitchReads); + Assert.That(_reader.SwitchReads, Is.EqualTo(1 + PinMameSwitchMatrix.Rows)); } - Assert.That(reads.Min(), Is.EqualTo(1 + PinMameSwitchMatrix.Rows)); } [Test] public void APollThatComesLateReadsTheWholeMatrix() { + UseClock(); + _outputs.BeginSession(PinMameSwitchNumbering.Wpc); + _outputs.Prepare(Array.Empty(), Array.Empty()); Subscribe(); + _outputs.Poll(true); + _reader.SwitchReads = 0; // the frame update polls when no simulation thread does _reader.SetSwitch(45, true); _reader.SetSwitch(158, true); - Thread.Sleep(5); + _now += Stopwatch.Frequency / 200; _outputs.Poll(true); Assert.That(_sink.Changes, Is.EquivalentTo(new[] { (PinMameOutputKind.Switch, 45, 1), (PinMameOutputKind.Switch, 158, 1) })); } @@ -846,6 +852,168 @@ public void SwitchNumbersAndMatrixPositionsConvertBothWays() Assert.That(PinMameSwitchMatrix.TryIndex(PinMameSwitchNumbering.Unknown, 11, out _), Is.False); } + [Test] + public void AValueThatDidNotChangeForALongRunDoesNotHideTheNextOne() + { + Subscribe(); + _outputs.Solenoid(5, 1); + _outputs.Poll(true); + // more than 2^30 entries go through the ring while the solenoid stays on, with the poll refreshing the orders + for (var step = 0; step < 6; step++) { + AdvanceRing(1L << 28); + for (var poll = 0; poll < 1024; poll++) { + _outputs.Poll(true); + } + } + _outputs.Solenoid(5, 0); + _outputs.Poll(true); + + // a receiver that starts now gets the solenoid's latest value + var late = new RecordingSink { Requested = true }; + _outputs.SetSink(late); + _outputs.Poll(true); + Assert.That(late.Snapshot, Does.Contain((PinMameOutputKind.Solenoid, 5, 0))); + } + + /// Moves the empty ring ahead as if that many entries had gone through it. + private void AdvanceRing(long entries) + { + var enqueue = Field("_enqueuePosition"); + var dequeue = Field("_dequeuePosition"); + var position = (long)enqueue.GetValue(_outputs); + Assert.That((long)dequeue.GetValue(_outputs), Is.EqualTo(position)); + position += entries; + enqueue.SetValue(_outputs, position); + dequeue.SetValue(_outputs, position); + var ring = (Array)Field("_ring").GetValue(_outputs); + for (var offset = 0; offset < ring.Length; offset++) { + var next = position + offset; + var index = (int)(next % ring.Length); + var slot = ring.GetValue(index); + slot.GetType().GetField("Sequence").SetValue(slot, next); + ring.SetValue(slot, index); + } + } + + [Test] + public void ARestartWhileTheMainThreadLagsStillDispatchesTheNewGamesLamps() + { + var lamps = new List(); + var gis = new List(); + _reader.Lamps.Enqueue((11, 1)); + _outputs.ReadOnMainThread(lamps, gis); + Assert.That(lamps.Select(l => (l.Id, l.Value)), Is.EqualTo(new[] { (11, 1) })); + + // the main thread stalls while the game runs on, until it restarts, and the new game turns lamp 11 on again + Subscribe(); + for (var round = 0; round < PinMameRealtimeOutputs.MainRingSize / 1000 + 1; round++) { + for (var number = 20; number < 1020; number++) { + _reader.Lamps.Enqueue((number, round & 1)); + } + _outputs.Poll(true); + } + _outputs.EndSession(); + _outputs.BeginRun(); + _outputs.BeginSession(PinMameSwitchNumbering.Wpc); + _outputs.Prepare(Array.Empty(), Array.Empty()); + _reader.Lamps.Enqueue((11, 1)); + _outputs.Poll(true); + + _outputs.ReadOnMainThread(lamps, gis); + Assert.That(lamps.Select(l => (l.Id, l.Value)), Does.Contain((11, 1))); + } + + [Test] + public void ASwitchReadBackAfterALongRunIsNotReplayedByAnOverflow() + { + _outputs.Prepare(new[] { 33 }, Array.Empty()); + Subscribe(); + // the engine closes switch 33, then the game opens it itself, which the poll reads back + _outputs.Switch(33, true); + _reader.SetSwitch(33, true); + _outputs.Poll(true); + _reader.SetSwitch(33, false); + _outputs.Poll(true); + Assert.That(_sink.Changes, Is.EqualTo(new[] { (PinMameOutputKind.Switch, 33, 1), (PinMameOutputKind.Switch, 33, 0) })); + _sink.Changes.Clear(); + + for (var step = 0; step < 2; step++) { + AdvanceRing(1L << 28); + for (var poll = 0; poll < 1024; poll++) { + _outputs.Poll(true); + } + } + for (var i = 0; i < PinMameRealtimeOutputs.EmulationRingSize + 10; i++) { + _outputs.Solenoid(40, i & 1); + } + _outputs.Poll(true); + _outputs.Poll(true); + Assert.That(_sink.Changes.Where(e => e.Item1 == PinMameOutputKind.Switch), Is.Empty); + } + + [Test] + public void ARestartThatFitTheMainRingBeforeItOverflowedStillDispatchesTheNewGamesLamps() + { + var lamps = new List(); + var gis = new List(); + _reader.Lamps.Enqueue((11, 1)); + _outputs.ReadOnMainThread(lamps, gis); + + // the main thread stalls; the ring has room for the restart's markers, then overflows with the new game's lamps + Subscribe(); + var fill = PinMameRealtimeOutputs.MainRingSize - 2; + for (var number = 0; number < fill; number++) { + _reader.Lamps.Enqueue((20 + number % 40, number / 40 & 1)); + } + while (_reader.Lamps.Count > 0) { + _outputs.Poll(true); + } + _outputs.EndSession(); + _outputs.BeginRun(); + _outputs.BeginSession(PinMameSwitchNumbering.Wpc); + _outputs.Prepare(Array.Empty(), Array.Empty()); + _reader.Lamps.Enqueue((11, 1)); + _reader.Lamps.Enqueue((12, 1)); + _outputs.Poll(true); + + _outputs.ReadOnMainThread(lamps, gis); + Assert.That(lamps.Select(l => (l.Id, l.Value)), Does.Contain((11, 1))); + } + + [Test] + public void AValueDroppedWhileTheRingReopensIsRecovered() + { + Subscribe(); + for (var i = 0; i < PinMameRealtimeOutputs.EmulationRingSize + 10; i++) { + _outputs.Solenoid(40, i & 1); + } + // as the poll reopens the ring, a producer that passed the open check reserves a slot, and another one, still + // seeing the ring full, drops coil 28's change + var done = false; + (long position, int order) stalled = default; + _sink.OnChange = () => { + if (!done && _sink.Changes[_sink.Changes.Count - 1].Item1 == PinMameOutputKind.Overflow) { + done = true; + stalled = ReserveSlot(); + var latest = (long[])Field("_latestSolenoids").GetValue(_outputs); + var order = (int)((long)Field("_enqueuePosition").GetValue(_outputs) * 2); + latest[28] = (long)order << 32 | 1u; + } + }; + _outputs.Poll(true); + FinishSlot(stalled, PinMameOutputKind.Solenoid, 41, 1); + _outputs.Poll(true); + Assert.That(done, Is.True); + Assert.That(_sink.Changes, Does.Contain((PinMameOutputKind.Solenoid, 28, 1))); + } + + /// Polls with a clock that moves only when the test moves it. + private void UseClock() + { + _now = Stopwatch.Frequency * 10; + _outputs = new PinMameRealtimeOutputs(_reader, () => _now); + } + private void Subscribe() { _outputs.SetSink(_sink); diff --git a/VisualPinball.Engine.PinMAME.Unity/Editor/PinMamePlayModeLifecycle.cs b/VisualPinball.Engine.PinMAME.Unity/Editor/PinMamePlayModeLifecycle.cs index be96432..0ad6009 100644 --- a/VisualPinball.Engine.PinMAME.Unity/Editor/PinMamePlayModeLifecycle.cs +++ b/VisualPinball.Engine.PinMAME.Unity/Editor/PinMamePlayModeLifecycle.cs @@ -112,6 +112,17 @@ private static void RequestStop(string reason) if (runState != 0 || sw.ElapsedMilliseconds > 50) { Logger.Info($"[PinMAME] Stop call returned after {sw.ElapsedMilliseconds}ms, RunState={PinMame.PinMame.RunState}"); } + // no callback runs anymore: what one recorded during the stop goes off as well + if (EditorApplication.isPlaying) { + try { + var engines = UnityEngine.Object.FindObjectsByType(FindObjectsInactive.Include, FindObjectsSortMode.None); + for (var i = 0; i < engines.Length; i++) { + engines[i].EndRealtimeSessionAfterStop(); + } + } catch (Exception e) { + Logger.Warn(e, "[PinMAME] Could not end the real-time feed's session after the native shutdown."); + } + } } catch (Exception e) { Logger.Warn(e, "[PinMAME] Native shutdown failed ({Reason}).", reason); } finally { diff --git a/VisualPinball.Engine.PinMAME.Unity/Runtime/PinMameGamelogicEngine.cs b/VisualPinball.Engine.PinMAME.Unity/Runtime/PinMameGamelogicEngine.cs index b508c1e..4ff99cb 100644 --- a/VisualPinball.Engine.PinMAME.Unity/Runtime/PinMameGamelogicEngine.cs +++ b/VisualPinball.Engine.PinMAME.Unity/Runtime/PinMameGamelogicEngine.cs @@ -1001,6 +1001,19 @@ public void StopForPlayModeExit() // teardown: the callbacks are unsubscribed again before the next start Logger.Debug(e, "[PinMAME] Unsubscribing callbacks on play mode exit failed."); } + // the game ended callback is gone, so the session ends here; the editor ends it again once PinMAME stopped + RealtimeOutputs.EndSession(); + } + + /// + /// Ends the real-time feed's session once PinMAME stopped, so what a callback that was still running at the stop + /// recorded after ended it goes off too, and a game start it reported doesn't + /// leave the feed reading a stopped ROM. + /// + public void EndRealtimeSessionAfterStop() + { + _isRunning = false; + RealtimeOutputs.EndSession(); } internal static bool TryResetNvram(string romId, out string backup) @@ -1080,11 +1093,17 @@ private void RequestStopGame(string reason) // teardown: the native side is stopped right after Logger.Debug(e, "[PinMAME] Unsubscribe during shutdown ({Reason}) failed.", reason); } + // the game ended callback is gone, so the session ends here, and again once PinMAME stopped: a callback that was + // still running may have recorded something after the first end + RealtimeOutputs.EndSession(); // PinmameStop may block (joins the emulation thread). Never do that on the Unity main thread. System.Threading.Tasks.Task.Run(() => { try { _pinMame?.StopGame(); + // a game start reported while stopping must not leave the feed reading a stopped ROM + _isRunning = false; + RealtimeOutputs.EndSession(); } catch (Exception e) { Logger.Warn(e, "[PinMAME] StopGame ({Reason}) failed.", reason); } finally { diff --git a/VisualPinball.Engine.PinMAME.Unity/Runtime/PinMameRealtimeOutputs.cs b/VisualPinball.Engine.PinMAME.Unity/Runtime/PinMameRealtimeOutputs.cs index 310e6b1..e57e6ce 100644 --- a/VisualPinball.Engine.PinMAME.Unity/Runtime/PinMameRealtimeOutputs.cs +++ b/VisualPinball.Engine.PinMAME.Unity/Runtime/PinMameRealtimeOutputs.cs @@ -309,6 +309,7 @@ public Session(PinMameSwitchNumbering numbering, int[] polled, int[] snapshot, b private int _fullScan; private int _scanColumn; private long _lastPollTimestamp; + private readonly System.Func _clock; // ---- PinMAME's lamp and GI state, the feed's backlog and the main-thread ring, under _readLock private readonly object _readLock = new(); @@ -329,6 +330,8 @@ public Session(PinMameSwitchNumbering numbering, int[] polled, int[] snapshot, b private readonly Entry[] _mainRing = new Entry[MainRingSize]; private int _mainCount; private bool _mainOverflow; + // a reset since the last drain, queued or not: an overflow's diff then starts from nothing dispatched + private bool _mainReset; // ---- main thread's view: what it dispatched. Under _readLock. private readonly int[] _mainLamps = new int[TableSize]; @@ -340,9 +343,16 @@ public Session(PinMameSwitchNumbering numbering, int[] polled, int[] snapshot, b private readonly int[] _lampOrder = new int[TableSize]; private readonly int[] _giOrder = new int[MaxGIs]; - public PinMameRealtimeOutputs(IPinMameOutputReader reader) + public PinMameRealtimeOutputs(IPinMameOutputReader reader) : this(reader, Stopwatch.GetTimestamp) + { + } + + /// Reads PinMAME's lamps, GI strings and switches. + /// The time in ticks, which tells a late or stalled poll. + internal PinMameRealtimeOutputs(IPinMameOutputReader reader, System.Func clock) { _reader = reader; + _clock = clock; for (var i = 0; i < EmulationRingSize; i++) { _ring[i].Sequence = i; } @@ -363,16 +373,18 @@ public PinMameRealtimeOutputs(IPinMameOutputReader reader) /// public void SetSink(IPinMameOutputSink sink) { + // one handoff under the poll's lock: a poll publishes either all to the old sink or, from the new epoch on, all + // to the new one lock (_readLock) { _backlogCount = 0; _backlogLost = 0; Volatile.Write(ref _sink, sink); - } - Volatile.Write(ref _ringEnabled, sink != null ? 1 : 0); - Interlocked.Increment(ref _sinks); - Interlocked.Increment(ref _epoch); - if (sink != null) { - Volatile.Write(ref _feedResync, 1); + Volatile.Write(ref _ringEnabled, sink != null ? 1 : 0); + Interlocked.Increment(ref _sinks); + Interlocked.Increment(ref _epoch); + if (sink != null) { + Volatile.Write(ref _feedResync, 1); + } } } @@ -408,7 +420,10 @@ private static void StoreLatest(ref long latest, int value, int order) } } - /// Raises the orders the poll compares against to the window below the current one, so they never wrap past it. + /// + /// Raises every order that is compared later to the window below the current one, so none wraps past it: the feed's, + /// and the ones kept with the latest values, which producers compare a new value against and a resync publishes. + /// private void KeepOrdersRecent() { var floor = CurrentOrder - OrderWindow; @@ -416,6 +431,36 @@ private void KeepOrdersRecent() Raise(_feedMechPositionOrders, floor); Raise(_feedMechSpeedOrders, floor); Raise(_feedSwitchOrders, floor); + Raise(_latestSolenoids, floor); + Raise(_latestMechPositions, floor); + Raise(_latestMechSpeeds, floor); + Raise(_latestSwitches, floor); + } + + /// + /// Raises old orders of latest values to just below the feed's floor, keeping each value; a producer that stores + /// meanwhile wins. Below, because the feed has published each of these values or a newer one (a switch read back, + /// say), so a resync must not take one of them for a change. + /// + private static void Raise(long[] latest, int floor) + { + var order = floor - 1; + for (var i = 0; i < latest.Length; i++) { + while (true) { + var current = Interlocked.Read(ref latest[i]); + if (current != 0 && !IsNewer(order, OrderOf(current))) { + break; + } + var raised = Pack(ValueOf(current), order); + if (raised == 0) { + // 0 is the mark of a value never stored, which every value replaces + raised = Pack(0, order - 1); + } + if (Interlocked.CompareExchange(ref latest[i], raised, current) == current) { + break; + } + } + } } private static void Raise(int[] orders, int floor) @@ -727,7 +772,7 @@ public void Poll(bool running) return; } try { - var now = Stopwatch.GetTimestamp(); + var now = _clock(); var late = now - Volatile.Read(ref _lastPollTimestamp) > SlowPollTicks; Volatile.Write(ref _lastPollTimestamp, now); @@ -736,6 +781,11 @@ public void Poll(bool running) return; } try { + // the sink is set under this lock, so what this poll publishes goes to the one it belongs to + sink = Volatile.Read(ref _sink); + if (sink == null) { + return; + } // taken before the drain: a session that starts later has values this poll may not have published var session = Volatile.Read(ref _session); ApplyPendingReset(); @@ -890,7 +940,10 @@ private void ChangeEpoch(IPinMameOutputSink sink, int epoch) } } - /// Publishes each element's latest value that is at least as new as what the feed has and differs from it. + /// + /// Publishes each element's latest value that is at least as new as what the feed has and differs from it. After an + /// overflow, a pulse queued while this runs can be lost with what overflowed; the final value is always right. + /// private void ResyncFromLatest(IPinMameOutputSink sink) { for (var number = 1; number <= MaxSolenoids; number++) { @@ -1128,7 +1181,7 @@ public void ReadOnMainThread(List lamps, List StalePollTicks) { + if (Volatile.Read(ref _sink) == null || _clock() - Volatile.Read(ref _lastPollTimestamp) > StalePollTicks) { Read(); } DrainMainThreadChanges(lamps, gis); @@ -1231,10 +1284,10 @@ private void RecordBacklog(int kind, int number, int value, int order) private void RecordMain(PinMameOutputKind kind, int number, int value) { - if (_mainOverflow) { - return; + if (kind == (PinMameOutputKind)ResetMarker) { + _mainReset = true; } - if (_mainCount == MainRingSize) { + if (_mainOverflow || _mainCount == MainRingSize) { _mainOverflow = true; return; } @@ -1251,6 +1304,12 @@ private void DrainMainThreadChanges(List lamps, List lamps, List Date: Mon, 30 Nov 2026 11:36:45 +0100 Subject: [PATCH 3/3] pinmame: commit a snapshot only for the session it was read from A game that stops or restarts while a snapshot is being delivered now always aborts it: the session swap and the snapshot's last session check share a small lock, which the poll only tries, so the simulation thread never waits for it. The switch read-back test advances far enough for an unrefreshed order to wrap. --- .../PinMameRealtimeOutputsTests.cs | 3 +- .../Runtime/PinMameRealtimeOutputs.cs | 29 +++++++++++++++---- 2 files changed, 25 insertions(+), 7 deletions(-) diff --git a/VisualPinball.Engine.PinMAME.Test/PinMameRealtimeOutputsTests.cs b/VisualPinball.Engine.PinMAME.Test/PinMameRealtimeOutputsTests.cs index e6c6a61..17845c8 100644 --- a/VisualPinball.Engine.PinMAME.Test/PinMameRealtimeOutputsTests.cs +++ b/VisualPinball.Engine.PinMAME.Test/PinMameRealtimeOutputsTests.cs @@ -937,7 +937,8 @@ public void ASwitchReadBackAfterALongRunIsNotReplayedByAnOverflow() Assert.That(_sink.Changes, Is.EqualTo(new[] { (PinMameOutputKind.Switch, 33, 1), (PinMameOutputKind.Switch, 33, 0) })); _sink.Changes.Clear(); - for (var step = 0; step < 2; step++) { + // far enough that an order left unrefreshed would wrap past the feed's + for (var step = 0; step < 6; step++) { AdvanceRing(1L << 28); for (var poll = 0; poll < 1024; poll++) { _outputs.Poll(true); diff --git a/VisualPinball.Engine.PinMAME.Unity/Runtime/PinMameRealtimeOutputs.cs b/VisualPinball.Engine.PinMAME.Unity/Runtime/PinMameRealtimeOutputs.cs index e57e6ce..56964b6 100644 --- a/VisualPinball.Engine.PinMAME.Unity/Runtime/PinMameRealtimeOutputs.cs +++ b/VisualPinball.Engine.PinMAME.Unity/Runtime/PinMameRealtimeOutputs.cs @@ -290,6 +290,8 @@ public Session(PinMameSwitchNumbering numbering, int[] polled, int[] snapshot, b // ---- the feed's tables: what the live receivers saw, and the order of the value. Poll only. private readonly object _pollLock = new(); + // a snapshot's last session check and its end, against a session change: a stop never waits for a whole poll + private readonly object _commitLock = new(); private int _pollEpoch; private int _pollSinks; private int _pollSessions; @@ -624,7 +626,10 @@ private bool TryTake(long position) /// How the game numbers switches and lamps, from its hardware generation. public void BeginSession(PinMameSwitchNumbering numbering) { - Volatile.Write(ref _session, new Session(numbering, System.Array.Empty(), System.Array.Empty(), false)); + // a snapshot that checked the old session ends before this, and one that didn't yet sees the new one + lock (_commitLock) { + Volatile.Write(ref _session, new Session(numbering, System.Array.Empty(), System.Array.Empty(), false)); + } Forget(true); if (numbering != PinMameSwitchNumbering.Unknown) { for (var index = 0; index < PinMameSwitchMatrix.StandardLamps; index++) { @@ -694,8 +699,11 @@ public void MarkUserMechRegistered(int number) /// public void EndSession() { - var session = Volatile.Read(ref _session); - Volatile.Write(ref _session, new Session(session.Numbering, session.Polled, System.Array.Empty(), false)); + // a snapshot that checked the old session ends before this, and one that didn't yet sees the new one + lock (_commitLock) { + var session = Volatile.Read(ref _session); + Volatile.Write(ref _session, new Session(session.Numbering, session.Polled, System.Array.Empty(), false)); + } Forget(false); } @@ -810,10 +818,19 @@ public void Poll(bool running) sink.AbortSnapshot(); throw; } - if (Volatile.Read(ref _session) == session) { - sink.EndSnapshot(); + // a session change holds the lock only to swap the session, so contention means the game ends or restarts + if (Monitor.TryEnter(_commitLock)) { + try { + if (Volatile.Read(ref _session) == session) { + sink.EndSnapshot(); + } else { + // the game ended or restarted meanwhile: the receivers get the next one's snapshot + sink.AbortSnapshot(); + } + } finally { + Monitor.Exit(_commitLock); + } } else { - // the game ended or restarted meanwhile: the receivers get the next one's snapshot sink.AbortSnapshot(); } }