void refresh_controllers() { for (s32 i = 0; i < MAX_GAMEPADS; i++) { if (haptics[i]) { SDL_HapticClose(haptics[i]); haptics[i] = nullptr; } if (controllers[i]) { SDL_GameControllerClose(controllers[i]); controllers[i] = nullptr; } } for (s32 i = 0; i < SDL_NumJoysticks(); i++) { if (SDL_IsGameController(i)) { controllers[i] = SDL_GameControllerOpen(i); SDL_Joystick* joystick = SDL_GameControllerGetJoystick(controllers[i]); if (SDL_JoystickIsHaptic(joystick)) { haptics[i] = SDL_HapticOpenFromJoystick(joystick); if (SDL_HapticRumbleInit(haptics[i])) // failed { SDL_HapticClose(haptics[i]); haptics[i] = nullptr; } } } } }
void JoyInitHaptic() { #if 0 uint8_t i; unsigned int haptic_query = 0; for (i = 0; i < 2; i++) { if (g.PadState[i].JoyDev && SDL_JoystickIsHaptic(g.PadState[i].JoyDev)) { if (g.PadState[i].haptic != NULL) { SDL_HapticClose(g.PadState[i].haptic); g.PadState[i].haptic = NULL; } g.PadState[i].haptic = SDL_HapticOpenFromJoystick(g.PadState[i].JoyDev); if (g.PadState[i].haptic == NULL) continue; if (SDL_HapticRumbleSupported(g.PadState[i].haptic) == SDL_FALSE) { printf("\nRumble not supported\n"); g.PadState[i].haptic = NULL; continue; } if (SDL_HapticRumbleInit(g.PadState[i].haptic) != 0) { printf("\nFailed to initialize rumble: %s\n", SDL_GetError()); g.PadState[i].haptic = NULL; continue; } } } #endif }
void JoystickInfo::TestForce() { #if SDL_MAJOR_VERSION >= 2 // This code just use standard rumble to check that SDL handles the pad correctly! --3kinox if(haptic == NULL) return; // Otherwise, core dump! SDL_HapticRumbleInit( haptic ); // Make the haptic pad rumble 60% strength for half a second, shoudld be enough for user to see if it works or not if( SDL_HapticRumblePlay( haptic, 0.60, 400 ) != 0) { fprintf(stderr,"ERROR: Rumble is not working! %s\n",SDL_GetError()); } #endif }
void SDLFrontend::initJoystickAndHaptic () { if (_haptic != nullptr) { SDL_HapticClose(_haptic); _haptic = nullptr; } const int joysticks = SDL_NumJoysticks(); SDL_Haptic *haptic = nullptr; for (int i = 0; i < joysticks; i++) { const char *name; if (SDL_IsGameController(i)) { name = SDL_GameControllerNameForIndex(i); } else { name = SDL_JoystickNameForIndex(i); } SDL_Joystick *joystick = SDL_JoystickOpen(i); info(LOG_CLIENT, String::format("found joystick %s", name ? name : "Unknown Joystick")); info(LOG_CLIENT, String::format("joystick axes: %i", SDL_JoystickNumAxes(joystick))); info(LOG_CLIENT, String::format("joystick hats: %i", SDL_JoystickNumHats(joystick))); info(LOG_CLIENT, String::format("joystick balls: %i", SDL_JoystickNumBalls(joystick))); info(LOG_CLIENT, String::format("joystick buttons: %i", SDL_JoystickNumButtons(joystick))); if (haptic == nullptr) haptic = SDL_HapticOpenFromJoystick(joystick); } if (!joysticks) { info(LOG_CLIENT, "no joysticks found"); } info(LOG_CLIENT, String::format("found %i touch device(s)", SDL_GetNumTouchDevices())); info(LOG_CLIENT, String::format("%i haptic devices", SDL_NumHaptics())); if (haptic == nullptr && SDL_MouseIsHaptic()) { haptic = SDL_HapticOpenFromMouse(); } if (haptic != nullptr) { const bool rumbleSupported = SDL_HapticRumbleSupported(haptic) && SDL_HapticRumbleInit(haptic) == 0; if (rumbleSupported) { info(LOG_CLIENT, "rumble support"); _haptic = haptic; } } if (_haptic == nullptr) { info(LOG_CLIENT, "no rumble support"); } }
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; }
C4GamePadOpener::C4GamePadOpener(int iGamepad) { int n = iGamepad; for (int i = 0; i < SDL_NumJoysticks(); i++) if (SDL_IsGameController(i) && n-- == 0) { controller = SDL_GameControllerOpen(i); if (!controller) LogF("SDL: %s", SDL_GetError()); SDL_Joystick *joystick = SDL_GameControllerGetJoystick(controller); haptic = SDL_HapticOpenFromJoystick(joystick); if (haptic && SDL_HapticRumbleSupported(haptic)) SDL_HapticRumbleInit(haptic); else LogF("Gamepad #%d %s does not support rumbling.", SDL_JoystickInstanceID(joystick), SDL_JoystickName(joystick)); break; } if (!controller) LogF("Gamepad %d not available", iGamepad); }
void JoystickControl::_Init(int id){ joystick = NULL; joystickHaptic = NULL; if(SDL_NumJoysticks() < id +1) log("No se puede abrir el joystick",LOG_ERROR); else joystick = SDL_JoystickOpen( id ); if( joystick == NULL ) log(string("No se puede leer el joystick! SDL Error:" + string(SDL_GetError())),LOG_ERROR); else{ log("Joystick cargado correctamente",LOG_DEBUG); //joystickHaptic = SDL_HapticOpenFromJoystick( joystick ); if( joystickHaptic == NULL ){ log(string("El Joystick no soporta haptics! SDL Error:" + string(SDL_GetError())),LOG_WARNING); } else{ //Get initialize rumble if( SDL_HapticRumbleInit( joystickHaptic ) < 0 ){ log(string("Unable to initialize rumble! SDL Error:" + string(SDL_GetError())),LOG_WARNING); } } } }
Controller::Controller(){ SDL_InitSubSystem(SDL_INIT_JOYSTICK); SDL_Init(SDL_INIT_HAPTIC); SDL_JoystickEventState(SDL_ENABLE); joystick = SDL_JoystickOpen(0); if (joystick){ joystickAnalogs.resize(SDL_JoystickNumAxes(joystick)); joystickButtonHeld.resize(SDL_JoystickNumButtons(joystick)); joystickButtonPressed.resize(SDL_JoystickNumButtons(joystick)); joystickButtonReleased.resize(SDL_JoystickNumButtons(joystick)); joystickDPad.resize(13); haptic = SDL_HapticOpenFromJoystick(joystick); if (SDL_HapticRumbleSupported(haptic) == SDL_TRUE){ SDL_HapticRumbleInit(haptic); rumbleSupport = true; } else rumbleSupport = false; } }
bool DEV_Joystick::RumblePlay(float strength, int duration) { #ifdef WITH_SDL if (m_private->m_haptic == NULL) { return false; } // Initialize simple rumble if (SDL_HapticRumbleInit(m_private->m_haptic) != 0) { return false; } // Play effect at strength for m_duration milliseconds if (SDL_HapticRumblePlay(m_private->m_haptic, strength, duration) != 0) { return false; } return true; #endif // WITH_SDL return false; }
int _create_controler(int i) { SDL_GameController *controller = SDL_GameControllerOpen(i); SDL_Joystick *joy = SDL_GameControllerGetJoystick(controller); int idx = _new_controler(); _G.controller[idx] = controller; memory_set(_G.state[idx], 0, sizeof(int) * GAMEPAD_BTN_MAX); if (SDL_JoystickIsHaptic(joy) == 1) { SDL_Haptic *haptic = SDL_HapticOpenFromJoystick(joy); SDL_HapticRumbleInit(haptic); _G.haptic[idx] = haptic; log_info("input.gamepad", "Gamepad %d has haptic support", i); } else { _G.haptic[idx] = NULL; } return idx; }
void test_rumble(int joy_idx) { SDL_Joystick* joy = SDL_JoystickOpen(joy_idx); if (!joy) { fprintf(stderr, "Unable to open joystick %d\n", joy_idx); } else { SDL_Haptic* haptic = SDL_HapticOpenFromJoystick(joy); if (!haptic) { fprintf(stderr, "Unable to open haptic on joystick %d\n", joy_idx); fprintf(stderr, "SDL_Error: %s\n", SDL_GetError()); } else { if (!SDL_HapticRumbleSupported(haptic)) { fprintf(stderr, "rumble not supported on joystick %d\n", joy_idx); } else { if (SDL_HapticRumbleInit(haptic) != 0) { fprintf(stderr, "failed to init rumble\n"); } else { SDL_HapticRumblePlay(haptic, 1.0, 3000); SDL_Delay(3000); } } SDL_HapticClose(haptic); } SDL_JoystickClose(joy); } }
/****** Initialize GamePad ******/ void DMG_GamePad::init() { //Initialize joystick subsystem if(SDL_InitSubSystem(SDL_INIT_JOYSTICK) == -1) { std::cout<<"JOY::Could not initialize SDL joysticks\n"; return; } jstick = NULL; jstick = SDL_JoystickOpen(config::joy_id); if((jstick == NULL) && (SDL_NumJoysticks() >= 1)) { std::cout<<"JOY::Could not initialize joystick \n"; } else if((jstick == NULL) && (SDL_NumJoysticks() == 0)) { std::cout<<"JOY::No joysticks detected \n"; return; } rumble = NULL; //Open haptics for rumbling if(config::use_haptics) { if(SDL_InitSubSystem(SDL_INIT_HAPTIC) == -1) { std::cout<<"JOY::Could not initialize SDL haptics\n"; return; } rumble = SDL_HapticOpenFromJoystick(jstick); if(rumble == NULL) { std::cout<<"JOY::Could not init rumble \n"; } else { SDL_HapticRumbleInit(rumble); std::cout<<"JOY::Rumble initialized\n"; } } }
internal void sdl_init_joysticks(struct sdl_event_context *ctx) { unsigned int player; int num_joy_sticks, jsi; SDL_GameController *controller; SDL_Joystick *joystick; SDL_Haptic *rumble; for (player = 0; player < MAX_CONTROLLERS; ++player) { ctx->players[player].controller = NULL; ctx->players[player].rumble = NULL; } num_joy_sticks = SDL_NumJoysticks(); debug(0, "SDL_NumJoysticks() == %d\n", num_joy_sticks); player = 0; for (jsi = 0; jsi < num_joy_sticks && player < MAX_CONTROLLERS; ++jsi) { if (!SDL_IsGameController(jsi)) { debug(0, "SDL_IsGameController(%d) == 0\n", jsi); continue; } controller = SDL_GameControllerOpen(jsi); ctx->players[player].controller = controller; debug(0, "ctx->players[%u].controller = %p\n", player, (void *)controller); joystick = SDL_GameControllerGetJoystick(controller); rumble = SDL_HapticOpenFromJoystick(joystick); if (SDL_HapticRumbleInit(rumble)) { ctx->players[player].rumble = rumble; } else { SDL_HapticClose(rumble); } ++player; } }
inline void SDLOpenGameControllers() { int MaxJoysticks = SDL_NumJoysticks(); for(int JoystickIndex = 0; JoystickIndex < MaxJoysticks; JoystickIndex++) { if (!SDL_IsGameController(JoystickIndex)) { continue; } else { GamePadHandle = SDL_GameControllerOpen(JoystickIndex); RumbleHandle = SDL_HapticOpen(JoystickIndex); // NOTE(Redab): SDL_HapticRumbleInit() returns 0 on // success, check for failure. if(RumbleHandle && SDL_HapticRumbleInit(RumbleHandle) != 0) { SDL_HapticClose(RumbleHandle); RumbleHandle = 0; } printf("Game controller added.\n"); break; } } }
/** * @brief The entry point of this force feedback demo. * @param[in] argc Number of arguments. * @param[in] argv Array of argc arguments. */ int main(int argc, char **argv) { int i; char *name; int index; SDL_HapticEffect efx[5]; int id[5]; int nefx; unsigned int supported; name = NULL; index = -1; if (argc > 1) { name = argv[1]; if ((strcmp(name, "--help") == 0) || (strcmp(name, "-h") == 0)) { printf("USAGE: %s [device]\n" "If device is a two-digit number it'll use it as an index, otherwise\n" "it'll use it as if it were part of the device's name.\n", argv[0]); return 0; } i = strlen(name); if ((i < 3) && isdigit(name[0]) && ((i == 1) || isdigit(name[1]))) { index = atoi(name); name = NULL; } } /* Initialize the force feedbackness */ SDL_Init(SDL_INIT_VIDEO | SDL_INIT_TIMER | SDL_INIT_JOYSTICK | SDL_INIT_HAPTIC); printf("%d Haptic devices detected.\n", SDL_NumHaptics()); if (SDL_NumHaptics() > 0) { /* We'll just use index or the first force feedback device found */ if (name == NULL) { i = (index != -1) ? index : 0; } /* Try to find matching device */ else { for (i = 0; i < SDL_NumHaptics(); i++) { if (strstr(SDL_HapticName(i), name) != NULL) break; } if (i >= SDL_NumHaptics()) { printf("Unable to find device matching '%s', aborting.\n", name); return 1; } } haptic = SDL_HapticOpen(i); if (haptic == NULL) { printf("Unable to create the haptic device: %s\n", SDL_GetError()); return 1; } printf("Device: %s\n", SDL_HapticName(i)); } else { printf("No Haptic devices found!\n"); return 1; } /* We only want force feedback errors. */ SDL_ClearError(); if (SDL_HapticRumbleSupported(haptic) == SDL_FALSE) { printf("\nRumble not supported!\n"); return 1; } if (SDL_HapticRumbleInit(haptic) != 0) { printf("\nFailed to initialize rumble: %s\n", SDL_GetError()); return 1; } printf("Playing 2 second rumble at 0.5 magnitude.\n"); if (SDL_HapticRumblePlay(haptic, 0.5, 5000) != 0) { printf("\nFailed to play rumble: %s\n", SDL_GetError() ); return 1; } SDL_Delay(2000); printf("Stopping rumble.\n"); SDL_HapticRumbleStop(haptic); SDL_Delay(2000); printf("Playing 2 second rumble at 0.3 magnitude.\n"); if (SDL_HapticRumblePlay(haptic, 0.3, 5000) != 0) { printf("\nFailed to play rumble: %s\n", SDL_GetError() ); return 1; } SDL_Delay(2000); /* Quit */ if (haptic != NULL) SDL_HapticClose(haptic); SDL_Quit(); return 0; }
bool Application::OnInit() { if(SDL_Init(SDL_INIT_EVERYTHING) < 0) { return false; } // Set up graphics SDL_Window *screen = SDL_CreateWindow("Psychokinesis", SDL_WINDOWPOS_UNDEFINED, SDL_WINDOWPOS_UNDEFINED, screenw, screenh, SDL_WINDOW_OPENGL); if(screen == NULL) { Logger::log("SDL_CreateWindow failure"); return false; } if((graphics.renderer = SDL_CreateRenderer(screen, -1, 0)) == NULL) { Logger::log("SDL_CreateRenderer failure"); return false; } graphics.camera = new Camera(); entities.push_back(new Entity(new CameraControl(graphics.camera), new NullPhysicsComponent(), new NullRenderComponent())); // Set up joystick controls std::stringstream ss; ss << SDL_NumJoysticks() << " joysticks were found"; Logger::log(ss.str()); SDL_JoystickEventState(SDL_ENABLE); joystick = SDL_JoystickOpen(0); // Set up rumble effects haptic = SDL_HapticOpen( 0 ); if (haptic == NULL) { Logger::log("SDL_HapticOpen failure"); } if (haptic != NULL && SDL_HapticRumbleInit( haptic ) != 0) { Logger::log("SDL_HapticRumbleInit failure: " + std::string(SDL_GetError())); haptic = NULL; } SDL_HapticEffect effect; memset(&effect, 0, sizeof(SDL_HapticEffect)); effect.type = SDL_HAPTIC_SINE; effect.periodic.direction.type = SDL_HAPTIC_POLAR; // Polar coordinates effect.periodic.direction.dir[0] = 18000; // Force comes from south effect.periodic.period = 1000; // 1000 ms effect.periodic.magnitude = 20000; // 20000/32767 strength effect.periodic.length = 1000; // .1 seconds long effect.periodic.attack_length = 0; // Takes 0 seconds to get max strength effect.periodic.fade_length = 0; // Takes 0 seconds to fade away effect_id = SDL_HapticNewEffect(haptic, &effect); Logger::log("Creating player"); Create(Entity::PLAYER, 4, 20); // Test blocks to shove around // Create(Entity::LITTLE_MAN, 26, 25); // Create(Entity::LITTLE_MAN, 21, 25); // Create(Entity::BIG_MAN, 17, 25); // Create(Entity::LITTLE_MAN, 26, 20); // Create(Entity::LITTLE_MAN, 11, 20); // Create(Entity::LITTLE_MAN, 7, 20); // Create(Entity::LITTLE_MAN, 26, 35); Create(Entity::LITTLE_MAN, 21, 35); Create(Entity::BIG_MAN, 17, 35); Create(Entity::LITTLE_MAN, 26, 30); Create(Entity::LITTLE_MAN, 11, 30); Create(Entity::LITTLE_MAN, 7, 30); /// \todo Make the bullet factory manage its own list entities.push_back(Bullet::Create(&Level::p_level->world, graphics, 20, 30, 20, 0)); mainhud.Hud_Load_Hit_Pts_Texture("art_assets/hit_pts_meter.png", graphics.renderer, Player::player->hit_pts); if(level.LoadAssets(graphics.renderer, "art_assets/sky2.png", "art_assets/lanscape.png") == NULL) { Logger::log("Level loading failure: " + std::string(SDL_GetError())); } Level::p_level->world.SetContactListener(&contactListen); oldtime = SDL_GetTicks(); return true; }
FDeviceInfoSDL FDeviceSDL::AddDevice(FDeviceIndex DeviceIndex) { FDeviceInfoSDL Device; if (SDL_IsGameController(DeviceIndex.value) && bIgnoreGameControllers) { // Let UE handle it return Device; } Device.DeviceIndex = DeviceIndex; Device.Joystick = SDL_JoystickOpen(DeviceIndex.value); if (Device.Joystick == nullptr) { return Device; } Device.InstanceId = FInstanceId(SDL_JoystickInstanceID(Device.Joystick)); // DEBUG Device.Name = FString(ANSI_TO_TCHAR(SDL_JoystickName(Device.Joystick))); UE_LOG(JoystickPluginLog, Log, TEXT("--- %s"), *Device.Name); UE_LOG(JoystickPluginLog, Log, TEXT("--- Number of Axis %i"), SDL_JoystickNumAxes(Device.Joystick)); UE_LOG(JoystickPluginLog, Log, TEXT("--- Number of Balls %i"), SDL_JoystickNumBalls(Device.Joystick)); UE_LOG(JoystickPluginLog, Log, TEXT("--- Number of Buttons %i"), SDL_JoystickNumButtons(Device.Joystick)); UE_LOG(JoystickPluginLog, Log, TEXT("--- Number of Hats %i"), SDL_JoystickNumHats(Device.Joystick)); if (SDL_JoystickIsHaptic(Device.Joystick)) { Device.Haptic = SDL_HapticOpenFromJoystick(Device.Joystick); if (Device.Haptic != nullptr) { UE_LOG(JoystickPluginLog, Log, TEXT("--- Rumble device detected")); if (SDL_HapticRumbleInit(Device.Haptic) != 0) { /*UE_LOG(JoystickPluginLog, Log, TEXT("--- testing Rumble device:")); if (SDL_HapticRumblePlay(OutDeviceInfo.Haptic, 0.5, 2000) != 0) { UE_LOG(JoystickPluginLog, Log, TEXT("--- play Rumble ....")); SDL_Delay(2000); } else { UE_LOG(JoystickPluginLog, Log, TEXT("--- not successful!")); SDL_HapticClose(OutDeviceInfo.Haptic); OutDeviceInfo.Haptic = nullptr; }*/ } } } for (auto &ExistingDevice : Devices) { if (ExistingDevice.Value.Joystick == nullptr && ExistingDevice.Value.Name == Device.Name) { Device.DeviceId = ExistingDevice.Key; Devices[Device.DeviceId] = Device; DeviceMapping.Add(Device.InstanceId, Device.DeviceId); EventInterface->JoystickPluggedIn(Device); return Device; } } Device.DeviceId = FDeviceId(Devices.Num()); Devices.Add(Device.DeviceId, Device); DeviceMapping.Add(Device.InstanceId, Device.DeviceId); EventInterface->JoystickPluggedIn(Device); return Device; }
int main(int argc, char *argv[]) { SDL_Joystick *joystick = NULL; SDL_Haptic *haptic = NULL; SDL_JoystickID instance = -1; SDL_bool keepGoing = SDL_TRUE; int i; SDL_bool enable_haptic = SDL_TRUE; Uint32 init_subsystems = SDL_INIT_VIDEO | SDL_INIT_JOYSTICK; for (i = 1; i < argc; ++i) { if (SDL_strcasecmp(argv[i], "--nohaptic") == 0) { enable_haptic = SDL_FALSE; } } if(enable_haptic) { init_subsystems |= SDL_INIT_HAPTIC; } /* Enable standard application logging */ SDL_LogSetPriority(SDL_LOG_CATEGORY_APPLICATION, SDL_LOG_PRIORITY_INFO); SDL_SetHint(SDL_HINT_JOYSTICK_ALLOW_BACKGROUND_EVENTS, "1"); /* Initialize SDL (Note: video is required to start event loop) */ if (SDL_Init(init_subsystems) < 0) { SDL_LogError(SDL_LOG_CATEGORY_APPLICATION, "Couldn't initialize SDL: %s\n", SDL_GetError()); exit(1); } //SDL_CreateWindow("Dummy", SDL_WINDOWPOS_CENTERED, SDL_WINDOWPOS_CENTERED, 128, 128, 0); SDL_Log("There are %d joysticks at startup\n", SDL_NumJoysticks()); if (enable_haptic) SDL_Log("There are %d haptic devices at startup\n", SDL_NumHaptics()); while(keepGoing) { SDL_Event event; while(SDL_PollEvent(&event)) { switch(event.type) { case SDL_QUIT: keepGoing = SDL_FALSE; break; case SDL_JOYDEVICEADDED: if (joystick != NULL) { SDL_Log("Only one joystick supported by this test\n"); } else { joystick = SDL_JoystickOpen(event.jdevice.which); instance = SDL_JoystickInstanceID(joystick); SDL_Log("Joy Added : %d : %s\n", event.jdevice.which, SDL_JoystickName(joystick)); if (enable_haptic) { if (SDL_JoystickIsHaptic(joystick)) { haptic = SDL_HapticOpenFromJoystick(joystick); if (haptic) { SDL_Log("Joy Haptic Opened\n"); if (SDL_HapticRumbleInit( haptic ) != 0) { SDL_Log("Could not init Rumble!: %s\n", SDL_GetError()); SDL_HapticClose(haptic); haptic = NULL; } } else { SDL_Log("Joy haptic open FAILED!: %s\n", SDL_GetError()); } } else { SDL_Log("No haptic found\n"); } } } break; case SDL_JOYDEVICEREMOVED: if (instance == event.jdevice.which) { SDL_Log("Joy Removed: %d\n", event.jdevice.which); instance = -1; if(enable_haptic && haptic) { SDL_HapticClose(haptic); haptic = NULL; } SDL_JoystickClose(joystick); joystick = NULL; } else { SDL_Log("Unknown joystick diconnected\n"); } break; case SDL_JOYAXISMOTION: // SDL_Log("Axis Move: %d\n", event.jaxis.axis); if (enable_haptic) SDL_HapticRumblePlay(haptic, 0.25, 250); break; case SDL_JOYBUTTONDOWN: SDL_Log("Button Press: %d\n", event.jbutton.button); if(enable_haptic && haptic) { SDL_HapticRumblePlay(haptic, 0.25, 250); } if (event.jbutton.button == 0) { SDL_Log("Exiting due to button press of button 0\n"); keepGoing = SDL_FALSE; } break; case SDL_JOYBUTTONUP: SDL_Log("Button Release: %d\n", event.jbutton.button); break; } } } SDL_Quit(); return 0; }
void Engine_InitSDLControls() { int NumJoysticks; Uint32 init_flags = SDL_INIT_VIDEO | SDL_INIT_EVENTS; // These flags are used in any case. if(control_mapper.use_joy == 1) { init_flags |= SDL_INIT_GAMECONTROLLER; // Update init flags for joystick. if(control_mapper.joy_rumble) { init_flags |= SDL_INIT_HAPTIC; // Update init flags for force feedback. } SDL_Init(init_flags); NumJoysticks = SDL_NumJoysticks(); if((NumJoysticks < 1) || ((NumJoysticks - 1) < control_mapper.joy_number)) { Sys_DebugLog(LOG_FILENAME, "Error: there is no joystick #%d present.", control_mapper.joy_number); return; } if(SDL_IsGameController(control_mapper.joy_number)) // If joystick has mapping (e.g. X360 controller) { SDL_GameControllerEventState(SDL_ENABLE); // Use GameController API sdl_controller = SDL_GameControllerOpen(control_mapper.joy_number); if(!sdl_controller) { Sys_DebugLog(LOG_FILENAME, "Error: can't open game controller #%d.", control_mapper.joy_number); SDL_GameControllerEventState(SDL_DISABLE); // If controller init failed, close state. control_mapper.use_joy = 0; } else if(control_mapper.joy_rumble) // Create force feedback interface. { sdl_haptic = SDL_HapticOpenFromJoystick(SDL_GameControllerGetJoystick(sdl_controller)); if(!sdl_haptic) { Sys_DebugLog(LOG_FILENAME, "Error: can't initialize haptic from game controller #%d.", control_mapper.joy_number); } } } else { SDL_JoystickEventState(SDL_ENABLE); // If joystick isn't mapped, use generic API. sdl_joystick = SDL_JoystickOpen(control_mapper.joy_number); if(!sdl_joystick) { Sys_DebugLog(LOG_FILENAME, "Error: can't open joystick #%d.", control_mapper.joy_number); SDL_JoystickEventState(SDL_DISABLE); // If joystick init failed, close state. control_mapper.use_joy = 0; } else if(control_mapper.joy_rumble) // Create force feedback interface. { sdl_haptic = SDL_HapticOpenFromJoystick(sdl_joystick); if(!sdl_haptic) { Sys_DebugLog(LOG_FILENAME, "Error: can't initialize haptic from joystick #%d.", control_mapper.joy_number); } } } if(sdl_haptic) // To check if force feedback is working or not. { SDL_HapticRumbleInit(sdl_haptic); SDL_HapticRumblePlay(sdl_haptic, 1.0, 300); } } else { SDL_Init(init_flags); } }
void EventosJoysticks::processarEvento(const SDL_Event& evento) { Joystick* joy; switch(evento.type) { case SDL_JOYAXISMOTION: joy = identificarJoystick(evento.jaxis.which); if(joy) { switch(evento.jaxis.axis) { case SDL_CONTROLLER_AXIS_LEFTX: joy->x = evento.caxis.value/32767.0f; filtrarInput(joy->x, joy); break; case SDL_CONTROLLER_AXIS_LEFTY: joy->y = evento.caxis.value/32767.0f; filtrarInput(joy->y, joy); break; case SDL_CONTROLLER_AXIS_RIGHTX: joy->xDir = evento.caxis.value/32767.0f; filtrarInput(joy->xDir, joy); break; case SDL_CONTROLLER_AXIS_RIGHTY: joy->yDir = evento.caxis.value/32767.0f; filtrarInput(joy->yDir, joy); break; case SDL_CONTROLLER_AXIS_TRIGGERLEFT: joy->z = evento.caxis.value/32767.0f; filtrarInput(joy->z, joy); break; case SDL_CONTROLLER_AXIS_TRIGGERRIGHT: joy->zDir = evento.caxis.value/32767.0f; filtrarInput(joy->zDir, joy); break; } } break; case SDL_CONTROLLERBUTTONDOWN: joy = identificarJoystick(evento.cbutton.which); if (joy) { joy->segurando[evento.cbutton.button] = true; if (evento.cbutton.state == SDL_PRESSED) { joy->pressionou[evento.cbutton.button] = true; } } break; case SDL_CONTROLLERBUTTONUP: joy = identificarJoystick(evento.cbutton.which); if (joy) { joy->segurando[evento.cbutton.button] = false; if (evento.cbutton.state == SDL_RELEASED) { joy->soltou[evento.cbutton.button] = true; } } break; case SDL_JOYBUTTONDOWN: joy = identificarJoystick(evento.jbutton.which); if(joy) { if (joy->eControle()) { // para aqui, pois controles são tratados separadamente break; } joy->segurando[evento.jbutton.button] = true; if(evento.jbutton.state == SDL_PRESSED) { joy->pressionou[evento.jbutton.button] = true; } } break; case SDL_JOYBUTTONUP: joy = identificarJoystick(evento.jbutton.which); if(joy) { if (joy->eControle()) { // para aqui, pois controles são tratados separadamente break; } joy->segurando[evento.jbutton.button] = false; if(evento.jbutton.state == SDL_RELEASED) { joy->soltou[evento.jbutton.button] = true; } } break; case SDL_JOYDEVICEADDED: joy = getPrimeiroJoystickLivre(); if(joy) { if (SDL_IsGameController(evento.jdevice.which)) { joy->sdl_controller = SDL_GameControllerOpen(evento.jdevice.which); joy->sdl_joystick = SDL_GameControllerGetJoystick(joy->sdl_controller); } else { joy->sdl_joystick = SDL_JoystickOpen(evento.jdevice.which); joy->sdl_controller = NULL; } joy->id = nextId; joy->sdl_haptic = SDL_HapticOpenFromJoystick(joy->sdl_joystick); if(joy->sdl_haptic) { if(SDL_HapticRumbleSupported(joy->sdl_haptic)) SDL_HapticRumbleInit(joy->sdl_haptic); } nextId++; } break; case SDL_JOYDEVICEREMOVED: joy = identificarJoystick(evento.jdevice.which); if(joy) { if(joy->sdl_haptic) { SDL_HapticClose(joy->sdl_haptic); joy->sdl_haptic = NULL; } if (joy->sdl_controller) { SDL_GameControllerClose(joy->sdl_controller); } else { SDL_JoystickClose(joy->sdl_joystick); } joy->sdl_controller = NULL; joy->sdl_joystick = NULL; joy->id = -1; } break; } }
// First time (lazy) initialization. void gfctrlJoyInit(void) { #ifndef SDL_JOYSTICK gfctrlJoyPresent = GFCTRL_JOY_NONE; for (int index = 0; index < GFCTRL_JOY_NUMBER; index++) { if (!Joysticks[index]) { Joysticks[index] = new jsJoystick(index); } // Don't configure the joystick if it doesn't work if (Joysticks[index]->notWorking()) { delete Joysticks[index]; Joysticks[index] = 0; } else { gfctrlJoyPresent = GFCTRL_JOY_PRESENT; } } #else #if SDL_MAJOR_VERSION >= 2 memset(&cfx, 0, sizeof(cfx)); if (SDL_InitSubSystem(SDL_INIT_JOYSTICK | SDL_INIT_HAPTIC) < 0) { #else if (SDL_Init(SDL_INIT_JOYSTICK) < 0) { #endif GfLogError("Couldn't initialize SDL: %s\n", SDL_GetError()); gfctrlJoyPresent = GFCTRL_JOY_UNTESTED; return; } #if SDL_MAJOR_VERSION >= 2 // Ignore the joystick events, we will poll directly as it is faster SDL_JoystickEventState(SDL_IGNORE); #endif gfctrlJoyPresent = SDL_NumJoysticks(); if (gfctrlJoyPresent > GFCTRL_JOY_NUMBER) gfctrlJoyPresent = GFCTRL_JOY_NUMBER; for (int index = 0; index < gfctrlJoyPresent; index++) { if (!Joysticks[index]) { Joysticks[index] = SDL_JoystickOpen(index); } // Don't configure the joystick if it doesn't work if (Joysticks[index] == NULL) { GfLogError("Couldn't open joystick %d: %s\n", index, SDL_GetError()); #if SDL_MAJOR_VERSION >= 2 } else { cfx_timeout[index] = 0; rfx_timeout[index] = 0; // Find which Haptic device relates to this joystick Haptics[index] = SDL_HapticOpenFromJoystick(Joysticks[index]); if (!Haptics[index]) { GfLogInfo("Joystick %d does not support haptic\n", index); break; #if 0 } else { // add an CF effect on startup gfctrlJoyConstantForce(index, 50000, 9000); #endif } // Check for Rumble capability if (SDL_HapticRumbleSupported(Haptics[index]) == SDL_TRUE) { if (SDL_HapticRumbleInit(Haptics[index]) != 0) GfLogError("Couldn't init rumble on joystick %d: %s\n", index, SDL_GetError()); #if 0 else gfctrlJoyRumble(index, 0.5); #endif } #endif } } #endif } #if SDL_JOYSTICK void gfctrlJoyConstantForce(int index, unsigned int level, int dir) { #if SDL_MAJOR_VERSION >= 2 if (!Haptics[index]) return; if ((SDL_HapticQuery(Haptics[index]) & SDL_HAPTIC_CONSTANT) == 0) return; cfx[index].type = SDL_HAPTIC_CONSTANT; cfx[index].constant.direction.type = SDL_HAPTIC_POLAR; cfx[index].constant.direction.dir[0] = dir; cfx[index].constant.length = 1000; cfx[index].constant.level = level; cfx[index].constant.attack_length = 0; cfx[index].constant.fade_length = 1000; #if __WIN32__ if (SDL_HapticGetEffectStatus(Haptics[index], id[index]) == SDL_TRUE) #else // Linux SDL doesn't support checking status at the moment :-( if (cfx_timeout[index] > SDL_GetTicks()) #endif SDL_HapticUpdateEffect(Haptics[index], id[index], &cfx[index]); else { SDL_HapticDestroyEffect(Haptics[index], id[index]); id[index] = SDL_HapticNewEffect(Haptics[index], &cfx[index]); SDL_HapticRunEffect(Haptics[index], id[index], 1); } cfx_timeout[index] = SDL_GetTicks() + cfx[index].constant.length; #endif } void gfctrlJoyRumble(int index, float level) { #if SDL_MAJOR_VERSION >= 2 if (!Haptics[index]) return; if (SDL_HapticRumbleSupported(Haptics[index]) != SDL_TRUE) return; // we have to stop the rumble before updating if (rfx_timeout[index] > SDL_GetTicks()) { if (SDL_HapticRumbleStop(Haptics[index]) != 0) GfLogError("Failed to stop rumble: %s\n", SDL_GetError() ); } if (SDL_HapticRumblePlay(Haptics[index], level, 100) != 0) GfLogError("Failed to play rumble: %s\n", SDL_GetError() ); rfx_timeout[index] = SDL_GetTicks() + 100; #endif } #endif // Shutdown time. void gfctrlJoyShutdown(void) { if (gfctrlJoyPresent != GFCTRL_JOY_UNTESTED) #ifndef SDL_JOYSTICK for (int index = 0; index < GFCTRL_JOY_NUMBER; index++) delete Joysticks[index]; #else for (int index = 0; index < gfctrlJoyPresent; index++) { SDL_JoystickClose(Joysticks[index]); Joysticks[index] = NULL; #if SDL_MAJOR_VERSION >= 2 if (Haptics[index]) { SDL_HapticClose(Haptics[index]); Haptics[index] = NULL; } #endif } #endif gfctrlJoyPresent = GFCTRL_JOY_UNTESTED; } /** Create the joystick control @ingroup ctrl @return pointer on a tCtrlJoyInfo structure <br>0 .. if no joystick present @note call GfctrlJoyRelease to free the tCtrlJoyInfo structure @see GfctrlJoyRelease @see tCtrlJoyInfo */ tCtrlJoyInfo * GfctrlJoyCreate(void) { if (gfctrlJoyPresent == GFCTRL_JOY_UNTESTED) gfctrlJoyInit(); tCtrlJoyInfo* joyInfo = (tCtrlJoyInfo *)calloc(1, sizeof(tCtrlJoyInfo)); #if SDL_JOYSTICK joyInfoCopy = joyInfo; #endif return joyInfo; } /** Release the tCtrlJoyInfo structure @ingroup ctrl @param joyInfo joystick structure @return none */ void GfctrlJoyRelease(tCtrlJoyInfo *joyInfo) { freez(joyInfo); }
bool input_init(void) { memset(inputs, 0, sizeof(inputs)); memset(lastinputs, 0, sizeof(lastinputs)); memset(mappings, -1, sizeof(mappings)); for (int i=0;i<INPUT_COUNT;i++) { mappings[i].key=-1; mappings[i].jbut=-1; mappings[i].jhat=-1; mappings[i].jaxis=-1; } // default mappings mappings[LEFTKEY].key = SDLK_LEFT; mappings[RIGHTKEY].key = SDLK_RIGHT; mappings[UPKEY].key = SDLK_UP; mappings[DOWNKEY].key = SDLK_DOWN; mappings[JUMPKEY].key = SDLK_z; mappings[FIREKEY].key = SDLK_x; mappings[PREVWPNKEY].key = SDLK_a; mappings[NEXTWPNKEY].key = SDLK_s; mappings[INVENTORYKEY].key = SDLK_q; mappings[MAPSYSTEMKEY].key = SDLK_w; mappings[ESCKEY].key = SDLK_ESCAPE; mappings[F1KEY].key = SDLK_F1; mappings[F2KEY].key = SDLK_F2; mappings[F3KEY].key = SDLK_F3; mappings[F4KEY].key = SDLK_F4; mappings[F5KEY].key = SDLK_F5; mappings[F6KEY].key = SDLK_F6; mappings[F7KEY].key = SDLK_F7; mappings[F8KEY].key = SDLK_F8; mappings[F9KEY].key = SDLK_F9; mappings[F10KEY].key = SDLK_F10; mappings[F11KEY].key = SDLK_F11; mappings[F12KEY].key = SDLK_F12; mappings[FREEZE_FRAME_KEY].key = SDLK_SPACE; mappings[FRAME_ADVANCE_KEY].key = SDLK_c; mappings[DEBUG_FLY_KEY].key = SDLK_v; mappings[HOMEKEY].key = SDLK_HOME; mappings[ENDKEY].key = SDLK_END; mappings[ENTERKEY].key = SDLK_RETURN; SDL_InitSubSystem(SDL_INIT_JOYSTICK | SDL_INIT_HAPTIC); if (SDL_NumJoysticks() > 0) { // Open joystick joy = SDL_JoystickOpen(0); if (joy) { stat("Opened Joystick 0"); stat("Name: %s", SDL_JoystickNameForIndex(0)); stat("Number of Axes: %d", SDL_JoystickNumAxes(joy)); stat("Number of Buttons: %d", SDL_JoystickNumButtons(joy)); stat("Number of Balls: %d", SDL_JoystickNumBalls(joy)); haptic = SDL_HapticOpenFromJoystick( joy ); if (haptic == NULL) { stat("No force feedback support"); } else { if (SDL_HapticRumbleInit( haptic ) != 0) stat("Coiuldn't init simple rumble"); } } else { stat("Couldn't open Joystick 0"); } } return 0; }
/** * @brief The entry point of this force feedback demo. * @param[in] argc Number of arguments. * @param[in] argv Array of argc arguments. */ int main(int argc, char **argv) { int i; char *name; int index; /* Enable standard application logging */ SDL_LogSetPriority(SDL_LOG_CATEGORY_APPLICATION, SDL_LOG_PRIORITY_INFO); name = NULL; index = -1; if (argc > 1) { size_t l; name = argv[1]; if ((strcmp(name, "--help") == 0) || (strcmp(name, "-h") == 0)) { SDL_Log("USAGE: %s [device]\n" "If device is a two-digit number it'll use it as an index, otherwise\n" "it'll use it as if it were part of the device's name.\n", argv[0]); return 0; } l = SDL_strlen(name); if ((l < 3) && SDL_isdigit(name[0]) && ((l == 1) || SDL_isdigit(name[1]))) { index = SDL_atoi(name); name = NULL; } } /* Initialize the force feedbackness */ SDL_Init(SDL_INIT_VIDEO | SDL_INIT_TIMER | SDL_INIT_JOYSTICK | SDL_INIT_HAPTIC); SDL_Log("%d Haptic devices detected.\n", SDL_NumHaptics()); if (SDL_NumHaptics() > 0) { /* We'll just use index or the first force feedback device found */ if (name == NULL) { i = (index != -1) ? index : 0; } /* Try to find matching device */ else { for (i = 0; i < SDL_NumHaptics(); i++) { if (strstr(SDL_HapticName(i), name) != NULL) break; } if (i >= SDL_NumHaptics()) { SDL_LogError(SDL_LOG_CATEGORY_APPLICATION, "Unable to find device matching '%s', aborting.\n", name); return 1; } } haptic = SDL_HapticOpen(i); if (haptic == NULL) { SDL_LogError(SDL_LOG_CATEGORY_APPLICATION, "Unable to create the haptic device: %s\n", SDL_GetError()); return 1; } SDL_Log("Device: %s\n", SDL_HapticName(i)); } else { SDL_LogError(SDL_LOG_CATEGORY_APPLICATION, "No Haptic devices found!\n"); return 1; } /* We only want force feedback errors. */ SDL_ClearError(); if (SDL_HapticRumbleSupported(haptic) == SDL_FALSE) { SDL_LogError(SDL_LOG_CATEGORY_APPLICATION, "Rumble not supported!\n"); return 1; } if (SDL_HapticRumbleInit(haptic) != 0) { SDL_LogError(SDL_LOG_CATEGORY_APPLICATION, "Failed to initialize rumble: %s\n", SDL_GetError()); return 1; } SDL_Log("Playing 2 second rumble at 0.5 magnitude.\n"); if (SDL_HapticRumblePlay(haptic, 0.5, 5000) != 0) { SDL_LogError(SDL_LOG_CATEGORY_APPLICATION, "Failed to play rumble: %s\n", SDL_GetError() ); return 1; } SDL_Delay(2000); SDL_Log("Stopping rumble.\n"); SDL_HapticRumbleStop(haptic); SDL_Delay(2000); SDL_Log("Playing 2 second rumble at 0.3 magnitude.\n"); if (SDL_HapticRumblePlay(haptic, 0.3f, 5000) != 0) { SDL_LogError(SDL_LOG_CATEGORY_APPLICATION, "Failed to play rumble: %s\n", SDL_GetError() ); return 1; } SDL_Delay(2000); /* Quit */ if (haptic != NULL) SDL_HapticClose(haptic); SDL_Quit(); return 0; }
bool init() { //Initialization flag bool success = true; //Initialize SDL if( SDL_Init( SDL_INIT_VIDEO | SDL_INIT_JOYSTICK | SDL_INIT_HAPTIC ) < 0 ) { printf( "SDL could not initialize! SDL Error: %s\n", SDL_GetError() ); success = false; } else { //Set texture filtering to linear if( !SDL_SetHint( SDL_HINT_RENDER_SCALE_QUALITY, "1" ) ) { printf( "Warning: Linear texture filtering not enabled!" ); } //Check for joysticks if( SDL_NumJoysticks() < 1 ) { printf( "Warning: No joysticks connected!\n" ); } else { //Load joystick gGameController = SDL_JoystickOpen( 0 ); if( gGameController == NULL ) { printf( "Warning: Unable to open game controller! SDL Error: %s\n", SDL_GetError() ); } else { //Get controller haptic device gControllerHaptic = SDL_HapticOpenFromJoystick( gGameController ); if( gControllerHaptic == NULL ) { printf( "Warning: Controller does not support haptics! SDL Error: %s\n", SDL_GetError() ); } else { //Get initialize rumble if( SDL_HapticRumbleInit( gControllerHaptic ) < 0 ) { printf( "Warning: Unable to initialize rumble! SDL Error: %s\n", SDL_GetError() ); } } } } //Create window gWindow = SDL_CreateWindow( "SDL Tutorial", SDL_WINDOWPOS_UNDEFINED, SDL_WINDOWPOS_UNDEFINED, SCREEN_WIDTH, SCREEN_HEIGHT, SDL_WINDOW_SHOWN ); if( gWindow == NULL ) { printf( "Window could not be created! SDL Error: %s\n", SDL_GetError() ); success = false; } else { //Create vsynced renderer for window gRenderer = SDL_CreateRenderer( gWindow, -1, SDL_RENDERER_ACCELERATED | SDL_RENDERER_PRESENTVSYNC ); if( gRenderer == NULL ) { printf( "Renderer could not be created! SDL Error: %s\n", SDL_GetError() ); success = false; } else { //Initialize renderer color SDL_SetRenderDrawColor( gRenderer, 0xFF, 0xFF, 0xFF, 0xFF ); //Initialize PNG loading int imgFlags = IMG_INIT_PNG; if( !( IMG_Init( imgFlags ) & imgFlags ) ) { printf( "SDL_image could not initialize! SDL_image Error: %s\n", IMG_GetError() ); success = false; } } } } return success; }