|
| 1 | +using System; |
| 2 | +using System.Runtime.InteropServices; |
| 3 | +using PadForge.Engine; |
| 4 | + |
| 5 | +namespace PadForge.Common.Input |
| 6 | +{ |
| 7 | + /// <summary> |
| 8 | + /// Virtual controller that sends MIDI messages (CC for axes, Note On/Off for buttons) |
| 9 | + /// to a Windows MIDI output port (e.g., loopMIDI virtual port). |
| 10 | + /// Uses winmm P/Invoke — no external dependencies. |
| 11 | + /// </summary> |
| 12 | + internal sealed class MidiVirtualController : IVirtualController |
| 13 | + { |
| 14 | + // winmm P/Invoke |
| 15 | + [DllImport("winmm.dll")] |
| 16 | + private static extern int midiOutGetNumDevs(); |
| 17 | + |
| 18 | + [DllImport("winmm.dll", CharSet = CharSet.Unicode)] |
| 19 | + private static extern int midiOutGetDevCapsW(uint uDeviceID, ref MIDIOUTCAPS lpMidiOutCaps, int cbMidiOutCaps); |
| 20 | + |
| 21 | + [DllImport("winmm.dll")] |
| 22 | + private static extern int midiOutOpen(out IntPtr lphmo, uint uDeviceID, IntPtr dwCallback, IntPtr dwCallbackInstance, int dwFlags); |
| 23 | + |
| 24 | + [DllImport("winmm.dll")] |
| 25 | + private static extern int midiOutClose(IntPtr hmo); |
| 26 | + |
| 27 | + [DllImport("winmm.dll")] |
| 28 | + private static extern int midiOutShortMsg(IntPtr hmo, uint dwMsg); |
| 29 | + |
| 30 | + [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)] |
| 31 | + private struct MIDIOUTCAPS |
| 32 | + { |
| 33 | + public ushort wMid; |
| 34 | + public ushort wPid; |
| 35 | + public uint vDriverVersion; |
| 36 | + [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 32)] |
| 37 | + public string szPname; |
| 38 | + public ushort wTechnology; |
| 39 | + public ushort wVoices; |
| 40 | + public ushort wNotes; |
| 41 | + public ushort wChannelMask; |
| 42 | + public uint dwSupport; |
| 43 | + } |
| 44 | + |
| 45 | + // MIDI status bytes |
| 46 | + private const byte NoteOff = 0x80; |
| 47 | + private const byte NoteOn = 0x90; |
| 48 | + private const byte ControlChange = 0xB0; |
| 49 | + |
| 50 | + private IntPtr _handle; |
| 51 | + private readonly uint _deviceId; |
| 52 | + private readonly int _channel; // 0-15 |
| 53 | + private bool _connected; |
| 54 | + private bool _disposed; |
| 55 | + |
| 56 | + // Change detection — only send messages when values actually change. |
| 57 | + private readonly byte[] _lastCcValues = new byte[6]; // LX, LY, LT, RX, RY, RT |
| 58 | + private ushort _lastButtons; |
| 59 | + |
| 60 | + // Default CC mappings: LX=1, LY=2, LT=3, RX=4, RY=5, RT=6 |
| 61 | + // These can be customized via MidiSlotConfig. |
| 62 | + internal int[] CcNumbers { get; set; } = { 1, 2, 3, 4, 5, 6 }; |
| 63 | + |
| 64 | + // Default note mappings: A=60, B=61, X=62, Y=63, LB=64, RB=65, Back=66, Start=67, LS=68, RS=69, Guide=70 |
| 65 | + internal int[] NoteNumbers { get; set; } = { 60, 61, 62, 63, 64, 65, 66, 67, 68, 69, 70 }; |
| 66 | + |
| 67 | + // Note velocity for button presses. |
| 68 | + internal byte Velocity { get; set; } = 127; |
| 69 | + |
| 70 | + public VirtualControllerType Type => VirtualControllerType.Midi; |
| 71 | + public bool IsConnected => _connected; |
| 72 | + |
| 73 | + public MidiVirtualController(uint deviceId, int channel) |
| 74 | + { |
| 75 | + _deviceId = deviceId; |
| 76 | + _channel = Math.Clamp(channel, 0, 15); |
| 77 | + } |
| 78 | + |
| 79 | + public void Connect() |
| 80 | + { |
| 81 | + if (_connected) return; |
| 82 | + int result = midiOutOpen(out _handle, _deviceId, IntPtr.Zero, IntPtr.Zero, 0); |
| 83 | + if (result != 0) |
| 84 | + throw new InvalidOperationException($"midiOutOpen failed with error {result} for device {_deviceId}"); |
| 85 | + _connected = true; |
| 86 | + |
| 87 | + // Initialize change detection to neutral values. |
| 88 | + for (int i = 0; i < _lastCcValues.Length; i++) |
| 89 | + _lastCcValues[i] = 64; // center for axes |
| 90 | + _lastButtons = 0; |
| 91 | + } |
| 92 | + |
| 93 | + public void Disconnect() |
| 94 | + { |
| 95 | + if (!_connected) return; |
| 96 | + _connected = false; |
| 97 | + |
| 98 | + // Send Note Off for any held buttons. |
| 99 | + for (int i = 0; i < 11 && i < NoteNumbers.Length; i++) |
| 100 | + { |
| 101 | + if ((_lastButtons & (1 << i)) != 0) |
| 102 | + SendNoteOff(NoteNumbers[i]); |
| 103 | + } |
| 104 | + _lastButtons = 0; |
| 105 | + |
| 106 | + if (_handle != IntPtr.Zero) |
| 107 | + { |
| 108 | + midiOutClose(_handle); |
| 109 | + _handle = IntPtr.Zero; |
| 110 | + } |
| 111 | + } |
| 112 | + |
| 113 | + public void SubmitGamepadState(Gamepad gp) |
| 114 | + { |
| 115 | + if (!_connected || _handle == IntPtr.Zero) return; |
| 116 | + |
| 117 | + // Axes → CC messages (convert to 0-127 range) |
| 118 | + // Stick axes: -32768..32767 → 0..127 |
| 119 | + // Trigger axes: 0..65535 → 0..127 |
| 120 | + byte lx = AxisToMidi(gp.ThumbLX); |
| 121 | + byte ly = AxisToMidi(gp.ThumbLY); |
| 122 | + byte lt = TriggerToMidi(gp.LeftTrigger); |
| 123 | + byte rx = AxisToMidi(gp.ThumbRX); |
| 124 | + byte ry = AxisToMidi(gp.ThumbRY); |
| 125 | + byte rt = TriggerToMidi(gp.RightTrigger); |
| 126 | + |
| 127 | + byte[] ccValues = { lx, ly, lt, rx, ry, rt }; |
| 128 | + for (int i = 0; i < 6 && i < CcNumbers.Length; i++) |
| 129 | + { |
| 130 | + if (ccValues[i] != _lastCcValues[i]) |
| 131 | + { |
| 132 | + SendCC(CcNumbers[i], ccValues[i]); |
| 133 | + _lastCcValues[i] = ccValues[i]; |
| 134 | + } |
| 135 | + } |
| 136 | + |
| 137 | + // Buttons → Note On/Off |
| 138 | + ushort buttons = gp.Buttons; |
| 139 | + ushort changed = (ushort)(buttons ^ _lastButtons); |
| 140 | + for (int i = 0; i < 11 && i < NoteNumbers.Length; i++) |
| 141 | + { |
| 142 | + ushort mask = (ushort)(1 << i); |
| 143 | + if ((changed & mask) == 0) continue; |
| 144 | + |
| 145 | + if ((buttons & mask) != 0) |
| 146 | + SendNoteOn(NoteNumbers[i], Velocity); |
| 147 | + else |
| 148 | + SendNoteOff(NoteNumbers[i]); |
| 149 | + } |
| 150 | + _lastButtons = buttons; |
| 151 | + } |
| 152 | + |
| 153 | + public void RegisterFeedbackCallback(int padIndex, Vibration[] vibrationStates) |
| 154 | + { |
| 155 | + // MIDI has no rumble feedback — no-op. |
| 156 | + } |
| 157 | + |
| 158 | + public void Dispose() |
| 159 | + { |
| 160 | + if (_disposed) return; |
| 161 | + _disposed = true; |
| 162 | + Disconnect(); |
| 163 | + } |
| 164 | + |
| 165 | + // ───────────────────────────────────────────── |
| 166 | + // MIDI message helpers |
| 167 | + // ───────────────────────────────────────────── |
| 168 | + |
| 169 | + private void SendCC(int ccNumber, byte value) |
| 170 | + { |
| 171 | + // CC message: [status | channel] [cc#] [value] |
| 172 | + uint msg = (uint)((ControlChange | _channel) | (ccNumber << 8) | (value << 16)); |
| 173 | + midiOutShortMsg(_handle, msg); |
| 174 | + } |
| 175 | + |
| 176 | + private void SendNoteOn(int note, byte velocity) |
| 177 | + { |
| 178 | + uint msg = (uint)((NoteOn | _channel) | (note << 8) | (velocity << 16)); |
| 179 | + midiOutShortMsg(_handle, msg); |
| 180 | + } |
| 181 | + |
| 182 | + private void SendNoteOff(int note) |
| 183 | + { |
| 184 | + uint msg = (uint)((NoteOff | _channel) | (note << 8)); |
| 185 | + midiOutShortMsg(_handle, msg); |
| 186 | + } |
| 187 | + |
| 188 | + // ───────────────────────────────────────────── |
| 189 | + // Value conversion |
| 190 | + // ───────────────────────────────────────────── |
| 191 | + |
| 192 | + private static byte AxisToMidi(short value) |
| 193 | + { |
| 194 | + // -32768..32767 → 0..127 |
| 195 | + return (byte)((value + 32768) * 127 / 65535); |
| 196 | + } |
| 197 | + |
| 198 | + private static byte TriggerToMidi(ushort value) |
| 199 | + { |
| 200 | + // 0..65535 → 0..127 |
| 201 | + return (byte)(value * 127 / 65535); |
| 202 | + } |
| 203 | + |
| 204 | + // ───────────────────────────────────────────── |
| 205 | + // Static helpers for port enumeration |
| 206 | + // ───────────────────────────────────────────── |
| 207 | + |
| 208 | + /// <summary> |
| 209 | + /// Returns available MIDI output port names. |
| 210 | + /// </summary> |
| 211 | + public static string[] GetOutputPortNames() |
| 212 | + { |
| 213 | + int count = midiOutGetNumDevs(); |
| 214 | + var names = new string[count]; |
| 215 | + for (uint i = 0; i < count; i++) |
| 216 | + { |
| 217 | + var caps = new MIDIOUTCAPS(); |
| 218 | + if (midiOutGetDevCapsW(i, ref caps, Marshal.SizeOf<MIDIOUTCAPS>()) == 0) |
| 219 | + names[i] = caps.szPname; |
| 220 | + else |
| 221 | + names[i] = $"MIDI Out {i}"; |
| 222 | + } |
| 223 | + return names; |
| 224 | + } |
| 225 | + |
| 226 | + /// <summary> |
| 227 | + /// Finds the device ID for a port by name. Returns null if not found. |
| 228 | + /// </summary> |
| 229 | + public static uint? FindDeviceIdByName(string portName) |
| 230 | + { |
| 231 | + if (string.IsNullOrEmpty(portName)) return null; |
| 232 | + int count = midiOutGetNumDevs(); |
| 233 | + for (uint i = 0; i < count; i++) |
| 234 | + { |
| 235 | + var caps = new MIDIOUTCAPS(); |
| 236 | + if (midiOutGetDevCapsW(i, ref caps, Marshal.SizeOf<MIDIOUTCAPS>()) == 0 |
| 237 | + && string.Equals(caps.szPname, portName, StringComparison.OrdinalIgnoreCase)) |
| 238 | + return i; |
| 239 | + } |
| 240 | + return null; |
| 241 | + } |
| 242 | + } |
| 243 | +} |
0 commit comments