From 86978232c8acc7656ee4af452fe302184d0891c4 Mon Sep 17 00:00:00 2001 From: freezy Date: Mon, 2 Nov 2026 10:17:30 +0100 Subject: [PATCH 01/10] display: establish shared cabinet output contracts Add immutable output plans, consumer eligibility, and owned SDR copy targets. Share provider ranking and skip incompatible scene surfaces. Include contract, GPU-copy, and native-window probes. --- CHANGELOG.md | 2 + .../CabinetDisplayTests.cs | 93 +++++++++++++ .../CabinetDisplayTests.cs.meta | 2 + VisualPinball.Plugins/Api/CabinetDisplays.cs | 122 ++++++++++++++++++ .../Api/CabinetDisplays.cs.meta | 2 + .../Resources/CabinetSurfaceSelector.cs | 43 ++++++ .../Resources/CabinetSurfaceSelector.cs.meta | 2 + .../Resources/PluginResourceRegistry.cs | 9 ++ .../Resources/ResourceContracts.cs | 8 +- .../cabinet-display-outputs.md | 21 +++ .../Rendering/CabinetNativeWindowTests.cs | 99 ++++++++++++++ .../CabinetNativeWindowTests.cs.meta | 2 + .../Rendering/CabinetOutputTextureTests.cs | 116 +++++++++++++++++ .../CabinetOutputTextureTests.cs.meta | 2 + .../NativeWindows/CabinetOutputTexture.cs | 88 +++++++++++++ .../CabinetOutputTexture.cs.meta | 2 + .../Plugins/CabinetScreenBinder.cs | 19 +-- .../Plugins/UnityDesktopSurface.cs | 25 ++++ .../Plugins/UnityDesktopSurface.cs.meta | 2 + .../Resources/CabinetOutput.shader | 36 ++++++ .../Resources/CabinetOutput.shader.meta | 9 ++ 21 files changed, 686 insertions(+), 18 deletions(-) create mode 100644 VisualPinball.Plugins.Test/CabinetDisplayTests.cs create mode 100644 VisualPinball.Plugins.Test/CabinetDisplayTests.cs.meta create mode 100644 VisualPinball.Plugins/Api/CabinetDisplays.cs create mode 100644 VisualPinball.Plugins/Api/CabinetDisplays.cs.meta create mode 100644 VisualPinball.Plugins/Resources/CabinetSurfaceSelector.cs create mode 100644 VisualPinball.Plugins/Resources/CabinetSurfaceSelector.cs.meta create mode 100644 VisualPinball.Unity/Documentation~/developer-guide/cabinet-display-outputs.md create mode 100644 VisualPinball.Unity/VisualPinball.Unity.Test/Rendering/CabinetNativeWindowTests.cs create mode 100644 VisualPinball.Unity/VisualPinball.Unity.Test/Rendering/CabinetNativeWindowTests.cs.meta create mode 100644 VisualPinball.Unity/VisualPinball.Unity.Test/Rendering/CabinetOutputTextureTests.cs create mode 100644 VisualPinball.Unity/VisualPinball.Unity.Test/Rendering/CabinetOutputTextureTests.cs.meta create mode 100644 VisualPinball.Unity/VisualPinball.Unity/NativeWindows/CabinetOutputTexture.cs create mode 100644 VisualPinball.Unity/VisualPinball.Unity/NativeWindows/CabinetOutputTexture.cs.meta create mode 100644 VisualPinball.Unity/VisualPinball.Unity/Plugins/UnityDesktopSurface.cs create mode 100644 VisualPinball.Unity/VisualPinball.Unity/Plugins/UnityDesktopSurface.cs.meta create mode 100644 VisualPinball.Unity/VisualPinball.Unity/Resources/CabinetOutput.shader create mode 100644 VisualPinball.Unity/VisualPinball.Unity/Resources/CabinetOutput.shader.meta diff --git a/CHANGELOG.md b/CHANGELOG.md index 36d105fff3..313d686a92 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -8,6 +8,8 @@ Built with Unity 6.5 ### Added +- Shared cabinet display configuration contracts, deterministic surface ranking, and an owned SDR output-copy target with GPU and native-window validation probes, preparing centralized Player display routing. + - Extensible shared plugin settings sections for paths and multiple mixer channels, with canonical plugin-owned values and provider validation for global edits. - Smooth 100 ms master fades when opening and closing the Player pause menu, with rapid-toggle cancellation and independent sound previews. diff --git a/VisualPinball.Plugins.Test/CabinetDisplayTests.cs b/VisualPinball.Plugins.Test/CabinetDisplayTests.cs new file mode 100644 index 0000000000..8adce32529 --- /dev/null +++ b/VisualPinball.Plugins.Test/CabinetDisplayTests.cs @@ -0,0 +1,93 @@ +// Visual Pinball Engine +// Copyright (C) 2026 freezy and VPE Team +// +// SPDX-License-Identifier: MIT +// Licensed under MIT. See https://opensource.org/license/mit. + +using System; +using NUnit.Framework; + +namespace VisualPinball.Plugins.Test +{ + public sealed class CabinetDisplayTests + { + [Test] + public void SnapshotCopiesInputAndKeepsAdoptedMissingOutputsManaged() + { + var assignments = new[] { new CabinetOutputAssignment("b2s", SurfaceRoles.Backglass, CabinetOutputMode.Player) }; + var targets = new[] { new CabinetDisplayTarget("screen", SurfaceRoles.Backglass, CabinetEndpointKind.DesktopRegion, CabinetEndpointState.Unavailable, reason: "Disconnected") }; + var snapshot = new CabinetDisplaySnapshot(4, 7, 9, targets, assignments); + assignments[0] = new CabinetOutputAssignment("b2s", SurfaceRoles.Backglass, CabinetOutputMode.Off); + targets[0] = new CabinetDisplayTarget("screen", SurfaceRoles.Backglass, CabinetEndpointKind.DesktopRegion, CabinetEndpointState.Available, -1920, 0, 1920, 1080); + Assert.That(snapshot.ModeFor("b2s", SurfaceRoles.Backglass), Is.EqualTo(CabinetOutputMode.Player)); + Assert.That(snapshot.ModeFor("pup", SurfaceRoles.Backglass), Is.EqualTo(CabinetOutputMode.Custom)); + Assert.That(snapshot.Targets[0].State, Is.EqualTo(CabinetEndpointState.Unavailable)); + } + + [Test] + public void DuplicateAssignmentsAndInvalidAvailableDestinationsAreRejected() + { + var adoption = new CabinetOutputAssignment("pup", SurfaceRoles.Topper, CabinetOutputMode.Player); + Assert.Throws(() => new CabinetDisplaySnapshot(1, 1, 1, Array.Empty(), new[] { adoption, adoption })); + Assert.Throws(() => new CabinetDisplayTarget("screen", "backglass", CabinetEndpointKind.DesktopRegion, CabinetEndpointState.Available)); + Assert.Throws(() => new CabinetDisplayTarget("device", "dmd", CabinetEndpointKind.Device, CabinetEndpointState.Available)); + var target = new CabinetDisplayTarget("screen", "dmd", CabinetEndpointKind.DesktopRegion, CabinetEndpointState.Available, width: 128, height: 32); + Assert.Throws(() => new CabinetDisplaySnapshot(1, 1, 1, new[] { target, target }, Array.Empty())); + var device = new CabinetDisplayTarget("device", "dmd", CabinetEndpointKind.Device, CabinetEndpointState.Available, deviceLeaseKey: "serial:COM3"); + Assert.That(new CabinetDisplaySnapshot(1, 1, 1, new[] { target, device }, Array.Empty()).TargetsFor("dmd").Count, Is.EqualTo(2)); + } + + [Test] + public void RankingFallsBackOnlyWhenIneligibleAndIsIndependentOfPublicationOrder() + { + var b2s = Descriptor("b2s/1", "b2s"); + var pup = Descriptor("pup/1", "pup"); + var other = Descriptor("other/1", "other"); + var order = new[] { "pup", "b2s" }; + Assert.That(CabinetSurfaceSelector.Choose(new[] { other, b2s, pup }, order, _ => true), Is.SameAs(pup)); + Assert.That(CabinetSurfaceSelector.Choose(new[] { pup, other, b2s }, order, item => item != pup), Is.SameAs(b2s)); + Assert.That(CabinetSurfaceSelector.Choose(new[] { pup, other, b2s }, order, _ => false), Is.Null); + Assert.That(CabinetSurfaceSelector.Choose(new[] { Descriptor("z", "unknown"), Descriptor("a", "unknown") }, order, _ => true)!.Id, Is.EqualTo("a")); + } + + [Test] + public void DesktopDemandDoesNotEnableAnAuthoredSceneScreen() + { + var source = new Surface { Consumers = CabinetSurfaceConsumers.ManagedDesktop, IsReady = true }; + Assert.That(CabinetSurfaceSelector.Eligible(source, CabinetSurfaceConsumers.Scene), Is.False); + Assert.That(CabinetSurfaceSelector.Eligible(source, CabinetSurfaceConsumers.ManagedDesktop), Is.True); + source.IsReady = false; + Assert.That(CabinetSurfaceSelector.Eligible(source, CabinetSurfaceConsumers.ManagedDesktop), Is.False); + } + + [Test] + public void RegistryProbeRejectsStaleInstancesAndReadinessChangesRecomputeSelection() + { + var registry = new PluginResourceRegistry(); + var descriptor = Descriptor("surface", "pup"); + var source = new Surface { Consumers = CabinetSurfaceConsumers.ManagedDesktop, IsReady = true }; + using var publication = registry.Publish(descriptor, source); + PluginResourceDescriptor? selected = null; + using var watch = registry.Observe(_ => selected = CabinetSurfaceSelector.Choose(registry.Snapshot(), new[] { "pup" }, d => registry.TryGetSource(d, out var current) && CabinetSurfaceSelector.Eligible(current!, CabinetSurfaceConsumers.Scene))); + source.Consumers |= CabinetSurfaceConsumers.Scene; + registry.NotifyChanged(descriptor.Id); + Assert.That(selected, Is.SameAs(descriptor)); + source.IsReady = false; + registry.NotifyChanged(descriptor.Id); + Assert.That(selected, Is.Null); + var stale = new PluginResourceDescriptor(descriptor.Id, "pup", "controller", "surface", "backglass", ResourceKind.Surface, 1, 2); + Assert.That(registry.TryGetSource(stale, out _), Is.False); + } + + private static PluginResourceDescriptor Descriptor(string id, string provider) => new PluginResourceDescriptor(id, provider, "controller", id, "backglass", ResourceKind.Surface, 1, 1); + private sealed class Surface : IPluginSurface, ICabinetSurface + { + public ResourceKind Kind => ResourceKind.Surface; + public int Width => 1; + public int Height => 1; + public string Backend => "test"; + public CabinetSurfaceConsumers Consumers { get; set; } + public bool IsReady { get; set; } + } + } +} diff --git a/VisualPinball.Plugins.Test/CabinetDisplayTests.cs.meta b/VisualPinball.Plugins.Test/CabinetDisplayTests.cs.meta new file mode 100644 index 0000000000..48f557c421 --- /dev/null +++ b/VisualPinball.Plugins.Test/CabinetDisplayTests.cs.meta @@ -0,0 +1,2 @@ +fileFormatVersion: 2 +guid: 9454015b46330444db1586920285aacf \ No newline at end of file diff --git a/VisualPinball.Plugins/Api/CabinetDisplays.cs b/VisualPinball.Plugins/Api/CabinetDisplays.cs new file mode 100644 index 0000000000..cc742c3e6c --- /dev/null +++ b/VisualPinball.Plugins/Api/CabinetDisplays.cs @@ -0,0 +1,122 @@ +// Visual Pinball Engine +// Copyright (C) 2026 freezy and VPE Team +// +// SPDX-License-Identifier: MIT +// Licensed under MIT. See https://opensource.org/license/mit. + +using System; +using System.Collections.Generic; +using System.Linq; + +namespace VisualPinball.Plugins +{ + /// Optional host capabilities for cabinet output configuration. + public static class CabinetDisplayCapability + { + /// An immutable , published for the game before preparation. + public const string Configuration = "vpe.cabinet-displays.v1"; + } + + /// Who places one plugin's physical output. Does not control its in-scene output. + public enum CabinetOutputMode { Custom = 0, Player = 1, Off = 2 } + /// Physical destination; device drivers remain responsible for device protocols. + public enum CabinetEndpointKind { DesktopRegion = 0, Device = 1 } + /// Availability of a configured destination, independent of its content source. + public enum CabinetEndpointState { Unassigned = 0, Available = 1, Disabled = 2, Unavailable = 3 } + + /// Immutable resolved destination. Desktop coordinates are physical pixels, including negative origins. + public sealed class CabinetDisplayTarget + { + public string EndpointId { get; } + public string Role { get; } + public CabinetEndpointKind Kind { get; } + public CabinetEndpointState State { get; } + public string Reason { get; } + public int X { get; } + public int Y { get; } + public int Width { get; } + public int Height { get; } + /// Canonical provider-resolved lease key, never a guessed USB identifier. + public string DeviceLeaseKey { get; } + + public CabinetDisplayTarget(string endpointId, string role, CabinetEndpointKind kind, CabinetEndpointState state, + int x = 0, int y = 0, int width = 0, int height = 0, string reason = "", string deviceLeaseKey = "") + { + if (string.IsNullOrWhiteSpace(endpointId)) throw new ArgumentException("An endpoint needs an ID.", nameof(endpointId)); + if (string.IsNullOrWhiteSpace(role)) throw new ArgumentException("An output needs a role.", nameof(role)); + if (!Enum.IsDefined(typeof(CabinetEndpointKind), kind)) throw new ArgumentOutOfRangeException(nameof(kind)); + if (!Enum.IsDefined(typeof(CabinetEndpointState), state)) throw new ArgumentOutOfRangeException(nameof(state)); + if (state == CabinetEndpointState.Available && kind == CabinetEndpointKind.DesktopRegion && (width < 1 || height < 1)) throw new ArgumentOutOfRangeException(nameof(width)); + if (state == CabinetEndpointState.Available && kind == CabinetEndpointKind.Device && string.IsNullOrWhiteSpace(deviceLeaseKey)) throw new ArgumentException("An available device needs a canonical lease key.", nameof(deviceLeaseKey)); + EndpointId = endpointId; Role = role; Kind = kind; State = state; + X = x; Y = y; Width = width; Height = height; Reason = reason ?? ""; DeviceLeaseKey = deviceLeaseKey ?? ""; + } + } + + /// Explicit adoption of one plugin output; absence always means Custom. + public sealed class CabinetOutputAssignment + { + public string PluginId { get; } + public string Role { get; } + public CabinetOutputMode Mode { get; } + public CabinetOutputAssignment(string pluginId, string role, CabinetOutputMode mode) + { + if (string.IsNullOrWhiteSpace(pluginId) || string.IsNullOrWhiteSpace(role)) throw new ArgumentException("An assignment needs a plugin and role."); + if (!Enum.IsDefined(typeof(CabinetOutputMode), mode)) throw new ArgumentOutOfRangeException(nameof(mode)); + PluginId = pluginId; Role = role; Mode = mode; + } + } + + /// + /// Game-scoped resolved configuration. Player/Off never imply falling back to a plugin-owned window when a monitor + /// disappears. Source production and in-scene visibility are independent of destination availability. + /// + public sealed class CabinetDisplaySnapshot + { + public long Revision { get; } + public long TopologyGeneration { get; } + public long Session { get; } + public IReadOnlyList Targets { get; } + public IReadOnlyList Assignments { get; } + public CabinetDisplaySnapshot(long revision, long topologyGeneration, long session, + IEnumerable targets, IEnumerable assignments) + { + Revision = revision; TopologyGeneration = topologyGeneration; Session = session; + var targetArray = (targets ?? throw new ArgumentNullException(nameof(targets))).ToArray(); + var assignmentArray = (assignments ?? throw new ArgumentNullException(nameof(assignments))).ToArray(); + if (targetArray.Any(value => value == null) || assignmentArray.Any(value => value == null)) throw new ArgumentException("Snapshot entries cannot be null."); + if (targetArray.GroupBy(value => (value.EndpointId, value.Role)).Any(group => group.Count() > 1)) throw new ArgumentException("Duplicate endpoint/role target.", nameof(targets)); + if (assignmentArray.GroupBy(value => (value.PluginId, value.Role)).Any(group => group.Count() > 1)) throw new ArgumentException("Duplicate plugin/role assignment.", nameof(assignments)); + Targets = Array.AsReadOnly(targetArray); Assignments = Array.AsReadOnly(assignmentArray); + } + + public CabinetOutputMode ModeFor(string pluginId, string role) + { + foreach (var assignment in Assignments) if (assignment.PluginId == pluginId && assignment.Role == role) return assignment.Mode; + return CabinetOutputMode.Custom; + } + + /// All destinations for this role, including unavailable ones; a monitor and device may mirror it. + public IReadOnlyList TargetsFor(string role) + => Array.AsReadOnly(Targets.Where(target => target.Role == role).ToArray()); + } + + /// Optional factory declaration. Inspecting roles must not create a gameplay instance or open a device. + public interface ICabinetDisplayPlugin + { + IReadOnlyList CabinetRoles { get; } + } + + /// Where an updated surface is eligible to be shown. + [Flags] + public enum CabinetSurfaceConsumers { None = 0, Scene = 1, ManagedDesktop = 2 } + + /// Optional metadata on an existing resource, not a second transport. Legacy surfaces remain scene-eligible. + /// Call PluginResourceRegistry.NotifyChanged for this publication whenever readiness or consumers changes. + public interface ICabinetSurface + { + CabinetSurfaceConsumers Consumers { get; } + /// False before the first composition or after withdrawal; a black image can still be ready. + bool IsReady { get; } + } +} diff --git a/VisualPinball.Plugins/Api/CabinetDisplays.cs.meta b/VisualPinball.Plugins/Api/CabinetDisplays.cs.meta new file mode 100644 index 0000000000..fe5d4c7839 --- /dev/null +++ b/VisualPinball.Plugins/Api/CabinetDisplays.cs.meta @@ -0,0 +1,2 @@ +fileFormatVersion: 2 +guid: d07fbd26b7bb9f64a91c7ec371ecd492 \ No newline at end of file diff --git a/VisualPinball.Plugins/Resources/CabinetSurfaceSelector.cs b/VisualPinball.Plugins/Resources/CabinetSurfaceSelector.cs new file mode 100644 index 0000000000..e97a8d72d5 --- /dev/null +++ b/VisualPinball.Plugins/Resources/CabinetSurfaceSelector.cs @@ -0,0 +1,43 @@ +// Visual Pinball Engine +// Copyright (C) 2026 freezy and VPE Team +// +// SPDX-License-Identifier: MIT +// Licensed under MIT. See https://opensource.org/license/mit. + +using System; +using System.Collections.Generic; + +namespace VisualPinball.Plugins +{ + /// Deterministic ranking shared by desktop and scene consumers; callers filter controller/session/role. + public static class CabinetSurfaceSelector + { + public static PluginResourceDescriptor? Choose(IEnumerable candidates, + IReadOnlyList providers, Func eligible) + { + if (candidates == null) throw new ArgumentNullException(nameof(candidates)); + if (providers == null) throw new ArgumentNullException(nameof(providers)); + if (eligible == null) throw new ArgumentNullException(nameof(eligible)); + PluginResourceDescriptor? best = null; + int bestRank = int.MaxValue; + foreach (var candidate in candidates) { + if (!eligible(candidate)) continue; + int rank = Rank(candidate.Provider, providers); + int providerOrder = best == null ? -1 : StringComparer.Ordinal.Compare(candidate.Provider, best.Provider); + if (best == null || rank < bestRank || (rank == bestRank && (providerOrder < 0 || (providerOrder == 0 && StringComparer.Ordinal.Compare(candidate.Id, best.Id) < 0)))) { + best = candidate; bestRank = rank; + } + } + return best; + } + + public static bool Eligible(IPluginResourceSource source, CabinetSurfaceConsumers consumer) + => source is ICabinetSurface surface ? surface.IsReady && (surface.Consumers & consumer) != 0 : (consumer & CabinetSurfaceConsumers.Scene) != 0; + + private static int Rank(string provider, IReadOnlyList order) + { + for (int i = 0; i < order.Count; i++) if (string.Equals(provider, order[i], StringComparison.Ordinal)) return i; + return int.MaxValue; + } + } +} diff --git a/VisualPinball.Plugins/Resources/CabinetSurfaceSelector.cs.meta b/VisualPinball.Plugins/Resources/CabinetSurfaceSelector.cs.meta new file mode 100644 index 0000000000..10ae7304e3 --- /dev/null +++ b/VisualPinball.Plugins/Resources/CabinetSurfaceSelector.cs.meta @@ -0,0 +1,2 @@ +fileFormatVersion: 2 +guid: 2389f02b7c8c1c749ac02e6a115ca4a5 \ No newline at end of file diff --git a/VisualPinball.Plugins/Resources/PluginResourceRegistry.cs b/VisualPinball.Plugins/Resources/PluginResourceRegistry.cs index 8b5f86045b..73ba539824 100644 --- a/VisualPinball.Plugins/Resources/PluginResourceRegistry.cs +++ b/VisualPinball.Plugins/Resources/PluginResourceRegistry.cs @@ -77,6 +77,15 @@ internal sealed class Entry /// /// What to look for. public IReadOnlyList Snapshot(PluginResourceSelection selection) => Candidates(selection).Select(entry => entry.Descriptor).ToArray(); + + /// Probes the current source for an observed descriptor. Borrow only on the owner thread; do not retain it. + public bool TryGetSource(PluginResourceDescriptor descriptor, out T? source) where T : class, IPluginResourceSource + { + source = null; + if (!_entries.TryGetValue(descriptor.Id, out var entry) || entry.Descriptor.Session != descriptor.Session || entry.Descriptor.Instance != descriptor.Instance || !Reachable(entry, new HashSet())) return false; + source = entry.Source as T; + return source != null; + } internal IReadOnlyList Candidates(PluginResourceSelection selection) { var found = _entries.Values.Where(entry => selection.Matches(entry.Descriptor) && Reachable(entry, new HashSet())).OrderBy(entry => entry.Descriptor.Id, StringComparer.Ordinal).ToList(); diff --git a/VisualPinball.Plugins/Resources/ResourceContracts.cs b/VisualPinball.Plugins/Resources/ResourceContracts.cs index e9832a2158..4bca464f53 100644 --- a/VisualPinball.Plugins/Resources/ResourceContracts.cs +++ b/VisualPinball.Plugins/Resources/ResourceContracts.cs @@ -908,8 +908,8 @@ public interface IPluginSurface : IPluginResourceSource string Backend { get; } } /// - /// Well-known values of resources: the - /// cabinet screens a table can show in the scene. + /// Well-known cabinet output roles. Surface resources use the auxiliary roles for scene and desktop consumers; + /// Playfield identifies the Player's separately configured main window, not an auxiliary surface route. /// /// /// A table marks a renderer with VPE's CabinetScreenComponent and one of these roles. While a game runs, VPE shows @@ -925,6 +925,10 @@ public interface IPluginSurface : IPluginResourceSource /// public static class SurfaceRoles { + /// The Player's main window; placement stays in Video settings. + public const string Playfield = "playfield"; + /// A composed score panel, distinct from a controller's raw DMD. + public const string ScorePanel = "score-panel"; /// The backglass. public const string Backglass = "backglass"; /// The screen of a topper above the backbox. diff --git a/VisualPinball.Unity/Documentation~/developer-guide/cabinet-display-outputs.md b/VisualPinball.Unity/Documentation~/developer-guide/cabinet-display-outputs.md new file mode 100644 index 0000000000..cfdc153efc --- /dev/null +++ b/VisualPinball.Unity/Documentation~/developer-guide/cabinet-display-outputs.md @@ -0,0 +1,21 @@ +# Cabinet display outputs + +The Player owns adopted desktop output placement. Plugins own content generation and device drivers. Existing installations retain Custom placement until the user adopts an output role; an unavailable managed target never silently falls back to a plugin-owned window. + +## Shared boundary + +`CabinetDisplaySnapshot` is an immutable game-scoped capability (`vpe.cabinet-displays.v1`) published before plugin preparation. It contains resolved destinations and explicit per-plugin role assignments. Missing capability or missing assignment means Custom. Player and Off suppress that role's legacy physical output independently of scene rendering. A factory can advertise supported roles through `ICabinetDisplayPlugin` without creating a game instance. + +`CabinetSurfaceSelector` provides deterministic provider ranking with caller-supplied readiness and eligibility. Scene consumers retain engine-DMD precedence. Legacy Unity texture surfaces remain scene-eligible; an updated `ICabinetSurface` must declare Scene and be ready. Producers call `PluginResourceRegistry.NotifyChanged` whenever readiness or consumer eligibility changes. Updated resources expose a desktop texture through `IUnityDesktopSurface`; its color-space property describes shader-sampled values after any hardware sRGB conversion. Producers must withdraw the publication or announce replacement before releasing a borrowed texture. The Unity test files follow the existing test assembly's GPL-3.0-or-later convention; the additive plugin API and presentation helper use MIT like their neighboring integration files. + +## Presentation ownership + +`CabinetOutputTexture` copies content into an owned, opaque SDR RenderTexture. A native window may borrow this output only. It never receives a producer texture pointer. Close or detach the native window and drain native retirement before releasing the owned output. NativeWindowHost remains the sole render-event pump during play. + +The Player must drive plugin BeforeRender, then its cabinet copy pass in the same LateUpdate, before NativeWindowHost at execution order 10000. Texture Changed events describe allocation/replacement, not each video frame. Copy live surfaces every frame unless a producer revision proves unchanged. The cabinet copy call must run even when no gameplay plugins are active. + +## Delivery and validation + +The initial shared boundary has pure contract tests, GPU-copy tests, and an EditMode native probe for two windows, pointer replacement and retirement. Run the native probe on each supported platform/backend before certifying it; a single Windows graphics backend does not certify Metal or Vulkan. + +The next Player phase adds persisted layout, Windows topology, browsing backglass and playfield monitor selection. Playfield placement stays in the Video transaction, not an auxiliary MainWindow endpoint. The asynchronous move, verification, Keep/Revert and cancellation must use one version token. Later phases adapt B2S, PinUP and DMD in that order, preserving legacy output for unsupported layouts and device configurations. diff --git a/VisualPinball.Unity/VisualPinball.Unity.Test/Rendering/CabinetNativeWindowTests.cs b/VisualPinball.Unity/VisualPinball.Unity.Test/Rendering/CabinetNativeWindowTests.cs new file mode 100644 index 0000000000..430bf32f25 --- /dev/null +++ b/VisualPinball.Unity/VisualPinball.Unity.Test/Rendering/CabinetNativeWindowTests.cs @@ -0,0 +1,99 @@ +// Visual Pinball Engine +// Copyright (C) 2026 freezy and VPE Team +// +// SPDX-License-Identifier: GPL-3.0-or-later + +using System.Collections; +using NUnit.Framework; +using UnityEditor; +using UnityEngine; +using UnityEngine.TestTools; +using VisualPinball.Plugins; + +namespace VisualPinball.Unity.Test +{ + public sealed class CabinetNativeWindowTests + { + private static readonly System.Collections.Generic.List Quarantine = new(); + [UnityTest] + public IEnumerator TwoWindowsPresentOwnedCopiesAndDrainAfterReplacement() + { + if (!NativeWindowSurface.IsSupported) Assert.Ignore("Native windows are unavailable on this graphics backend."); + // EditMode: drive the same event pair as NativeWindowHost, without starting a table or plugin. + if (Application.isPlaying) Assert.Ignore("Run this probe in EditMode; NativeWindowHost owns events during play."); + var first = new CabinetOutputTexture(64, 32); + var second = new CabinetOutputTexture(32, 64); + System.Exception failure = null; + var source = new Texture2D(1, 1, TextureFormat.RGBA32, false, true); + source.SetPixel(0, 0, Color.green); source.Apply(); + first.Copy(source, FrameColorSpace.Linear); second.Copy(source, FrameColorSpace.Linear); + Object.DestroyImmediate(source); + NativeWindowSurface a = null, b = null; + try { + Capture(() => { + a = new NativeWindowSurface(20, 20, 64, 32); + b = new NativeWindowSurface(90, 20, 32, 64); + a.SetTexture(first.Texture.GetNativeTexturePtr()); b.SetTexture(second.Texture.GetNativeTexturePtr()); + a.Configure(20, 20, 64, 32, true, false); b.Configure(90, 20, 32, 64, true, false); + }, ref failure); + bool ready = false; + for (int i = 0; i < 30 && !ready && failure == null; i++) { + Capture(() => { Events(); ready = a.Diagnostics.PresentedFrames > 0 && b.Diagnostics.PresentedFrames > 0; }, ref failure); + yield return null; + } + if (failure == null) Capture(() => { + Assert.That(ready, Is.True, "Both windows must present."); + Assert.That(a.Diagnostics.SourceWidth, Is.EqualTo(64)); + Assert.That(b.Diagnostics.SourceWidth, Is.EqualTo(32)); + a.SetTexture(second.Texture.GetNativeTexturePtr()); + }, ref failure); + ulong frames = 0; + if (failure == null) Capture(() => frames = a.Diagnostics.PresentedFrames, ref failure); + ready = false; + for (int i = 0; i < 30 && !ready && failure == null; i++) { + Capture(() => { Events(); var state = a.Diagnostics; ready = state.SourceWidth == 32 && state.PresentedFrames > frames; }, ref failure); + yield return null; + } + if (failure == null) Capture(() => Assert.That(ready, Is.True, "The replacement pointer must present new frames."), ref failure); + } finally { + Capture(() => a?.Dispose(), ref failure); + Capture(() => b?.Dispose(), ref failure); + // Also safe if the test is cancelled: retain the outputs in an editor callback until native work drains. + ReleaseAfterDrain(first, second); + } + for (int i = 0; i < 60 && NativeWindowSurface.PendingResourceCount > 0; i++) { Events(); yield return null; } + Assert.That(NativeWindowSurface.PendingResourceCount, Is.Zero, "Native GPU resources must drain before releasing the owned outputs."); + if (failure != null) System.Runtime.ExceptionServices.ExceptionDispatchInfo.Capture(failure).Throw(); + } + + private static void Capture(System.Action action, ref System.Exception failure) + { + try { action(); } catch (System.Exception error) { failure ??= error; } + } + + private static void ReleaseAfterDrain(CabinetOutputTexture first, CabinetOutputTexture second) + { + int updates = 0; + EditorApplication.CallbackFunction drain = null; + drain = () => { + if (NativeWindowSurface.PendingResourceCount > 0 && updates++ < 600) { Events(); return; } + EditorApplication.update -= drain; + if (NativeWindowSurface.PendingResourceCount > 0) { + Quarantine.Add(first); Quarantine.Add(second); + Debug.LogWarning("Cabinet native probe retained its outputs because GPU retirement did not drain."); + return; + } + first.Dispose(); second.Dispose(); + }; + EditorApplication.update += drain; + } + + private static void Events() + { + NativeWindowSurface.Pump(); + GL.IssuePluginEvent(NativeWindowSurface.RenderEventFunction, NativeWindowSurface.DrawEventId); + GL.IssuePluginEvent(NativeWindowSurface.RenderEventFunction, NativeWindowSurface.PresentEventId); + EditorApplication.QueuePlayerLoopUpdate(); + } + } +} diff --git a/VisualPinball.Unity/VisualPinball.Unity.Test/Rendering/CabinetNativeWindowTests.cs.meta b/VisualPinball.Unity/VisualPinball.Unity.Test/Rendering/CabinetNativeWindowTests.cs.meta new file mode 100644 index 0000000000..992109586f --- /dev/null +++ b/VisualPinball.Unity/VisualPinball.Unity.Test/Rendering/CabinetNativeWindowTests.cs.meta @@ -0,0 +1,2 @@ +fileFormatVersion: 2 +guid: 4d1fe316feccce140b680f66f56cbc61 \ No newline at end of file diff --git a/VisualPinball.Unity/VisualPinball.Unity.Test/Rendering/CabinetOutputTextureTests.cs b/VisualPinball.Unity/VisualPinball.Unity.Test/Rendering/CabinetOutputTextureTests.cs new file mode 100644 index 0000000000..f9552bb7ea --- /dev/null +++ b/VisualPinball.Unity/VisualPinball.Unity.Test/Rendering/CabinetOutputTextureTests.cs @@ -0,0 +1,116 @@ +// Visual Pinball Engine +// Copyright (C) 2026 freezy and VPE Team +// +// SPDX-License-Identifier: GPL-3.0-or-later + +using NUnit.Framework; +using UnityEngine; +using VisualPinball.Plugins; + +namespace VisualPinball.Unity.Test +{ + public sealed class CabinetOutputTextureTests + { + [Test] + public void CopyOwnsItsPixelsAfterProducerDestructionAndLetterboxes() + { + var source = Solid(16, 8, new Color(.25f, .25f, .25f, 1)); + using var output = new CabinetOutputTexture(16, 16); + output.Copy(source, FrameColorSpace.Srgb); + Object.DestroyImmediate(source); + var pixels = Read(output.Texture); + try { + Assert.That(pixels.GetPixel(8, 8).r, Is.EqualTo(.25f).Within(.015)); + Assert.That(pixels.GetPixel(8, 1).r, Is.LessThan(.005)); + } finally { Object.DestroyImmediate(pixels); } + } + + [Test] + public void RepeatedCopyUpdatesPixelsWithoutReplacementEventsAndEncodesLinearLight() + { + using var output = new CabinetOutputTexture(8, 8); + var pointer = output.Texture.GetNativeTexturePtr(); + var source = Solid(8, 8, Color.red); + try { + output.Copy(source, FrameColorSpace.Linear); + Assert.That(output.Texture.GetNativeTexturePtr(), Is.EqualTo(pointer)); + var pixels = Read(output.Texture); + Assert.That(pixels.GetPixel(4, 4).r, Is.GreaterThan(.98)); + Object.DestroyImmediate(pixels); + Fill(source, new Color(.25f, .25f, .25f, 1)); + output.Copy(source, FrameColorSpace.Linear); + pixels = Read(output.Texture); + try { Assert.That(pixels.GetPixel(4, 4).r, Is.EqualTo(.537f).Within(.015)); } + finally { Object.DestroyImmediate(pixels); } + } finally { Object.DestroyImmediate(source); } + } + + [TestCase(8f / 255, FrameColorSpace.Srgb, 8f / 255)] + [TestCase(.002f, FrameColorSpace.Linear, .02584f)] + public void ConversionPreservesShadowDetail(float input, FrameColorSpace space, float expected) + { + var source = new Texture2D(1, 1, TextureFormat.RGBAFloat, false, true); + source.SetPixel(0, 0, new Color(input, input, input, 1)); source.Apply(); + using var output = new CabinetOutputTexture(8, 8); + try { + output.Copy(source, space); + var pixels = Read(output.Texture); + try { Assert.That(pixels.GetPixel(4, 4).r, Is.EqualTo(expected).Within(1.1f / 255)); } + finally { Object.DestroyImmediate(pixels); } + } finally { Object.DestroyImmediate(source); } + } + + [Test] + public void EncodedPremultipliedInputAndLostOutputAllocationAreHandled() + { + var source = Solid(8, 8, new Color(.25f, 0, 0, .5f)); + using var output = new CabinetOutputTexture(8, 8); + long revision = output.Revision; + output.Texture.Release(); + try { + output.Copy(source, FrameColorSpace.Srgb, FrameAlpha.Premultiplied); + Assert.That(output.Revision, Is.GreaterThan(revision)); + var pixels = Read(output.Texture); + // Decode .5, compose at .5 alpha over black, encode: about .361. + try { Assert.That(pixels.GetPixel(4, 4).r, Is.EqualTo(.361f).Within(2f / 255)); } + finally { Object.DestroyImmediate(pixels); } + } finally { Object.DestroyImmediate(source); } + } + + [Test] + public void CopyRestoresGlobalRenderStateAndComposesPremultipliedInputOverBlack() + { + var source = Solid(8, 8, new Color(.25f, 0, 0, .5f)); + using var output = new CabinetOutputTexture(8, 8); + var previous = RenderTexture.active; + bool srgb = GL.sRGBWrite; + try { + output.Copy(source, FrameColorSpace.Linear, FrameAlpha.Premultiplied); + Assert.That(RenderTexture.active, Is.SameAs(previous)); + Assert.That(GL.sRGBWrite, Is.EqualTo(srgb)); + var pixels = Read(output.Texture); + try { Assert.That(pixels.GetPixel(4, 4).r, Is.EqualTo(.537f).Within(.015)); Assert.That(pixels.GetPixel(4, 4).a, Is.GreaterThan(.99)); } + finally { Object.DestroyImmediate(pixels); } + } finally { Object.DestroyImmediate(source); } + } + + private static Texture2D Solid(int width, int height, Color color) + { + var texture = new Texture2D(width, height, TextureFormat.RGBA32, false, true); + Fill(texture, color); return texture; + } + private static void Fill(Texture2D texture, Color color) + { + var colors = new Color[texture.width * texture.height]; + for (int i = 0; i < colors.Length; i++) colors[i] = color; + texture.SetPixels(colors); texture.Apply(); + } + private static Texture2D Read(RenderTexture source) + { + var previous = RenderTexture.active; + var texture = new Texture2D(source.width, source.height, TextureFormat.RGBA32, false, true); + try { RenderTexture.active = source; texture.ReadPixels(new Rect(0, 0, source.width, source.height), 0, 0); texture.Apply(); return texture; } + finally { RenderTexture.active = previous; } + } + } +} diff --git a/VisualPinball.Unity/VisualPinball.Unity.Test/Rendering/CabinetOutputTextureTests.cs.meta b/VisualPinball.Unity/VisualPinball.Unity.Test/Rendering/CabinetOutputTextureTests.cs.meta new file mode 100644 index 0000000000..11304be8d1 --- /dev/null +++ b/VisualPinball.Unity/VisualPinball.Unity.Test/Rendering/CabinetOutputTextureTests.cs.meta @@ -0,0 +1,2 @@ +fileFormatVersion: 2 +guid: 98bcfe731dd7f684aa3d46a5574e7a1f \ No newline at end of file diff --git a/VisualPinball.Unity/VisualPinball.Unity/NativeWindows/CabinetOutputTexture.cs b/VisualPinball.Unity/VisualPinball.Unity/NativeWindows/CabinetOutputTexture.cs new file mode 100644 index 0000000000..964a798d32 --- /dev/null +++ b/VisualPinball.Unity/VisualPinball.Unity/NativeWindows/CabinetOutputTexture.cs @@ -0,0 +1,88 @@ +// Visual Pinball Engine +// Copyright (C) 2026 freezy and VPE Team +// +// SPDX-License-Identifier: MIT +// Licensed under MIT. See https://opensource.org/license/mit. + +using System; +using UnityEngine; +using VisualPinball.Plugins; + +namespace VisualPinball.Unity +{ + /// + /// Player-owned SDR output. Native windows borrow only this texture, never the producer's. Submit copies after + /// plugin BeforeRender and before NativeWindowHost. Close/detach the native window before disposing this object. + /// + public sealed class CabinetOutputTexture : IDisposable + { + private readonly Material _copy; + private bool _disposed; + public RenderTexture Texture { get; } + /// Changes after allocation/recreation. A borrowing window must resubmit its native pointer. + public long Revision { get; private set; } + public CabinetOutputTexture(int width, int height) + { + if (width < 1 || height < 1 || width > SystemInfo.maxTextureSize || height > SystemInfo.maxTextureSize || (long)width * height > 33554432) throw new ArgumentOutOfRangeException(nameof(width), "Cabinet outputs support up to 32 megapixels."); + var shader = Resources.Load("CabinetOutput"); + if (shader == null || !shader.isSupported) throw new PlatformNotSupportedException("The cabinet output copy shader is unavailable."); + _copy = new Material(shader) { hideFlags = HideFlags.HideAndDontSave }; + Texture = new RenderTexture(width, height, 0, RenderTextureFormat.ARGB32, RenderTextureReadWrite.Linear) { + name = "Cabinet output", hideFlags = HideFlags.HideAndDontSave, filterMode = FilterMode.Bilinear, wrapMode = TextureWrapMode.Clamp, + }; + try { EnsureCreated(); } + catch { Dispose(); throw; } + Clear(); + } + + /// Restores a lost allocation; callers must clear or copy its pixels before presentation. + public bool EnsureCreated() + { + if (_disposed) throw new ObjectDisposedException(nameof(CabinetOutputTexture)); + if (Texture.IsCreated()) return false; + if (!Texture.Create()) throw new InvalidOperationException("Cannot allocate cabinet output texture."); + Revision++; + return true; + } + + /// Copies immediately; source is not retained. Color space describes shader-sampled values. + public void Copy(UnityEngine.Texture source, FrameColorSpace colorSpace, FrameAlpha alpha = FrameAlpha.None, bool flipY = false) + { + if (_disposed) throw new ObjectDisposedException(nameof(CabinetOutputTexture)); + EnsureCreated(); + if (source == null || source.width < 1 || source.height < 1) { Clear(); return; } + double aspect = (double)source.width / source.height; + double outputAspect = (double)Texture.width / Texture.height; + float width = (float)System.Math.Min(1, aspect / outputAspect), height = (float)System.Math.Min(1, outputAspect / aspect); + _copy.SetVector("_Content", new Vector4((1 - width) * .5f, (1 - height) * .5f, width, height)); + _copy.SetFloat("_Encoded", colorSpace == FrameColorSpace.Srgb ? 1 : 0); + _copy.SetFloat("_Alpha", alpha == FrameAlpha.Premultiplied ? 2 : alpha == FrameAlpha.Straight ? 1 : 0); + _copy.SetFloat("_FlipY", flipY ? 1 : 0); + var active = RenderTexture.active; + bool srgb = GL.sRGBWrite; + try { GL.sRGBWrite = false; Graphics.Blit(source, Texture, _copy); } + finally { GL.sRGBWrite = srgb; RenderTexture.active = active; } + } + + public void Clear() + { + if (_disposed) throw new ObjectDisposedException(nameof(CabinetOutputTexture)); + EnsureCreated(); + var active = RenderTexture.active; + try { RenderTexture.active = Texture; GL.Clear(false, true, Color.black); } + finally { RenderTexture.active = active; } + } + + public void Dispose() + { + if (_disposed) return; + _disposed = true; + if (Texture != null) { Texture.Release(); Destroy(Texture); } + if (_copy != null) Destroy(_copy); + } + private static void Destroy(UnityEngine.Object value) + { + if (Application.isPlaying) UnityEngine.Object.Destroy(value); else UnityEngine.Object.DestroyImmediate(value); + } + } +} diff --git a/VisualPinball.Unity/VisualPinball.Unity/NativeWindows/CabinetOutputTexture.cs.meta b/VisualPinball.Unity/VisualPinball.Unity/NativeWindows/CabinetOutputTexture.cs.meta new file mode 100644 index 0000000000..5ab9671997 --- /dev/null +++ b/VisualPinball.Unity/VisualPinball.Unity/NativeWindows/CabinetOutputTexture.cs.meta @@ -0,0 +1,2 @@ +fileFormatVersion: 2 +guid: f108b488cbed78846896120c3043a345 \ No newline at end of file diff --git a/VisualPinball.Unity/VisualPinball.Unity/Plugins/CabinetScreenBinder.cs b/VisualPinball.Unity/VisualPinball.Unity/Plugins/CabinetScreenBinder.cs index 812d73e6c6..640f4e3b52 100644 --- a/VisualPinball.Unity/VisualPinball.Unity/Plugins/CabinetScreenBinder.cs +++ b/VisualPinball.Unity/VisualPinball.Unity/Plugins/CabinetScreenBinder.cs @@ -166,7 +166,7 @@ public static string TextureProperty(Material material, string requested) private void RegistryChanged(PluginResourceChange change) { - if (change.Descriptor.Kind == ResourceKind.Surface && change.Kind != ResourceChangeKind.Changed) { + if (change.Descriptor.Kind == ResourceKind.Surface) { Refresh(); } } @@ -246,21 +246,8 @@ private string Choose(string role) var candidates = _registry.Snapshot(new PluginResourceSelection(ResourceKind.Surface) { Role = role, Controller = _controller, Session = _session, }); - return candidates - .OrderBy(descriptor => Rank(descriptor.Provider)) - .ThenBy(descriptor => descriptor.Provider, StringComparer.Ordinal) - .ThenBy(descriptor => descriptor.Id, StringComparer.Ordinal) - .FirstOrDefault()?.Id; - } - - private int Rank(string provider) - { - for (var i = 0; i < _providers.Count; i++) { - if (string.Equals(_providers[i], provider, StringComparison.Ordinal)) { - return i; - } - } - return int.MaxValue; + return CabinetSurfaceSelector.Choose(candidates, _providers, descriptor => + _registry.TryGetSource(descriptor, out var source) && CabinetSurfaceSelector.Eligible(source, CabinetSurfaceConsumers.Scene))?.Id; } /// diff --git a/VisualPinball.Unity/VisualPinball.Unity/Plugins/UnityDesktopSurface.cs b/VisualPinball.Unity/VisualPinball.Unity/Plugins/UnityDesktopSurface.cs new file mode 100644 index 0000000000..070b324c17 --- /dev/null +++ b/VisualPinball.Unity/VisualPinball.Unity/Plugins/UnityDesktopSurface.cs @@ -0,0 +1,25 @@ +// Visual Pinball Engine +// Copyright (C) 2026 freezy and VPE Team +// +// SPDX-License-Identifier: MIT +// Licensed under MIT. See https://opensource.org/license/mit. + +using UnityEngine; +using VisualPinball.Plugins; + +namespace VisualPinball.Unity +{ + /// + /// Optional desktop representation of the same published surface. Generating it must not require a plugin-owned + /// window. Withdraw the publication before releasing its texture. Read only on the owner thread while ready. + /// DesktopTexture is re-read every render frame; the inherited Changed event describes the scene Texture only. + /// + public interface IUnityDesktopSurface : IUnityTextureResource, ICabinetSurface + { + Texture DesktopTexture { get; } + /// Encoding of shader-sampled RGB values, after any texture hardware sRGB conversion. + FrameColorSpace SampleColorSpace { get; } + FrameAlpha DesktopAlpha { get; } + bool DesktopFlipY { get; } + } +} diff --git a/VisualPinball.Unity/VisualPinball.Unity/Plugins/UnityDesktopSurface.cs.meta b/VisualPinball.Unity/VisualPinball.Unity/Plugins/UnityDesktopSurface.cs.meta new file mode 100644 index 0000000000..c3ee4c73d4 --- /dev/null +++ b/VisualPinball.Unity/VisualPinball.Unity/Plugins/UnityDesktopSurface.cs.meta @@ -0,0 +1,2 @@ +fileFormatVersion: 2 +guid: 16dc050c4fe71db48a00938723928ead \ No newline at end of file diff --git a/VisualPinball.Unity/VisualPinball.Unity/Resources/CabinetOutput.shader b/VisualPinball.Unity/VisualPinball.Unity/Resources/CabinetOutput.shader new file mode 100644 index 0000000000..4c75fcd256 --- /dev/null +++ b/VisualPinball.Unity/VisualPinball.Unity/Resources/CabinetOutput.shader @@ -0,0 +1,36 @@ +Shader "VisualPinball/CabinetOutput" +{ + Properties { _MainTex ("Source", 2D) = "black" {} } + SubShader + { + Cull Off ZWrite Off ZTest Always + Pass + { + CGPROGRAM + #pragma vertex vert_img + #pragma fragment frag + #include "UnityCG.cginc" + sampler2D _MainTex; + float4 _MainTex_TexelSize; + float4 _Content; + float _Encoded, _Alpha, _FlipY; + float3 Decode(float3 value) { return float3(GammaToLinearSpaceExact(value.r), GammaToLinearSpaceExact(value.g), GammaToLinearSpaceExact(value.b)); } + float3 Encode(float3 value) { return float3(LinearToGammaSpaceExact(value.r), LinearToGammaSpaceExact(value.g), LinearToGammaSpaceExact(value.b)); } + float4 frag(v2f_img input) : SV_Target + { + float2 uv = (input.uv - _Content.xy) / _Content.zw; + if (any(uv < 0) || any(uv > 1)) return float4(0, 0, 0, 1); + if (_FlipY > .5) uv.y = 1 - uv.y; + uv = clamp(uv, abs(_MainTex_TexelSize.xy) * .5, 1 - abs(_MainTex_TexelSize.xy) * .5); + float4 color = tex2D(_MainTex, uv); + float alpha = _Alpha < .5 ? 1 : saturate(color.a); + // Unpremultiply in the producer's encoding before converting to linear light. + if (_Alpha > 1.5) color.rgb = alpha > .00001 ? color.rgb / alpha : 0; + float3 light = _Encoded > .5 ? Decode(color.rgb) : color.rgb; + // Cabinet endpoints are opaque: compose over black, then encode exactly once. + return float4(Encode(max(0, light * alpha)), 1); + } + ENDCG + } + } +} diff --git a/VisualPinball.Unity/VisualPinball.Unity/Resources/CabinetOutput.shader.meta b/VisualPinball.Unity/VisualPinball.Unity/Resources/CabinetOutput.shader.meta new file mode 100644 index 0000000000..e73beadf31 --- /dev/null +++ b/VisualPinball.Unity/VisualPinball.Unity/Resources/CabinetOutput.shader.meta @@ -0,0 +1,9 @@ +fileFormatVersion: 2 +guid: 137056a43514fe44ab6be8b494b2a2de +ShaderImporter: + externalObjects: {} + defaultTextures: [] + nonModifiableTextures: [] + userData: + assetBundleName: + assetBundleVariant: From 77c7093050fd8a926e5fe1ff8871aae52f5b3df7 Mon Sep 17 00:00:00 2001 From: freezy Date: Mon, 2 Nov 2026 11:59:33 +0100 Subject: [PATCH 02/10] display: add transformed copies and inset composition --- CHANGELOG.md | 2 + .../cabinet-display-outputs.md | 6 ++ .../Rendering/CabinetOutputTextureTests.cs | 70 +++++++++++++++++++ .../NativeWindows/CabinetOutputTexture.cs | 50 +++++++++++-- .../Resources/CabinetOutput.shader | 21 ++++-- 5 files changed, 139 insertions(+), 10 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 313d686a92..e0e3e2fbb3 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -8,6 +8,8 @@ Built with Unity 6.5 ### Added +- Cabinet output content rotation, mirroring, and explicit-load inset composition with asymmetric GPU validation. + - Shared cabinet display configuration contracts, deterministic surface ranking, and an owned SDR output-copy target with GPU and native-window validation probes, preparing centralized Player display routing. - Extensible shared plugin settings sections for paths and multiple mixer channels, with canonical plugin-owned values and provider validation for global edits. diff --git a/VisualPinball.Unity/Documentation~/developer-guide/cabinet-display-outputs.md b/VisualPinball.Unity/Documentation~/developer-guide/cabinet-display-outputs.md index cfdc153efc..83352d188e 100644 --- a/VisualPinball.Unity/Documentation~/developer-guide/cabinet-display-outputs.md +++ b/VisualPinball.Unity/Documentation~/developer-guide/cabinet-display-outputs.md @@ -19,3 +19,9 @@ The Player must drive plugin BeforeRender, then its cabinet copy pass in the sam The initial shared boundary has pure contract tests, GPU-copy tests, and an EditMode native probe for two windows, pointer replacement and retirement. Run the native probe on each supported platform/backend before certifying it; a single Windows graphics backend does not certify Metal or Vulkan. The next Player phase adds persisted layout, Windows topology, browsing backglass and playfield monitor selection. Playfield placement stays in the Video transaction, not an auxiliary MainWindow endpoint. The asynchronous move, verification, Keep/Revert and cancellation must use one version token. Later phases adapt B2S, PinUP and DMD in that order, preserving legacy output for unsupported layouts and device configurations. + +## Content transforms and a shared panel + +The owned output texture can copy clockwise quarter-turn rotation and output-axis mirrors into a normalized viewport. The viewport uses bottom-left Unity UV coordinates; the Player converts its saved top-left percentages once. Inside the viewport, contain-fit bars are opaque black. Outside it, existing pixels are retained using an explicit color Load/Store action. This supports a Full DMD background and an independently selected DMD inset in one native window. The existing four-argument full-frame copy API remains available. Producer textures are unbound from the copy material immediately after submission. + +Physical multi-monitor and rotated-panel certification remains outstanding. The test suite covers all eight dihedral transforms, asymmetric partial viewports and render-state restoration, alpha/color conversion, two native presenters and deferred output retirement on the available Windows D3D12 backend. Metal and Vulkan must pass their platform matrices before certification. diff --git a/VisualPinball.Unity/VisualPinball.Unity.Test/Rendering/CabinetOutputTextureTests.cs b/VisualPinball.Unity/VisualPinball.Unity.Test/Rendering/CabinetOutputTextureTests.cs index f9552bb7ea..3316583b80 100644 --- a/VisualPinball.Unity/VisualPinball.Unity.Test/Rendering/CabinetOutputTextureTests.cs +++ b/VisualPinball.Unity/VisualPinball.Unity.Test/Rendering/CabinetOutputTextureTests.cs @@ -94,6 +94,76 @@ public void CopyRestoresGlobalRenderStateAndComposesPremultipliedInputOverBlack( } finally { Object.DestroyImmediate(source); } } + [Test] + public void AllEightRotationsAndMirrorsMapAllFourAsymmetricCorners() + { + var colors = new[] { Color.red, Color.green, Color.blue, new Color(1, 1, 0) }; + var source = Solid(8, 8, Color.black); + for (int y = 0; y < 8; y++) for (int x = 0; x < 8; x++) source.SetPixel(x, y, colors[(y >= 4 ? 0 : 2) + (x < 4 ? 0 : 1)]); + source.Apply(); + using var output = new CabinetOutputTexture(8, 8); + var rotations = new[] { 0, 1, 2, 3, 0, 0, 1, 1 }; + var expected = new[] { new[] { 0, 1, 2, 3 }, new[] { 2, 0, 3, 1 }, new[] { 3, 2, 1, 0 }, new[] { 1, 3, 0, 2 }, new[] { 1, 0, 3, 2 }, new[] { 2, 3, 0, 1 }, new[] { 0, 2, 1, 3 }, new[] { 3, 1, 2, 0 } }; + try { + for (int test = 0; test < 8; test++) { + output.Copy(source, FrameColorSpace.Linear, FrameAlpha.None, false, rotations[test], test == 4 || test == 6, test == 5 || test == 7, new Rect(0, 0, 1, 1)); + var pixels = Read(output.Texture); + try { + for (int corner = 0; corner < 4; corner++) { + var actual = pixels.GetPixel(corner % 2 == 0 ? 1 : 6, corner < 2 ? 6 : 1); var wanted = colors[expected[test][corner]]; + Assert.That(actual.r, Is.EqualTo(wanted.r).Within(.01), "red transform " + test + " corner " + corner); + Assert.That(actual.g, Is.EqualTo(wanted.g).Within(.01), "green transform " + test + " corner " + corner); + Assert.That(actual.b, Is.EqualTo(wanted.b).Within(.01), "blue transform " + test + " corner " + corner); + } + } finally { Object.DestroyImmediate(pixels); } + } + // Exercise the explicit-load GL path with asymmetric content, following a differently sized source. + output.Copy(Texture2D.whiteTexture, FrameColorSpace.Linear, FrameAlpha.None, false, 0, false, false, new Rect(0, 0, .5f, .5f)); + var previous = RenderTexture.active; bool srgb = GL.sRGBWrite; + output.Copy(source, FrameColorSpace.Linear, FrameAlpha.None, false, 1, false, false, new Rect(0, 0, .5f, .5f)); + Assert.That(RenderTexture.active, Is.SameAs(previous)); Assert.That(GL.sRGBWrite, Is.EqualTo(srgb)); + var partial = Read(output.Texture); + try { + for (int corner = 0; corner < 4; corner++) { + var actual = partial.GetPixel(corner % 2 == 0 ? 0 : 3, corner < 2 ? 3 : 0); var wanted = colors[expected[1][corner]]; + Assert.That(actual.r, Is.EqualTo(wanted.r).Within(.01)); Assert.That(actual.g, Is.EqualTo(wanted.g).Within(.01)); Assert.That(actual.b, Is.EqualTo(wanted.b).Within(.01)); + } + } finally { Object.DestroyImmediate(partial); } + } finally { Object.DestroyImmediate(source); } + } + + [Test] + public void ViewportUsesBottomLeftUvOrigin() + { + var background = Solid(8, 8, Color.red); var inset = Solid(8, 2, Color.green); + using var output = new CabinetOutputTexture(16, 16); + try { + output.Copy(background, FrameColorSpace.Linear); + output.Copy(inset, FrameColorSpace.Linear, FrameAlpha.None, false, 0, false, false, new Rect(0, 0, 1, .25f)); + var pixels = Read(output.Texture); + try { Assert.That(pixels.GetPixel(8, 1).g, Is.GreaterThan(.95)); Assert.That(pixels.GetPixel(8, 14).r, Is.GreaterThan(.95)); } + finally { Object.DestroyImmediate(pixels); } + } finally { Object.DestroyImmediate(background); Object.DestroyImmediate(inset); } + } + + [Test] + public void InsetPreservesBackgroundAndClearsOnlyItsOwnViewportWhenMissing() + { + var background = Solid(8, 8, Color.red); var inset = Solid(8, 8, Color.green); + using var output = new CabinetOutputTexture(16, 16); + try { + output.Copy(background, FrameColorSpace.Linear); + output.Copy(inset, FrameColorSpace.Linear, FrameAlpha.None, false, 0, false, false, new Rect(.25f, .25f, .5f, .5f)); + var pixels = Read(output.Texture); + try { Assert.That(pixels.GetPixel(1, 1).r, Is.GreaterThan(.95)); Assert.That(pixels.GetPixel(8, 8).g, Is.GreaterThan(.95)); } + finally { Object.DestroyImmediate(pixels); } + output.Copy(null, FrameColorSpace.Linear, FrameAlpha.None, false, 0, false, false, new Rect(.25f, .25f, .5f, .5f)); + pixels = Read(output.Texture); + try { Assert.That(pixels.GetPixel(1, 1).r, Is.GreaterThan(.95)); Assert.That((pixels.GetPixel(8, 8).r + pixels.GetPixel(8, 8).g + pixels.GetPixel(8, 8).b), Is.LessThan(.01)); } + finally { Object.DestroyImmediate(pixels); } + } finally { Object.DestroyImmediate(background); Object.DestroyImmediate(inset); } + } + private static Texture2D Solid(int width, int height, Color color) { var texture = new Texture2D(width, height, TextureFormat.RGBA32, false, true); diff --git a/VisualPinball.Unity/VisualPinball.Unity/NativeWindows/CabinetOutputTexture.cs b/VisualPinball.Unity/VisualPinball.Unity/NativeWindows/CabinetOutputTexture.cs index 964a798d32..31b53faca7 100644 --- a/VisualPinball.Unity/VisualPinball.Unity/NativeWindows/CabinetOutputTexture.cs +++ b/VisualPinball.Unity/VisualPinball.Unity/NativeWindows/CabinetOutputTexture.cs @@ -6,6 +6,7 @@ using System; using UnityEngine; +using UnityEngine.Rendering; using VisualPinball.Plugins; namespace VisualPinball.Unity @@ -17,6 +18,9 @@ namespace VisualPinball.Unity public sealed class CabinetOutputTexture : IDisposable { private readonly Material _copy; + private readonly RenderBuffer[] _insetColor = new RenderBuffer[1]; + private static readonly RenderBufferLoadAction[] InsetLoad = { RenderBufferLoadAction.Load }; + private static readonly RenderBufferStoreAction[] InsetStore = { RenderBufferStoreAction.Store }; private bool _disposed; public RenderTexture Texture { get; } /// Changes after allocation/recreation. A borrowing window must resubmit its native pointer. @@ -47,21 +51,55 @@ public bool EnsureCreated() /// Copies immediately; source is not retained. Color space describes shader-sampled values. public void Copy(UnityEngine.Texture source, FrameColorSpace colorSpace, FrameAlpha alpha = FrameAlpha.None, bool flipY = false) + => Copy(source, colorSpace, alpha, flipY, 0, false, false, new Rect(0, 0, 1, 1)); + + /// Contains transformed content inside a normalized viewport measured from the bottom-left (Unity UV coordinates). Preserves pixels outside; letterbox bars inside are opaque black. Rotation is clockwise quarter-turns. + public void Copy(UnityEngine.Texture source, FrameColorSpace colorSpace, FrameAlpha alpha, bool flipY, + int rotation, bool mirrorX, bool mirrorY, Rect viewport) { if (_disposed) throw new ObjectDisposedException(nameof(CabinetOutputTexture)); - EnsureCreated(); - if (source == null || source.width < 1 || source.height < 1) { Clear(); return; } + if (viewport.x < 0 || viewport.y < 0 || viewport.width <= 0 || viewport.height <= 0 || viewport.xMax > 1 || viewport.yMax > 1 + || float.IsNaN(viewport.x) || float.IsNaN(viewport.y) || float.IsNaN(viewport.width) || float.IsNaN(viewport.height)) throw new ArgumentOutOfRangeException(nameof(viewport)); + if (EnsureCreated()) Clear(); + if (source == null || source.width < 1 || source.height < 1) source = Texture2D.blackTexture; + rotation = ((rotation % 4) + 4) % 4; double aspect = (double)source.width / source.height; - double outputAspect = (double)Texture.width / Texture.height; + if ((rotation & 1) != 0) aspect = 1 / aspect; + double outputAspect = Texture.width * (double)viewport.width / (Texture.height * viewport.height); float width = (float)System.Math.Min(1, aspect / outputAspect), height = (float)System.Math.Min(1, outputAspect / aspect); - _copy.SetVector("_Content", new Vector4((1 - width) * .5f, (1 - height) * .5f, width, height)); + _copy.SetVector("_Viewport", new Vector4(viewport.x, viewport.y, viewport.width, viewport.height)); + _copy.SetVector("_Content", new Vector4(viewport.x + (1 - width) * .5f * viewport.width, viewport.y + (1 - height) * .5f * viewport.height, width * viewport.width, height * viewport.height)); + _copy.SetVector("_SourceTexel", new Vector4(1f / source.width, 1f / source.height, source.width, source.height)); _copy.SetFloat("_Encoded", colorSpace == FrameColorSpace.Srgb ? 1 : 0); _copy.SetFloat("_Alpha", alpha == FrameAlpha.Premultiplied ? 2 : alpha == FrameAlpha.Straight ? 1 : 0); _copy.SetFloat("_FlipY", flipY ? 1 : 0); + _copy.SetFloat("_Rotation", rotation); + _copy.SetVector("_Mirror", new Vector4(mirrorX ? 1 : 0, mirrorY ? 1 : 0, 0, 0)); var active = RenderTexture.active; bool srgb = GL.sRGBWrite; - try { GL.sRGBWrite = false; Graphics.Blit(source, Texture, _copy); } - finally { GL.sRGBWrite = srgb; RenderTexture.active = active; } + try { + GL.sRGBWrite = false; + if (viewport == new Rect(0, 0, 1, 1)) Graphics.Blit(source, Texture, _copy); + else { + // Explicitly retain the base image; a Blit may choose DontCare on tile-based GPUs. + _insetColor[0] = Texture.colorBuffer; + Graphics.SetRenderTarget(new RenderTargetSetup(_insetColor, Texture.depthBuffer, 0, CubemapFace.Unknown, InsetLoad, InsetStore, RenderBufferLoadAction.DontCare, RenderBufferStoreAction.DontCare)); + _copy.SetTexture("_MainTex", source); + GL.PushMatrix(); + try { + GL.LoadOrtho(); + if (!_copy.SetPass(0)) throw new InvalidOperationException("Cannot draw cabinet inset."); + GL.Begin(GL.QUADS); + try { + GL.TexCoord2(0, 0); GL.Vertex3(0, 0, 0); + GL.TexCoord2(1, 0); GL.Vertex3(1, 0, 0); + GL.TexCoord2(1, 1); GL.Vertex3(1, 1, 0); + GL.TexCoord2(0, 1); GL.Vertex3(0, 1, 0); + } finally { GL.End(); } + } finally { GL.PopMatrix(); } + } + } + finally { _copy.SetTexture("_MainTex", null); GL.sRGBWrite = srgb; RenderTexture.active = active; } } public void Clear() diff --git a/VisualPinball.Unity/VisualPinball.Unity/Resources/CabinetOutput.shader b/VisualPinball.Unity/VisualPinball.Unity/Resources/CabinetOutput.shader index 4c75fcd256..aa8778c007 100644 --- a/VisualPinball.Unity/VisualPinball.Unity/Resources/CabinetOutput.shader +++ b/VisualPinball.Unity/VisualPinball.Unity/Resources/CabinetOutput.shader @@ -1,3 +1,8 @@ +// Visual Pinball Engine +// Copyright (C) 2026 freezy and VPE Team +// +// SPDX-License-Identifier: MIT + Shader "VisualPinball/CabinetOutput" { Properties { _MainTex ("Source", 2D) = "black" {} } @@ -6,22 +11,30 @@ Shader "VisualPinball/CabinetOutput" Cull Off ZWrite Off ZTest Always Pass { + Blend SrcAlpha OneMinusSrcAlpha CGPROGRAM #pragma vertex vert_img #pragma fragment frag #include "UnityCG.cginc" sampler2D _MainTex; - float4 _MainTex_TexelSize; - float4 _Content; - float _Encoded, _Alpha, _FlipY; + float4 _SourceTexel; + float4 _Content, _Viewport, _Mirror; + float _Encoded, _Alpha, _FlipY, _Rotation; float3 Decode(float3 value) { return float3(GammaToLinearSpaceExact(value.r), GammaToLinearSpaceExact(value.g), GammaToLinearSpaceExact(value.b)); } float3 Encode(float3 value) { return float3(LinearToGammaSpaceExact(value.r), LinearToGammaSpaceExact(value.g), LinearToGammaSpaceExact(value.b)); } float4 frag(v2f_img input) : SV_Target { + float2 viewportUv = (input.uv - _Viewport.xy) / _Viewport.zw; + if (any(viewportUv < 0) || any(viewportUv > 1)) return float4(0, 0, 0, 0); float2 uv = (input.uv - _Content.xy) / _Content.zw; if (any(uv < 0) || any(uv > 1)) return float4(0, 0, 0, 1); + if (_Mirror.x > .5) uv.x = 1 - uv.x; + if (_Mirror.y > .5) uv.y = 1 - uv.y; + if (_Rotation > 2.5) uv = float2(uv.y, 1 - uv.x); + else if (_Rotation > 1.5) uv = 1 - uv; + else if (_Rotation > .5) uv = float2(1 - uv.y, uv.x); if (_FlipY > .5) uv.y = 1 - uv.y; - uv = clamp(uv, abs(_MainTex_TexelSize.xy) * .5, 1 - abs(_MainTex_TexelSize.xy) * .5); + uv = clamp(uv, abs(_SourceTexel.xy) * .5, 1 - abs(_SourceTexel.xy) * .5); float4 color = tex2D(_MainTex, uv); float alpha = _Alpha < .5 ? 1 : saturate(color.a); // Unpremultiply in the producer's encoding before converting to linear light. From d221b54e5178cde7807f5e316931ae0fe16221d3 Mon Sep 17 00:00:00 2001 From: freezy Date: Mon, 2 Nov 2026 12:53:09 +0100 Subject: [PATCH 03/10] display: add independent hardware profile contracts --- .../CabinetDisplayTests.cs | 26 +++++++++ VisualPinball.Plugins/Api/CabinetDevices.cs | 53 +++++++++++++++++++ .../Api/CabinetDevices.cs.meta | 2 + VisualPinball.Plugins/Api/CabinetDisplays.cs | 22 ++++++-- 4 files changed, 100 insertions(+), 3 deletions(-) create mode 100644 VisualPinball.Plugins/Api/CabinetDevices.cs create mode 100644 VisualPinball.Plugins/Api/CabinetDevices.cs.meta diff --git a/VisualPinball.Plugins.Test/CabinetDisplayTests.cs b/VisualPinball.Plugins.Test/CabinetDisplayTests.cs index 8adce32529..69d276cbad 100644 --- a/VisualPinball.Plugins.Test/CabinetDisplayTests.cs +++ b/VisualPinball.Plugins.Test/CabinetDisplayTests.cs @@ -79,6 +79,32 @@ public void RegistryProbeRejectsStaleInstancesAndReadinessChangesRecomputeSelect Assert.That(registry.TryGetSource(stale, out _), Is.False); } + [Test] + public void MonitorAndDeviceAdoptionAreIndependentAndLegacyOverloadMeansMonitor() + { + var snapshot = new CabinetDisplaySnapshot(1, 1, 1, Array.Empty(), new[] { + new CabinetOutputAssignment("dmd", SurfaceRoles.Dmd, CabinetOutputMode.Player), + new CabinetOutputAssignment("dmd", SurfaceRoles.Dmd, CabinetOutputMode.Off, CabinetEndpointKind.Device) }); + Assert.That(snapshot.ModeFor("dmd", SurfaceRoles.Dmd), Is.EqualTo(CabinetOutputMode.Player)); + Assert.That(snapshot.ModeFor("dmd", SurfaceRoles.Dmd, CabinetEndpointKind.Device), Is.EqualTo(CabinetOutputMode.Off)); + Assert.That(snapshot.ModeFor("other", SurfaceRoles.Dmd, CabinetEndpointKind.Device), Is.EqualTo(CabinetOutputMode.Custom)); + } + + [Test] + public void DeviceProfileRequestIsDetachedAndTargetCannotContradictItsProfile() + { + var settings = new PluginSettingsSnapshot(1, Newtonsoft.Json.Linq.JObject.Parse("{\"port\":\"COM3\"}")); + var keys = new[] { "port" }; var request = new CabinetDeviceProfileRequest(settings, keys, "windows"); + settings.Values["port"] = "COM4"; keys[0] = "other"; + Assert.That(request.Settings.String("port"), Is.EqualTo("COM3")); Assert.That(request.SavedKeys, Is.EqualTo(new[] { "port" })); + var profile = new CabinetDeviceProfile("profile", "dmd", SurfaceRoles.Dmd, "DMD", "serial:COM3", "usb:family", "{}"); + var target = CabinetDisplayTarget.Device("device", SurfaceRoles.Dmd, CabinetEndpointState.Available, profile); + Assert.That(target.DeviceProfile, Is.SameAs(profile)); Assert.That(target.DeviceLeaseKey, Is.EqualTo(profile.LeaseKey)); + Assert.Throws(() => CabinetDisplayTarget.Device("device", SurfaceRoles.Topper, CabinetEndpointState.Available, profile)); + Assert.Throws(() => CabinetDisplayTarget.Device("device", SurfaceRoles.Dmd, CabinetEndpointState.Available, null)); + Assert.Throws(() => new CabinetDeviceProfile("p", "dmd", SurfaceRoles.Dmd, "DMD", "", "", "{}")); + } + private static PluginResourceDescriptor Descriptor(string id, string provider) => new PluginResourceDescriptor(id, provider, "controller", id, "backglass", ResourceKind.Surface, 1, 1); private sealed class Surface : IPluginSurface, ICabinetSurface { diff --git a/VisualPinball.Plugins/Api/CabinetDevices.cs b/VisualPinball.Plugins/Api/CabinetDevices.cs new file mode 100644 index 0000000000..88b9c8e977 --- /dev/null +++ b/VisualPinball.Plugins/Api/CabinetDevices.cs @@ -0,0 +1,53 @@ +// Visual Pinball Engine +// Copyright (C) 2026 freezy and VPE Team +// +// SPDX-License-Identifier: MIT + +using System; +using System.Collections.Generic; +using System.Linq; + +namespace VisualPinball.Plugins +{ + /// Adapter-owned device configuration. Enumerating a profile must never open hardware. + public sealed class CabinetDeviceProfile + { + public string Id { get; } + public string Provider { get; } + public string Role { get; } + public string Label { get; } + public string LeaseKey { get; } + /// Optional conservative reservation shared by auto and explicit choices of one driver family. + public string FamilyLeaseKey { get; } + /// Opaque adapter-owned payload, detached from mutable settings; never contains handles or live state. + public string Configuration { get; } + public bool Available { get; } + public string Reason { get; } + public CabinetDeviceProfile(string id, string provider, string role, string label, string leaseKey, string familyLeaseKey, string configuration, bool available = true, string reason = "") + { + if (string.IsNullOrWhiteSpace(id) || string.IsNullOrWhiteSpace(provider) || string.IsNullOrWhiteSpace(role)) throw new ArgumentException("A device profile needs an ID, provider and role."); + if (available && string.IsNullOrWhiteSpace(leaseKey)) throw new ArgumentException("An available profile needs a canonical device lease key."); + if ((configuration?.Length ?? 0) > 65536) throw new ArgumentException("Device configuration exceeds 65536 characters."); + Id = id; Provider = provider; Role = role; Label = label ?? id; LeaseKey = leaseKey ?? ""; FamilyLeaseKey = familyLeaseKey ?? ""; + Configuration = configuration ?? ""; Available = available; Reason = reason ?? ""; + } + } + + public sealed class CabinetDeviceProfileRequest + { + public PluginSettingsSnapshot Settings { get; } + public IReadOnlyCollection SavedKeys { get; } + public string Platform { get; } + public CabinetDeviceProfileRequest(PluginSettingsSnapshot settings, IEnumerable savedKeys, string platform) + { + Settings = (settings ?? throw new ArgumentNullException(nameof(settings))).Copy(); + SavedKeys = Array.AsReadOnly((savedKeys ?? throw new ArgumentNullException(nameof(savedKeys))).ToArray()); Platform = platform ?? ""; + } + } + + /// Optional factory API. Profiles describe configuration capability, not physical presence or a successful probe. + public interface ICabinetDeviceProfileProvider + { + IReadOnlyList GetDeviceProfiles(CabinetDeviceProfileRequest request); + } +} diff --git a/VisualPinball.Plugins/Api/CabinetDevices.cs.meta b/VisualPinball.Plugins/Api/CabinetDevices.cs.meta new file mode 100644 index 0000000000..3f1679a7ea --- /dev/null +++ b/VisualPinball.Plugins/Api/CabinetDevices.cs.meta @@ -0,0 +1,2 @@ +fileFormatVersion: 2 +guid: de7bb407e2584df39fc2e16978b4597f diff --git a/VisualPinball.Plugins/Api/CabinetDisplays.cs b/VisualPinball.Plugins/Api/CabinetDisplays.cs index cc742c3e6c..194a6d1d6c 100644 --- a/VisualPinball.Plugins/Api/CabinetDisplays.cs +++ b/VisualPinball.Plugins/Api/CabinetDisplays.cs @@ -38,6 +38,8 @@ public sealed class CabinetDisplayTarget public int Height { get; } /// Canonical provider-resolved lease key, never a guessed USB identifier. public string DeviceLeaseKey { get; } + /// Adapter profile; null on targets made with the legacy public constructor. + public CabinetDeviceProfile? DeviceProfile { get; } public CabinetDisplayTarget(string endpointId, string role, CabinetEndpointKind kind, CabinetEndpointState state, int x = 0, int y = 0, int width = 0, int height = 0, string reason = "", string deviceLeaseKey = "") @@ -51,6 +53,14 @@ public CabinetDisplayTarget(string endpointId, string role, CabinetEndpointKind EndpointId = endpointId; Role = role; Kind = kind; State = state; X = x; Y = y; Width = width; Height = height; Reason = reason ?? ""; DeviceLeaseKey = deviceLeaseKey ?? ""; } + private CabinetDisplayTarget(string endpointId, string role, CabinetEndpointState state, CabinetDeviceProfile? profile, string reason) + : this(endpointId, role, CabinetEndpointKind.Device, state, reason: reason, deviceLeaseKey: profile?.LeaseKey ?? "") { DeviceProfile = profile; } + public static CabinetDisplayTarget Device(string endpointId, string role, CabinetEndpointState state, CabinetDeviceProfile? profile, string reason = "") + { + if (profile != null && profile.Role != role) throw new ArgumentException("The profile role must match the target.", nameof(profile)); + if (state == CabinetEndpointState.Available && (profile == null || !profile.Available)) throw new ArgumentException("An available device needs an available profile.", nameof(profile)); + return new CabinetDisplayTarget(endpointId, role, state, profile, reason); + } } /// Explicit adoption of one plugin output; absence always means Custom. @@ -59,11 +69,15 @@ public sealed class CabinetOutputAssignment public string PluginId { get; } public string Role { get; } public CabinetOutputMode Mode { get; } + public CabinetEndpointKind Kind { get; } public CabinetOutputAssignment(string pluginId, string role, CabinetOutputMode mode) + : this(pluginId, role, mode, CabinetEndpointKind.DesktopRegion) { } + public CabinetOutputAssignment(string pluginId, string role, CabinetOutputMode mode, CabinetEndpointKind kind) { if (string.IsNullOrWhiteSpace(pluginId) || string.IsNullOrWhiteSpace(role)) throw new ArgumentException("An assignment needs a plugin and role."); if (!Enum.IsDefined(typeof(CabinetOutputMode), mode)) throw new ArgumentOutOfRangeException(nameof(mode)); - PluginId = pluginId; Role = role; Mode = mode; + if (!Enum.IsDefined(typeof(CabinetEndpointKind), kind)) throw new ArgumentOutOfRangeException(nameof(kind)); + PluginId = pluginId; Role = role; Mode = mode; Kind = kind; } } @@ -86,13 +100,15 @@ public CabinetDisplaySnapshot(long revision, long topologyGeneration, long sessi var assignmentArray = (assignments ?? throw new ArgumentNullException(nameof(assignments))).ToArray(); if (targetArray.Any(value => value == null) || assignmentArray.Any(value => value == null)) throw new ArgumentException("Snapshot entries cannot be null."); if (targetArray.GroupBy(value => (value.EndpointId, value.Role)).Any(group => group.Count() > 1)) throw new ArgumentException("Duplicate endpoint/role target.", nameof(targets)); - if (assignmentArray.GroupBy(value => (value.PluginId, value.Role)).Any(group => group.Count() > 1)) throw new ArgumentException("Duplicate plugin/role assignment.", nameof(assignments)); + if (assignmentArray.GroupBy(value => (value.PluginId, value.Role, value.Kind)).Any(group => group.Count() > 1)) throw new ArgumentException("Duplicate plugin/role/kind assignment.", nameof(assignments)); Targets = Array.AsReadOnly(targetArray); Assignments = Array.AsReadOnly(assignmentArray); } public CabinetOutputMode ModeFor(string pluginId, string role) + => ModeFor(pluginId, role, CabinetEndpointKind.DesktopRegion); + public CabinetOutputMode ModeFor(string pluginId, string role, CabinetEndpointKind kind) { - foreach (var assignment in Assignments) if (assignment.PluginId == pluginId && assignment.Role == role) return assignment.Mode; + foreach (var assignment in Assignments) if (assignment.PluginId == pluginId && assignment.Role == role && assignment.Kind == kind) return assignment.Mode; return CabinetOutputMode.Custom; } From 68d7abe29d11369892d9f01308c45cfd25d9cec5 Mon Sep 17 00:00:00 2001 From: freezy Date: Mon, 2 Nov 2026 13:12:34 +0100 Subject: [PATCH 04/10] display: expose read-only legacy placement previews --- .../CabinetDisplayTests.cs | 11 ++++ .../Api/CabinetDisplayImport.cs | 58 +++++++++++++++++++ .../Api/CabinetDisplayImport.cs.meta | 2 + 3 files changed, 71 insertions(+) create mode 100644 VisualPinball.Plugins/Api/CabinetDisplayImport.cs create mode 100644 VisualPinball.Plugins/Api/CabinetDisplayImport.cs.meta diff --git a/VisualPinball.Plugins.Test/CabinetDisplayTests.cs b/VisualPinball.Plugins.Test/CabinetDisplayTests.cs index 69d276cbad..0f408c36a2 100644 --- a/VisualPinball.Plugins.Test/CabinetDisplayTests.cs +++ b/VisualPinball.Plugins.Test/CabinetDisplayTests.cs @@ -105,6 +105,17 @@ public void DeviceProfileRequestIsDetachedAndTargetCannotContradictItsProfile() Assert.Throws(() => new CabinetDeviceProfile("p", "dmd", SurfaceRoles.Dmd, "DMD", "", "", "{}")); } + [Test] + public void ImportPreviewCopiesSettingsAndKeepsUnusableGeometryUnsupported() + { + var settings = new PluginSettingsSnapshot(1); settings.Values["x"] = 10; var keys = new[] { "x" }; + var request = new CabinetDisplayImportRequest(settings, keys, "windows"); settings.Values["x"] = 20; keys[0] = "y"; + Assert.That(request.Settings.Integer("x"), Is.EqualTo(10)); Assert.That(request.SavedKeys, Is.EqualTo(new[] { "x" })); + Assert.That(new CabinetDisplayImportCandidate(SurfaceRoles.Dmd, 0, 0, 0, 32).Supported, Is.False); + Assert.That(new CabinetDisplayImportCandidate(SurfaceRoles.Dmd, int.MaxValue, 0, 128, 32).Supported, Is.False); + var hardware = new CabinetDisplayImportCandidate(SurfaceRoles.Dmd, "profile"); Assert.That(hardware.Kind, Is.EqualTo(CabinetEndpointKind.Device)); Assert.That(hardware.DeviceProfileId, Is.EqualTo("profile")); + } + private static PluginResourceDescriptor Descriptor(string id, string provider) => new PluginResourceDescriptor(id, provider, "controller", id, "backglass", ResourceKind.Surface, 1, 1); private sealed class Surface : IPluginSurface, ICabinetSurface { diff --git a/VisualPinball.Plugins/Api/CabinetDisplayImport.cs b/VisualPinball.Plugins/Api/CabinetDisplayImport.cs new file mode 100644 index 0000000000..1bcaf84784 --- /dev/null +++ b/VisualPinball.Plugins/Api/CabinetDisplayImport.cs @@ -0,0 +1,58 @@ +// Visual Pinball Engine +// Copyright (C) 2026 freezy and VPE Team +// +// SPDX-License-Identifier: MIT +// Licensed under MIT. See https://opensource.org/license/mit. + +using System; +using System.Collections.Generic; +using System.Linq; + +namespace VisualPinball.Plugins +{ + /// Read-only settings for a migration preview. Providers must not write files, create instances or open outputs. + public sealed class CabinetDisplayImportRequest + { + public PluginSettingsSnapshot Settings { get; } + public IReadOnlyCollection SavedKeys { get; } + public string Platform { get; } + public string GameKey { get; } + public CabinetDisplayImportRequest(PluginSettingsSnapshot settings, IEnumerable savedKeys, string platform, string gameKey = "") + { + Settings = (settings ?? throw new ArgumentNullException(nameof(settings))).Copy(); + SavedKeys = Array.AsReadOnly((savedKeys ?? throw new ArgumentNullException(nameof(savedKeys))).ToArray()); + Platform = platform ?? ""; GameKey = gameKey ?? ""; + } + } + + /// One adapter-described legacy output. Coordinates use physical virtual-desktop pixels, the same space as CabinetDisplayTarget; adapters must convert monitor-relative or DPI-scaled legacy values. No monitor identity is inferred here. + public sealed class CabinetDisplayImportCandidate + { + public string Role { get; } + public CabinetEndpointKind Kind { get; } + public int X { get; } + public int Y { get; } + public int Width { get; } + public int Height { get; } + public string DeviceProfileId { get; } + public string Note { get; } + public bool Supported { get; } + public CabinetDisplayImportCandidate(string role, int x, int y, int width, int height, string note = "", bool supported = true) + { + if (string.IsNullOrWhiteSpace(role)) throw new ArgumentException("An import candidate needs a role."); + Role = role; Kind = CabinetEndpointKind.DesktopRegion; X = x; Y = y; Width = width; Height = height; + DeviceProfileId = ""; Note = note ?? ""; Supported = supported && width > 0 && height > 0 && (long)x + width <= int.MaxValue && (long)y + height <= int.MaxValue; + } + public CabinetDisplayImportCandidate(string role, string deviceProfileId, string note = "", bool supported = true) + { + if (string.IsNullOrWhiteSpace(role) || string.IsNullOrWhiteSpace(deviceProfileId)) throw new ArgumentException("A device candidate needs a role and profile ID."); + Role = role; Kind = CabinetEndpointKind.Device; DeviceProfileId = deviceProfileId; Note = note ?? ""; Supported = supported; + } + } + + /// Optional factory capability for a user-reviewed migration. Never mutates legacy or external configuration. Playfield placement is outside this API and remains in Video. + public interface ICabinetDisplayImportProvider + { + IReadOnlyList GetDisplayImportCandidates(CabinetDisplayImportRequest request); + } +} diff --git a/VisualPinball.Plugins/Api/CabinetDisplayImport.cs.meta b/VisualPinball.Plugins/Api/CabinetDisplayImport.cs.meta new file mode 100644 index 0000000000..d7b1bf507a --- /dev/null +++ b/VisualPinball.Plugins/Api/CabinetDisplayImport.cs.meta @@ -0,0 +1,2 @@ +fileFormatVersion: 2 +guid: c76a7c4675464e65b669f58cdc328da4 From 5d0a42c1311447578d2e53e5f666aba7885a76a3 Mon Sep 17 00:00:00 2001 From: freezy Date: Mon, 2 Nov 2026 16:21:27 +0100 Subject: [PATCH 05/10] display: define known cabinet output roles --- CHANGELOG.md | 2 + .../CabinetDisplayTests.cs | 63 ++++++++++------- VisualPinball.Plugins/Api/CabinetDevices.cs | 6 +- .../Api/CabinetDisplayImport.cs | 10 +-- VisualPinball.Plugins/Api/CabinetDisplays.cs | 68 +++++++++++++++---- .../Resources/ResourceContracts.cs | 2 + .../cabinet-display-outputs.md | 6 ++ .../Display/CabinetScreenComponent.cs | 3 + 8 files changed, 114 insertions(+), 46 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index e0e3e2fbb3..bc036c61d7 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -8,6 +8,8 @@ Built with Unity 6.5 ### Added +- Closed shared cabinet output roles with independent LCD/HD game display routing and preserved custom scene bindings. + - Cabinet output content rotation, mirroring, and explicit-load inset composition with asymmetric GPU validation. - Shared cabinet display configuration contracts, deterministic surface ranking, and an owned SDR output-copy target with GPU and native-window validation probes, preparing centralized Player display routing. diff --git a/VisualPinball.Plugins.Test/CabinetDisplayTests.cs b/VisualPinball.Plugins.Test/CabinetDisplayTests.cs index 0f408c36a2..2d0a55c12e 100644 --- a/VisualPinball.Plugins.Test/CabinetDisplayTests.cs +++ b/VisualPinball.Plugins.Test/CabinetDisplayTests.cs @@ -14,27 +14,27 @@ public sealed class CabinetDisplayTests [Test] public void SnapshotCopiesInputAndKeepsAdoptedMissingOutputsManaged() { - var assignments = new[] { new CabinetOutputAssignment("b2s", SurfaceRoles.Backglass, CabinetOutputMode.Player) }; - var targets = new[] { new CabinetDisplayTarget("screen", SurfaceRoles.Backglass, CabinetEndpointKind.DesktopRegion, CabinetEndpointState.Unavailable, reason: "Disconnected") }; + var assignments = new[] { new CabinetOutputAssignment("b2s", CabinetOutputRole.Backglass, CabinetOutputMode.Player) }; + var targets = new[] { new CabinetDisplayTarget("screen", CabinetOutputRole.Backglass, CabinetEndpointKind.DesktopRegion, CabinetEndpointState.Unavailable, reason: "Disconnected") }; var snapshot = new CabinetDisplaySnapshot(4, 7, 9, targets, assignments); - assignments[0] = new CabinetOutputAssignment("b2s", SurfaceRoles.Backglass, CabinetOutputMode.Off); - targets[0] = new CabinetDisplayTarget("screen", SurfaceRoles.Backglass, CabinetEndpointKind.DesktopRegion, CabinetEndpointState.Available, -1920, 0, 1920, 1080); - Assert.That(snapshot.ModeFor("b2s", SurfaceRoles.Backglass), Is.EqualTo(CabinetOutputMode.Player)); - Assert.That(snapshot.ModeFor("pup", SurfaceRoles.Backglass), Is.EqualTo(CabinetOutputMode.Custom)); + assignments[0] = new CabinetOutputAssignment("b2s", CabinetOutputRole.Backglass, CabinetOutputMode.Off); + targets[0] = new CabinetDisplayTarget("screen", CabinetOutputRole.Backglass, CabinetEndpointKind.DesktopRegion, CabinetEndpointState.Available, -1920, 0, 1920, 1080); + Assert.That(snapshot.ModeFor("b2s", CabinetOutputRole.Backglass), Is.EqualTo(CabinetOutputMode.Player)); + Assert.That(snapshot.ModeFor("pup", CabinetOutputRole.Backglass), Is.EqualTo(CabinetOutputMode.Custom)); Assert.That(snapshot.Targets[0].State, Is.EqualTo(CabinetEndpointState.Unavailable)); } [Test] public void DuplicateAssignmentsAndInvalidAvailableDestinationsAreRejected() { - var adoption = new CabinetOutputAssignment("pup", SurfaceRoles.Topper, CabinetOutputMode.Player); + var adoption = new CabinetOutputAssignment("pup", CabinetOutputRole.Topper, CabinetOutputMode.Player); Assert.Throws(() => new CabinetDisplaySnapshot(1, 1, 1, Array.Empty(), new[] { adoption, adoption })); - Assert.Throws(() => new CabinetDisplayTarget("screen", "backglass", CabinetEndpointKind.DesktopRegion, CabinetEndpointState.Available)); - Assert.Throws(() => new CabinetDisplayTarget("device", "dmd", CabinetEndpointKind.Device, CabinetEndpointState.Available)); - var target = new CabinetDisplayTarget("screen", "dmd", CabinetEndpointKind.DesktopRegion, CabinetEndpointState.Available, width: 128, height: 32); + Assert.Throws(() => new CabinetDisplayTarget("screen", CabinetOutputRole.Backglass, CabinetEndpointKind.DesktopRegion, CabinetEndpointState.Available)); + Assert.Throws(() => new CabinetDisplayTarget("device", CabinetOutputRole.Dmd, CabinetEndpointKind.Device, CabinetEndpointState.Available)); + var target = new CabinetDisplayTarget("screen", CabinetOutputRole.Dmd, CabinetEndpointKind.DesktopRegion, CabinetEndpointState.Available, width: 128, height: 32); Assert.Throws(() => new CabinetDisplaySnapshot(1, 1, 1, new[] { target, target }, Array.Empty())); - var device = new CabinetDisplayTarget("device", "dmd", CabinetEndpointKind.Device, CabinetEndpointState.Available, deviceLeaseKey: "serial:COM3"); - Assert.That(new CabinetDisplaySnapshot(1, 1, 1, new[] { target, device }, Array.Empty()).TargetsFor("dmd").Count, Is.EqualTo(2)); + var device = new CabinetDisplayTarget("device", CabinetOutputRole.Dmd, CabinetEndpointKind.Device, CabinetEndpointState.Available, deviceLeaseKey: "serial:COM3"); + Assert.That(new CabinetDisplaySnapshot(1, 1, 1, new[] { target, device }, Array.Empty()).TargetsFor(CabinetOutputRole.Dmd).Count, Is.EqualTo(2)); } [Test] @@ -83,11 +83,11 @@ public void RegistryProbeRejectsStaleInstancesAndReadinessChangesRecomputeSelect public void MonitorAndDeviceAdoptionAreIndependentAndLegacyOverloadMeansMonitor() { var snapshot = new CabinetDisplaySnapshot(1, 1, 1, Array.Empty(), new[] { - new CabinetOutputAssignment("dmd", SurfaceRoles.Dmd, CabinetOutputMode.Player), - new CabinetOutputAssignment("dmd", SurfaceRoles.Dmd, CabinetOutputMode.Off, CabinetEndpointKind.Device) }); - Assert.That(snapshot.ModeFor("dmd", SurfaceRoles.Dmd), Is.EqualTo(CabinetOutputMode.Player)); - Assert.That(snapshot.ModeFor("dmd", SurfaceRoles.Dmd, CabinetEndpointKind.Device), Is.EqualTo(CabinetOutputMode.Off)); - Assert.That(snapshot.ModeFor("other", SurfaceRoles.Dmd, CabinetEndpointKind.Device), Is.EqualTo(CabinetOutputMode.Custom)); + new CabinetOutputAssignment("dmd", CabinetOutputRole.Dmd, CabinetOutputMode.Player), + new CabinetOutputAssignment("dmd", CabinetOutputRole.Dmd, CabinetOutputMode.Off, CabinetEndpointKind.Device) }); + Assert.That(snapshot.ModeFor("dmd", CabinetOutputRole.Dmd), Is.EqualTo(CabinetOutputMode.Player)); + Assert.That(snapshot.ModeFor("dmd", CabinetOutputRole.Dmd, CabinetEndpointKind.Device), Is.EqualTo(CabinetOutputMode.Off)); + Assert.That(snapshot.ModeFor("other", CabinetOutputRole.Dmd, CabinetEndpointKind.Device), Is.EqualTo(CabinetOutputMode.Custom)); } [Test] @@ -97,12 +97,12 @@ public void DeviceProfileRequestIsDetachedAndTargetCannotContradictItsProfile() var keys = new[] { "port" }; var request = new CabinetDeviceProfileRequest(settings, keys, "windows"); settings.Values["port"] = "COM4"; keys[0] = "other"; Assert.That(request.Settings.String("port"), Is.EqualTo("COM3")); Assert.That(request.SavedKeys, Is.EqualTo(new[] { "port" })); - var profile = new CabinetDeviceProfile("profile", "dmd", SurfaceRoles.Dmd, "DMD", "serial:COM3", "usb:family", "{}"); - var target = CabinetDisplayTarget.Device("device", SurfaceRoles.Dmd, CabinetEndpointState.Available, profile); + var profile = new CabinetDeviceProfile("profile", "dmd", CabinetOutputRole.Dmd, "DMD", "serial:COM3", "usb:family", "{}"); + var target = CabinetDisplayTarget.Device("device", CabinetOutputRole.Dmd, CabinetEndpointState.Available, profile); Assert.That(target.DeviceProfile, Is.SameAs(profile)); Assert.That(target.DeviceLeaseKey, Is.EqualTo(profile.LeaseKey)); - Assert.Throws(() => CabinetDisplayTarget.Device("device", SurfaceRoles.Topper, CabinetEndpointState.Available, profile)); - Assert.Throws(() => CabinetDisplayTarget.Device("device", SurfaceRoles.Dmd, CabinetEndpointState.Available, null)); - Assert.Throws(() => new CabinetDeviceProfile("p", "dmd", SurfaceRoles.Dmd, "DMD", "", "", "{}")); + Assert.Throws(() => CabinetDisplayTarget.Device("device", CabinetOutputRole.Topper, CabinetEndpointState.Available, profile)); + Assert.Throws(() => CabinetDisplayTarget.Device("device", CabinetOutputRole.Dmd, CabinetEndpointState.Available, null)); + Assert.Throws(() => new CabinetDeviceProfile("p", "dmd", CabinetOutputRole.Dmd, "DMD", "", "", "{}")); } [Test] @@ -111,9 +111,22 @@ public void ImportPreviewCopiesSettingsAndKeepsUnusableGeometryUnsupported() var settings = new PluginSettingsSnapshot(1); settings.Values["x"] = 10; var keys = new[] { "x" }; var request = new CabinetDisplayImportRequest(settings, keys, "windows"); settings.Values["x"] = 20; keys[0] = "y"; Assert.That(request.Settings.Integer("x"), Is.EqualTo(10)); Assert.That(request.SavedKeys, Is.EqualTo(new[] { "x" })); - Assert.That(new CabinetDisplayImportCandidate(SurfaceRoles.Dmd, 0, 0, 0, 32).Supported, Is.False); - Assert.That(new CabinetDisplayImportCandidate(SurfaceRoles.Dmd, int.MaxValue, 0, 128, 32).Supported, Is.False); - var hardware = new CabinetDisplayImportCandidate(SurfaceRoles.Dmd, "profile"); Assert.That(hardware.Kind, Is.EqualTo(CabinetEndpointKind.Device)); Assert.That(hardware.DeviceProfileId, Is.EqualTo("profile")); + Assert.That(new CabinetDisplayImportCandidate(CabinetOutputRole.Dmd, 0, 0, 0, 32).Supported, Is.False); + Assert.That(new CabinetDisplayImportCandidate(CabinetOutputRole.Dmd, int.MaxValue, 0, 128, 32).Supported, Is.False); + var hardware = new CabinetDisplayImportCandidate(CabinetOutputRole.Dmd, "profile"); Assert.That(hardware.Kind, Is.EqualTo(CabinetEndpointKind.Device)); Assert.That(hardware.DeviceProfileId, Is.EqualTo("profile")); + } + + [Test] + public void SharedRolesAreClosedAndKeepHdDisplaySeparateFromBackglassAndVideoPanel() + { + Assert.That(CabinetOutputRoles.TryParse("pup-screen-8", out _), Is.False); + Assert.That(CabinetOutputRoles.TryParse("playfield", out _), Is.False, "Playfield placement belongs to Video."); + Assert.That(CabinetOutputRoles.Parse("game-display"), Is.EqualTo(CabinetOutputRole.GameDisplay)); + Assert.That(CabinetOutputRoles.Parse("full-dmd"), Is.EqualTo(CabinetOutputRole.FullDmd)); + Assert.That(CabinetOutputRole.GameDisplay.Id(), Is.Not.EqualTo(CabinetOutputRole.FullDmd.Id())); + Assert.Throws(() => new CabinetOutputAssignment("plugin", (CabinetOutputRole)0, CabinetOutputMode.Player)); + Assert.Throws(() => new CabinetDisplayImportCandidate((CabinetOutputRole)999, 0, 0, 100, 100)); + Assert.Throws(() => new CabinetDeviceProfile("profile", "plugin", (CabinetOutputRole)999, "Panel", "key", "", "{}")); } private static PluginResourceDescriptor Descriptor(string id, string provider) => new PluginResourceDescriptor(id, provider, "controller", id, "backglass", ResourceKind.Surface, 1, 1); diff --git a/VisualPinball.Plugins/Api/CabinetDevices.cs b/VisualPinball.Plugins/Api/CabinetDevices.cs index 88b9c8e977..1cd8c8497d 100644 --- a/VisualPinball.Plugins/Api/CabinetDevices.cs +++ b/VisualPinball.Plugins/Api/CabinetDevices.cs @@ -14,7 +14,7 @@ public sealed class CabinetDeviceProfile { public string Id { get; } public string Provider { get; } - public string Role { get; } + public CabinetOutputRole Role { get; } public string Label { get; } public string LeaseKey { get; } /// Optional conservative reservation shared by auto and explicit choices of one driver family. @@ -23,9 +23,9 @@ public sealed class CabinetDeviceProfile public string Configuration { get; } public bool Available { get; } public string Reason { get; } - public CabinetDeviceProfile(string id, string provider, string role, string label, string leaseKey, string familyLeaseKey, string configuration, bool available = true, string reason = "") + public CabinetDeviceProfile(string id, string provider, CabinetOutputRole role, string label, string leaseKey, string familyLeaseKey, string configuration, bool available = true, string reason = "") { - if (string.IsNullOrWhiteSpace(id) || string.IsNullOrWhiteSpace(provider) || string.IsNullOrWhiteSpace(role)) throw new ArgumentException("A device profile needs an ID, provider and role."); + if (string.IsNullOrWhiteSpace(id) || string.IsNullOrWhiteSpace(provider) || !CabinetOutputRoles.IsDefined(role)) throw new ArgumentException("A device profile needs an ID, provider and role."); if (available && string.IsNullOrWhiteSpace(leaseKey)) throw new ArgumentException("An available profile needs a canonical device lease key."); if ((configuration?.Length ?? 0) > 65536) throw new ArgumentException("Device configuration exceeds 65536 characters."); Id = id; Provider = provider; Role = role; Label = label ?? id; LeaseKey = leaseKey ?? ""; FamilyLeaseKey = familyLeaseKey ?? ""; diff --git a/VisualPinball.Plugins/Api/CabinetDisplayImport.cs b/VisualPinball.Plugins/Api/CabinetDisplayImport.cs index 1bcaf84784..8db47c66a0 100644 --- a/VisualPinball.Plugins/Api/CabinetDisplayImport.cs +++ b/VisualPinball.Plugins/Api/CabinetDisplayImport.cs @@ -28,7 +28,7 @@ public CabinetDisplayImportRequest(PluginSettingsSnapshot settings, IEnumerable< /// One adapter-described legacy output. Coordinates use physical virtual-desktop pixels, the same space as CabinetDisplayTarget; adapters must convert monitor-relative or DPI-scaled legacy values. No monitor identity is inferred here. public sealed class CabinetDisplayImportCandidate { - public string Role { get; } + public CabinetOutputRole Role { get; } public CabinetEndpointKind Kind { get; } public int X { get; } public int Y { get; } @@ -37,15 +37,15 @@ public sealed class CabinetDisplayImportCandidate public string DeviceProfileId { get; } public string Note { get; } public bool Supported { get; } - public CabinetDisplayImportCandidate(string role, int x, int y, int width, int height, string note = "", bool supported = true) + public CabinetDisplayImportCandidate(CabinetOutputRole role, int x, int y, int width, int height, string note = "", bool supported = true) { - if (string.IsNullOrWhiteSpace(role)) throw new ArgumentException("An import candidate needs a role."); + if (!CabinetOutputRoles.IsDefined(role)) throw new ArgumentException("An import candidate needs a role."); Role = role; Kind = CabinetEndpointKind.DesktopRegion; X = x; Y = y; Width = width; Height = height; DeviceProfileId = ""; Note = note ?? ""; Supported = supported && width > 0 && height > 0 && (long)x + width <= int.MaxValue && (long)y + height <= int.MaxValue; } - public CabinetDisplayImportCandidate(string role, string deviceProfileId, string note = "", bool supported = true) + public CabinetDisplayImportCandidate(CabinetOutputRole role, string deviceProfileId, string note = "", bool supported = true) { - if (string.IsNullOrWhiteSpace(role) || string.IsNullOrWhiteSpace(deviceProfileId)) throw new ArgumentException("A device candidate needs a role and profile ID."); + if (!CabinetOutputRoles.IsDefined(role) || string.IsNullOrWhiteSpace(deviceProfileId)) throw new ArgumentException("A device candidate needs a role and profile ID."); Role = role; Kind = CabinetEndpointKind.Device; DeviceProfileId = deviceProfileId; Note = note ?? ""; Supported = supported; } } diff --git a/VisualPinball.Plugins/Api/CabinetDisplays.cs b/VisualPinball.Plugins/Api/CabinetDisplays.cs index 194a6d1d6c..23e24c7def 100644 --- a/VisualPinball.Plugins/Api/CabinetDisplays.cs +++ b/VisualPinball.Plugins/Api/CabinetDisplays.cs @@ -17,6 +17,48 @@ public static class CabinetDisplayCapability public const string Configuration = "vpe.cabinet-displays.v1"; } + /// Shared cabinet destinations with Player-defined semantics. Plug-in-private screens are not cabinet roles. + public enum CabinetOutputRole + { + Backglass = 1, + Dmd = 2, + /// The game’s LCD/HD display, independent of backglass artwork and cabinet video panels. + GameDisplay = 3, + Topper = 4, + ScorePanel = 5, + /// A cabinet video panel for DMD surrounds and media, distinct from the game LCD. + FullDmd = 6, + } + + /// Conversion at the generic resource/persistence boundary. The cabinet API itself uses the enum. + public static class CabinetOutputRoles + { + public static bool IsDefined(CabinetOutputRole role) => Enum.IsDefined(typeof(CabinetOutputRole), role); + public static string Id(this CabinetOutputRole role) => role switch { + CabinetOutputRole.Backglass => SurfaceRoles.Backglass, + CabinetOutputRole.Dmd => SurfaceRoles.Dmd, + CabinetOutputRole.GameDisplay => SurfaceRoles.GameDisplay, + CabinetOutputRole.FullDmd => SurfaceRoles.FullDmd, + CabinetOutputRole.Topper => SurfaceRoles.Topper, + CabinetOutputRole.ScorePanel => SurfaceRoles.ScorePanel, + _ => throw new ArgumentOutOfRangeException(nameof(role)), + }; + public static bool TryParse(string id, out CabinetOutputRole role) + { + switch (id) { + case SurfaceRoles.Backglass: role = CabinetOutputRole.Backglass; return true; + case SurfaceRoles.Dmd: role = CabinetOutputRole.Dmd; return true; + case SurfaceRoles.GameDisplay: role = CabinetOutputRole.GameDisplay; return true; + case SurfaceRoles.FullDmd: role = CabinetOutputRole.FullDmd; return true; + case SurfaceRoles.Topper: role = CabinetOutputRole.Topper; return true; + case SurfaceRoles.ScorePanel: role = CabinetOutputRole.ScorePanel; return true; + default: role = default; return false; + } + } + public static CabinetOutputRole Parse(string id) + => TryParse(id, out var role) ? role : throw new ArgumentException("Unknown cabinet output role: " + id, nameof(id)); + } + /// Who places one plugin's physical output. Does not control its in-scene output. public enum CabinetOutputMode { Custom = 0, Player = 1, Off = 2 } /// Physical destination; device drivers remain responsible for device protocols. @@ -28,7 +70,7 @@ public enum CabinetEndpointState { Unassigned = 0, Available = 1, Disabled = 2, public sealed class CabinetDisplayTarget { public string EndpointId { get; } - public string Role { get; } + public CabinetOutputRole Role { get; } public CabinetEndpointKind Kind { get; } public CabinetEndpointState State { get; } public string Reason { get; } @@ -41,11 +83,11 @@ public sealed class CabinetDisplayTarget /// Adapter profile; null on targets made with the legacy public constructor. public CabinetDeviceProfile? DeviceProfile { get; } - public CabinetDisplayTarget(string endpointId, string role, CabinetEndpointKind kind, CabinetEndpointState state, + public CabinetDisplayTarget(string endpointId, CabinetOutputRole role, CabinetEndpointKind kind, CabinetEndpointState state, int x = 0, int y = 0, int width = 0, int height = 0, string reason = "", string deviceLeaseKey = "") { if (string.IsNullOrWhiteSpace(endpointId)) throw new ArgumentException("An endpoint needs an ID.", nameof(endpointId)); - if (string.IsNullOrWhiteSpace(role)) throw new ArgumentException("An output needs a role.", nameof(role)); + if (!CabinetOutputRoles.IsDefined(role)) throw new ArgumentException("An output needs a role.", nameof(role)); if (!Enum.IsDefined(typeof(CabinetEndpointKind), kind)) throw new ArgumentOutOfRangeException(nameof(kind)); if (!Enum.IsDefined(typeof(CabinetEndpointState), state)) throw new ArgumentOutOfRangeException(nameof(state)); if (state == CabinetEndpointState.Available && kind == CabinetEndpointKind.DesktopRegion && (width < 1 || height < 1)) throw new ArgumentOutOfRangeException(nameof(width)); @@ -53,9 +95,9 @@ public CabinetDisplayTarget(string endpointId, string role, CabinetEndpointKind EndpointId = endpointId; Role = role; Kind = kind; State = state; X = x; Y = y; Width = width; Height = height; Reason = reason ?? ""; DeviceLeaseKey = deviceLeaseKey ?? ""; } - private CabinetDisplayTarget(string endpointId, string role, CabinetEndpointState state, CabinetDeviceProfile? profile, string reason) + private CabinetDisplayTarget(string endpointId, CabinetOutputRole role, CabinetEndpointState state, CabinetDeviceProfile? profile, string reason) : this(endpointId, role, CabinetEndpointKind.Device, state, reason: reason, deviceLeaseKey: profile?.LeaseKey ?? "") { DeviceProfile = profile; } - public static CabinetDisplayTarget Device(string endpointId, string role, CabinetEndpointState state, CabinetDeviceProfile? profile, string reason = "") + public static CabinetDisplayTarget Device(string endpointId, CabinetOutputRole role, CabinetEndpointState state, CabinetDeviceProfile? profile, string reason = "") { if (profile != null && profile.Role != role) throw new ArgumentException("The profile role must match the target.", nameof(profile)); if (state == CabinetEndpointState.Available && (profile == null || !profile.Available)) throw new ArgumentException("An available device needs an available profile.", nameof(profile)); @@ -67,14 +109,14 @@ public static CabinetDisplayTarget Device(string endpointId, string role, Cabine public sealed class CabinetOutputAssignment { public string PluginId { get; } - public string Role { get; } + public CabinetOutputRole Role { get; } public CabinetOutputMode Mode { get; } public CabinetEndpointKind Kind { get; } - public CabinetOutputAssignment(string pluginId, string role, CabinetOutputMode mode) + public CabinetOutputAssignment(string pluginId, CabinetOutputRole role, CabinetOutputMode mode) : this(pluginId, role, mode, CabinetEndpointKind.DesktopRegion) { } - public CabinetOutputAssignment(string pluginId, string role, CabinetOutputMode mode, CabinetEndpointKind kind) + public CabinetOutputAssignment(string pluginId, CabinetOutputRole role, CabinetOutputMode mode, CabinetEndpointKind kind) { - if (string.IsNullOrWhiteSpace(pluginId) || string.IsNullOrWhiteSpace(role)) throw new ArgumentException("An assignment needs a plugin and role."); + if (string.IsNullOrWhiteSpace(pluginId) || !CabinetOutputRoles.IsDefined(role)) throw new ArgumentException("An assignment needs a plugin and role."); if (!Enum.IsDefined(typeof(CabinetOutputMode), mode)) throw new ArgumentOutOfRangeException(nameof(mode)); if (!Enum.IsDefined(typeof(CabinetEndpointKind), kind)) throw new ArgumentOutOfRangeException(nameof(kind)); PluginId = pluginId; Role = role; Mode = mode; Kind = kind; @@ -104,23 +146,23 @@ public CabinetDisplaySnapshot(long revision, long topologyGeneration, long sessi Targets = Array.AsReadOnly(targetArray); Assignments = Array.AsReadOnly(assignmentArray); } - public CabinetOutputMode ModeFor(string pluginId, string role) + public CabinetOutputMode ModeFor(string pluginId, CabinetOutputRole role) => ModeFor(pluginId, role, CabinetEndpointKind.DesktopRegion); - public CabinetOutputMode ModeFor(string pluginId, string role, CabinetEndpointKind kind) + public CabinetOutputMode ModeFor(string pluginId, CabinetOutputRole role, CabinetEndpointKind kind) { foreach (var assignment in Assignments) if (assignment.PluginId == pluginId && assignment.Role == role && assignment.Kind == kind) return assignment.Mode; return CabinetOutputMode.Custom; } /// All destinations for this role, including unavailable ones; a monitor and device may mirror it. - public IReadOnlyList TargetsFor(string role) + public IReadOnlyList TargetsFor(CabinetOutputRole role) => Array.AsReadOnly(Targets.Where(target => target.Role == role).ToArray()); } /// Optional factory declaration. Inspecting roles must not create a gameplay instance or open a device. public interface ICabinetDisplayPlugin { - IReadOnlyList CabinetRoles { get; } + IReadOnlyList CabinetRoles { get; } } /// Where an updated surface is eligible to be shown. diff --git a/VisualPinball.Plugins/Resources/ResourceContracts.cs b/VisualPinball.Plugins/Resources/ResourceContracts.cs index 4bca464f53..d5947b350d 100644 --- a/VisualPinball.Plugins/Resources/ResourceContracts.cs +++ b/VisualPinball.Plugins/Resources/ResourceContracts.cs @@ -940,6 +940,8 @@ public static class SurfaceRoles public const string Dmd = "dmd"; /// A large DMD-sized screen in the backbox, PinUP's "FullDMD". public const string FullDmd = "full-dmd"; + /// A game LCD/HD display, independent of backglass artwork and dot-matrix output. + public const string GameDisplay = "game-display"; } /// One named trigger with an integer value, carried by . /// Nothing in VPE publishes trigger resources yet. diff --git a/VisualPinball.Unity/Documentation~/developer-guide/cabinet-display-outputs.md b/VisualPinball.Unity/Documentation~/developer-guide/cabinet-display-outputs.md index 83352d188e..f0c70a7e80 100644 --- a/VisualPinball.Unity/Documentation~/developer-guide/cabinet-display-outputs.md +++ b/VisualPinball.Unity/Documentation~/developer-guide/cabinet-display-outputs.md @@ -25,3 +25,9 @@ The next Player phase adds persisted layout, Windows topology, browsing backglas The owned output texture can copy clockwise quarter-turn rotation and output-axis mirrors into a normalized viewport. The viewport uses bottom-left Unity UV coordinates; the Player converts its saved top-left percentages once. Inside the viewport, contain-fit bars are opaque black. Outside it, existing pixels are retained using an explicit color Load/Store action. This supports a Full DMD background and an independently selected DMD inset in one native window. The existing four-argument full-frame copy API remains available. Producer textures are unbound from the copy material immediately after submission. Physical multi-monitor and rotated-panel certification remains outstanding. The test suite covers all eight dihedral transforms, asymmetric partial viewports and render-state restoration, alpha/color conversion, two native presenters and deferred output retirement on the available Windows D3D12 backend. Metal and Vulkan must pass their platform matrices before certification. + +## Known output roles + +The cabinet API uses the closed `CabinetOutputRole` enum: Backglass, Dmd, GameDisplay, FullDmd, Topper and ScorePanel. The game LCD/HD display, cabinet Full DMD video panel and backglass are independent destinations; none is inferred from image dimensions. GameDisplay uses ordinary texture presentation, without DMD dot processing. Playfield placement remains in Video. + +Generic resource descriptors and authored custom scene bindings retain string IDs for compatibility. Convert only known IDs with `CabinetOutputRoles.TryParse` at that boundary. Shared targets, assignments, device profiles, import candidates and factory role declarations use the enum. Private plug-in screens stay inside the plug-in and cannot become arbitrary global cabinet settings. Stable string IDs in saved JSON remain compatible, including separate `game-display` and `full-dmd` records. diff --git a/VisualPinball.Unity/VisualPinball.Unity/Display/CabinetScreenComponent.cs b/VisualPinball.Unity/VisualPinball.Unity/Display/CabinetScreenComponent.cs index 90e7ef3519..884e6f0712 100644 --- a/VisualPinball.Unity/VisualPinball.Unity/Display/CabinetScreenComponent.cs +++ b/VisualPinball.Unity/VisualPinball.Unity/Display/CabinetScreenComponent.cs @@ -29,6 +29,7 @@ public enum CabinetScreenRole Dmd, FullDmd, Custom, + GameDisplay, // Appended to preserve existing serialized enum values. } /// @@ -76,6 +77,7 @@ public class CabinetScreenComponent : MonoBehaviour, IPackable CabinetScreenRole.Topper => SurfaceRoles.Topper, CabinetScreenRole.Dmd => SurfaceRoles.Dmd, CabinetScreenRole.FullDmd => SurfaceRoles.FullDmd, + CabinetScreenRole.GameDisplay => SurfaceRoles.GameDisplay, _ => CustomRole?.Trim() ?? string.Empty, }; @@ -94,6 +96,7 @@ public void SetRoleName(string role) case SurfaceRoles.Topper: Role = CabinetScreenRole.Topper; break; case SurfaceRoles.Dmd: Role = CabinetScreenRole.Dmd; break; case SurfaceRoles.FullDmd: Role = CabinetScreenRole.FullDmd; break; + case SurfaceRoles.GameDisplay: Role = CabinetScreenRole.GameDisplay; break; default: Role = CabinetScreenRole.Custom; CustomRole = role ?? string.Empty; From d695a64ff2db497015b67e83dfb70bc982a6cbcf Mon Sep 17 00:00:00 2001 From: freezy Date: Mon, 2 Nov 2026 23:57:49 +0100 Subject: [PATCH 06/10] packaging: preserve collision-only playfield meshes --- CHANGELOG.md | 2 + .../developer-guide/packaging/export.md | 2 + .../Packaging/PackageWriter.cs | 10 ++- .../VPT/PlayfieldMeshPackagingTests.cs | 88 +++++++++++++++++-- .../Extensions/MeshExtensions.cs | 4 +- .../Packaging/PackagedFiles.cs | 2 +- .../VPT/Playfield/PlayfieldMeshComponent.cs | 20 +++-- .../VPT/Playfield/PlayfieldPackable.cs | 24 +++++ 8 files changed, 134 insertions(+), 18 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index bc036c61d7..d582491a18 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -213,6 +213,8 @@ Built with Unity 6.5 ### Fixed +- Preserve custom playfield collider meshes without an enabled renderer when exporting tables, and load hidden collision meshes without UVs, so authored openings remain functional in the Player. + - The flipper collider gizmo follows the bat's rotation in edit mode so its shape can be compared with the visible mesh. - A ball held by a moving kicker keeps its height above the kicker, instead of being pulled down to the kicker's base, and balls only passing over it are left alone. - Devices assigned in the coil, lamp, switch and wire managers survive a recompile or entering play mode, instead of being dropped until the scene is reloaded. diff --git a/VisualPinball.Unity/Documentation~/developer-guide/packaging/export.md b/VisualPinball.Unity/Documentation~/developer-guide/packaging/export.md index bf6919880f..3012fa3735 100644 --- a/VisualPinball.Unity/Documentation~/developer-guide/packaging/export.md +++ b/VisualPinball.Unity/Documentation~/developer-guide/packaging/export.md @@ -71,6 +71,8 @@ Physics-only meshes are exported to `table/colliders.glb`. Related metadata is w This lets editor re-import reconnect those meshes correctly. +Custom playfields with no enabled renderer store their authored collision mesh in `table/colliders.glb` and reference it from `PlayfieldMesh` data under `table/refs`. Both the Editor and Player restore the mesh to its `MeshFilter` before collider generation. Visible custom playfields reuse their scene mesh. Packages exported before this collision-only support must be exported again from the source table; the absent geometry cannot be recovered from those packages. + ## Packables and References Gameplay and authoring data is split into two trees: diff --git a/VisualPinball.Unity/VisualPinball.Unity.Editor/Packaging/PackageWriter.cs b/VisualPinball.Unity/VisualPinball.Unity.Editor/Packaging/PackageWriter.cs index ff1ce40423..a6cdac6f86 100644 --- a/VisualPinball.Unity/VisualPinball.Unity.Editor/Packaging/PackageWriter.cs +++ b/VisualPinball.Unity/VisualPinball.Unity.Editor/Packaging/PackageWriter.cs @@ -841,6 +841,7 @@ private Func> PrepareColliderMeshes() var meshGos = new List(); var colliderMeshesMeta = new Dictionary(); GameObjectExport export = null; + GameObject exportRoot = null; try { foreach (var colMesh in _table.GetComponentsInChildren(!ExportActivesOnly)) { for (var index = 0; index < colMesh.NumColliderMeshes; index++) { @@ -872,7 +873,11 @@ private Func> PrepareColliderMeshes() Format = GltfFormat.Binary, }; export = new GameObjectExport(exportSettings, logger: logger); - export.AddScene(meshGos.ToArray(), _table.transform.worldToLocalMatrix, "Colliders"); + // Keep collider nodes below a container even when there is only one mesh. + // The Editor glTF importer renames a lone root node to the asset filename. + exportRoot = new GameObject("Colliders"); + foreach (var meshGo in meshGos) meshGo.transform.SetParent(exportRoot.transform, false); + export.AddScene(new[] { exportRoot }, _table.transform.worldToLocalMatrix, "Colliders"); var glbMeta = _metaFolder.AddFile(PackageApi.ColliderMeshesMeta, PackageApi.Packer.FileExtension); glbMeta.SetData(PackageApi.Packer.Pack(colliderMeshesMeta)); @@ -881,8 +886,9 @@ private Func> PrepareColliderMeshes() } finally { // cleanup scene + if (exportRoot) Object.DestroyImmediate(exportRoot); foreach (var meshGo in meshGos) { - Object.DestroyImmediate(meshGo); + if (meshGo) Object.DestroyImmediate(meshGo); } } diff --git a/VisualPinball.Unity/VisualPinball.Unity.Test/VPT/PlayfieldMeshPackagingTests.cs b/VisualPinball.Unity/VisualPinball.Unity.Test/VPT/PlayfieldMeshPackagingTests.cs index f12215b2d1..113282fd32 100644 --- a/VisualPinball.Unity/VisualPinball.Unity.Test/VPT/PlayfieldMeshPackagingTests.cs +++ b/VisualPinball.Unity/VisualPinball.Unity.Test/VPT/PlayfieldMeshPackagingTests.cs @@ -19,6 +19,8 @@ using System.IO; using System.Reflection; using NUnit.Framework; +using Unity.Collections; +using Unity.Mathematics; using UnityEditor; using UnityEngine; using UnityEngine.TestTools; @@ -56,14 +58,46 @@ public void AutoGenerateRoundTrips() } } + [TestCase(true)] + [TestCase(false)] + public void MissingMeshFilterDoesNotBreakColliderExport(bool autoGenerate) + { + var target = new GameObject("Playfield"); + try { + var mesh = target.AddComponent(); mesh.AutoGenerate = autoGenerate; + Assert.That(target.TryGetComponent(out _), Is.False); + Assert.That(mesh.NumColliderMeshes, Is.Zero); Assert.That(mesh.GetColliderMesh(0), Is.Null); + Assert.DoesNotThrow(() => mesh.UnpackReferences(null, target.transform, null, null)); + Assert.DoesNotThrow(() => mesh.UnpackReferences(Array.Empty(), target.transform, null, null)); + } finally { Object.DestroyImmediate(target); } + } + + [UnityTest] + public IEnumerator ShouldKeepAnAuthoredPlayfieldMeshThroughAPackageRoundTrip() => RoundTrip(true, true, false); + + [UnityTest] + public IEnumerator CollisionOnlyMeshSurvivesEditorImport() => RoundTrip(false, false, false); + + [UnityTest] + public IEnumerator DisabledRendererMeshSurvivesEditorImport() => RoundTrip(true, false, false); + + [UnityTest] + public IEnumerator CollisionOnlyMeshSurvivesRuntimeImport() => RoundTrip(false, false, true); + + [UnityTest] + public IEnumerator DisabledRendererMeshSurvivesRuntimeImport() => RoundTrip(true, false, true); + [UnityTest] - public IEnumerator ShouldKeepAnAuthoredPlayfieldMeshThroughAPackageRoundTrip() + public IEnumerator MultipleCollisionMeshesSurviveEditorImport() => RoundTrip(false, false, false, true); + + private IEnumerator RoundTrip(bool hasRenderer, bool rendererEnabled, bool runtime, bool extraCollider = false) { var tableName = "PlayfieldMeshPackagingTest-" + Guid.NewGuid().ToString("N"); var packagePath = Path.Combine(Path.GetTempPath(), tableName + ".vpe"); GameObject source = null; GameObject imported = null; Mesh authored = null; + Mesh secondaryMesh = null; Material material = null; try { source = new GameObject(tableName); @@ -79,24 +113,51 @@ public IEnumerator ShouldKeepAnAuthoredPlayfieldMeshThroughAPackageRoundTrip() new Vector3(0.3f, 0f, 1.1f), new Vector3(0.25f, 0f, 0.9f), new Vector3(0.2f, 0f, 1.1f), new Vector3(0f, 0f, 1.1f), }; authored.triangles = new[] { 0, 2, 1, 0, 3, 2, 0, 4, 3, 0, 5, 4, 0, 6, 5 }; + authored.uv = Array.ConvertAll(authored.vertices, v => new Vector2(v.x, v.z)); authored.RecalculateNormals(); authored.RecalculateBounds(); playfieldGo.AddComponent().sharedMesh = authored; - material = new Material(Shader.Find("Universal Render Pipeline/Lit") ?? Shader.Find("Standard")) { name = "Authored Playfield" }; - playfieldGo.AddComponent().sharedMaterial = material; + if (hasRenderer) { + material = new Material(Shader.Find("Universal Render Pipeline/Lit") ?? Shader.Find("Standard")) { name = "Authored Playfield" }; + var renderer = playfieldGo.AddComponent(); + renderer.sharedMaterial = material; renderer.enabled = rendererEnabled; + } + playfieldGo.AddComponent(); var playfieldMesh = playfieldGo.AddComponent(); playfieldMesh.AutoGenerate = false; + if (hasRenderer) playfieldGo.GetComponent().enabled = rendererEnabled; + if (extraCollider) { + var secondary = new GameObject("Secondary collider"); secondary.transform.SetParent(source.transform, false); + secondaryMesh = Object.Instantiate(authored); secondaryMesh.triangles = new[] { 0, 2, 1 }; + secondary.AddComponent(); secondary.AddComponent().sharedMesh = secondaryMesh; + secondary.AddComponent(); + } var sourceBounds = authored.bounds; var sourceTriangles = authored.triangles.Length / 3; + Assert.That(playfieldMesh.NumColliderMeshes, Is.EqualTo(hasRenderer && rendererEnabled ? 0 : 1), "only hidden custom geometry uses the collider payload"); new PackageWriter(source).WritePackageSync(packagePath); - var importTask = new PackageReader(packagePath).ImportIntoScene(tableName); - while (!importTask.IsCompleted) { yield return null; } - if (importTask.IsFaulted) { throw importTask.Exception!.GetBaseException(); } - foreach (var table in Object.FindObjectsByType(FindObjectsSortMode.None)) { - if (table.gameObject != source && table.name == tableName) { imported = table.gameObject; break; } + Assert.That(playfieldGo.GetComponent().sharedMesh, Is.SameAs(authored), "export leaves the source mesh in place"); + Assert.That(playfieldGo.GetComponent() != null, Is.EqualTo(hasRenderer), "export must not add a renderer to collision-only geometry"); + if (hasRenderer) Assert.That(playfieldGo.GetComponent().enabled, Is.EqualTo(rendererEnabled)); + if (runtime) { + var load = new RuntimePackageReader(packagePath).ImportIntoScene(); + while (!load.IsCompleted) yield return null; + imported = load.GetAwaiter().GetResult(); + } else { + var importTask = new PackageReader(packagePath).ImportIntoScene(tableName); + while (!importTask.IsCompleted) { yield return null; } + if (importTask.IsFaulted) { throw importTask.Exception!.GetBaseException(); } + foreach (var table in Object.FindObjectsByType(FindObjectsSortMode.None)) { + if (table.gameObject != source && table.name == tableName) { imported = table.gameObject; break; } + } } Assert.That(imported, Is.Not.Null); + if (extraCollider) { + var secondary = imported.GetComponentInChildren(true); + Assert.That(secondary, Is.Not.Null); + Assert.That(secondary.GetComponent().sharedMesh.triangles.Length / 3, Is.EqualTo(1), "the second GUID resolves its distinct geometry"); + } var restored = imported.GetComponentInChildren(true); Assert.That(restored, Is.Not.Null, "the playfield mesh component must survive the package round trip"); @@ -108,11 +169,22 @@ public IEnumerator ShouldKeepAnAuthoredPlayfieldMeshThroughAPackageRoundTrip() Assert.That(restoredMesh.triangles.Length / 3, Is.EqualTo(sourceTriangles), "the authored mesh, not a generated plane"); Assert.That(restoredMesh.bounds.size.x, Is.EqualTo(sourceBounds.size.x).Within(1e-4f)); Assert.That(restoredMesh.bounds.size.z, Is.EqualTo(sourceBounds.size.z).Within(1e-4f)); + Assert.That(restoredMesh.isReadable, Is.True, "runtime physics must be able to read the restored triangles"); + if (!hasRenderer || !rendererEnabled) Assert.That(restored.GetComponent(), Is.Null, "collision-only geometry stays invisible"); + var transforms = new NativeParallelHashMap(1, Allocator.Temp); + var colliders = new ColliderReference(ref transforms, Allocator.Temp); + try { + var api = new PlayfieldApi(restored.gameObject, null, null); + ((IApiColliderGenerator)api).CreateColliders(ref colliders, float4x4.identity, 0f); + Assert.That(colliders.TriangleColliders.Length, Is.EqualTo(sourceTriangles)); + Assert.That(colliders.PlaneColliders.Length, Is.EqualTo(1), "only the glass plane remains; no solid playfield fallback"); + } finally { colliders.Dispose(); transforms.Dispose(); } } finally { if (source) { Object.DestroyImmediate(source); } if (imported) { Object.DestroyImmediate(imported); } if (authored) { Object.DestroyImmediate(authored); } + if (secondaryMesh) { Object.DestroyImmediate(secondaryMesh); } if (material) { Object.DestroyImmediate(material); } AssetDatabase.DeleteAsset("Assets/Resources/" + tableName); File.Delete(packagePath); diff --git a/VisualPinball.Unity/VisualPinball.Unity/Extensions/MeshExtensions.cs b/VisualPinball.Unity/VisualPinball.Unity/Extensions/MeshExtensions.cs index 4b28815524..745711bf64 100644 --- a/VisualPinball.Unity/VisualPinball.Unity/Extensions/MeshExtensions.cs +++ b/VisualPinball.Unity/VisualPinball.Unity/Extensions/MeshExtensions.cs @@ -38,9 +38,11 @@ public static Mesh ToVpMesh(this UnityEngine.Mesh unityMesh) var unityNormals = new NativeArray(meshData.vertexCount, Allocator.TempJob); meshData.GetVertices(unityVertices); meshData.GetNormals(unityNormals); + // Collision-only GLBs can omit UVs; their physics still needs the vertices and triangles. + var unityUvs = unityMesh.uv; for (var i = 0; i < vpMesh.Vertices.Length; i++) { - var unityUv = unityMesh.uv[i]; + var unityUv = i < unityUvs.Length ? unityUvs[i] : Vector2.zero; vpMesh.Vertices[i] = new Vertex3DNoTex2( unityVertices[i].x, unityVertices[i].y, unityVertices[i].z, unityNormals[i].x, unityNormals[i].y, unityNormals[i].z, diff --git a/VisualPinball.Unity/VisualPinball.Unity/Packaging/PackagedFiles.cs b/VisualPinball.Unity/VisualPinball.Unity/Packaging/PackagedFiles.cs index c84ccc1932..bc7d21f39e 100644 --- a/VisualPinball.Unity/VisualPinball.Unity/Packaging/PackagedFiles.cs +++ b/VisualPinball.Unity/VisualPinball.Unity/Packaging/PackagedFiles.cs @@ -170,7 +170,7 @@ public async Task UnpackMeshesRuntime(CancellationToken cancellationToken = defa importRoot.hideFlags = HideFlags.HideAndDontSave; try { // Colliders need placeholder materials too; use the pipeline generator included in players. - var gltf = new GltfImport(materialGenerator: RuntimeGltfMaterialGenerator.Create(), logger: new ConsoleLogger()); + var gltf = new GltfImport(deferAgent: new GLTFast.UninterruptedDeferAgent(), materialGenerator: RuntimeGltfMaterialGenerator.Create(), logger: new ConsoleLogger()); var loaded = await gltf.Load(colliderMeshData, cancellationToken: cancellationToken); cancellationToken.ThrowIfCancellationRequested(); if (!loaded) { diff --git a/VisualPinball.Unity/VisualPinball.Unity/VPT/Playfield/PlayfieldMeshComponent.cs b/VisualPinball.Unity/VisualPinball.Unity/VPT/Playfield/PlayfieldMeshComponent.cs index 1d5b9cdc0c..ff567a10eb 100644 --- a/VisualPinball.Unity/VisualPinball.Unity/VPT/Playfield/PlayfieldMeshComponent.cs +++ b/VisualPinball.Unity/VisualPinball.Unity/VPT/Playfield/PlayfieldMeshComponent.cs @@ -24,7 +24,7 @@ namespace VisualPinball.Unity.Playfield [PackAs("PlayfieldMesh")] [ExecuteInEditMode] [AddComponentMenu("Pinball/Mesh/Playfield Mesh")] - public class PlayfieldMeshComponent : MeshComponent, IPackable + public class PlayfieldMeshComponent : MeshComponent, IPackable, IColliderMesh { #region Data @@ -34,16 +34,24 @@ public class PlayfieldMeshComponent : MeshComponent PlayfieldMeshPackable.Pack(this); - public byte[] PackReferences(Transform root, PackagedRefs refs, PackagedFiles files) => null; + public byte[] PackReferences(Transform root, PackagedRefs refs, PackagedFiles files) => PlayfieldMeshReferencesPackable.Pack(this, files); public void Unpack(byte[] bytes) => PlayfieldMeshPackable.Unpack(bytes, this); - public void UnpackReferences(byte[] data, Transform root, PackagedRefs refs, PackagedFiles files) { } + public void UnpackReferences(byte[] data, Transform root, PackagedRefs refs, PackagedFiles files) => PlayfieldMeshReferencesPackable.Unpack(data, this, files); + + public int NumColliderMeshes { + get { + if (AutoGenerate || !TryGetComponent(out var filter) || !filter.sharedMesh) return 0; + var renderer = GetComponent(); + return !(renderer && renderer.enabled) ? 1 : 0; + } + } + public UnityEngine.Mesh GetColliderMesh(int index) => index == 0 && TryGetComponent(out var filter) ? filter.sharedMesh : null; #endregion diff --git a/VisualPinball.Unity/VisualPinball.Unity/VPT/Playfield/PlayfieldPackable.cs b/VisualPinball.Unity/VisualPinball.Unity/VPT/Playfield/PlayfieldPackable.cs index fcd693769b..a725b61798 100644 --- a/VisualPinball.Unity/VisualPinball.Unity/VPT/Playfield/PlayfieldPackable.cs +++ b/VisualPinball.Unity/VisualPinball.Unity/VPT/Playfield/PlayfieldPackable.cs @@ -78,6 +78,30 @@ public static void Unpack(byte[] bytes, Playfield.PlayfieldMeshComponent comp) } } + public struct PlayfieldMeshReferencesPackable + { + public string ColliderMeshGuid; + + public static byte[] Pack(Playfield.PlayfieldMeshComponent comp, PackagedFiles files) + { + var guid = files.GetColliderMeshGuid(comp, 0); + return string.IsNullOrEmpty(guid) ? null : PackageApi.Packer.Pack(new PlayfieldMeshReferencesPackable { ColliderMeshGuid = guid }); + } + + public static void Unpack(byte[] bytes, Playfield.PlayfieldMeshComponent comp, PackagedFiles files) + { + if (bytes == null || bytes.Length == 0) return; + var data = PackageApi.Packer.Unpack(bytes); + if (string.IsNullOrEmpty(data.ColliderMeshGuid)) return; + var mesh = files.GetColliderMesh(data.ColliderMeshGuid, 0); + // Report incomplete collision data rather than silently installing a null mesh. + if (!mesh) throw new System.IO.InvalidDataException("The packaged custom playfield collider mesh is missing."); + var filter = comp.GetComponent(); + if (!filter) filter = comp.gameObject.AddComponent(); + filter.sharedMesh = mesh; + } + } + public struct PlayfieldColliderPackable { public float Gravity; From d2350428adfda790ab69e80f2618909a326e7837 Mon Sep 17 00:00:00 2001 From: freezy Date: Wed, 4 Nov 2026 21:23:17 +0100 Subject: [PATCH 07/10] display: let the screen binder take a provider order per role --- .../Plugins/CabinetScreenBinder.cs | 28 ++++++++++++++++--- 1 file changed, 24 insertions(+), 4 deletions(-) diff --git a/VisualPinball.Unity/VisualPinball.Unity/Plugins/CabinetScreenBinder.cs b/VisualPinball.Unity/VisualPinball.Unity/Plugins/CabinetScreenBinder.cs index 640f4e3b52..5caf86a149 100644 --- a/VisualPinball.Unity/VisualPinball.Unity/Plugins/CabinetScreenBinder.cs +++ b/VisualPinball.Unity/VisualPinball.Unity/Plugins/CabinetScreenBinder.cs @@ -20,7 +20,7 @@ namespace VisualPinball.Unity /// /// /// Every cabinet screen follows the published for its role. When several plugins - /// publish the same role, the one listed first in the provider order wins; providers not listed come after, by ID. + /// publish the same role, the one listed first in that role's provider order wins; providers not listed come after, by ID. /// The surface's texture is written into the screen's material with a property block, and the screen's hide root is /// activated. Without a surface, or before its texture exists, the material's own texture is put back and the hide /// root is deactivated, so screens without a provider are hidden from the start when the binder is created before the @@ -76,7 +76,7 @@ internal Screen(CabinetScreenComponent component, Renderer renderer, int propert private readonly PluginResourceRegistry _registry; private readonly string _controller; private readonly long _session; - private readonly IReadOnlyList _providers; + private readonly Func> _providers; private readonly MaterialPropertyBlock _properties = new MaterialPropertyBlock(); private readonly IDisposable _observation; private bool _engineDmd; @@ -93,12 +93,26 @@ internal Screen(CabinetScreenComponent component, Renderer renderer, int propert /// The game session; only surfaces of this session are shown. /// Plugin IDs in order of preference, for roles several plugins provide. public CabinetScreenBinder(GameObject table, IGamelogicEngine engine, PluginResourceRegistry registry, string controller, long session, IReadOnlyList providers) + : this(table, engine, registry, controller, session, Fixed(providers)) + { + } + + /// + /// Starts showing surfaces on the cabinet screens of , including inactive ones. + /// + /// The table's root object. + /// The table's gamelogic engine, or null if it has none. + /// The registry plugins publish their surfaces to. + /// The game's controller ID; only surfaces of this controller are shown. + /// The game session; only surfaces of this session are shown. + /// For each role, plugin IDs in order of preference, for roles several plugins provide. + public CabinetScreenBinder(GameObject table, IGamelogicEngine engine, PluginResourceRegistry registry, string controller, long session, Func> providers) { _engine = engine; _registry = registry; _controller = controller ?? string.Empty; _session = session; - _providers = providers?.ToArray() ?? Array.Empty(); + _providers = providers ?? Fixed(null); foreach (var component in table.GetComponentsInChildren(true)) { var renderer = component.TargetRenderer; @@ -235,6 +249,12 @@ private void Refresh() } } + private static Func> Fixed(IReadOnlyList providers) + { + var order = providers?.ToArray() ?? Array.Empty(); + return _ => order; + } + /// /// The ID of the surface a role shows: the one of the most preferred provider, or null for none. /// @@ -246,7 +266,7 @@ private string Choose(string role) var candidates = _registry.Snapshot(new PluginResourceSelection(ResourceKind.Surface) { Role = role, Controller = _controller, Session = _session, }); - return CabinetSurfaceSelector.Choose(candidates, _providers, descriptor => + return CabinetSurfaceSelector.Choose(candidates, _providers(role) ?? Array.Empty(), descriptor => _registry.TryGetSource(descriptor, out var source) && CabinetSurfaceSelector.Eligible(source, CabinetSurfaceConsumers.Scene))?.Id; } From f31f9ca178b9ea9185c6461a95b086bf616c6cd7 Mon Sep 17 00:00:00 2001 From: freezy Date: Wed, 4 Nov 2026 22:35:23 +0100 Subject: [PATCH 08/10] plugins: drop hardware endpoints, the display import and the full DMD output from the cabinet contract Physical DMD panels are no longer player destinations, so cabinet targets are desktop regions only and assignments are keyed by plug-in and role. The import of plug-in saved window positions is gone. The full DMD scene surface stays for the plug-in that publishes it. --- .../CabinetDisplayTests.cs | 74 +++++-------------- VisualPinball.Plugins/Api/CabinetDevices.cs | 53 ------------- .../Api/CabinetDevices.cs.meta | 2 - .../Api/CabinetDisplayImport.cs | 58 --------------- .../Api/CabinetDisplayImport.cs.meta | 2 - VisualPinball.Plugins/Api/CabinetDisplays.cs | 48 +++--------- 6 files changed, 28 insertions(+), 209 deletions(-) delete mode 100644 VisualPinball.Plugins/Api/CabinetDevices.cs delete mode 100644 VisualPinball.Plugins/Api/CabinetDevices.cs.meta delete mode 100644 VisualPinball.Plugins/Api/CabinetDisplayImport.cs delete mode 100644 VisualPinball.Plugins/Api/CabinetDisplayImport.cs.meta diff --git a/VisualPinball.Plugins.Test/CabinetDisplayTests.cs b/VisualPinball.Plugins.Test/CabinetDisplayTests.cs index 2d0a55c12e..c52340515e 100644 --- a/VisualPinball.Plugins.Test/CabinetDisplayTests.cs +++ b/VisualPinball.Plugins.Test/CabinetDisplayTests.cs @@ -15,10 +15,10 @@ public sealed class CabinetDisplayTests public void SnapshotCopiesInputAndKeepsAdoptedMissingOutputsManaged() { var assignments = new[] { new CabinetOutputAssignment("b2s", CabinetOutputRole.Backglass, CabinetOutputMode.Player) }; - var targets = new[] { new CabinetDisplayTarget("screen", CabinetOutputRole.Backglass, CabinetEndpointKind.DesktopRegion, CabinetEndpointState.Unavailable, reason: "Disconnected") }; + var targets = new[] { new CabinetDisplayTarget("screen", CabinetOutputRole.Backglass, CabinetEndpointState.Unavailable, reason: "Disconnected") }; var snapshot = new CabinetDisplaySnapshot(4, 7, 9, targets, assignments); assignments[0] = new CabinetOutputAssignment("b2s", CabinetOutputRole.Backglass, CabinetOutputMode.Off); - targets[0] = new CabinetDisplayTarget("screen", CabinetOutputRole.Backglass, CabinetEndpointKind.DesktopRegion, CabinetEndpointState.Available, -1920, 0, 1920, 1080); + targets[0] = new CabinetDisplayTarget("screen", CabinetOutputRole.Backglass, CabinetEndpointState.Available, -1920, 0, 1920, 1080); Assert.That(snapshot.ModeFor("b2s", CabinetOutputRole.Backglass), Is.EqualTo(CabinetOutputMode.Player)); Assert.That(snapshot.ModeFor("pup", CabinetOutputRole.Backglass), Is.EqualTo(CabinetOutputMode.Custom)); Assert.That(snapshot.Targets[0].State, Is.EqualTo(CabinetEndpointState.Unavailable)); @@ -29,12 +29,11 @@ public void DuplicateAssignmentsAndInvalidAvailableDestinationsAreRejected() { var adoption = new CabinetOutputAssignment("pup", CabinetOutputRole.Topper, CabinetOutputMode.Player); Assert.Throws(() => new CabinetDisplaySnapshot(1, 1, 1, Array.Empty(), new[] { adoption, adoption })); - Assert.Throws(() => new CabinetDisplayTarget("screen", CabinetOutputRole.Backglass, CabinetEndpointKind.DesktopRegion, CabinetEndpointState.Available)); - Assert.Throws(() => new CabinetDisplayTarget("device", CabinetOutputRole.Dmd, CabinetEndpointKind.Device, CabinetEndpointState.Available)); - var target = new CabinetDisplayTarget("screen", CabinetOutputRole.Dmd, CabinetEndpointKind.DesktopRegion, CabinetEndpointState.Available, width: 128, height: 32); + Assert.Throws(() => new CabinetDisplayTarget("screen", CabinetOutputRole.Backglass, CabinetEndpointState.Available)); + var target = new CabinetDisplayTarget("screen", CabinetOutputRole.Dmd, CabinetEndpointState.Available, width: 128, height: 32); Assert.Throws(() => new CabinetDisplaySnapshot(1, 1, 1, new[] { target, target }, Array.Empty())); - var device = new CabinetDisplayTarget("device", CabinetOutputRole.Dmd, CabinetEndpointKind.Device, CabinetEndpointState.Available, deviceLeaseKey: "serial:COM3"); - Assert.That(new CabinetDisplaySnapshot(1, 1, 1, new[] { target, device }, Array.Empty()).TargetsFor(CabinetOutputRole.Dmd).Count, Is.EqualTo(2)); + var second = new CabinetDisplayTarget("second", CabinetOutputRole.Dmd, CabinetEndpointState.Disabled); + Assert.That(new CabinetDisplaySnapshot(1, 1, 1, new[] { target, second }, Array.Empty()).TargetsFor(CabinetOutputRole.Dmd).Count, Is.EqualTo(2)); } [Test] @@ -79,56 +78,17 @@ public void RegistryProbeRejectsStaleInstancesAndReadinessChangesRecomputeSelect Assert.That(registry.TryGetSource(stale, out _), Is.False); } - [Test] - public void MonitorAndDeviceAdoptionAreIndependentAndLegacyOverloadMeansMonitor() - { - var snapshot = new CabinetDisplaySnapshot(1, 1, 1, Array.Empty(), new[] { - new CabinetOutputAssignment("dmd", CabinetOutputRole.Dmd, CabinetOutputMode.Player), - new CabinetOutputAssignment("dmd", CabinetOutputRole.Dmd, CabinetOutputMode.Off, CabinetEndpointKind.Device) }); - Assert.That(snapshot.ModeFor("dmd", CabinetOutputRole.Dmd), Is.EqualTo(CabinetOutputMode.Player)); - Assert.That(snapshot.ModeFor("dmd", CabinetOutputRole.Dmd, CabinetEndpointKind.Device), Is.EqualTo(CabinetOutputMode.Off)); - Assert.That(snapshot.ModeFor("other", CabinetOutputRole.Dmd, CabinetEndpointKind.Device), Is.EqualTo(CabinetOutputMode.Custom)); - } - - [Test] - public void DeviceProfileRequestIsDetachedAndTargetCannotContradictItsProfile() - { - var settings = new PluginSettingsSnapshot(1, Newtonsoft.Json.Linq.JObject.Parse("{\"port\":\"COM3\"}")); - var keys = new[] { "port" }; var request = new CabinetDeviceProfileRequest(settings, keys, "windows"); - settings.Values["port"] = "COM4"; keys[0] = "other"; - Assert.That(request.Settings.String("port"), Is.EqualTo("COM3")); Assert.That(request.SavedKeys, Is.EqualTo(new[] { "port" })); - var profile = new CabinetDeviceProfile("profile", "dmd", CabinetOutputRole.Dmd, "DMD", "serial:COM3", "usb:family", "{}"); - var target = CabinetDisplayTarget.Device("device", CabinetOutputRole.Dmd, CabinetEndpointState.Available, profile); - Assert.That(target.DeviceProfile, Is.SameAs(profile)); Assert.That(target.DeviceLeaseKey, Is.EqualTo(profile.LeaseKey)); - Assert.Throws(() => CabinetDisplayTarget.Device("device", CabinetOutputRole.Topper, CabinetEndpointState.Available, profile)); - Assert.Throws(() => CabinetDisplayTarget.Device("device", CabinetOutputRole.Dmd, CabinetEndpointState.Available, null)); - Assert.Throws(() => new CabinetDeviceProfile("p", "dmd", CabinetOutputRole.Dmd, "DMD", "", "", "{}")); - } - - [Test] - public void ImportPreviewCopiesSettingsAndKeepsUnusableGeometryUnsupported() - { - var settings = new PluginSettingsSnapshot(1); settings.Values["x"] = 10; var keys = new[] { "x" }; - var request = new CabinetDisplayImportRequest(settings, keys, "windows"); settings.Values["x"] = 20; keys[0] = "y"; - Assert.That(request.Settings.Integer("x"), Is.EqualTo(10)); Assert.That(request.SavedKeys, Is.EqualTo(new[] { "x" })); - Assert.That(new CabinetDisplayImportCandidate(CabinetOutputRole.Dmd, 0, 0, 0, 32).Supported, Is.False); - Assert.That(new CabinetDisplayImportCandidate(CabinetOutputRole.Dmd, int.MaxValue, 0, 128, 32).Supported, Is.False); - var hardware = new CabinetDisplayImportCandidate(CabinetOutputRole.Dmd, "profile"); Assert.That(hardware.Kind, Is.EqualTo(CabinetEndpointKind.Device)); Assert.That(hardware.DeviceProfileId, Is.EqualTo("profile")); - } - - [Test] - public void SharedRolesAreClosedAndKeepHdDisplaySeparateFromBackglassAndVideoPanel() - { - Assert.That(CabinetOutputRoles.TryParse("pup-screen-8", out _), Is.False); - Assert.That(CabinetOutputRoles.TryParse("playfield", out _), Is.False, "Playfield placement belongs to Video."); - Assert.That(CabinetOutputRoles.Parse("game-display"), Is.EqualTo(CabinetOutputRole.GameDisplay)); - Assert.That(CabinetOutputRoles.Parse("full-dmd"), Is.EqualTo(CabinetOutputRole.FullDmd)); - Assert.That(CabinetOutputRole.GameDisplay.Id(), Is.Not.EqualTo(CabinetOutputRole.FullDmd.Id())); - Assert.Throws(() => new CabinetOutputAssignment("plugin", (CabinetOutputRole)0, CabinetOutputMode.Player)); - Assert.Throws(() => new CabinetDisplayImportCandidate((CabinetOutputRole)999, 0, 0, 100, 100)); - Assert.Throws(() => new CabinetDeviceProfile("profile", "plugin", (CabinetOutputRole)999, "Panel", "key", "", "{}")); - } - + [Test] + public void SharedRolesAreClosedAndKeepHdDisplaySeparateFromBackglass() + { + Assert.That(CabinetOutputRoles.TryParse("pup-screen-8", out _), Is.False); + Assert.That(CabinetOutputRoles.TryParse("playfield", out _), Is.False, "Playfield placement belongs to Video."); + Assert.That(CabinetOutputRoles.Parse("game-display"), Is.EqualTo(CabinetOutputRole.GameDisplay)); + Assert.That(CabinetOutputRoles.TryParse("full-dmd", out _), Is.False, "Full DMD is a screen PinUP places itself."); + Assert.That(CabinetOutputRole.GameDisplay.Id(), Is.Not.EqualTo(CabinetOutputRole.Backglass.Id())); + Assert.Throws(() => new CabinetOutputAssignment("plugin", (CabinetOutputRole)0, CabinetOutputMode.Player)); + } + private static PluginResourceDescriptor Descriptor(string id, string provider) => new PluginResourceDescriptor(id, provider, "controller", id, "backglass", ResourceKind.Surface, 1, 1); private sealed class Surface : IPluginSurface, ICabinetSurface { diff --git a/VisualPinball.Plugins/Api/CabinetDevices.cs b/VisualPinball.Plugins/Api/CabinetDevices.cs deleted file mode 100644 index 1cd8c8497d..0000000000 --- a/VisualPinball.Plugins/Api/CabinetDevices.cs +++ /dev/null @@ -1,53 +0,0 @@ -// Visual Pinball Engine -// Copyright (C) 2026 freezy and VPE Team -// -// SPDX-License-Identifier: MIT - -using System; -using System.Collections.Generic; -using System.Linq; - -namespace VisualPinball.Plugins -{ - /// Adapter-owned device configuration. Enumerating a profile must never open hardware. - public sealed class CabinetDeviceProfile - { - public string Id { get; } - public string Provider { get; } - public CabinetOutputRole Role { get; } - public string Label { get; } - public string LeaseKey { get; } - /// Optional conservative reservation shared by auto and explicit choices of one driver family. - public string FamilyLeaseKey { get; } - /// Opaque adapter-owned payload, detached from mutable settings; never contains handles or live state. - public string Configuration { get; } - public bool Available { get; } - public string Reason { get; } - public CabinetDeviceProfile(string id, string provider, CabinetOutputRole role, string label, string leaseKey, string familyLeaseKey, string configuration, bool available = true, string reason = "") - { - if (string.IsNullOrWhiteSpace(id) || string.IsNullOrWhiteSpace(provider) || !CabinetOutputRoles.IsDefined(role)) throw new ArgumentException("A device profile needs an ID, provider and role."); - if (available && string.IsNullOrWhiteSpace(leaseKey)) throw new ArgumentException("An available profile needs a canonical device lease key."); - if ((configuration?.Length ?? 0) > 65536) throw new ArgumentException("Device configuration exceeds 65536 characters."); - Id = id; Provider = provider; Role = role; Label = label ?? id; LeaseKey = leaseKey ?? ""; FamilyLeaseKey = familyLeaseKey ?? ""; - Configuration = configuration ?? ""; Available = available; Reason = reason ?? ""; - } - } - - public sealed class CabinetDeviceProfileRequest - { - public PluginSettingsSnapshot Settings { get; } - public IReadOnlyCollection SavedKeys { get; } - public string Platform { get; } - public CabinetDeviceProfileRequest(PluginSettingsSnapshot settings, IEnumerable savedKeys, string platform) - { - Settings = (settings ?? throw new ArgumentNullException(nameof(settings))).Copy(); - SavedKeys = Array.AsReadOnly((savedKeys ?? throw new ArgumentNullException(nameof(savedKeys))).ToArray()); Platform = platform ?? ""; - } - } - - /// Optional factory API. Profiles describe configuration capability, not physical presence or a successful probe. - public interface ICabinetDeviceProfileProvider - { - IReadOnlyList GetDeviceProfiles(CabinetDeviceProfileRequest request); - } -} diff --git a/VisualPinball.Plugins/Api/CabinetDevices.cs.meta b/VisualPinball.Plugins/Api/CabinetDevices.cs.meta deleted file mode 100644 index 3f1679a7ea..0000000000 --- a/VisualPinball.Plugins/Api/CabinetDevices.cs.meta +++ /dev/null @@ -1,2 +0,0 @@ -fileFormatVersion: 2 -guid: de7bb407e2584df39fc2e16978b4597f diff --git a/VisualPinball.Plugins/Api/CabinetDisplayImport.cs b/VisualPinball.Plugins/Api/CabinetDisplayImport.cs deleted file mode 100644 index 8db47c66a0..0000000000 --- a/VisualPinball.Plugins/Api/CabinetDisplayImport.cs +++ /dev/null @@ -1,58 +0,0 @@ -// Visual Pinball Engine -// Copyright (C) 2026 freezy and VPE Team -// -// SPDX-License-Identifier: MIT -// Licensed under MIT. See https://opensource.org/license/mit. - -using System; -using System.Collections.Generic; -using System.Linq; - -namespace VisualPinball.Plugins -{ - /// Read-only settings for a migration preview. Providers must not write files, create instances or open outputs. - public sealed class CabinetDisplayImportRequest - { - public PluginSettingsSnapshot Settings { get; } - public IReadOnlyCollection SavedKeys { get; } - public string Platform { get; } - public string GameKey { get; } - public CabinetDisplayImportRequest(PluginSettingsSnapshot settings, IEnumerable savedKeys, string platform, string gameKey = "") - { - Settings = (settings ?? throw new ArgumentNullException(nameof(settings))).Copy(); - SavedKeys = Array.AsReadOnly((savedKeys ?? throw new ArgumentNullException(nameof(savedKeys))).ToArray()); - Platform = platform ?? ""; GameKey = gameKey ?? ""; - } - } - - /// One adapter-described legacy output. Coordinates use physical virtual-desktop pixels, the same space as CabinetDisplayTarget; adapters must convert monitor-relative or DPI-scaled legacy values. No monitor identity is inferred here. - public sealed class CabinetDisplayImportCandidate - { - public CabinetOutputRole Role { get; } - public CabinetEndpointKind Kind { get; } - public int X { get; } - public int Y { get; } - public int Width { get; } - public int Height { get; } - public string DeviceProfileId { get; } - public string Note { get; } - public bool Supported { get; } - public CabinetDisplayImportCandidate(CabinetOutputRole role, int x, int y, int width, int height, string note = "", bool supported = true) - { - if (!CabinetOutputRoles.IsDefined(role)) throw new ArgumentException("An import candidate needs a role."); - Role = role; Kind = CabinetEndpointKind.DesktopRegion; X = x; Y = y; Width = width; Height = height; - DeviceProfileId = ""; Note = note ?? ""; Supported = supported && width > 0 && height > 0 && (long)x + width <= int.MaxValue && (long)y + height <= int.MaxValue; - } - public CabinetDisplayImportCandidate(CabinetOutputRole role, string deviceProfileId, string note = "", bool supported = true) - { - if (!CabinetOutputRoles.IsDefined(role) || string.IsNullOrWhiteSpace(deviceProfileId)) throw new ArgumentException("A device candidate needs a role and profile ID."); - Role = role; Kind = CabinetEndpointKind.Device; DeviceProfileId = deviceProfileId; Note = note ?? ""; Supported = supported; - } - } - - /// Optional factory capability for a user-reviewed migration. Never mutates legacy or external configuration. Playfield placement is outside this API and remains in Video. - public interface ICabinetDisplayImportProvider - { - IReadOnlyList GetDisplayImportCandidates(CabinetDisplayImportRequest request); - } -} diff --git a/VisualPinball.Plugins/Api/CabinetDisplayImport.cs.meta b/VisualPinball.Plugins/Api/CabinetDisplayImport.cs.meta deleted file mode 100644 index d7b1bf507a..0000000000 --- a/VisualPinball.Plugins/Api/CabinetDisplayImport.cs.meta +++ /dev/null @@ -1,2 +0,0 @@ -fileFormatVersion: 2 -guid: c76a7c4675464e65b669f58cdc328da4 diff --git a/VisualPinball.Plugins/Api/CabinetDisplays.cs b/VisualPinball.Plugins/Api/CabinetDisplays.cs index 23e24c7def..c8ea71d460 100644 --- a/VisualPinball.Plugins/Api/CabinetDisplays.cs +++ b/VisualPinball.Plugins/Api/CabinetDisplays.cs @@ -26,8 +26,6 @@ public enum CabinetOutputRole GameDisplay = 3, Topper = 4, ScorePanel = 5, - /// A cabinet video panel for DMD surrounds and media, distinct from the game LCD. - FullDmd = 6, } /// Conversion at the generic resource/persistence boundary. The cabinet API itself uses the enum. @@ -38,7 +36,6 @@ public static class CabinetOutputRoles CabinetOutputRole.Backglass => SurfaceRoles.Backglass, CabinetOutputRole.Dmd => SurfaceRoles.Dmd, CabinetOutputRole.GameDisplay => SurfaceRoles.GameDisplay, - CabinetOutputRole.FullDmd => SurfaceRoles.FullDmd, CabinetOutputRole.Topper => SurfaceRoles.Topper, CabinetOutputRole.ScorePanel => SurfaceRoles.ScorePanel, _ => throw new ArgumentOutOfRangeException(nameof(role)), @@ -49,7 +46,6 @@ public static bool TryParse(string id, out CabinetOutputRole role) case SurfaceRoles.Backglass: role = CabinetOutputRole.Backglass; return true; case SurfaceRoles.Dmd: role = CabinetOutputRole.Dmd; return true; case SurfaceRoles.GameDisplay: role = CabinetOutputRole.GameDisplay; return true; - case SurfaceRoles.FullDmd: role = CabinetOutputRole.FullDmd; return true; case SurfaceRoles.Topper: role = CabinetOutputRole.Topper; return true; case SurfaceRoles.ScorePanel: role = CabinetOutputRole.ScorePanel; return true; default: role = default; return false; @@ -61,47 +57,31 @@ public static CabinetOutputRole Parse(string id) /// Who places one plugin's physical output. Does not control its in-scene output. public enum CabinetOutputMode { Custom = 0, Player = 1, Off = 2 } - /// Physical destination; device drivers remain responsible for device protocols. - public enum CabinetEndpointKind { DesktopRegion = 0, Device = 1 } /// Availability of a configured destination, independent of its content source. public enum CabinetEndpointState { Unassigned = 0, Available = 1, Disabled = 2, Unavailable = 3 } - /// Immutable resolved destination. Desktop coordinates are physical pixels, including negative origins. + /// Immutable resolved destination: a region of the desktop, in physical pixels, including negative origins. + /// Physical DMD panels are not player destinations. Their plug-ins open them from their own settings. public sealed class CabinetDisplayTarget { public string EndpointId { get; } public CabinetOutputRole Role { get; } - public CabinetEndpointKind Kind { get; } public CabinetEndpointState State { get; } public string Reason { get; } public int X { get; } public int Y { get; } public int Width { get; } public int Height { get; } - /// Canonical provider-resolved lease key, never a guessed USB identifier. - public string DeviceLeaseKey { get; } - /// Adapter profile; null on targets made with the legacy public constructor. - public CabinetDeviceProfile? DeviceProfile { get; } - public CabinetDisplayTarget(string endpointId, CabinetOutputRole role, CabinetEndpointKind kind, CabinetEndpointState state, - int x = 0, int y = 0, int width = 0, int height = 0, string reason = "", string deviceLeaseKey = "") + public CabinetDisplayTarget(string endpointId, CabinetOutputRole role, CabinetEndpointState state, + int x = 0, int y = 0, int width = 0, int height = 0, string reason = "") { if (string.IsNullOrWhiteSpace(endpointId)) throw new ArgumentException("An endpoint needs an ID.", nameof(endpointId)); if (!CabinetOutputRoles.IsDefined(role)) throw new ArgumentException("An output needs a role.", nameof(role)); - if (!Enum.IsDefined(typeof(CabinetEndpointKind), kind)) throw new ArgumentOutOfRangeException(nameof(kind)); if (!Enum.IsDefined(typeof(CabinetEndpointState), state)) throw new ArgumentOutOfRangeException(nameof(state)); - if (state == CabinetEndpointState.Available && kind == CabinetEndpointKind.DesktopRegion && (width < 1 || height < 1)) throw new ArgumentOutOfRangeException(nameof(width)); - if (state == CabinetEndpointState.Available && kind == CabinetEndpointKind.Device && string.IsNullOrWhiteSpace(deviceLeaseKey)) throw new ArgumentException("An available device needs a canonical lease key.", nameof(deviceLeaseKey)); - EndpointId = endpointId; Role = role; Kind = kind; State = state; - X = x; Y = y; Width = width; Height = height; Reason = reason ?? ""; DeviceLeaseKey = deviceLeaseKey ?? ""; - } - private CabinetDisplayTarget(string endpointId, CabinetOutputRole role, CabinetEndpointState state, CabinetDeviceProfile? profile, string reason) - : this(endpointId, role, CabinetEndpointKind.Device, state, reason: reason, deviceLeaseKey: profile?.LeaseKey ?? "") { DeviceProfile = profile; } - public static CabinetDisplayTarget Device(string endpointId, CabinetOutputRole role, CabinetEndpointState state, CabinetDeviceProfile? profile, string reason = "") - { - if (profile != null && profile.Role != role) throw new ArgumentException("The profile role must match the target.", nameof(profile)); - if (state == CabinetEndpointState.Available && (profile == null || !profile.Available)) throw new ArgumentException("An available device needs an available profile.", nameof(profile)); - return new CabinetDisplayTarget(endpointId, role, state, profile, reason); + if (state == CabinetEndpointState.Available && (width < 1 || height < 1)) throw new ArgumentOutOfRangeException(nameof(width)); + EndpointId = endpointId; Role = role; State = state; + X = x; Y = y; Width = width; Height = height; Reason = reason ?? ""; } } @@ -111,15 +91,11 @@ public sealed class CabinetOutputAssignment public string PluginId { get; } public CabinetOutputRole Role { get; } public CabinetOutputMode Mode { get; } - public CabinetEndpointKind Kind { get; } public CabinetOutputAssignment(string pluginId, CabinetOutputRole role, CabinetOutputMode mode) - : this(pluginId, role, mode, CabinetEndpointKind.DesktopRegion) { } - public CabinetOutputAssignment(string pluginId, CabinetOutputRole role, CabinetOutputMode mode, CabinetEndpointKind kind) { if (string.IsNullOrWhiteSpace(pluginId) || !CabinetOutputRoles.IsDefined(role)) throw new ArgumentException("An assignment needs a plugin and role."); if (!Enum.IsDefined(typeof(CabinetOutputMode), mode)) throw new ArgumentOutOfRangeException(nameof(mode)); - if (!Enum.IsDefined(typeof(CabinetEndpointKind), kind)) throw new ArgumentOutOfRangeException(nameof(kind)); - PluginId = pluginId; Role = role; Mode = mode; Kind = kind; + PluginId = pluginId; Role = role; Mode = mode; } } @@ -142,19 +118,17 @@ public CabinetDisplaySnapshot(long revision, long topologyGeneration, long sessi var assignmentArray = (assignments ?? throw new ArgumentNullException(nameof(assignments))).ToArray(); if (targetArray.Any(value => value == null) || assignmentArray.Any(value => value == null)) throw new ArgumentException("Snapshot entries cannot be null."); if (targetArray.GroupBy(value => (value.EndpointId, value.Role)).Any(group => group.Count() > 1)) throw new ArgumentException("Duplicate endpoint/role target.", nameof(targets)); - if (assignmentArray.GroupBy(value => (value.PluginId, value.Role, value.Kind)).Any(group => group.Count() > 1)) throw new ArgumentException("Duplicate plugin/role/kind assignment.", nameof(assignments)); + if (assignmentArray.GroupBy(value => (value.PluginId, value.Role)).Any(group => group.Count() > 1)) throw new ArgumentException("Duplicate plugin/role assignment.", nameof(assignments)); Targets = Array.AsReadOnly(targetArray); Assignments = Array.AsReadOnly(assignmentArray); } public CabinetOutputMode ModeFor(string pluginId, CabinetOutputRole role) - => ModeFor(pluginId, role, CabinetEndpointKind.DesktopRegion); - public CabinetOutputMode ModeFor(string pluginId, CabinetOutputRole role, CabinetEndpointKind kind) { - foreach (var assignment in Assignments) if (assignment.PluginId == pluginId && assignment.Role == role && assignment.Kind == kind) return assignment.Mode; + foreach (var assignment in Assignments) if (assignment.PluginId == pluginId && assignment.Role == role) return assignment.Mode; return CabinetOutputMode.Custom; } - /// All destinations for this role, including unavailable ones; a monitor and device may mirror it. + /// All destinations for this role, including unavailable ones. public IReadOnlyList TargetsFor(CabinetOutputRole role) => Array.AsReadOnly(Targets.Where(target => target.Role == role).ToArray()); } From 0afaa60af75b37f3b53c6fafa6fa40ba6909a42f Mon Sep 17 00:00:00 2001 From: freezy Date: Fri, 6 Nov 2026 01:58:09 +0100 Subject: [PATCH 09/10] plugins: let plug-ins report the defaults they find on the system IPluginSystemDefaults lets a plug-in describe what it takes from other applications on this computer while its own settings are empty: folders, configuration files and the output placements they suggest. The Player shows them on its first start without knowing the plug-in, and the user can replace each one with the player's own value. Only read, never written back. --- .../Api/PluginSystemDefaults.cs | 81 +++++++++++++++++++ .../Api/PluginSystemDefaults.cs.meta | 2 + 2 files changed, 83 insertions(+) create mode 100644 VisualPinball.Plugins/Api/PluginSystemDefaults.cs create mode 100644 VisualPinball.Plugins/Api/PluginSystemDefaults.cs.meta diff --git a/VisualPinball.Plugins/Api/PluginSystemDefaults.cs b/VisualPinball.Plugins/Api/PluginSystemDefaults.cs new file mode 100644 index 0000000000..7920bff9a3 --- /dev/null +++ b/VisualPinball.Plugins/Api/PluginSystemDefaults.cs @@ -0,0 +1,81 @@ +// Visual Pinball Engine +// Copyright (C) 2026 freezy and VPE Team +// +// SPDX-License-Identifier: MIT +// Licensed under MIT. See https://opensource.org/license/mit. + +using System; +using System.Collections.Generic; +using System.Threading; + +namespace VisualPinball.Plugins +{ + /// + /// Optional on an (or its ): what the + /// plugin finds on this computer and uses while its own settings are empty, such as another application's folders or + /// configuration files. The Player shows the findings when it starts for the first time, so the user sees where their + /// defaults come from and can replace them with the player's own values. + /// + public interface IPluginSystemDefaults + { + /// + /// Looks for the plugin's defaults on this computer. Called on a worker thread, also while the plugin is switched off. + /// Only reads: never writes another application's files or settings. + /// + /// The plugin's effective global settings. + /// Cancelled when the Player no longer needs the result. + IReadOnlyList FindSystemDefaults(PluginSettingsSnapshot settings, CancellationToken cancellation); + } + + /// One thing a plugin found on this computer, or looked for and didn't find. + public sealed class PluginSystemDefault + { + /// What it is, such as AltSound. + /// Where it comes from, such as the application that set it up: VPinMAME. + public PluginSystemDefault(string title, string source) + { + Title = title ?? throw new ArgumentNullException(nameof(title)); + Source = source ?? ""; + } + + /// What it is, such as AltSound. + public string Title { get; } + /// Where it comes from, such as the application that set it up: VPinMAME. + public string Source { get; } + /// The folder or file found, or empty when nothing was found. + public string Path { get; set; } = ""; + /// Whether something was found. Without it, says what was looked for. + public bool Found => Path.Length > 0; + /// One line on what was found and what it is for, such as 12 replacement sound packs. + public string Description { get; set; } = ""; + /// + /// The plugin's global setting that replaces this default when set (a or + /// field), or null when the default can only be shown. + /// + public string? FieldId { get; set; } + /// + /// Whether the plugin uses this default by itself while is empty (the default). When false, the Player + /// saves the found path into once the user accepts the findings. + /// + public bool UsedWhenEmpty { get; set; } = true; + /// Where on the desktop the found configuration puts the plugin's cabinet outputs. + public IReadOnlyList Outputs { get; set; } = Array.Empty(); + } + + /// A cabinet output's placement in another application's configuration, in desktop pixels. + public readonly struct PluginSuggestedOutput + { + public PluginSuggestedOutput(CabinetOutputRole role, int x, int y, int width, int height) + { + Role = role; X = x; Y = y; Width = width; Height = height; + } + + public CabinetOutputRole Role { get; } + /// Left edge, in virtual desktop pixels (negative left of the primary monitor). + public int X { get; } + /// Top edge, in virtual desktop pixels. + public int Y { get; } + public int Width { get; } + public int Height { get; } + } +} diff --git a/VisualPinball.Plugins/Api/PluginSystemDefaults.cs.meta b/VisualPinball.Plugins/Api/PluginSystemDefaults.cs.meta new file mode 100644 index 0000000000..2d92b1153a --- /dev/null +++ b/VisualPinball.Plugins/Api/PluginSystemDefaults.cs.meta @@ -0,0 +1,2 @@ +fileFormatVersion: 2 +guid: 93b3feb85ea153945841755224a195e0 \ No newline at end of file From 1199a9ec3fa661fc6bff2c14b4efebb68d09370e Mon Sep 17 00:00:00 2001 From: freezy Date: Sat, 7 Nov 2026 01:19:46 +0100 Subject: [PATCH 10/10] doc: Full DMD isn't a cabinet output role The guide still listed FullDmd as a role, and device profiles and import candidates as enum users, though the contract dropped them. A plug-in that publishes a Full DMD surface opens its own window, and old full-dmd layout records are dropped on load. --- .../developer-guide/cabinet-display-outputs.md | 8 +++++--- 1 file changed, 5 insertions(+), 3 deletions(-) diff --git a/VisualPinball.Unity/Documentation~/developer-guide/cabinet-display-outputs.md b/VisualPinball.Unity/Documentation~/developer-guide/cabinet-display-outputs.md index f0c70a7e80..417fa0a3aa 100644 --- a/VisualPinball.Unity/Documentation~/developer-guide/cabinet-display-outputs.md +++ b/VisualPinball.Unity/Documentation~/developer-guide/cabinet-display-outputs.md @@ -22,12 +22,14 @@ The next Player phase adds persisted layout, Windows topology, browsing backglas ## Content transforms and a shared panel -The owned output texture can copy clockwise quarter-turn rotation and output-axis mirrors into a normalized viewport. The viewport uses bottom-left Unity UV coordinates; the Player converts its saved top-left percentages once. Inside the viewport, contain-fit bars are opaque black. Outside it, existing pixels are retained using an explicit color Load/Store action. This supports a Full DMD background and an independently selected DMD inset in one native window. The existing four-argument full-frame copy API remains available. Producer textures are unbound from the copy material immediately after submission. +The owned output texture can copy clockwise quarter-turn rotation and output-axis mirrors into a normalized viewport. The viewport uses bottom-left Unity UV coordinates; the Player converts its saved top-left percentages once. Inside the viewport, contain-fit bars are opaque black. Outside it, existing pixels are retained using an explicit color Load/Store action. This supports a background output and an independently selected inset, such as a DMD, in one native window. The existing four-argument full-frame copy API remains available. Producer textures are unbound from the copy material immediately after submission. Physical multi-monitor and rotated-panel certification remains outstanding. The test suite covers all eight dihedral transforms, asymmetric partial viewports and render-state restoration, alpha/color conversion, two native presenters and deferred output retirement on the available Windows D3D12 backend. Metal and Vulkan must pass their platform matrices before certification. ## Known output roles -The cabinet API uses the closed `CabinetOutputRole` enum: Backglass, Dmd, GameDisplay, FullDmd, Topper and ScorePanel. The game LCD/HD display, cabinet Full DMD video panel and backglass are independent destinations; none is inferred from image dimensions. GameDisplay uses ordinary texture presentation, without DMD dot processing. Playfield placement remains in Video. +The cabinet API uses the closed `CabinetOutputRole` enum: Backglass, Dmd, GameDisplay, Topper and ScorePanel. The game LCD/HD display and the backglass are independent destinations; neither is inferred from image dimensions. GameDisplay uses ordinary texture presentation, without DMD dot processing. Playfield placement remains in Video. -Generic resource descriptors and authored custom scene bindings retain string IDs for compatibility. Convert only known IDs with `CabinetOutputRoles.TryParse` at that boundary. Shared targets, assignments, device profiles, import candidates and factory role declarations use the enum. Private plug-in screens stay inside the plug-in and cannot become arbitrary global cabinet settings. Stable string IDs in saved JSON remain compatible, including separate `game-display` and `full-dmd` records. +Full DMD is not a cabinet role. A plug-in that publishes a Full DMD scene surface (`SurfaceRoles.FullDmd`) opens its own window for it, and `CabinetOutputRoles.TryParse` rejects `full-dmd`. + +Generic resource descriptors and authored custom scene bindings retain string IDs for compatibility. Convert only known IDs with `CabinetOutputRoles.TryParse` at that boundary. Shared targets, assignments and factory role declarations use the enum. Private plug-in screens stay inside the plug-in and cannot become arbitrary global cabinet settings. Saved JSON keeps the stable string IDs, such as `game-display`. Records whose ID isn't a role, such as older `full-dmd` entries, are dropped when the Player loads a layout.