- int joy_count = SDL_NumJoysticks();
- for( int i=0; i<joy_count; i++ ) {
- if( SDL_IsGameController(i) ) {
- vg_input.controller_handle = SDL_GameControllerOpen(i);
- vg_input.controller_joystick_id = i;
- vg_success( "Attached game controller with joystick ID %d\n", i );
- return;
+ if( ev->type == SDL_CONTROLLERDEVICEADDED ){
+ int is_controller = SDL_IsGameController( ev->cdevice.which );
+ const char *name = SDL_JoystickNameForIndex( ev->cdevice.which );
+
+ Sint32 index = ev->cdevice.which;
+ SDL_JoystickID instance_id = SDL_JoystickGetDeviceInstanceID( index );
+ vg_info( "SDL_CONTROLLERDEVICEADDED | device index: %d, name: '%s'\n",
+ index, name );
+
+ if( is_controller ){
+ vg_open_gamecontroller( index );
+ }
+ }
+ else if( ev->type == SDL_CONTROLLERDEVICEREMOVED ){
+ vg_info( "SDL_CONTROLLERDEVICEREMOVED | instance_id: %d\n",
+ ev->cdevice.which );
+
+ for( int i=0; i<VG_MAX_CONTROLLERS; i++ ){
+ struct vg_controller *controller = &vg_input.controllers[i];
+
+ if( controller->handle ){
+ if( controller->instance_id == ev->cdevice.which ){
+ vg_info( " . closing controller at index #%d\n", i );
+ SDL_GameControllerClose( controller->handle );
+ controller->handle = NULL;
+ controller->instance_id = -1;
+
+ if( vg_input.active_controller_index == i ){
+ vg_input.active_controller_index = -1;
+ vg_info( " . active controller is now keyboard and mouse\n" );
+ }
+ break;
+ }
+ }