diff --git a/CHANGELOG.md b/CHANGELOG.md index 36d105fff3..d582491a18 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -8,6 +8,12 @@ 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. + - 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. @@ -207,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.Plugins.Test/CabinetDisplayTests.cs b/VisualPinball.Plugins.Test/CabinetDisplayTests.cs new file mode 100644 index 0000000000..c52340515e --- /dev/null +++ b/VisualPinball.Plugins.Test/CabinetDisplayTests.cs @@ -0,0 +1,103 @@ +// 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", CabinetOutputRole.Backglass, CabinetOutputMode.Player) }; + 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, 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", CabinetOutputRole.Topper, CabinetOutputMode.Player); + Assert.Throws(() => new CabinetDisplaySnapshot(1, 1, 1, Array.Empty(), new[] { adoption, adoption })); + 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 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] + 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); + } + + [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 + { + 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..c8ea71d460 --- /dev/null +++ b/VisualPinball.Plugins/Api/CabinetDisplays.cs @@ -0,0 +1,154 @@ +// 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"; + } + + /// 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, + } + + /// 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.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.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 } + /// Availability of a configured destination, independent of its content source. + public enum CabinetEndpointState { Unassigned = 0, Available = 1, Disabled = 2, Unavailable = 3 } + + /// 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 CabinetEndpointState State { get; } + public string Reason { get; } + public int X { get; } + public int Y { get; } + public int Width { get; } + public int Height { get; } + + 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(CabinetEndpointState), state)) throw new ArgumentOutOfRangeException(nameof(state)); + 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 ?? ""; + } + } + + /// Explicit adoption of one plugin output; absence always means Custom. + public sealed class CabinetOutputAssignment + { + public string PluginId { get; } + public CabinetOutputRole Role { get; } + public CabinetOutputMode Mode { get; } + public CabinetOutputAssignment(string pluginId, CabinetOutputRole role, CabinetOutputMode mode) + { + 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)); + 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, CabinetOutputRole 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. + 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; } + } + + /// 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/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 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..d5947b350d 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. @@ -936,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 new file mode 100644 index 0000000000..417fa0a3aa --- /dev/null +++ b/VisualPinball.Unity/Documentation~/developer-guide/cabinet-display-outputs.md @@ -0,0 +1,35 @@ +# 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. + +## 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 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, 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. + +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. 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/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..3316583b80 --- /dev/null +++ b/VisualPinball.Unity/VisualPinball.Unity.Test/Rendering/CabinetOutputTextureTests.cs @@ -0,0 +1,186 @@ +// 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); } + } + + [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); + 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.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/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; 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/NativeWindows/CabinetOutputTexture.cs b/VisualPinball.Unity/VisualPinball.Unity/NativeWindows/CabinetOutputTexture.cs new file mode 100644 index 0000000000..31b53faca7 --- /dev/null +++ b/VisualPinball.Unity/VisualPinball.Unity/NativeWindows/CabinetOutputTexture.cs @@ -0,0 +1,126 @@ +// 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 UnityEngine.Rendering; +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 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. + 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) + => 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)); + 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; + 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("_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; + 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() + { + 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/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/Plugins/CabinetScreenBinder.cs b/VisualPinball.Unity/VisualPinball.Unity/Plugins/CabinetScreenBinder.cs index 812d73e6c6..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; @@ -166,7 +180,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(); } } @@ -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,21 +266,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(role) ?? Array.Empty(), 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..aa8778c007 --- /dev/null +++ b/VisualPinball.Unity/VisualPinball.Unity/Resources/CabinetOutput.shader @@ -0,0 +1,49 @@ +// Visual Pinball Engine +// Copyright (C) 2026 freezy and VPE Team +// +// SPDX-License-Identifier: MIT + +Shader "VisualPinball/CabinetOutput" +{ + Properties { _MainTex ("Source", 2D) = "black" {} } + SubShader + { + Cull Off ZWrite Off ZTest Always + Pass + { + Blend SrcAlpha OneMinusSrcAlpha + CGPROGRAM + #pragma vertex vert_img + #pragma fragment frag + #include "UnityCG.cginc" + sampler2D _MainTex; + 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(_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. + 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: 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;