-
Notifications
You must be signed in to change notification settings - Fork 11
/
Copy pathGorgonDirectInputDriver.cs
244 lines (213 loc) · 10.3 KB
/
GorgonDirectInputDriver.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
#region MIT
//
// Gorgon
// Copyright (C) 2015 Michael Winsor
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
//
// Created: Sunday, September 13, 2015 1:47:57 PM
//
#endregion
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using Gorgon.Diagnostics;
using Gorgon.Input.DirectInput.Properties;
using DI = SharpDX.DirectInput;
namespace Gorgon.Input.DirectInput;
/// <summary>
/// The driver for DirectInput functionality.
/// </summary>
/// <remarks>
/// This driver will enumerate all gaming devices except those covered by the XInput driver. To use those devices, use the XInput driver directly.
/// </remarks>
internal sealed class GorgonDirectInputDriver
: GorgonGamingDeviceDriver
{
#region Variables.
// Primary direct input interface.
private Lazy<DI.DirectInput> _directInput;
// List of xinput device ID values.
private readonly Lazy<IEnumerable<string>> _xinputDeviceIDs;
// The available axis mappings for the individual gaming devices.
private readonly Dictionary<IGorgonGamingDeviceInfo, IReadOnlyDictionary<GamingDeviceAxis, DI.DeviceObjectId>> _axisMappings =
new();
#endregion
#region Methods.
#if FALSE // This code does not work with .NET 5 - System.Management does not work on .NET 5 (another screw up by Microsoft, it's SUPPOSED to work).
/// <summary>
/// Function to build the device ID for an XInput device.
/// </summary>
/// <param name="deviceName">The device name from WMI.</param>
/// <param name="pidIndex">The index of the PID in the WMI device ID.</param>
/// <param name="vidIndex">The index of the VID in the WMI device ID.</param>
/// <returns>A string containing the PID and VID portions of the device ID.</returns>
private static string GetXInputDeviceID(string deviceName, int pidIndex, int vidIndex)
{
var buffer = new StringBuilder();
string pidValue = deviceName.Substring(pidIndex + 4, 4);
string vidValue = deviceName.Substring(vidIndex + 4, 4);
buffer.Append(pidValue);
buffer.Append(vidValue);
return buffer.ToString();
}
#endif
/// <summary>
/// Function to build a list of XInput device ID values.
/// </summary>
/// <returns>A list of XInput device ID values.</returns>
private static IEnumerable<string> GetXInputDeviceIDs()
{
#if FALSE // This code does not work with .NET 5 - System.Management does not work on .NET 5 (another screw up by Microsoft, it's SUPPOSED to work).
// This monstrosity is based on the code at:
// https://msdn.microsoft.com/en-ca/library/windows/desktop/ee417014(v=vs.85).aspx
//
using var search = new ManagementObjectSearcher("SELECT DeviceID FROM Win32_PnPEntity");
IEnumerable<string> xinputDevices = (from pnpDevice in search.Get().Cast<ManagementBaseObject>()
let deviceID = pnpDevice.GetPropertyValue("DeviceID")
where deviceID is string
let deviceName = deviceID.ToString()
let pidIndex = deviceName.IndexOf("PID_", StringComparison.OrdinalIgnoreCase)
let vidIndex = deviceName.IndexOf("VID_", StringComparison.OrdinalIgnoreCase)
where deviceName.IndexOf("IG_", StringComparison.OrdinalIgnoreCase) != -1
&& pidIndex != -1
&& vidIndex != -1
select GetXInputDeviceID(deviceName, pidIndex, vidIndex))
.ToArray();
return xinputDevices;
#endif
#pragma warning disable IDE0022 // Use expression body for methods
return Array.Empty<string>();
#pragma warning restore IDE0022 // Use expression body for methods
}
/// <summary>
/// Function to determine if the device is an XInput controller.
/// </summary>
/// <param name="device">Device to evaluate.</param>
/// <returns><b>true</b> if the device is an xinput controller, <b>false</b> if not.</returns>
private bool IsXInputController(DI.DeviceInstance device)
{
StringBuilder buffer = new StringBuilder(device.ProductGuid.ToString()).Remove(0, 8);
foreach (string deviceID in _xinputDeviceIDs.Value)
{
buffer.Insert(0, deviceID);
if (new Guid(buffer.ToString()) == device.ProductGuid)
{
return true;
}
buffer.Remove(0, 8);
}
return false;
}
/// <summary>Releases unmanaged and - optionally - managed resources.</summary>
/// <param name="disposing">
/// <c>true</c> to release both managed and unmanaged resources; <c>false</c> to release only unmanaged resources.</param>
protected override void Dispose(bool disposing)
{
if (!disposing)
{
return;
}
Lazy<DI.DirectInput> di = Interlocked.Exchange(ref _directInput, null);
if ((di is null) || (!di.IsValueCreated))
{
return;
}
di.Value.Dispose();
}
/// <summary>
/// Function to enumerate the gaming devices supported by this driver.
/// </summary>
/// <param name="connectedOnly">[Optional] <b>true</b> to only enumerate devices that are connected, or <b>false</b> to enumerate all devices.</param>
/// <returns>A read only list of gaming device info values.</returns>
/// <remarks>
/// This will return only the devices supported by the driver. In some cases, the driver may not return a complete listing of all gaming devices attached to the system because the underlying provider
/// may not support those device types.
/// </remarks>
public override IReadOnlyList<IGorgonGamingDeviceInfo> EnumerateGamingDevices(bool connectedOnly = false)
{
IList<DI.DeviceInstance> devices = _directInput.Value.GetDevices(DI.DeviceClass.GameControl, DI.DeviceEnumerationFlags.AttachedOnly);
Log.Print("Enumerating DirectInput gaming devices...", LoggingLevel.Verbose);
bool FilterDiDevices(DI.DeviceInstance device)
{
bool notXInputController = !IsXInputController(device);
if (!notXInputController)
{
Log.Print("WARNING: Found XInput controller. The Direct Input driver does not support this type of controller. Skipping...", LoggingLevel.Verbose);
return false;
}
bool isAttached = _directInput.Value.IsDeviceAttached(device.InstanceGuid);
if ((connectedOnly) || (isAttached))
{
return true;
}
Log.Print($"WARNING: Found gaming device '{device.ProductName}', but it is not attached and enumeration is filtered for attached devices only. Skipping...",
LoggingLevel.Verbose);
return false;
}
DirectInputDeviceInfo CreateDeviceInfo(DI.DeviceInstance device)
{
var info = new DirectInputDeviceInfo(device);
using (var joystick = new DI.Joystick(_directInput.Value, info.DeviceID))
{
_axisMappings[info] = info.GetDeviceCaps(joystick);
Log.Print($"Found DirectInput gaming device \"{info.Description}\"", LoggingLevel.Verbose);
}
return info;
}
// Enumerate all controllers.
IReadOnlyList<DirectInputDeviceInfo> result = devices.Where(FilterDiDevices)
.Select(CreateDeviceInfo)
.ToArray();
return result;
}
/// <summary>
/// Function to create a <see cref="GorgonGamingDevice"/> object.
/// </summary>
/// <param name="gamingDeviceInfo">The <see cref="IGorgonGamingDeviceInfo"/> used to determine which device to associate with the resulting object.</param>
/// <returns>A <see cref="GorgonGamingDevice"/> representing the data from the physical device.</returns>
/// <remarks>
/// <para>
/// This will create a new instance of a <see cref="IGorgonGamingDevice"/> which will relay data from the physical device using the native provider.
/// </para>
/// <para>
/// Some devices may allocate native resources in order to communicate with the underlying native providers, and because of this, it is important to call the <see cref="IDisposable.Dispose"/> method
/// on the object when you are done with the object so that those resources may be freed.
/// </para>
/// </remarks>
public override IGorgonGamingDevice CreateGamingDevice(IGorgonGamingDeviceInfo gamingDeviceInfo)
=> new DirectInputDevice(gamingDeviceInfo, _directInput.Value, _axisMappings[gamingDeviceInfo])
{
// Attempt to acquire the device immediately.
IsAcquired = true
};
#endregion
#region Constructor/Finalizer.
/// <summary>
/// Initializes a new instance of the <see cref="GorgonDirectInputDriver"/> class.
/// </summary>
public GorgonDirectInputDriver()
: base(Resources.GORINP_DI_DESC)
{
_directInput = new Lazy<DI.DirectInput>(() => new DI.DirectInput(), true);
_xinputDeviceIDs = new Lazy<IEnumerable<string>>(GetXInputDeviceIDs, true);
}
#endregion
}