[Add] Select joystick by name with option -J [string] as well as id with -j [id]

This commit is contained in:
Allanis 2013-02-01 23:37:13 +00:00
parent c124c9fcca
commit 1bc828e8dd
3 changed files with 39 additions and 4 deletions

View File

@ -1,11 +1,30 @@
#include <SDL.h>
#include <string.h>
#include "def.h"
#include "log.h"
#include "joystick.h"
static SDL_Joystick* joystick = NULL;
int joystick_get(char* namjoystick) {
int i;
for(i = 0; i < SDL_NumJoysticks(); i++)
if(strstr(SDL_JoystickName(i), namjoystick))
return i;
WARN("Joystick '%s' not found, using default joystick '%s'",
namjoystick, SDL_JoystickName(0));
return 0;
}
int joystick_use(int indjoystick) {
if(indjoystick < 0 || indjoystick >= SDL_NumJoysticks()) {
WARN("Joystick of index number %d does not exist. Switching to default (0)", indjoystick);
indjoystick = 0;
}
if(joystick)
// Might as well close it if it is open already.
SDL_JoystickClose(joystick);
// Start using the joystick.
LOG("Using joystick %d", indjoystick);
joystick = SDL_JoystickOpen(indjoystick);

View File

@ -1,7 +1,12 @@
#pragma once
// Get the joystick index number based on its name.
int joystick_get(char* namjoystick);
// set the game to use the joystick of index indjoystick.
int joystick_use(int indjoystick);
// Exit functions.
int joystick_init(void);
void joystick_exit(void);

View File

@ -1,5 +1,6 @@
#include <SDL.h>
#include <unistd.h>
#include <string.h>
#include "def.h"
#include "log.h"
@ -24,12 +25,13 @@ static void update_all(void);
// Usage.
void print_usage(char** argv) {
LOG("USAGE: %s [-f] [-j n] [-hv]", argv[0]);
LOG("USAGE: %s [-f] [-j n | -J s] [-hv]", argv[0]);
LOG("Options are:");
LOG("\t-f - Fullscreen");
LOG("\t-w n - Set width to (n)");
LOG("\t-h n - Set height to (n)");
LOG("\t-j n - Use joystick (n)");
LOG("\t-K s - Use joystick whose name contains (s)");
LOG("\t-h - Display this message and exit.");
LOG("\t-v - Print the version and exit");
}
@ -43,10 +45,11 @@ int main(int argc, char** argv) {
gl_screen.fullscreen = 0;
// Joystick.
int indjoystick = -1;
char* namjoystick = NULL;
// Parse arguments.
int c = 0;
while((c = getopt(argc, argv, "fj:hv")) != -1) {
while((c = getopt(argc, argv, "fJ:j:hv")) != -1) {
switch(c) {
case 'f':
gl_screen.fullscreen = 1;
@ -54,6 +57,9 @@ int main(int argc, char** argv) {
case 'j':
indjoystick = atoi(optarg);
break;
case 'J':
namjoystick = strdup(optarg);
break;
case 'v':
LOG("Lephisto: version %d.%d.%d\n", VMAJOR, VMINOR, VREV);
case 'h':
@ -73,10 +79,15 @@ int main(int argc, char** argv) {
}
// Input.
if(indjoystick >= 0) {
if(indjoystick >= 0 || namjoystick != NULL) {
if(joystick_init())
WARN("Error initializing joystick input");
joystick_use(indjoystick);
if(namjoystick != NULL) {
joystick_use(joystick_get(namjoystick));
free(namjoystick);
}
else if(indjoystick >= 0)
joystick_use(indjoystick);
}
// Data loading.