| 1 | // Copyright 2010 Dolphin Emulator Project |
| 2 | // SPDX-License-Identifier: GPL-2.0-or-later |
| 3 | |
| 4 | #include "InputCommon/ControllerInterface/DInput/DInputJoystick.h" |
| 5 | |
| 6 | #include <algorithm> |
| 7 | #include <limits> |
| 8 | #include <mutex> |
| 9 | #include <set> |
| 10 | #include <type_traits> |
| 11 | |
| 12 | #include <fmt/format.h> |
| 13 | |
| 14 | #include "Common/HRWrap.h" |
| 15 | #include "Common/Logging/Log.h" |
| 16 | #include "InputCommon/ControllerInterface/ControllerInterface.h" |
| 17 | #include "InputCommon/ControllerInterface/DInput/DInput.h" |
| 18 | #include "InputCommon/ControllerInterface/DInput/XInputFilter.h" |
| 19 | |
| 20 | namespace ciface::DInput |
| 21 | { |
| 22 | constexpr DWORD DATA_BUFFER_SIZE = 32; |
| 23 | |
| 24 | struct GUIDComparator |
| 25 | { |
| 26 | bool operator()(const GUID& left, const GUID& right) const |
| 27 | { |
| 28 | static_assert(std::is_trivially_copyable_v<GUID>); |
| 29 | |
| 30 | return memcmp(&left, &right, sizeof(left)) < 0; |
| 31 | } |
| 32 | }; |
| 33 | |
| 34 | static std::set<GUID, GUIDComparator> s_guids_in_use; |
| 35 | static std::mutex s_guids_mutex; |
| 36 | |
| 37 | void InitJoystick(IDirectInput8* const idi8, HWND hwnd) |
| 38 | { |
| 39 | std::list<DIDEVICEINSTANCE> joysticks; |
| 40 | idi8->EnumDevices(DI8DEVCLASS_GAMECTRL, DIEnumDevicesCallback, (LPVOID)&joysticks, |
| 41 | DIEDFL_ATTACHEDONLY); |
| 42 | |
| 43 | std::unordered_set<DWORD> xinput_guids = GetXInputGUIDS(); |
| 44 | for (DIDEVICEINSTANCE& joystick : joysticks) |
| 45 | { |
| 46 | // Skip XInput Devices |
| 47 | if (xinput_guids.contains(joystick.guidProduct.Data1)) |
| 48 | { |
| 49 | continue; |
| 50 | } |
| 51 | |
| 52 | // Skip devices we are already using. |
| 53 | { |
| 54 | std::lock_guard lk(s_guids_mutex); |
| 55 | if (s_guids_in_use.contains(joystick.guidInstance)) |
| 56 | { |
| 57 | continue; |
| 58 | } |
| 59 | } |
| 60 | |
| 61 | LPDIRECTINPUTDEVICE8 js_device; |
| 62 | // Don't print any warnings on failure |
| 63 | if (SUCCEEDED(idi8->CreateDevice(joystick.guidInstance, &js_device, nullptr))) |
| 64 | { |
| 65 | if (SUCCEEDED(js_device->SetDataFormat(&c_dfDIJoystick))) |
| 66 | { |
| 67 | HRESULT hr = js_device->SetCooperativeLevel(GetAncestor(hwnd, GA_ROOT), |
| 68 | DISCL_BACKGROUND | DISCL_EXCLUSIVE); |
| 69 | if (FAILED(hr)) |
| 70 | { |
| 71 | WARN_LOG_FMT(CONTROLLERINTERFACE, |
| 72 | "DInput: Failed to acquire device exclusively. Force feedback will be " |
| 73 | "unavailable. {}", |
| 74 | Common::HRWrap(hr)); |
| 75 | // Fall back to non-exclusive mode, with no rumble |
| 76 | if (FAILED( |
| 77 | js_device->SetCooperativeLevel(nullptr, DISCL_BACKGROUND | DISCL_NONEXCLUSIVE))) |
| 78 | { |
| 79 | js_device->Release(); |
| 80 | continue; |
| 81 | } |
| 82 | } |
| 83 | |
| 84 | auto js = std::make_shared<Joystick>(js_device); |
| 85 | // only add if it has some inputs/outputs. |
| 86 | // Don't even add it to our static list in case we first created it without a window handle, |
| 87 | // failing to get exclusive mode, and then later managed to obtain it, which mean it |
| 88 | // could now have some outputs if it didn't before. |
| 89 | if (js->Inputs().size() || js->Outputs().size()) |
| 90 | { |
| 91 | if (g_controller_interface.AddDevice(std::move(js))) |
| 92 | { |
| 93 | std::lock_guard lk(s_guids_mutex); |
| 94 | s_guids_in_use.insert(joystick.guidInstance); |
| 95 | } |
| 96 | } |
| 97 | } |
| 98 | else |
| 99 | { |
| 100 | js_device->Release(); |
| 101 | } |
| 102 | } |
| 103 | } |
| 104 | } |
| 105 | |
| 106 | Joystick::Joystick(const LPDIRECTINPUTDEVICE8 device) : m_device(device) |
| 107 | { |
| 108 | // seems this needs to be done before GetCapabilities |
| 109 | // polled or buffered data |
| 110 | DIPROPDWORD dipdw; |
| 111 | dipdw.diph.dwSize = sizeof(DIPROPDWORD); |
| 112 | dipdw.diph.dwHeaderSize = sizeof(DIPROPHEADER); |
| 113 | dipdw.diph.dwObj = 0; |
| 114 | dipdw.diph.dwHow = DIPH_DEVICE; |
| 115 | dipdw.dwData = DATA_BUFFER_SIZE; |
| 116 | // set the buffer size, |
| 117 | // if we can't set the property, we can't use buffered data |
| 118 | m_buffered = SUCCEEDED(m_device->SetProperty(DIPROP_BUFFERSIZE, &dipdw.diph)); |
| 119 | |
| 120 | // seems this needs to be done after SetProperty of buffer size |
| 121 | m_device->Acquire(); |
| 122 | |
| 123 | // get joystick caps |
| 124 | DIDEVCAPS js_caps; |
| 125 | js_caps.dwSize = sizeof(js_caps); |
| 126 | if (FAILED(m_device->GetCapabilities(&js_caps))) |
| 127 | return; |
| 128 | |
| 129 | // max of 32 buttons and 4 hats / the limit of the data format I am using |
| 130 | js_caps.dwButtons = std::min((DWORD)32, js_caps.dwButtons); |
| 131 | js_caps.dwPOVs = std::min((DWORD)4, js_caps.dwPOVs); |
| 132 | |
| 133 | // m_must_poll = (js_caps.dwFlags & DIDC_POLLEDDATAFORMAT) != 0; |
| 134 | |
| 135 | // buttons |
| 136 | for (u8 i = 0; i != js_caps.dwButtons; ++i) |
| 137 | AddInput(new Button(i, m_state_in.rgbButtons[i])); |
| 138 | |
| 139 | // hats |
| 140 | for (u8 i = 0; i != js_caps.dwPOVs; ++i) |
| 141 | { |
| 142 | // each hat gets 4 input instances associated with it, (up down left right) |
| 143 | for (u8 d = 0; d != 4; ++d) |
| 144 | AddInput(new Hat(i, m_state_in.rgdwPOV[i], d)); |
| 145 | } |
| 146 | |
| 147 | // get up to 6 axes and 2 sliders |
| 148 | DIPROPRANGE range; |
| 149 | range.diph.dwSize = sizeof(range); |
| 150 | range.diph.dwHeaderSize = sizeof(range.diph); |
| 151 | range.diph.dwHow = DIPH_BYOFFSET; |
| 152 | // screw EnumObjects, just go through all the axis offsets and try to GetProperty |
| 153 | // this should be more foolproof, less code, and probably faster |
| 154 | for (unsigned int offset = 0; offset < DIJOFS_BUTTON(0) / sizeof(LONG); ++offset) |
| 155 | { |
| 156 | range.diph.dwObj = offset * sizeof(LONG); |
| 157 | // Try to set a range with 16 bits of precision: |
| 158 | range.lMin = std::numeric_limits<s16>::min(); |
| 159 | range.lMax = std::numeric_limits<s16>::max(); |
| 160 | m_device->SetProperty(DIPROP_RANGE, &range.diph); |
| 161 | // Not all devices support setting DIPROP_RANGE so we must GetProperty right back. |
| 162 | // This also checks that the axis is present. |
| 163 | // Note: Even though not all devices support setting DIPROP_RANGE, some require it. |
| 164 | if (SUCCEEDED(m_device->GetProperty(DIPROP_RANGE, &range.diph))) |
| 165 | { |
| 166 | const LONG base = (range.lMin + range.lMax) / 2; |
| 167 | const LONG& ax = (&m_state_in.lX)[offset]; |
| 168 | |
| 169 | // each axis gets a negative and a positive input instance associated with it |
| 170 | AddFullAnalogSurfaceInputs(new Axis(offset, ax, base, range.lMin - base), |
| 171 | new Axis(offset, ax, base, range.lMax - base)); |
| 172 | } |
| 173 | } |
| 174 | |
| 175 | // Force feedback: |
| 176 | std::list<DIDEVICEOBJECTINSTANCE> objects; |
| 177 | if (SUCCEEDED(m_device->EnumObjects(DIEnumDeviceObjectsCallback, (LPVOID)&objects, DIDFT_AXIS))) |
| 178 | { |
| 179 | const int num_ff_axes = std::ranges::count_if( |
| 180 | objects, [](const auto& pdidoi) { return (pdidoi.dwFlags & DIDOI_FFACTUATOR) != 0; }); |
| 181 | InitForceFeedback(m_device, num_ff_axes); |
| 182 | } |
| 183 | |
| 184 | // Set hats to center: |
| 185 | // "The center position is normally reported as -1" -MSDN |
| 186 | std::ranges::fill(m_state_in.rgdwPOV, -1); |
| 187 | } |
| 188 | |
| 189 | Joystick::~Joystick() |
| 190 | { |
| 191 | DIDEVICEINSTANCE info = {}; |
| 192 | info.dwSize = sizeof(info); |
| 193 | if (SUCCEEDED(m_device->GetDeviceInfo(&info))) |
| 194 | { |
| 195 | std::lock_guard lk(s_guids_mutex); |
| 196 | s_guids_in_use.erase(info.guidInstance); |
| 197 | } |
| 198 | else |
| 199 | { |
| 200 | ERROR_LOG_FMT(CONTROLLERINTERFACE, "DInputJoystick: GetDeviceInfo failed."); |
| 201 | } |
| 202 | |
| 203 | DeInitForceFeedback(); |
| 204 | |
| 205 | m_device->Unacquire(); |
| 206 | m_device->Release(); |
| 207 | } |
| 208 | |
| 209 | std::string Joystick::GetName() const |
| 210 | { |
| 211 | return GetDeviceName(m_device); |
| 212 | } |
| 213 | |
| 214 | std::string Joystick::GetSource() const |
| 215 | { |
| 216 | return DINPUT_SOURCE_NAME; |
| 217 | } |
| 218 | |
| 219 | bool Joystick::IsValid() const |
| 220 | { |
| 221 | return SUCCEEDED(m_device->Acquire()); |
| 222 | } |
| 223 | |
| 224 | Core::DeviceRemoval Joystick::UpdateInput() |
| 225 | { |
| 226 | HRESULT hr = 0; |
| 227 | |
| 228 | // just always poll, |
| 229 | // MSDN says if this isn't needed it doesn't do anything |
| 230 | m_device->Poll(); |
| 231 | |
| 232 | if (m_buffered) |
| 233 | { |
| 234 | DIDEVICEOBJECTDATA evtbuf[DATA_BUFFER_SIZE]; |
| 235 | DWORD numevents = DATA_BUFFER_SIZE; |
| 236 | hr = m_device->GetDeviceData(sizeof(*evtbuf), evtbuf, &numevents, 0); |
| 237 | |
| 238 | if (SUCCEEDED(hr)) |
| 239 | { |
| 240 | for (LPDIDEVICEOBJECTDATA evt = evtbuf; evt != (evtbuf + numevents); ++evt) |
| 241 | { |
| 242 | // all the buttons are at the end of the data format |
| 243 | // they are bytes rather than longs |
| 244 | if (evt->dwOfs < DIJOFS_BUTTON(0)) |
| 245 | *(DWORD*)(((BYTE*)&m_state_in) + evt->dwOfs) = evt->dwData; |
| 246 | else |
| 247 | ((BYTE*)&m_state_in)[evt->dwOfs] = (BYTE)evt->dwData; |
| 248 | } |
| 249 | |
| 250 | // seems like this needs to be done maybe... |
| 251 | if (DI_BUFFEROVERFLOW == hr) |
| 252 | hr = m_device->GetDeviceState(sizeof(m_state_in), &m_state_in); |
| 253 | } |
| 254 | } |
| 255 | else |
| 256 | { |
| 257 | hr = m_device->GetDeviceState(sizeof(m_state_in), &m_state_in); |
| 258 | } |
| 259 | |
| 260 | // try reacquire if input lost |
| 261 | if (DIERR_INPUTLOST == hr || DIERR_NOTACQUIRED == hr) |
| 262 | m_device->Acquire(); |
| 263 | |
| 264 | return Core::DeviceRemoval::Keep; |
| 265 | } |
| 266 | |
| 267 | // get name |
| 268 | |
| 269 | std::string Joystick::Button::GetName() const |
| 270 | { |
| 271 | return fmt::format("Button {}", m_index); |
| 272 | } |
| 273 | |
| 274 | std::string Joystick::Axis::GetName() const |
| 275 | { |
| 276 | const char sign = m_range < 0 ? '-' : '+'; |
| 277 | if (m_index < 6) // axis |
| 278 | return fmt::format("Axis {:c}{}{:c}", 'X' + m_index % 3, m_index > 2 ? "r" : "", sign); |
| 279 | else // slider |
| 280 | return fmt::format("Slider {}{:c}", m_index - 6, sign); |
| 281 | } |
| 282 | |
| 283 | std::string Joystick::Hat::GetName() const |
| 284 | { |
| 285 | return fmt::format("Hat {} {:c}", m_index, "NESW"[m_direction]); |
| 286 | } |
| 287 | |
| 288 | // get / set state |
| 289 | |
| 290 | ControlState Joystick::Axis::GetState() const |
| 291 | { |
| 292 | return ControlState(m_axis - m_base) / m_range; |
| 293 | } |
| 294 | |
| 295 | ControlState Joystick::Button::GetState() const |
| 296 | { |
| 297 | return ControlState(m_button > 0); |
| 298 | } |
| 299 | |
| 300 | ControlState Joystick::Hat::GetState() const |
| 301 | { |
| 302 | // "Some drivers report the centered position of the POV indicator as 65,535. |
| 303 | // Determine whether the indicator is centered as follows" -MSDN |
| 304 | const bool is_centered = (0xffff == LOWORD(m_hat)); |
| 305 | |
| 306 | if (is_centered) |
| 307 | return 0; |
| 308 | |
| 309 | return (std::abs(int(m_hat / 4500 - m_direction * 2 + 8) % 8 - 4) > 2); |
| 310 | } |
| 311 | } // namespace ciface::DInput |