JoystickScriptingInterface::JoystickScriptingInterface() : #ifdef HAVE_SDL2 _openJoysticks(), #endif _isInitialized(false) { #ifdef HAVE_SDL2 bool initSuccess = (SDL_Init(SDL_INIT_GAMECONTROLLER) == 0); if (initSuccess) { int joystickCount = SDL_NumJoysticks(); for (int i = 0; i < joystickCount; i++) { SDL_GameController* controller = SDL_GameControllerOpen(i); if (controller) { SDL_JoystickID id = getInstanceId(controller); Joystick* joystick = new Joystick(id, SDL_GameControllerName(controller), controller); _openJoysticks[id] = joystick; } } _isInitialized = true; } else { qDebug() << "Error initializing SDL"; } #endif }
bool Joystick::open(int deviceindex) { close(); joyhandle = SDL_JoystickOpen(deviceindex); if (joyhandle) { instanceid = SDL_JoystickInstanceID(joyhandle); // SDL_JoystickGetGUIDString uses 32 bytes plus the null terminator. char cstr[33]; SDL_JoystickGUID sdlguid = SDL_JoystickGetGUID(joyhandle); SDL_JoystickGetGUIDString(sdlguid, cstr, (int) sizeof(cstr)); pguid = std::string(cstr); // See if SDL thinks this is a Game Controller. openGamepad(deviceindex); // Prefer the Joystick name for consistency. const char *joyname = SDL_JoystickName(joyhandle); if (!joyname && controller) joyname = SDL_GameControllerName(controller); if (joyname) name = joyname; } return isConnected(); }
void print_joystick_info(int joy_idx, SDL_Joystick* joy, SDL_GameController* gamepad) { SDL_JoystickGUID guid = SDL_JoystickGetGUID(joy); char guid_str[1024]; SDL_JoystickGetGUIDString(guid, guid_str, sizeof(guid_str)); printf("Joystick Name: '%s'\n", SDL_JoystickName(joy)); printf("Joystick GUID: %s\n", guid_str); printf("Joystick Number: %2d\n", joy_idx); printf("Number of Axes: %2d\n", SDL_JoystickNumAxes(joy)); printf("Number of Buttons: %2d\n", SDL_JoystickNumButtons(joy)); printf("Number of Hats: %2d\n", SDL_JoystickNumHats(joy)); printf("Number of Balls: %2d\n", SDL_JoystickNumBalls(joy)); printf("GameController:\n"); if (!gamepad) { printf(" not a gamepad\n"); } else { printf(" Name: '%s'\n", SDL_GameControllerName(gamepad)); printf(" Mapping: '%s'\n", SDL_GameControllerMappingForGUID(guid)); } printf("\n"); }
void SDL2Manager::init() { #ifdef HAVE_SDL2 bool initSuccess = (SDL_Init(SDL_INIT_GAMECONTROLLER) == 0); if (initSuccess) { int joystickCount = SDL_NumJoysticks(); for (int i = 0; i < joystickCount; i++) { SDL_GameController* controller = SDL_GameControllerOpen(i); if (controller) { SDL_JoystickID id = getInstanceId(controller); if (!_openJoysticks.contains(id)) { Joystick* joystick = new Joystick(id, SDL_GameControllerName(controller), controller); _openJoysticks[id] = joystick; auto userInputMapper = DependencyManager::get<UserInputMapper>(); joystick->registerToUserInputMapper(*userInputMapper); joystick->assignDefaultInputMapping(*userInputMapper); emit joystickAdded(joystick); } } } _isInitialized = true; } else { qDebug() << "Error initializing SDL2 Manager"; } #endif }
std::string name() const { const char* result = SDL_GameControllerName(ptr.get()); if(result == nullptr) { return "Unknown"; } return { result }; }
const std::string DEV_Joystick::GetName() { #ifdef WITH_SDL return (SDL_CHECK(SDL_GameControllerName)) ? SDL_GameControllerName(m_private->m_gamecontroller) : ""; #else /* WITH_SDL */ return ""; #endif /* WITH_SDL */ }
QString GameController::getSDLName() { QString temp; if (controller) { temp = SDL_GameControllerName(controller); } return temp; }
void SDL2Manager::pluginUpdate(float deltaTime, bool jointsCaptured) { #ifdef HAVE_SDL2 if (_isInitialized) { auto userInputMapper = DependencyManager::get<UserInputMapper>(); for (auto joystick : _openJoysticks) { joystick->update(deltaTime, jointsCaptured); } PerformanceTimer perfTimer("SDL2Manager::update"); SDL_GameControllerUpdate(); SDL_Event event; while (SDL_PollEvent(&event)) { if (event.type == SDL_CONTROLLERAXISMOTION) { Joystick* joystick = _openJoysticks[event.caxis.which]; if (joystick) { joystick->handleAxisEvent(event.caxis); } } else if (event.type == SDL_CONTROLLERBUTTONDOWN || event.type == SDL_CONTROLLERBUTTONUP) { Joystick* joystick = _openJoysticks[event.cbutton.which]; if (joystick) { joystick->handleButtonEvent(event.cbutton); } if (event.cbutton.button == SDL_CONTROLLER_BUTTON_BACK) { // this will either start or stop a global back event QEvent::Type backType = (event.type == SDL_CONTROLLERBUTTONDOWN) ? HFBackEvent::startType() : HFBackEvent::endType(); HFBackEvent backEvent(backType); qApp->sendEvent(qApp, &backEvent); } } else if (event.type == SDL_CONTROLLERDEVICEADDED) { SDL_GameController* controller = SDL_GameControllerOpen(event.cdevice.which); SDL_JoystickID id = getInstanceId(controller); if (!_openJoysticks.contains(id)) { Joystick* joystick = new Joystick(id, SDL_GameControllerName(controller), controller); _openJoysticks[id] = joystick; joystick->registerToUserInputMapper(*userInputMapper); joystick->assignDefaultInputMapping(*userInputMapper); emit joystickAdded(joystick); } } else if (event.type == SDL_CONTROLLERDEVICEREMOVED) { Joystick* joystick = _openJoysticks[event.cdevice.which]; _openJoysticks.remove(event.cdevice.which); userInputMapper->removeDevice(joystick->getDeviceID()); emit joystickRemoved(joystick); } } } #endif }
int GameController::getName(State & state, SDL_GameController * gamecontroller) { Stack * stack = state.stack; const char * name = SDL_GameControllerName(gamecontroller); if (name){ stack->push<const std::string &>(name); return 1; } else{ return 0; } }
void JoystickScriptingInterface::update() { #ifdef HAVE_SDL2 if (_isInitialized) { PerformanceTimer perfTimer("JoystickScriptingInterface::update"); SDL_GameControllerUpdate(); SDL_Event event; while (SDL_PollEvent(&event)) { if (event.type == SDL_CONTROLLERAXISMOTION) { Joystick* joystick = _openJoysticks[event.caxis.which]; if (joystick) { joystick->handleAxisEvent(event.caxis); } } else if (event.type == SDL_CONTROLLERBUTTONDOWN || event.type == SDL_CONTROLLERBUTTONUP) { Joystick* joystick = _openJoysticks[event.cbutton.which]; if (joystick) { joystick->handleButtonEvent(event.cbutton); } if (event.cbutton.button == SDL_CONTROLLER_BUTTON_BACK) { // this will either start or stop a global back event QEvent::Type backType = (event.type == SDL_CONTROLLERBUTTONDOWN) ? HFBackEvent::startType() : HFBackEvent::endType(); HFBackEvent backEvent(backType); qApp->sendEvent(qApp, &backEvent); } else if (event.cbutton.button == SDL_CONTROLLER_BUTTON_A) { // this will either start or stop a global action event QEvent::Type actionType = (event.type == SDL_CONTROLLERBUTTONDOWN) ? HFActionEvent::startType() : HFActionEvent::endType(); // global action events fire in the center of the screen HFActionEvent actionEvent(actionType, Application::getInstance()->getCamera()->computeViewPickRay(0.5f, 0.5f)); qApp->sendEvent(qApp, &actionEvent); } } else if (event.type == SDL_CONTROLLERDEVICEADDED) { SDL_GameController* controller = SDL_GameControllerOpen(event.cdevice.which); SDL_JoystickID id = getInstanceId(controller); Joystick* joystick = new Joystick(id, SDL_GameControllerName(controller), controller); _openJoysticks[id] = joystick; emit joystickAdded(joystick); } else if (event.type == SDL_CONTROLLERDEVICEREMOVED) { Joystick* joystick = _openJoysticks[event.cdevice.which]; _openJoysticks.remove(event.cdevice.which); emit joystickRemoved(joystick); } } } #endif }
bool Joystick::attachGameController(int which) { Q_ASSERT(device_attached != true); controller = SDL_GameControllerOpen(which); if (controller == nullptr) { qCWarning(phxInput, "Joystick: Unable to open sdl game controller: %s", SDL_GetError()); return false; } setDeviceName(SDL_GameControllerName(controller)); device_attached = true; return true; }
static int _SaveMappings() { char bind[2056]; const char* name; if (_this->controller != NULL) { name = SDL_GameControllerName(_this->controller); } else { name = SDL_JoystickName(_this->joystick); } SDL_JoystickGUID guid = SDL_JoystickGetGUID(_this->joystick); char guid_string[33]; SDL_JoystickGetGUIDString(guid, guid_string, 33); guid_string[32] = 0; snprintf(bind, 2056, "%s,%s,platform:%s,", guid_string, name, SDL_GetPlatform()); int index = strlen(bind); for (int i = 0; i < NUM_MAPPINGS; ++i) { const char* to = NULL; if (_this->mappings[i].type == SDL_CONTROLLER_BINDTYPE_AXIS) { to = SDL_GameControllerGetStringForAxis(_this->mappings[i].value.axis); } else if (_this->mappings[i].type != SDL_CONTROLLER_BINDTYPE_BUTTON){ to = SDL_GameControllerGetStringForButton(_this->mappings[i].value.button); } if (to == NULL) { continue; } char from[10]; if (_this->mappings[i].bind.bindType == SDL_CONTROLLER_BINDTYPE_AXIS) { snprintf(from, 10, "a%d", _this->mappings[i].bind.value.axis); } else if (_this->mappings[i].bind.bindType == SDL_CONTROLLER_BINDTYPE_BUTTON) { snprintf(from, 10, "b%d", _this->mappings[i].bind.value.button); } if (_this->mappings[i].bind.bindType == SDL_CONTROLLER_BINDTYPE_HAT) { snprintf(from, 10, "h%d.%d", _this->mappings[i].bind.value.hat.hat, _this->mappings[i].bind.value.hat.hat_mask); } else { continue; } snprintf(bind, 2056 - index, "%s:%s,", to, from); index += strlen(to) + strlen(from); } SDL_GameControllerAddMapping(bind); // TODO Save to file SDL_Log("Mapping: %s\n", bind); }
void DecafSDL::openInputDevices() { mVpad0Config = nullptr; mVpad0Controller = nullptr; for (const auto &device : config::input::devices) { if (config::input::vpad0.compare(device.id) != 0) { continue; } if (device.type == config::input::Joystick) { auto numJoysticks = SDL_NumJoysticks(); for (int i = 0; i < numJoysticks; ++i) { if (!SDL_IsGameController(i)) { continue; } auto controller = SDL_GameControllerOpen(i); if (!controller) { gCliLog->error("Failed to open game controller {}: {}", i, SDL_GetError()); continue; } auto name = SDL_GameControllerName(controller); if (!device.device_name.empty() && device.device_name.compare(name) != 0) { SDL_GameControllerClose(controller); continue; } mVpad0Controller = controller; break; } if (!mVpad0Controller) { continue; } } mVpad0Config = &device; break; } if (!mVpad0Config) { gCliLog->warn("No input device found for gamepad (VPAD0)"); } }
/* * Open controllers and joysticks */ void S2D_OpenControllers() { char guid_str[33]; // Enumerate joysticks for (int device_index = 0; device_index < SDL_NumJoysticks(); ++device_index) { // Check if joystick supports SDL's game controller interface (a mapping is available) if (SDL_IsGameController(device_index)) { SDL_GameController *controller = SDL_GameControllerOpen(device_index); SDL_JoystickID intance_id = SDL_JoystickInstanceID(SDL_GameControllerGetJoystick(controller)); SDL_JoystickGetGUIDString( SDL_JoystickGetGUID(SDL_GameControllerGetJoystick(controller)), guid_str, 33 ); if (intance_id > last_intance_id) { if (controller) { S2D_Log(S2D_INFO, "Controller #%i: %s\n GUID: %s", intance_id, SDL_GameControllerName(controller), guid_str); } else { S2D_Log(S2D_ERROR, "Could not open controller #%i: %s", intance_id, SDL_GetError()); } last_intance_id = intance_id; } // Controller interface not supported, try to open as joystick } else { SDL_Joystick *joy = SDL_JoystickOpen(device_index); SDL_JoystickID intance_id = SDL_JoystickInstanceID(joy); if (!joy) { S2D_Log(S2D_ERROR, "Could not open controller"); } else if(intance_id > last_intance_id) { SDL_JoystickGetGUIDString( SDL_JoystickGetGUID(joy), guid_str, 33 ); S2D_Log(S2D_INFO, "Controller #%i: %s\n GUID: %s\n Axes: %d\n Buttons: %d\n Balls: %d", intance_id, SDL_JoystickName(joy), guid_str, SDL_JoystickNumAxes(joy), SDL_JoystickNumButtons(joy), SDL_JoystickNumBalls(joy) ); S2D_Log(S2D_WARN, "Controller #%i does not have a mapping available", intance_id); last_intance_id = intance_id; } } } }
void GameEngine::CaptureJoystick(int id){ if (SDL_IsGameController(id)){ m_gameController = SDL_GameControllerOpen(id); if(m_gameController){ #ifdef DEBUG const char *name = SDL_GameControllerName(m_gameController); std::cout << "Found a valid controller at index " << id << ", named: " << name << std::endl; delete name; #endif } else{ std::cout << "Error while capturing game controller " << SDL_GetError() << std::endl; } } }
void I_InitGamepad(void) { if (SDL_InitSubSystem(SDL_INIT_GAMECONTROLLER | SDL_INIT_HAPTIC) < 0) C_Warning("Gamepad support couldn't be initialized."); else { int numjoysticks = SDL_NumJoysticks(); for (int i = 0; i < numjoysticks; i++) if ((joystick = SDL_JoystickOpen(i))) if (SDL_IsGameController(i)) { gamecontroller = SDL_GameControllerOpen(i); break; } if (!gamecontroller) SDL_QuitSubSystem(SDL_INIT_GAMECONTROLLER | SDL_INIT_HAPTIC); else { const char *name = SDL_GameControllerName(gamecontroller); if (*name) { if (M_StrCaseStr(name, "xinput")) C_Output("An <i><b>XInput</b></i> gamepad is connected."); else C_Output("A <i><b>DirectInput</b></i> gamepad called \"%s\" is connected.", name); } else C_Output("A gamepad is connected."); if (!(haptic = SDL_HapticOpenFromJoystick(joystick)) || SDL_HapticRumbleInit(haptic) < 0) C_Warning("This gamepad doesn't support vibration."); } } gamepadbuttons = 0; gamepadthumbLX = 0; gamepadthumbLY = 0; gamepadthumbRX = 0; gamepadthumbRY = 0; }
/* =============== IN_StartupJoystick =============== */ void IN_StartupJoystick (void) { // abort startup if user requests no joystick if ( gEngfuncs.CheckParm ("-nojoy", NULL ) ) return; // assume no joystick joy_avail = 0; int nJoysticks = SDL_NumJoysticks(); if ( nJoysticks > 0 ) { for ( int i = 0; i < nJoysticks; i++ ) { if ( SDL_IsGameController( i ) ) { s_pJoystick = SDL_GameControllerOpen( i ); if ( s_pJoystick ) { //save the joystick's number of buttons and POV status joy_numbuttons = SDL_CONTROLLER_BUTTON_MAX; joy_haspov = 0; // old button and POV states default to no buttons pressed joy_oldbuttonstate = joy_oldpovstate = 0; // mark the joystick as available and advanced initialization not completed // this is needed as cvars are not available during initialization gEngfuncs.Con_Printf ("joystick found\n\n", SDL_GameControllerName(s_pJoystick)); joy_avail = 1; joy_advancedinit = 0; break; } } } } else { gEngfuncs.Con_DPrintf ("joystick not found -- driver not present\n\n"); } }
void init_controllers_and_audio() { SDL_SetHint(SDL_HINT_JOYSTICK_ALLOW_BACKGROUND_EVENTS, "1"); SDL_SetHint(SDL_HINT_GAMECONTROLLERCONFIG, "1"); Uint32 SDL_INIT_FLAGS = SDL_INIT_GAMECONTROLLER; // custom mappings SDL_HINT_GAMECONTROLLERCONFIG; if(ENABLE_AUDIO) { SDL_INIT_FLAGS |= SDL_INIT_AUDIO; // this does not seem to work :S } if(SDL_Init(SDL_INIT_FLAGS) == 0) { if( ENABLE_AUDIO && Mix_OpenAudio( 44100, MIX_DEFAULT_FORMAT, 2, 1024 ) < 0) { std::cout << "Unable to open audio device" << std::endl; std::cout << Mix_GetError() << std::endl; } //TODO: SDL_JOYDEVICEADDED or SDL_JOYDEVICEREMOVED //SDL_GameControllerEventState(int state); SDL_JoystickEventState(SDL_ENABLE); if(SDL_NumJoysticks() == 0) { std::cout << "No joysticks" << std::endl; } else { for (int i = 0; i < SDL_NumJoysticks(); ++i) { if (SDL_IsGameController(i)) { controller = SDL_GameControllerOpen(i); if (controller) { std::cout << "Controller: " << SDL_GameControllerName(controller) << std::endl; break; } else { std::cout << "Could not open gamecontroller " << i << ":" << SDL_GetError() << std::endl; } } else { std::cout << "Not controller" << std::endl; } } } } else { std::cout << "SDL Failed to initialize" << std::endl; std::cout << SDL_GetError() << std::endl; } }
* Gamecontroller object methods * -------------------------------------------------------- */ /* * Controller:name() * * Returns: * The controller name */ static int l_gamectl_name(lua_State *L) { SDL_GameController *c = commonGetAs(L, 1, GameCtlName, SDL_GameController *); const char *name; name = SDL_GameControllerName(c); if (name == NULL) return commonPushSDLError(L, 1); return commonPush(L, "s", name); } /* * Controller:getAttached() * * Returns: * True if attached */ static int l_gamectl_getAttached(lua_State *L) {
const char* Gamepad::GetDeviceName (int id) { return SDL_GameControllerName (gameControllers[id]); }
SDL_bool WatchGameController(SDL_GameController *gamecontroller) { const char *name = SDL_GameControllerName(gamecontroller); const char *basetitle = "Game Controller Test: "; const size_t titlelen = SDL_strlen(basetitle) + SDL_strlen(name) + 1; char *title = (char *)SDL_malloc(titlelen); SDL_Window *window = NULL; retval = SDL_FALSE; done = SDL_FALSE; if (title) { SDL_snprintf(title, titlelen, "%s%s", basetitle, name); } /* Create a window to display controller state */ window = SDL_CreateWindow(title, SDL_WINDOWPOS_CENTERED, SDL_WINDOWPOS_CENTERED, SCREEN_WIDTH, SCREEN_HEIGHT, 0); if (window == NULL) { SDL_LogError(SDL_LOG_CATEGORY_APPLICATION, "Couldn't create window: %s\n", SDL_GetError()); return SDL_FALSE; } screen = SDL_CreateRenderer(window, -1, 0); if (screen == NULL) { SDL_LogError(SDL_LOG_CATEGORY_APPLICATION, "Couldn't create renderer: %s\n", SDL_GetError()); SDL_DestroyWindow(window); return SDL_FALSE; } SDL_SetRenderDrawColor(screen, 0x00, 0x00, 0x00, SDL_ALPHA_OPAQUE); SDL_RenderClear(screen); SDL_RenderPresent(screen); SDL_RaiseWindow(window); /* scale for platforms that don't give you the window size you asked for. */ SDL_RenderSetLogicalSize(screen, SCREEN_WIDTH, SCREEN_HEIGHT); background = LoadTexture(screen, "controllermap.bmp", SDL_FALSE); button = LoadTexture(screen, "button.bmp", SDL_TRUE); axis = LoadTexture(screen, "axis.bmp", SDL_TRUE); if (!background || !button || !axis) { SDL_DestroyRenderer(screen); SDL_DestroyWindow(window); return SDL_FALSE; } SDL_SetTextureColorMod(button, 10, 255, 21); SDL_SetTextureColorMod(axis, 10, 255, 21); /* !!! FIXME: */ /*SDL_RenderSetLogicalSize(screen, background->w, background->h);*/ /* Print info about the controller we are watching */ SDL_Log("Watching controller %s\n", name ? name : "Unknown Controller"); /* Loop, getting controller events! */ #ifdef __EMSCRIPTEN__ emscripten_set_main_loop_arg(loop, gamecontroller, 0, 1); #else while (!done) { loop(gamecontroller); } #endif SDL_DestroyRenderer(screen); screen = NULL; background = NULL; button = NULL; axis = NULL; SDL_DestroyWindow(window); return retval; }
SDL_bool WatchGameController(SDL_GameController * gamecontroller) { /* This is indexed by SDL_GameControllerButton. */ static const struct { int x; int y; } button_positions[] = { {387, 167}, /* A */ {431, 132}, /* B */ {342, 132}, /* X */ {389, 101}, /* Y */ {174, 132}, /* BACK */ {233, 132}, /* GUIDE */ {289, 132}, /* START */ {75, 154}, /* LEFTSTICK */ {305, 230}, /* RIGHTSTICK */ {77, 40}, /* LEFTSHOULDER */ {396, 36}, /* RIGHTSHOULDER */ {154, 188}, /* DPAD_UP */ {154, 249}, /* DPAD_DOWN */ {116, 217}, /* DPAD_LEFT */ {186, 217}, /* DPAD_RIGHT */ }; /* This is indexed by SDL_GameControllerAxis. */ static const struct { int x; int y; double angle; } axis_positions[] = { {75, 154, 0.0}, /* LEFTX */ {75, 154, 90.0}, /* LEFTY */ {305, 230, 0.0}, /* RIGHTX */ {305, 230, 90.0}, /* RIGHTY */ {91, 0, 90.0}, /* TRIGGERLEFT */ {375, 0, 90.0}, /* TRIGGERRIGHT */ }; const char *name = SDL_GameControllerName(gamecontroller); const char *basetitle = "Game Controller Test: "; const size_t titlelen = SDL_strlen(basetitle) + SDL_strlen(name) + 1; char *title = (char *)SDL_malloc(titlelen); SDL_Texture *background, *button, *axis; SDL_Window *window = NULL; SDL_Renderer *screen = NULL; SDL_bool retval = SDL_FALSE; SDL_bool done = SDL_FALSE; SDL_Event event; int i; if (title) { SDL_snprintf(title, titlelen, "%s%s", basetitle, name); } /* Create a window to display controller state */ window = SDL_CreateWindow(title, SDL_WINDOWPOS_CENTERED, SDL_WINDOWPOS_CENTERED, SCREEN_WIDTH, SCREEN_HEIGHT, 0); if (window == NULL) { SDL_LogError(SDL_LOG_CATEGORY_APPLICATION, "Couldn't create window: %s\n", SDL_GetError()); return SDL_FALSE; } screen = SDL_CreateRenderer(window, -1, 0); if (screen == NULL) { SDL_LogError(SDL_LOG_CATEGORY_APPLICATION, "Couldn't create renderer: %s\n", SDL_GetError()); SDL_DestroyWindow(window); return SDL_FALSE; } SDL_SetRenderDrawColor(screen, 0x00, 0x00, 0x00, SDL_ALPHA_OPAQUE); SDL_RenderClear(screen); SDL_RenderPresent(screen); SDL_RaiseWindow(window); /* scale for platforms that don't give you the window size you asked for. */ SDL_RenderSetLogicalSize(screen, SCREEN_WIDTH, SCREEN_HEIGHT); background = LoadTexture(screen, "controllermap.bmp", SDL_FALSE); button = LoadTexture(screen, "button.bmp", SDL_TRUE); axis = LoadTexture(screen, "axis.bmp", SDL_TRUE); if (!background || !button || !axis) { SDL_DestroyRenderer(screen); SDL_DestroyWindow(window); return SDL_FALSE; } SDL_SetTextureColorMod(button, 10, 255, 21); SDL_SetTextureColorMod(axis, 10, 255, 21); /* !!! FIXME: */ /*SDL_RenderSetLogicalSize(screen, background->w, background->h);*/ /* Print info about the controller we are watching */ SDL_Log("Watching controller %s\n", name ? name : "Unknown Controller"); /* Loop, getting controller events! */ while (!done) { /* blank screen, set up for drawing this frame. */ SDL_SetRenderDrawColor(screen, 0xFF, 0xFF, 0xFF, SDL_ALPHA_OPAQUE); SDL_RenderClear(screen); SDL_RenderCopy(screen, background, NULL, NULL); while (SDL_PollEvent(&event)) { switch (event.type) { case SDL_KEYDOWN: if (event.key.keysym.sym != SDLK_ESCAPE) { break; } /* Fall through to signal quit */ case SDL_QUIT: done = SDL_TRUE; break; default: break; } } /* Update visual controller state */ for (i = 0; i < SDL_CONTROLLER_BUTTON_MAX; ++i) { if (SDL_GameControllerGetButton(gamecontroller, (SDL_GameControllerButton)i) == SDL_PRESSED) { const SDL_Rect dst = { button_positions[i].x, button_positions[i].y, 50, 50 }; SDL_RenderCopyEx(screen, button, NULL, &dst, 0, NULL, 0); } } for (i = 0; i < SDL_CONTROLLER_AXIS_MAX; ++i) { const Sint16 deadzone = 8000; /* !!! FIXME: real deadzone */ const Sint16 value = SDL_GameControllerGetAxis(gamecontroller, (SDL_GameControllerAxis)(i)); if (value < -deadzone) { const SDL_Rect dst = { axis_positions[i].x, axis_positions[i].y, 50, 50 }; const double angle = axis_positions[i].angle; SDL_RenderCopyEx(screen, axis, NULL, &dst, angle, NULL, 0); } else if (value > deadzone) { const SDL_Rect dst = { axis_positions[i].x, axis_positions[i].y, 50, 50 }; const double angle = axis_positions[i].angle + 180.0; SDL_RenderCopyEx(screen, axis, NULL, &dst, angle, NULL, 0); } } SDL_RenderPresent(screen); if (!SDL_GameControllerGetAttached(gamecontroller)) { done = SDL_TRUE; retval = SDL_TRUE; /* keep going, wait for reattach. */ } } SDL_DestroyRenderer(screen); SDL_DestroyWindow(window); return retval; }
/* * Show the window */ int S2D_Show(Window *window) { // Setting up variables int mouse_x, mouse_y; // Mouse positions const Uint8 *key_state; Uint32 frames = 0; // Total frames since start Uint32 start_ms = SDL_GetTicks(); // Elapsed time since start Uint32 begin_ms = start_ms; // Time at beginning of loop Uint32 end_ms; // Time at end of loop Uint32 elapsed_ms; // Total elapsed time Uint32 loop_ms; // Elapsed time of loop int delay_ms; // Amount of delay to achieve desired frame rate double fps; // The actual frame rate // Enable VSync if (window->vsync) { if (!SDL_SetHint(SDL_HINT_RENDER_VSYNC, "1")) { S2D_Log("VSync cannot be enabled", S2D_WARN); } } // Detect Controllers and Joysticks ////////////////////////////////////////// if (SDL_NumJoysticks() > 0) { sprintf(S2D_msg, "Joysticks detected: %i", SDL_NumJoysticks()); S2D_Log(S2D_msg, S2D_INFO); } // Variables for controllers and joysticks SDL_GameController *controller = NULL; SDL_Joystick *joy = NULL; // Enumerate joysticks for (int i = 0; i < SDL_NumJoysticks(); ++i) { // Check to see if joystick supports SDL's game controller interface if (SDL_IsGameController(i)) { controller = SDL_GameControllerOpen(i); if (controller) { sprintf(S2D_msg, "Found a valid controller, named: %s\n", SDL_GameControllerName(controller)); S2D_Log(S2D_msg, S2D_INFO); break; // Break after first available controller } else { sprintf(S2D_msg, "Could not open game controller %i: %s\n", i, SDL_GetError()); S2D_Log(S2D_msg, S2D_ERROR); } // Controller interface not supported, try to open as joystick } else { sprintf(S2D_msg, "Joystick %i is not supported by the game controller interface", i); S2D_Log(S2D_msg, S2D_WARN); joy = SDL_JoystickOpen(i); // Joystick is valid if (joy) { sprintf(S2D_msg, "Opened Joystick %i\n" "Name: %s\n" "Axes: %d\n" "Buttons: %d\n" "Balls: %d\n", i, SDL_JoystickName(joy), SDL_JoystickNumAxes(joy), SDL_JoystickNumButtons(joy), SDL_JoystickNumBalls(joy) ); S2D_Log(S2D_msg, S2D_INFO); // Joystick not valid } else { sprintf(S2D_msg, "Could not open Joystick %i", i); S2D_Log(S2D_msg, S2D_ERROR); } break; // Break after first available joystick } } // Main Event Loop /////////////////////////////////////////////////////////// bool quit = false; while (!quit) { // Clear Frame ///////////////////////////////////////////////////////////// S2D_GL_Clear(window->background); // Set FPS ///////////////////////////////////////////////////////////////// frames++; end_ms = SDL_GetTicks(); elapsed_ms = end_ms - start_ms; fps = frames / (elapsed_ms / 1000.0); loop_ms = end_ms - begin_ms; delay_ms = (1000 / window->fps_cap) - loop_ms; if (delay_ms < 0) delay_ms = 0; // Note: `loop_ms + delay_ms` should equal `1000 / fps_cap` SDL_Delay(delay_ms); begin_ms = SDL_GetTicks(); // Handle Input //////////////////////////////////////////////////////////// SDL_Event e; while (SDL_PollEvent(&e)) { switch (e.type) { case SDL_KEYDOWN: if (window->on_key) window->on_key(SDL_GetScancodeName(e.key.keysym.scancode)); break; case SDL_MOUSEBUTTONDOWN: if (window->on_mouse) window->on_mouse(e.button.x, e.button.y); break; case SDL_JOYAXISMOTION: if (window->on_controller) window->on_controller(true, e.jaxis.axis, e.jaxis.value, false, 0); break; case SDL_JOYBUTTONDOWN: if (window->on_controller) window->on_controller(false, 0, 0, true, e.jbutton.button); break; case SDL_WINDOWEVENT: switch (e.window.event) { case SDL_WINDOWEVENT_RESIZED: S2D_GL_SetView(e.window.data1, e.window.data2, window->width, window->height); break; } break; case SDL_QUIT: quit = true; break; } } // Detect keys held down int num_keys; key_state = SDL_GetKeyboardState(&num_keys); for (int i = 0; i < num_keys; i++) { if (window->on_key_down) { if (key_state[i] == 1) { window->on_key_down(SDL_GetScancodeName(i)); } } } // Store the mouse position SDL_GetMouseState(&mouse_x, &mouse_y); // Update Window State ///////////////////////////////////////////////////// // Store new values in the window window->mouse.x = mouse_x; window->mouse.y = mouse_y; window->mouse.real_x = mouse_x; window->mouse.real_y = mouse_y; window->frames = frames; window->elapsed_ms = elapsed_ms; window->loop_ms = loop_ms; window->delay_ms = delay_ms; window->fps = fps; // scale the mouse position, if necessary if (window->s_width != window->width) { window->mouse.x = (int)((double)window->mouse.real_x * ((double)window->s_width / (double)window->width) + 0.5); } if (window->s_height != window->height) { window->mouse.y = (int)((double)window->mouse.real_y * ((double)window->s_height / (double)window->height) + 0.5); } // Call update and render callbacks if (window->update) window->update(); if (window->render) window->render(); // Draw Frame ////////////////////////////////////////////////////////////// SDL_GL_SwapWindow(window->sdl); } return 0; }
void WatchGameController(SDL_GameController * gamecontroller) { SDL_Window *window = NULL; SDL_Renderer *screen = NULL; const char *name = NULL; int done = 0; SDL_Event event; int i; /* Create a window to display controller axis position */ window = SDL_CreateWindow("Game Controller Test", SDL_WINDOWPOS_CENTERED, SDL_WINDOWPOS_CENTERED, SCREEN_WIDTH, SCREEN_HEIGHT, SDL_WINDOW_SHOWN); if (window == NULL) { fprintf(stderr, "Couldn't create window: %s\n", SDL_GetError()); return; } screen = SDL_CreateRenderer(window, -1, 0); if (screen == NULL) { fprintf(stderr, "Couldn't create renderer: %s\n", SDL_GetError()); SDL_DestroyWindow(window); return; } SDL_SetRenderDrawColor(screen, 0x00, 0x00, 0x00, SDL_ALPHA_OPAQUE); SDL_RenderClear(screen); SDL_RenderPresent(screen); SDL_RaiseWindow(window); /* Print info about the controller we are watching */ name = SDL_GameControllerName(gamecontroller); printf("Watching controller %s\n", name ? name : "Unknown Controller"); /* Loop, getting controller events! */ while (!done) { /* blank screen, set up for drawing this frame. */ SDL_SetRenderDrawColor(screen, 0x00, 0x00, 0x00, SDL_ALPHA_OPAQUE); SDL_RenderClear(screen); while (SDL_PollEvent(&event)) { switch (event.type) { case SDL_CONTROLLERAXISMOTION: printf("Controller %d axis %d value: %d\n", event.caxis.which, event.caxis.axis, event.caxis.value); break; case SDL_CONTROLLERBUTTONDOWN: printf("Controller %d button %d down\n", event.cbutton.which, event.cbutton.button); break; case SDL_CONTROLLERBUTTONUP: printf("Controller %d button %d up\n", event.cbutton.which, event.cbutton.button); break; case SDL_KEYDOWN: if (event.key.keysym.sym != SDLK_ESCAPE) { break; } /* Fall through to signal quit */ case SDL_QUIT: done = 1; s_ForceQuit = SDL_TRUE; break; default: break; } } /* Update visual controller state */ SDL_SetRenderDrawColor(screen, 0x00, 0xFF, 0x00, SDL_ALPHA_OPAQUE); for (i = 0; i <SDL_CONTROLLER_BUTTON_MAX; ++i) { if (SDL_GameControllerGetButton(gamecontroller, i) == SDL_PRESSED) { DrawRect(screen, i * 34, SCREEN_HEIGHT - 34, 32, 32); } } SDL_SetRenderDrawColor(screen, 0xFF, 0x00, 0x00, SDL_ALPHA_OPAQUE); for (i = 0; i < SDL_CONTROLLER_AXIS_MAX / 2; ++i) { /* Draw the X/Y axis */ int x, y; x = (((int) SDL_GameControllerGetAxis(gamecontroller, i * 2 + 0)) + 32768); x *= SCREEN_WIDTH; x /= 65535; if (x < 0) { x = 0; } else if (x > (SCREEN_WIDTH - 16)) { x = SCREEN_WIDTH - 16; } y = (((int) SDL_GameControllerGetAxis(gamecontroller, i * 2 + 1)) + 32768); y *= SCREEN_HEIGHT; y /= 65535; if (y < 0) { y = 0; } else if (y > (SCREEN_HEIGHT - 16)) { y = SCREEN_HEIGHT - 16; } DrawRect(screen, x, y, 16, 16); } SDL_SetRenderDrawColor(screen, 0x00, 0x00, 0xFF, SDL_ALPHA_OPAQUE); SDL_RenderPresent(screen); if ( !done ) done = SDL_GameControllerGetAttached( gamecontroller ) == 0; } SDL_DestroyRenderer(screen); SDL_DestroyWindow(window); }
String getControllerName(u32 controllerIndex) { return {SDL_GameControllerName(g_controllerHandles[controllerIndex])}; }
SDL_bool WatchGameController(SDL_GameController * gamecontroller) { const char *name = SDL_GameControllerName(gamecontroller); const char *basetitle = "Game Controller Test: "; const size_t titlelen = SDL_strlen(basetitle) + SDL_strlen(name) + 1; char *title = (char *)SDL_malloc(titlelen); SDL_Window *window = NULL; SDL_Renderer *screen = NULL; SDL_bool retval = SDL_FALSE; SDL_bool done = SDL_FALSE; SDL_Event event; int i; if (title) { SDL_snprintf(title, titlelen, "%s%s", basetitle, name); } /* Create a window to display controller axis position */ window = SDL_CreateWindow(title, SDL_WINDOWPOS_CENTERED, SDL_WINDOWPOS_CENTERED, SCREEN_WIDTH, SCREEN_HEIGHT, 0); if (window == NULL) { SDL_LogError(SDL_LOG_CATEGORY_APPLICATION, "Couldn't create window: %s\n", SDL_GetError()); return SDL_FALSE; } screen = SDL_CreateRenderer(window, -1, 0); if (screen == NULL) { SDL_LogError(SDL_LOG_CATEGORY_APPLICATION, "Couldn't create renderer: %s\n", SDL_GetError()); SDL_DestroyWindow(window); return SDL_FALSE; } SDL_SetRenderDrawColor(screen, 0x00, 0x00, 0x00, SDL_ALPHA_OPAQUE); SDL_RenderClear(screen); SDL_RenderPresent(screen); SDL_RaiseWindow(window); /* Print info about the controller we are watching */ SDL_Log("Watching controller %s\n", name ? name : "Unknown Controller"); /* Loop, getting controller events! */ while (!done) { /* blank screen, set up for drawing this frame. */ SDL_SetRenderDrawColor(screen, 0x00, 0x00, 0x00, SDL_ALPHA_OPAQUE); SDL_RenderClear(screen); while (SDL_PollEvent(&event)) { switch (event.type) { case SDL_CONTROLLERAXISMOTION: SDL_Log("Controller %d axis %d ('%s') value: %d\n", event.caxis.which, event.caxis.axis, ControllerAxisName((SDL_GameControllerAxis)event.caxis.axis), event.caxis.value); break; case SDL_CONTROLLERBUTTONDOWN: SDL_Log("Controller %d button %d ('%s') down\n", event.cbutton.which, event.cbutton.button, ControllerButtonName((SDL_GameControllerButton)event.cbutton.button)); break; case SDL_CONTROLLERBUTTONUP: SDL_Log("Controller %d button %d ('%s') up\n", event.cbutton.which, event.cbutton.button, ControllerButtonName((SDL_GameControllerButton)event.cbutton.button)); break; case SDL_KEYDOWN: if (event.key.keysym.sym != SDLK_ESCAPE) { break; } /* Fall through to signal quit */ case SDL_QUIT: done = SDL_TRUE; break; default: break; } } /* Update visual controller state */ SDL_SetRenderDrawColor(screen, 0x00, 0xFF, 0x00, SDL_ALPHA_OPAQUE); for (i = 0; i <SDL_CONTROLLER_BUTTON_MAX; ++i) { if (SDL_GameControllerGetButton(gamecontroller, (SDL_GameControllerButton)i) == SDL_PRESSED) { DrawRect(screen, i * 34, SCREEN_HEIGHT - 34, 32, 32); } } SDL_SetRenderDrawColor(screen, 0xFF, 0x00, 0x00, SDL_ALPHA_OPAQUE); for (i = 0; i < SDL_CONTROLLER_AXIS_MAX / 2; ++i) { /* Draw the X/Y axis */ int x, y; x = (((int) SDL_GameControllerGetAxis(gamecontroller, (SDL_GameControllerAxis)(i * 2 + 0))) + 32768); x *= SCREEN_WIDTH; x /= 65535; if (x < 0) { x = 0; } else if (x > (SCREEN_WIDTH - 16)) { x = SCREEN_WIDTH - 16; } y = (((int) SDL_GameControllerGetAxis(gamecontroller, (SDL_GameControllerAxis)(i * 2 + 1))) + 32768); y *= SCREEN_HEIGHT; y /= 65535; if (y < 0) { y = 0; } else if (y > (SCREEN_HEIGHT - 16)) { y = SCREEN_HEIGHT - 16; } DrawRect(screen, x, y, 16, 16); } SDL_SetRenderDrawColor(screen, 0x00, 0x00, 0xFF, SDL_ALPHA_OPAQUE); SDL_RenderPresent(screen); if (!SDL_GameControllerGetAttached(gamecontroller)) { done = SDL_TRUE; retval = SDL_TRUE; /* keep going, wait for reattach. */ } } SDL_DestroyRenderer(screen); SDL_DestroyWindow(window); return retval; }
Common::UString GameController::getControllerName() const { return SDL_GameControllerName(_sdlController); }