| 272 | } |
| 273 | |
| 274 | void Controller::handleEventInRender(const SDL_Event& event, bool emitEvents) { |
| 275 | switch (event.type) { |
| 276 | case SDL_CONTROLLERDEVICEADDED: |
| 277 | addControllerInRender(event.cdevice.which); |
| 278 | break; |
| 279 | case SDL_CONTROLLERDEVICEREMOVED: { |
| 280 | auto joystickId = s_cast<DeviceID>(event.cdevice.which); |
| 281 | if (auto it = _deviceMap.find(joystickId); it != _deviceMap.end()) { |
| 282 | SDL_GameControllerClose(s_cast<SDL_GameController*>(it->second->controller)); |
| 283 | SharedApplication.invokeInLogic([joystickId, this]() { |
| 284 | if (auto it = _deviceMap.find(joystickId); it != _deviceMap.end()) { |
| 285 | _availableDeviceIds.push(it->second->id); |
| 286 | _deviceMap.erase(it); |
| 287 | } |
| 288 | }); |
| 289 | } |
| 290 | break; |
| 291 | } |
| 292 | case SDL_CONTROLLERAXISMOTION: { |
| 293 | auto joystickId = s_cast<DeviceID>(event.caxis.which); |
| 294 | std::string axisName = SDL_GameControllerGetStringForAxis(s_cast<SDL_GameControllerAxis>(event.caxis.axis)); |
| 295 | float value = s_cast<float>(event.caxis.value) / SDL_JOYSTICK_AXIS_MAX; |
| 296 | SharedApplication.invokeInLogic([axisName, joystickId, value, emitEvents, this]() { |
| 297 | if (auto it = _deviceMap.find(joystickId); it != _deviceMap.end()) { |
| 298 | if (!emitEvents) { |
| 299 | it->second->axisMap[axisName] = 0.0f; |
| 300 | return; |
| 301 | } |
| 302 | it->second->axisMap[axisName] = value; |
| 303 | EventArgs<int, Slice, float> axis("Axis"_slice, it->second->id, axisName, value); |
| 304 | handler(&axis); |
| 305 | } |
| 306 | }); |
| 307 | break; |
| 308 | } |
| 309 | case SDL_CONTROLLERBUTTONDOWN: |
| 310 | case SDL_CONTROLLERBUTTONUP: { |
| 311 | auto joystickId = s_cast<DeviceID>(event.cbutton.which); |
| 312 | std::string buttonName = SDL_GameControllerGetStringForButton(s_cast<SDL_GameControllerButton>(event.cbutton.button)); |
| 313 | bool isDown = event.cbutton.state > 0; |
| 314 | SharedApplication.invokeInLogic([buttonName, joystickId, isDown, emitEvents, this]() { |
| 315 | if (auto it = _deviceMap.find(joystickId); it != _deviceMap.end()) { |
| 316 | if (!emitEvents) { |
| 317 | it->second->buttonMap[buttonName] = Device::ButtonState{.oldState = false, .newState = false}; |
| 318 | return; |
| 319 | } |
| 320 | Device::ButtonState state{.oldState = false, .newState = false}; |
| 321 | if (auto bit = it->second->buttonMap.find(buttonName); bit != it->second->buttonMap.end()) { |
| 322 | bit->second.newState = isDown; |
| 323 | state = bit->second; |
| 324 | } else { |
| 325 | state.newState = isDown; |
| 326 | it->second->buttonMap[buttonName] = state; |
| 327 | } |
| 328 | if (!state.oldState && state.newState) { |
| 329 | EventArgs<int, Slice> button("ButtonDown"_slice, it->second->id, buttonName); |
| 330 | handler(&button); |
| 331 | } else if (state.oldState && !state.newState) { |
no test coverage detected