Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
59 changes: 48 additions & 11 deletions VisualPinball.Engine.DMD.Unity/Runtime/DmdBridgePlayer.cs
Original file line number Diff line number Diff line change
Expand Up @@ -116,12 +116,15 @@ public class DmdBridgePlayer : MonoBehaviour, IDiagnosticsSource
private DmdBridgeSettings _settings;
private DmdBridgeSettings _appliedSettings;
private DmdBridgeSettings _lastFallbackSettings;
/// <summary>The stacking set on the component over the INI's, until the INI changes; null while the INI's holds.</summary>
private bool? _stayOnTopOverride;
private DateTime _appliedConfigWriteTimeUtc;
private string _appliedConfigPath;
private bool _missingDisplayWarningLogged;
private bool _nativeWindowWarningLogged;
private bool _missingConfigWarningLogged;
private float _nextNativeWindowLayoutSyncTime;
private float _nextRestackTime;
private float _suppressNativeWindowLayoutSyncUntil;
private bool _defaultAltColorPathResolved;
private string _defaultAltColorPath;
Expand Down Expand Up @@ -237,7 +240,12 @@ private void Update()
{
// Drives a host-pumped native window (macOS/SDL) on the main thread; no-op on the
// self-driven Windows backend. Must run every frame.
(_managed ? _managedInput?.Pipeline as DmdPipeline : _pipeline)?.PumpMainThread();
var pipeline = _managed ? _managedInput?.Pipeline as DmdPipeline : _pipeline;
pipeline?.PumpMainThread();
if (pipeline != null && Time.unscaledTime >= _nextRestackTime) {
_nextRestackTime = Time.unscaledTime + SettingsCheckInterval;
pipeline.RestackNativeWindows(_settings?.NativeWindowStayOnTop ?? false);
}
if (_managed || PlayerIntegrationMode.HostManaged) return;

// Settings (component fields + DmdDevice.ini) change rarely; checking ~4x/sec keeps the
Expand Down Expand Up @@ -739,6 +747,10 @@ private DmdBridgeSettings LoadSettings()
Logger.Info("[DMD] No DmdDevice.ini found at {Path:l}, using component settings.", configPath);
_missingConfigWarningLogged = true;
}
// without the INI only the component counts, and a restored INI is read anew
_appliedConfigPath = null;
_appliedConfigWriteTimeUtc = default;
_stayOnTopOverride = null;
_lastFallbackSettings = fallback.Clone();
return fallback;
}
Expand All @@ -755,12 +767,18 @@ private DmdBridgeSettings LoadSettings()
return _settings;
}

var iniChanged = !string.Equals(_appliedConfigPath, configPath, StringComparison.Ordinal) || _appliedConfigWriteTimeUtc != writeTimeUtc;
_appliedConfigPath = configPath;
_appliedConfigWriteTimeUtc = writeTimeUtc;
var fallbackChanged = _lastFallbackSettings != null && !fallback.Equals(_lastFallbackSettings);
var settings = DmdBridgeConfig.Load(configPath, fallback);
if (iniChanged) {
// the INI was edited since: what it says now holds, as for the rest of the presentation, unless the
// stacking also changed on the component
_stayOnTopOverride = null;
}
if (fallbackChanged) {
CopyPresentationSettings(fallback, settings);
_stayOnTopOverride = ApplyComponentPresentation(_lastFallbackSettings, fallback, settings, _stayOnTopOverride);
Comment thread
coderabbitai[bot] marked this conversation as resolved.
Resolved
}
_lastFallbackSettings = fallback.Clone();
return settings;
Expand Down Expand Up @@ -874,30 +892,31 @@ private void SyncNativeWindowLayout()
}

_nextNativeWindowLayoutSyncTime = Time.unscaledTime + 0.15f;
if (!_pipeline.TryReadNativeWindowLayout(out var left, out var top, out var width, out var height, out var stayOnTop, out var isMovingOrSizing)
// the window's stacking isn't the user's to change there, and over the player's window it's kept on top whatever
// the setting: only where it was moved to goes back into the settings
if (!_pipeline.TryReadNativeWindowLayout(out var left, out var top, out var width, out var height, out _, out var isMovingOrSizing)
|| isMovingOrSizing) {
return;
}

if (_nativeWindowLeft == left
&& _nativeWindowTop == top
&& _nativeWindowWidth == width
&& _nativeWindowHeight == height
&& _nativeWindowStayOnTop == stayOnTop) {
&& _nativeWindowHeight == height) {
return;
}

_nativeWindowLeft = left;
_nativeWindowTop = top;
_nativeWindowWidth = width;
_nativeWindowHeight = height;
_nativeWindowStayOnTop = stayOnTop;
CopyPresentationSettingsTo(_settings);
CopyPresentationSettingsTo(_appliedSettings);
CopyPresentationSettingsTo(_lastFallbackSettings);
CopyNativeWindowBoundsTo(_settings);
CopyNativeWindowBoundsTo(_appliedSettings);
CopyNativeWindowBoundsTo(_lastFallbackSettings);
}

private void CopyPresentationSettingsTo(DmdBridgeSettings settings)
// Not the stacking: that stays what the settings say, which can come from DmdDevice.ini rather than this component.
private void CopyNativeWindowBoundsTo(DmdBridgeSettings settings)
{
if (settings == null) {
return;
Expand All @@ -907,7 +926,25 @@ private void CopyPresentationSettingsTo(DmdBridgeSettings settings)
settings.NativeWindowTop = _nativeWindowTop;
settings.NativeWindowWidth = _nativeWindowWidth;
settings.NativeWindowHeight = _nativeWindowHeight;
settings.NativeWindowStayOnTop = _nativeWindowStayOnTop;
}

/// <summary>
/// The component's look and placement over what DmdDevice.ini says, once one of the component's settings changed.
/// The stacking only once it was changed on the component: the window's own isn't read back into the component,
/// so its value can still be the default under an INI's <c>stayontop</c>. Changed there, it holds through the
/// component's other changes.
/// </summary>
/// <param name="stayOnTopOverride">The stacking changed on the component before, null if it wasn't</param>
/// <returns>The stacking changed on the component so far, null if it wasn't</returns>
internal static bool? ApplyComponentPresentation(DmdBridgeSettings previous, DmdBridgeSettings component, DmdBridgeSettings target, bool? stayOnTopOverride)
{
var stayOnTop = target.NativeWindowStayOnTop;
CopyPresentationSettings(component, target);
if (previous == null || component.NativeWindowStayOnTop != previous.NativeWindowStayOnTop) {
return component.NativeWindowStayOnTop;
}
target.NativeWindowStayOnTop = stayOnTopOverride ?? stayOnTop;
return stayOnTopOverride;
}

private static void CopyPresentationSettings(DmdBridgeSettings source, DmdBridgeSettings target)
Expand Down
15 changes: 15 additions & 0 deletions VisualPinball.Engine.DMD.Unity/Runtime/DmdPipeline.cs
Original file line number Diff line number Diff line change
Expand Up @@ -177,6 +177,21 @@ public void ApplySettings(DmdBridgeSettings settings)
}
}

/// <summary>
/// Keeps the native windows above the player's window where they lie over it, wherever they were moved, and gives the
/// others the stacking set for them.
/// </summary>
public void RestackNativeWindows(bool stayOnTop)
{
foreach (var destination in _destinations) {
if (destination is INativeDmdWindow window && !window.IsMovingOrSizing) {
int left = window.WindowLeft, top = window.WindowTop, width = window.WindowWidth, height = window.WindowHeight;
bool onTop = PlayerWindow.OnTop(stayOnTop, left, top, width, height);
if (window.WindowStayOnTop != onTop) window.ConfigureWindow(new DmdWindowLayout(left, top, width, height, onTop));
}
}
}

public bool TryReadNativeWindowLayout(out int left, out int top, out int width, out int height, out bool stayOnTop, out bool isMovingOrSizing)
{
foreach (var destination in _destinations) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -35,7 +35,7 @@ public static DmdWindowLayout CreateLayout(DmdBridgeSettings settings)
settings.NativeWindowTop,
settings.NativeWindowWidth,
settings.NativeWindowHeight,
settings.NativeWindowStayOnTop);
PlayerWindow.OnTop(settings.NativeWindowStayOnTop, settings.NativeWindowLeft, settings.NativeWindowTop, settings.NativeWindowWidth, settings.NativeWindowHeight));
}

public static DmdWindowStyle CreateStyle(DmdBridgeSettings settings)
Expand Down
78 changes: 78 additions & 0 deletions VisualPinball.Engine.DMD.Unity/Runtime/PlayerWindow.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,78 @@
// 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.Runtime.InteropServices;
using System.Text;
using UnityEngine;

namespace VisualPinball.Engine.DMD.Unity
{
/// <summary>
/// The window the player draws the game in, which the native DMD window must stay above where they overlap. Without
/// "Keep on top", the player's window covered it each time it took the focus, such as when the game started.
/// </summary>
internal static class PlayerWindow
{
private const string UnityWindowClass = "UnityWndClass"; // the player's own; the DMD's and other outputs' have their own
private static IntPtr _window;

/// <summary>Whether the native DMD window stays on top: as set, and always where it lies over the player's window.</summary>
internal static bool OnTop(bool stayOnTop, RectInt window, RectInt? player)
=> stayOnTop || player is { } bounds && bounds.Overlaps(window);

internal static bool OnTop(bool stayOnTop, int left, int top, int width, int height)
=> stayOnTop || OnTop(false, new RectInt(left, top, width, height), Bounds());

/// <summary>
/// Where the player's window is on the desktop, in physical pixels. Null in the editor, on other platforms, while it is
/// minimized or hidden, and in exclusive fullscreen, which no window shows over, like the Player's own outputs.
/// </summary>
internal static RectInt? Bounds()
{
try {
if (Application.platform != RuntimePlatform.WindowsPlayer || Screen.fullScreenMode == FullScreenMode.ExclusiveFullScreen) return null;
if (_window == IntPtr.Zero || !IsWindow(_window)) _window = Find();
if (_window == IntPtr.Zero || !IsWindowVisible(_window) || IsIconic(_window)) return null;
// what shows of it: a framed window's rectangle takes in the resize borders, which are invisible, so a DMD
// right next to it would count as over it
if (DwmGetWindowAttribute(_window, ExtendedFrameBounds, out var rect, Marshal.SizeOf<NativeRect>()) != 0
&& !GetWindowRect(_window, out rect)) return null;
return new RectInt(rect.Left, rect.Top, rect.Right - rect.Left, rect.Bottom - rect.Top);
} catch (Exception) {
return null; // off the main thread, where Unity's screen can't be asked: the next restack on it decides
}
}

private static IntPtr Find()
{
uint process = (uint)System.Diagnostics.Process.GetCurrentProcess().Id;
var found = IntPtr.Zero;
var name = new StringBuilder(64);
EnumWindows((window, _) => {
GetWindowThreadProcessId(window, out uint owner);
if (owner != process) return true;
name.Clear();
if (GetClassName(window, name, name.Capacity) == 0 || name.ToString() != UnityWindowClass) return true;
found = window;
return false;
}, IntPtr.Zero);
return found;
}

[StructLayout(LayoutKind.Sequential)] private struct NativeRect { public int Left, Top, Right, Bottom; }
private delegate bool EnumWindowsProc(IntPtr window, IntPtr data);
[DllImport("user32.dll")] private static extern bool EnumWindows(EnumWindowsProc callback, IntPtr data);
[DllImport("user32.dll")] private static extern uint GetWindowThreadProcessId(IntPtr window, out uint process);
[DllImport("user32.dll", CharSet = CharSet.Unicode)] private static extern int GetClassName(IntPtr window, StringBuilder name, int count);
[DllImport("user32.dll")] private static extern bool IsWindow(IntPtr window);
[DllImport("user32.dll")] private static extern bool IsWindowVisible(IntPtr window);
[DllImport("user32.dll")] private static extern bool IsIconic(IntPtr window);
[DllImport("user32.dll")] private static extern bool GetWindowRect(IntPtr window, out NativeRect rect);
private const int ExtendedFrameBounds = 9; // DWMWA_EXTENDED_FRAME_BOUNDS
[DllImport("dwmapi.dll")] private static extern int DwmGetWindowAttribute(IntPtr window, int attribute, out NativeRect rect, int size);
}
}
2 changes: 2 additions & 0 deletions VisualPinball.Engine.DMD.Unity/Runtime/PlayerWindow.cs.meta

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

Original file line number Diff line number Diff line change
Expand Up @@ -47,6 +47,7 @@ private static PluginField Hardware(string id, string label, SettingKind kind, J
{
var field = Field(id, label, kind, value, provider, minimum, maximum); field.Scope = ConfigurationScope.GlobalOnly; return field;
}
private static PluginField Describe(PluginField field, string description) { field.Description = description; return field; }
private static PluginField Coordinate(string id, string label, string row, int value, double? minimum = null, double? maximum = null)
{
var field = Field(id, label, SettingKind.Integer, value, minimum: minimum, maximum: maximum); field.Row = row; return field;
Expand All @@ -63,7 +64,7 @@ private static PluginField Coordinate(string id, string label, string row, int v
Field("EnableNativeWindow", "Native borderless window", SettingKind.Boolean, false),
Coordinate("NativeWindowLeft", "Left", "native-position", 100), Coordinate("NativeWindowTop", "Top", "native-position", 100),
Coordinate("NativeWindowWidth", "Width", "native-size", 512, minimum: 1, maximum: 16384), Coordinate("NativeWindowHeight", "Height", "native-size", 128, minimum: 1, maximum: 16384),
Field("NativeWindowStayOnTop", "Keep on top", SettingKind.Boolean, false), Field("FlipHorizontally", "Mirror horizontally", SettingKind.Boolean, false)),
Describe(Field("NativeWindowStayOnTop", "Keep on top", SettingKind.Boolean, false), "Keeps the window above other applications. Over the player's own window it always stays on top, except in exclusive fullscreen."), Field("FlipHorizontally", "Mirror horizontally", SettingKind.Boolean, false)),
new PluginSettingsGroup("Cabinet hardware", "Outputs are acquired exclusively. A disabled plugin opens no device.",
Hardware("EnableZeDmd", "ZeDMD", SettingKind.Boolean, false), Hardware("ZeDmdPort", "ZeDMD port", SettingKind.Text, ""), Hardware("ZeDmdBrightness", "ZeDMD brightness", SettingKind.Integer, 8, minimum: 0, maximum: 15), Hardware("ZeDmdDebug", "ZeDMD diagnostics", SettingKind.Boolean, false),
Hardware("EnablePinDmd3", "PinDMD 3", SettingKind.Boolean, false), Hardware("PinDmd3Port", "PinDMD 3 port", SettingKind.Text, ""),
Expand Down
Loading
Loading