void SetupInput() { for (int port=0;port<4;port++) { kcode[port]=0xFFFF; rt[port]=0; lt[port]=0; } // Open joystick device int numjoys = SDL_NumJoysticks(); printf("Number of Joysticks found = %i\n", numjoys); if (numjoys > 0) JoySDL = SDL_JoystickOpen(0); printf("Joystick openned\n"); if(JoySDL) { int AxisCount,ButtonCount; const char* Name; AxisCount = 0; ButtonCount = 0; // Name[0] = '\0'; AxisCount = SDL_JoystickNumAxes(JoySDL); ButtonCount = SDL_JoystickNumButtons(JoySDL); Name = SDL_JoystickName(0); printf("SDL: Found '%s' joystick with %d axis and %d buttons\n",Name,AxisCount,ButtonCount); if (strcmp(Name,"Microsoft X-Box 360 pad")==0) { JMapBtn=JMapBtn_360; JMapAxis=JMapAxis_360; printf("Using Xbox 360 map\n"); } } else printf("SDL: No Joystick Found\n"); SDL_ShowCursor( 0 ); }
static void read_joy (unsigned int nr) { unsigned int num, i, axes, axis; SDL_Joystick *joy; if (currprefs.input_selected_setting == 0) { if (jsem_isjoy (0, &currprefs) != (int)nr && jsem_isjoy (1, &currprefs) != (int)nr) return; } joy = joys[nr].joy; axes = SDL_JoystickNumAxes (joy); for (i = 0; i < axes; i++) { axis = SDL_JoystickGetAxis (joy, i); setjoystickstate (nr, i, axis, 32767); } num = SDL_JoystickNumButtons (joy); for (i = 0; i < num; i++) { int bs = SDL_JoystickGetButton (joy, i) ? 1 : 0; setjoybuttonstate (nr, i, bs); } }
static struct device *open_device(int joystick_index) { // If the device is already open, just up its count and return it for (struct slist *iter = device_list; iter; iter = iter->next) { struct device *d = iter->data; if (d->joystick_index == joystick_index) { d->open_count++; return d; } } // Otherwise open and throw it on the list SDL_Joystick *j = SDL_JoystickOpen(joystick_index); if (!j) return NULL; struct device *d = xmalloc(sizeof(*d)); d->joystick_index = joystick_index; d->joystick = j; d->num_axes = SDL_JoystickNumAxes(j); d->num_buttons = SDL_JoystickNumButtons(j); d->open_count = 1; device_list = slist_prepend(device_list, d); return d; }
void Input::updateGamepadState(SDL_Joystick* joystick, GamepadState& state) { //save old state int prev_direction = state.direction; char prev_button[16]; memcpy(prev_button, state.button, 16); //set all to 0 memset(&state, 0, sizeof(GamepadState)); if (joystick == NULL) return; state.num_axis = SDL_JoystickNumAxes((::SDL_Joystick*) joystick); state.num_buttons = SDL_JoystickNumButtons((::SDL_Joystick*)joystick); if (state.num_axis > 8) state.num_axis = 8; if (state.num_buttons > 16) state.num_buttons = 16; for (int i = 0; i < state.num_axis; ++i) //axis state.axis[i] = SDL_JoystickGetAxis((::SDL_Joystick*) joystick, i) / 32768.0f; //range -32768 to 32768 for (int i = 0; i < state.num_buttons; ++i) //buttons state.button[i] = SDL_JoystickGetButton((::SDL_Joystick*) joystick, i); state.hat = (HATState)(SDL_JoystickGetHat((::SDL_Joystick*) joystick, 0) - SDL_HAT_CENTERED); //one hat is enough memcpy(state.prev_button, prev_button, 16); //copy prev buttons state Vector2 axis_direction(state.axis[LEFT_ANALOG_X], state.axis[LEFT_ANALOG_Y]); state.prev_direction = prev_direction; state.direction = 0; float limit = 0.6; if (axis_direction.x < -limit) state.direction |= PAD_LEFT; else if (axis_direction.x > limit) state.direction |= PAD_RIGHT; if (axis_direction.y < -limit) state.direction |= PAD_UP; else if (axis_direction.y > limit) state.direction |= PAD_DOWN; }
static struct joy *find_joy(int joy_num) { SDL_Joystick *j; int i; if (joy_num >= num_sdl_joysticks) return NULL; for (i = 0; i < num_joys; i++) { if (joy[i].joy_num == joy_num) return &joy[i]; } i = num_joys; num_joys++; j = joy[i].device = SDL_JoystickOpen(joy_num); if (j == NULL) return NULL; joy[i].joy_num = joy_num; joy[i].num_axes = SDL_JoystickNumAxes(j); joy[i].num_buttons = SDL_JoystickNumButtons(j); LOG_DEBUG(1,"\t%s\n", SDL_JoystickName(joy_num)); LOG_DEBUG(2,"\tNumber of Axes: %d\n", joy[i].num_axes); LOG_DEBUG(2,"\tNumber of Buttons: %d\n", joy[i].num_buttons); return &joy[i]; }
bool cJoystick :: Stick_Open( unsigned int index ) { // if a joystick is already opened close it first if( m_joystick_open ) { Stick_Close(); } m_joystick = SDL_JoystickOpen( index ); if( !m_joystick ) { printf( "Couldn't open joystick %d\n", index ); m_joystick_open = 0; return 0; } m_current_joystick = index; m_num_buttons = SDL_JoystickNumButtons( m_joystick ); m_num_axes = SDL_JoystickNumAxes( m_joystick ); m_num_balls = SDL_JoystickNumBalls( m_joystick ); // setup available buttons m_buttons.assign( m_num_buttons, 0 ); if( m_debug ) { printf( "Opened Joystick %d\n", m_current_joystick ); printf( "Name: %s\n", Get_Name().c_str() ); printf( "Number of Buttons: %d\n", m_num_buttons ); printf( "Number of Axes: %d\n", m_num_axes ); printf( "Number of Balls: %d\n\n", m_num_balls ); } m_joystick_open = 1; return 1; }
// initializes SDL joystick system and loads assignments for joysticks found void init_joysticks( void ) { if (ignore_joystick) return; if (SDL_InitSubSystem(SDL_INIT_JOYSTICK)) { fprintf(stderr, "warning: failed to initialize joystick system: %s\n", SDL_GetError()); ignore_joystick = true; return; } SDL_JoystickEventState(SDL_IGNORE); joysticks = SDL_NumJoysticks(); joystick = malloc(joysticks * sizeof(*joystick)); for (int j = 0; j < joysticks; j++) { memset(&joystick[j], 0, sizeof(*joystick)); joystick[j].handle = SDL_JoystickOpen(j); if (joystick[j].handle != NULL) { printf("joystick detected: %s ", SDL_JoystickName(j)); printf("(%d axes, %d buttons, %d hats)\n", SDL_JoystickNumAxes(joystick[j].handle), SDL_JoystickNumButtons(joystick[j].handle), SDL_JoystickNumHats(joystick[j].handle)); if (!load_joystick_assignments(j)) reset_joystick_assignments(j); } } if (joysticks == 0) printf("no joysticks detected\n"); }
void joy_get_caps (int max) { SDL_Joystick *joy; int j; for (j=0; j < JOY_NUM_AXES; j++) joystick.axis_valid[j] = 0; for (j=JOYSTICKID1; j<JOYSTICKID1+max; j++) { joy = SDL_JoystickOpen (j); if (joy) { nprintf (("JOYSTICK", "Joystick #%d: %s\n", j - JOYSTICKID1 + 1, SDL_JoystickName(SDL_JoystickOpen(j)))); if (j == Cur_joystick) { for (int i = 0; i < SDL_JoystickNumAxes(joy); i++) { joystick.axis_valid[i] = 1; } } SDL_JoystickClose (joy); } } }
static boolean IsValidAxis(int axis) { int num_axes; if (axis < 0) { return true; } if (IS_BUTTON_AXIS(axis)) { return true; } if (IS_HAT_AXIS(axis)) { return HAT_AXIS_HAT(axis) < SDL_JoystickNumHats(joystick); } num_axes = SDL_JoystickNumAxes(joystick); return axis < num_axes; }
bool Gamepad::otworz(){ this->urzadzenie = SDL_JoystickOpen(0); if(this->urzadzenie == 0) return false; this->iloscPrzyciskow = SDL_JoystickNumButtons(this->urzadzenie); this->iloscNawigatorow = SDL_JoystickNumHats(this->urzadzenie); this->iloscDzojstikow = SDL_JoystickNumAxes(this->urzadzenie); this->przyciskiPolozenie = new bool[this->iloscPrzyciskow]; this->przyciskiWcisniete = new bool[this->iloscPrzyciskow]; this->nawigatoryPolozenie = new int[this->iloscNawigatorow]; this->nawigatoryWcisniete = new int[this->iloscNawigatorow]; this->dzojstiki = new short int[this->iloscDzojstikow]; for(int i = 0; i < this->iloscPrzyciskow; i++) this->przyciskiPolozenie[i] = this->przyciskiWcisniete[i] = false; for(int i = 0; i < this->iloscNawigatorow; i++) this->nawigatoryPolozenie[i] = this->nawigatoryWcisniete[i] = 0; return true; }
CControls::CControls() { mem_zero(&m_LastData, sizeof(m_LastData)); m_LastDummy = 0; m_OtherFire = 0; #if !defined(__ANDROID__) if (g_Config.m_InpJoystick) #endif { SDL_Init(SDL_INIT_JOYSTICK); m_Joystick = SDL_JoystickOpen(0); if( m_Joystick && SDL_JoystickNumAxes(m_Joystick) < NUM_JOYSTICK_AXES ) { SDL_JoystickClose(m_Joystick); m_Joystick = NULL; } m_Gamepad = SDL_JoystickOpen(2); SDL_JoystickEventState(SDL_QUERY); m_UsingGamepad = false; #if defined(CONF_FAMILY_UNIX) if( getenv("OUYA") ) m_UsingGamepad = true; #endif } #if !defined(__ANDROID__) else { m_Joystick = NULL; m_Gamepad = NULL; m_UsingGamepad = false; } #endif }
bool init_event(void) { int i; // printf("sizeof joymap=%d nb_joy=%d\n",sizeof(JOYMAP),conf.nb_joy); jmap=calloc(sizeof(JOYMAP),1); #ifdef WII conf.nb_joy = 4; #else conf.nb_joy = SDL_NumJoysticks(); #endif if( conf.nb_joy>0) { if (conf.joy!=NULL) free(conf.joy); conf.joy=calloc(sizeof(SDL_Joystick*),conf.nb_joy); SDL_JoystickEventState(SDL_ENABLE); jmap->jbutton=calloc(conf.nb_joy,sizeof(struct BUT_MAP*)); jmap->jaxe= calloc(conf.nb_joy,sizeof(struct BUT_MAPJAXIS*)); jmap->jhat= calloc(conf.nb_joy,sizeof(struct BUT_MAP*)); /* Open all the available joystick */ for (i=0;i<conf.nb_joy;i++) { conf.joy[i]=SDL_JoystickOpen(i); /* printf("joy \"%s\", axe:%d, button:%d\n", SDL_JoystickName(i), SDL_JoystickNumAxes(conf.joy[i])+ (SDL_JoystickNumHats(conf.joy[i]) * 2), SDL_JoystickNumButtons(conf.joy[i]));*/ jmap->jbutton[i]=calloc(SDL_JoystickNumButtons(conf.joy[i]),sizeof(struct BUT_MAP)); jmap->jaxe[i]=calloc(SDL_JoystickNumAxes(conf.joy[i]),sizeof(struct BUT_MAPJAXIS)); jmap->jhat[i]=calloc(SDL_JoystickNumHats(conf.joy[i]),sizeof(struct BUT_MAP)); } } create_joymap_from_string(1,CF_STR(cf_get_item_by_name("p1control"))); create_joymap_from_string(2,CF_STR(cf_get_item_by_name("p2control"))); return true; }
void CInput::Init() { m_pGraphics = Kernel()->RequestInterface<IEngineGraphics>(); m_pConsole = Kernel()->RequestInterface<IConsole>(); // FIXME: unicode handling: use SDL_StartTextInput/SDL_StopTextInput on inputs MouseModeRelative(); if(!SDL_WasInit(SDL_INIT_JOYSTICK)) { if(SDL_InitSubSystem(SDL_INIT_JOYSTICK) < 0) { dbg_msg("joystick", "unable to init SDL joystick: %s", SDL_GetError()); return; } } if(SDL_NumJoysticks() > 0) { m_pJoystick = SDL_JoystickOpen(0); if(!m_pJoystick) { dbg_msg("joystick", "Could not open 0th joystick: %s", SDL_GetError()); return; } dbg_msg("joystick", "Opened Joystick 0"); dbg_msg("joystick", "Name: %s", SDL_JoystickNameForIndex(0)); dbg_msg("joystick", "Number of Axes: %d", SDL_JoystickNumAxes(m_pJoystick)); dbg_msg("joystick", "Number of Buttons: %d", SDL_JoystickNumButtons(m_pJoystick)); dbg_msg("joystick", "Number of Balls: %d", SDL_JoystickNumBalls(m_pJoystick)); } else { dbg_msg("joystick", "No joysticks found"); } }
static void initJoystick(int i, bool isTemp) { assert(i == 0 || i == 1); if(!bJoystickSupport) return; if(joys[i] == NULL && SDL_NumJoysticks() > i && !SDL_JoystickOpened(i)) { notes << "opening joystick " << i << endl; notes << " (\"" << SDL_JoystickName(i) << "\")" << endl; joys[i] = SDL_JoystickOpen(i); if(joys[i]) { notes << " Number of Axes: " << SDL_JoystickNumAxes(joys[i]) << endl; notes << " Number of Buttons: " << SDL_JoystickNumButtons(joys[i]) << endl; notes << " Number of Balls: " << SDL_JoystickNumBalls(joys[i]) << endl; if(isTemp) joysticks_inited_temp[i] = true; } else warnings << "Could not open joystick" << endl; } // Save the initial axis values SDL_Delay(40); // Small hack: this little delay is needed here for the joysticks to initialize correctly (bug in SDL?) SDL_JoystickUpdate(); updateAxisStates(); if(!isTemp) joysticks_inited_temp[i] = false; }
void InputManager::addJoystickByDeviceIndex(int id) { assert(id >= 0 && id < SDL_NumJoysticks()); // open joystick & add to our list SDL_Joystick* joy = SDL_JoystickOpen(id); assert(joy); // add it to our list so we can close it again later SDL_JoystickID joyId = SDL_JoystickInstanceID(joy); mJoysticks[joyId] = joy; char guid[65]; SDL_JoystickGetGUIDString(SDL_JoystickGetGUID(joy), guid, 65); // create the InputConfig mInputConfigs[joyId] = new InputConfig(joyId, SDL_JoystickName(joy), guid); if(!loadInputConfig(mInputConfigs[joyId])) { LOG(LogInfo) << "Added unconfigured joystick " << SDL_JoystickName(joy) << " (GUID: " << guid << ", instance ID: " << joyId << ", device index: " << id << ")."; } else { LOG(LogInfo) << "Added known joystick " << SDL_JoystickName(joy) << " (instance ID: " << joyId << ", device index: " << id << ")"; } // set up the prevAxisValues int numAxes = SDL_JoystickNumAxes(joy); mPrevAxisValues[joyId] = new int[numAxes]; std::fill(mPrevAxisValues[joyId], mPrevAxisValues[joyId] + numAxes, 0); // initialize array to 0 }
//joy : return joystick boolean coordinate int joy(int index) { int ret,tmp; if (index>=SDL_NumJoysticks())return -1; SDL_JoystickUpdate(); ret=0; if (SDLjoy[index] && SDL_JoystickNumAxes(SDLjoy[index])>=2 ){ tmp= SDL_JoystickGetAxis(SDLjoy[index],0); if (tmp<0) ret+=1; if (tmp>0) ret+=2; tmp= SDL_JoystickGetAxis(SDLjoy[index],1); if (tmp<0) ret+=4; if (tmp>0) ret+=8; } if (SDLjoy[index] && SDL_JoystickNumHats(SDLjoy[index])>0 ){ ret+=SDL_JoystickGetHat(SDLjoy[index],0); } if (autotimer()!=0)return -1; return ret; }
Joystick::Joystick(SDL_Joystick* const joystick, const int sdl_index, const unsigned int index) : m_joystick(joystick) , m_sdl_index(sdl_index) , m_index(index) { // really bad HACKS: // to not use SDL for an XInput device // too many people on the forums pick the SDL device and ask: // "why don't my 360 gamepad triggers/rumble work correctly" #ifdef _WIN32 // checking the name is probably good (and hacky) enough // but i'll double check with the num of buttons/axes std::string lcasename = GetName(); std::transform(lcasename.begin(), lcasename.end(), lcasename.begin(), tolower); if ((std::string::npos != lcasename.find("xbox 360")) && (10 == SDL_JoystickNumButtons(joystick)) && (5 == SDL_JoystickNumAxes(joystick)) && (1 == SDL_JoystickNumHats(joystick)) && (0 == SDL_JoystickNumBalls(joystick)) ) { // this device won't be used return; } #endif // get buttons for (u8 i = 0; i != SDL_JoystickNumButtons(m_joystick); ++i) AddInput(new Button(i, m_joystick)); // get hats for (u8 i = 0; i != SDL_JoystickNumHats(m_joystick); ++i) { // each hat gets 4 input instances associated with it, (up down left right) for (u8 d = 0; d != 4; ++d) AddInput(new Hat(i, m_joystick, d)); } // get axes for (u8 i = 0; i != SDL_JoystickNumAxes(m_joystick); ++i) { // each axis gets a negative and a positive input instance associated with it AddAnalogInputs(new Axis(i, m_joystick, -32768), new Axis(i, m_joystick, 32767)); } #ifdef USE_SDL_HAPTIC // try to get supported ff effects m_haptic = SDL_HapticOpenFromJoystick( m_joystick ); if (m_haptic) { //SDL_HapticSetGain( m_haptic, 1000 ); //SDL_HapticSetAutocenter( m_haptic, 0 ); const unsigned int supported_effects = SDL_HapticQuery( m_haptic ); // constant effect if (supported_effects & SDL_HAPTIC_CONSTANT) { m_state_out.push_back(EffectIDState()); AddOutput(new ConstantEffect(m_state_out.back())); } // ramp effect if (supported_effects & SDL_HAPTIC_RAMP) { m_state_out.push_back(EffectIDState()); AddOutput(new RampEffect(m_state_out.back())); } // sine effect if (supported_effects & SDL_HAPTIC_SINE) { m_state_out.push_back(EffectIDState()); AddOutput(new SineEffect(m_state_out.back())); } // square effect if (supported_effects & SDL_HAPTIC_SQUARE) { m_state_out.push_back(EffectIDState()); AddOutput(new SquareEffect(m_state_out.back())); } // triangle effect if (supported_effects & SDL_HAPTIC_TRIANGLE) { m_state_out.push_back(EffectIDState()); AddOutput(new TriangleEffect(m_state_out.back())); } } #endif }
void test_joystick(int joy_idx) { SDL_Joystick* joy = SDL_JoystickOpen(joy_idx); if (!joy) { fprintf(stderr, "Unable to open joystick %d\n", joy_idx); } else { initscr(); //cbreak(); //noecho(); //nonl(); curs_set(0); int num_axes = SDL_JoystickNumAxes(joy); int num_buttons = SDL_JoystickNumButtons(joy); int num_hats = SDL_JoystickNumHats(joy); int num_balls = SDL_JoystickNumBalls(joy); Sint16* axes = calloc(num_axes, sizeof(Sint16)); Uint8* buttons = calloc(num_buttons, sizeof(Uint8)); Uint8* hats = calloc(num_hats, sizeof(Uint8)); Uint8* balls = calloc(num_balls, 2*sizeof(Sint16)); int quit = 0; SDL_Event event; while(!quit) { SDL_Delay(10); bool something_new = false; while (SDL_PollEvent(&event)) { something_new = true; switch(event.type) { case SDL_JOYAXISMOTION: assert(event.jaxis.axis < num_axes); axes[event.jaxis.axis] = event.jaxis.value; break; case SDL_JOYBUTTONDOWN: case SDL_JOYBUTTONUP: assert(event.jbutton.button < num_buttons); buttons[event.jbutton.button] = event.jbutton.state; break; case SDL_JOYHATMOTION: assert(event.jhat.hat < num_hats); hats[event.jhat.hat] = event.jhat.value; break; case SDL_JOYBALLMOTION: assert(event.jball.ball < num_balls); balls[2*event.jball.ball + 0] = event.jball.xrel; balls[2*event.jball.ball + 1] = event.jball.yrel; break; case SDL_QUIT: quit = 1; printf("Recieved interrupt, exiting\n"); break; default: fprintf(stderr, "Error: Unhandled event type: %d\n", event.type); } } if (something_new) { //clear(); move(0,0); printw("Joystick Name: '%s'\n", SDL_JoystickName(joy)); printw("Joystick Number: %d\n", joy_idx); printw("\n"); printw("Axes %2d:\n", num_axes); for(int i = 0; i < num_axes; ++i) { int len = COLS - 20; printw(" %2d: %6d ", i, axes[i]); print_bar((axes[i] + 32767) * (len-1) / 65534, len); addch('\n'); } printw("\n"); printw("Buttons %2d:\n", num_buttons); for(int i = 0; i < num_buttons; ++i) { printw(" %2d: %d %s\n", i, buttons[i], buttons[i] ? "[#]":"[ ]"); } printw("\n"); printw("Hats %2d:\n", num_hats); for(int i = 0; i < num_hats; ++i) { printw(" %2d: value: %d\n", i, hats[i]); printw(" +-----+ up: %c\n" " |%c %c %c| down: %c\n" " |%c %c %c| left: %c\n" " |%c %c %c| right: %c\n" " +-----+\n", (hats[i] & SDL_HAT_UP)?'1':'0', ((hats[i] & SDL_HAT_UP) && (hats[i] & SDL_HAT_LEFT)) ? 'O' : ' ', ((hats[i] & SDL_HAT_UP) && !(hats[i] & (SDL_HAT_LEFT | SDL_HAT_RIGHT))) ? 'O' : ' ', ((hats[i] & SDL_HAT_UP) && (hats[i] & SDL_HAT_RIGHT)) ? 'O' : ' ', (hats[i] & SDL_HAT_DOWN)?'1':'0', (!(hats[i] & (SDL_HAT_UP | SDL_HAT_DOWN)) && (hats[i] & SDL_HAT_LEFT)) ? 'O' : ' ', (!(hats[i] & (SDL_HAT_UP | SDL_HAT_DOWN)) && !(hats[i] & (SDL_HAT_LEFT | SDL_HAT_RIGHT))) ? 'O' : ' ', (!(hats[i] & (SDL_HAT_UP | SDL_HAT_DOWN)) && (hats[i] & SDL_HAT_RIGHT)) ? 'O' : ' ', (hats[i] & SDL_HAT_LEFT)?'1':'0', ((hats[i] & SDL_HAT_DOWN) && (hats[i] & SDL_HAT_LEFT)) ? 'O' : ' ', ((hats[i] & SDL_HAT_DOWN) && !(hats[i] & (SDL_HAT_LEFT | SDL_HAT_RIGHT))) ? 'O' : ' ', ((hats[i] & SDL_HAT_DOWN) && (hats[i] & SDL_HAT_RIGHT)) ? 'O' : ' ', (hats[i] & SDL_HAT_RIGHT)?'1':'0'); } printw("\n"); printw("Balls %2d: ", num_balls); for(int i = 0; i < num_balls; ++i) { printw(" %2d: %6d %6d\n", i, balls[2*i+0], balls[2*i+0]); } printw("\n"); printw("\n"); printw("Press Ctrl-c to exit\n"); refresh(); } } // while free(balls); free(hats); free(buttons); free(axes); endwin(); } }
// captures joystick input for configuring assignments // returns false if non-joystick input was detected // TODO: input from joystick other than the one being configured probably should not be ignored bool detect_joystick_assignment( int j, Joystick_assignment *assignment ) { // get initial joystick state to compare against to see if anything was pressed const int axes = SDL_JoystickNumAxes(joystick[j].handle); Sint16 *axis = malloc(axes * sizeof(*axis)); for (int i = 0; i < axes; i++) axis[i] = SDL_JoystickGetAxis(joystick[j].handle, i); const int buttons = SDL_JoystickNumButtons(joystick[j].handle); Uint8 *button = malloc(buttons * sizeof(*button)); for (int i = 0; i < buttons; i++) button[i] = SDL_JoystickGetButton(joystick[j].handle, i); const int hats = SDL_JoystickNumHats(joystick[j].handle); Uint8 *hat = malloc(hats * sizeof(*hat)); for (int i = 0; i < hats; i++) hat[i] = SDL_JoystickGetHat(joystick[j].handle, i); bool detected = false; do { setjasondelay(1); SDL_JoystickUpdate(); for (int i = 0; i < axes; ++i) { Sint16 temp = SDL_JoystickGetAxis(joystick[j].handle, i); if (abs(temp - axis[i]) > joystick_analog_max * 2 / 3) { assignment->type = AXIS; assignment->num = i; assignment->negative_axis = temp < axis[i]; detected = true; break; } } for (int i = 0; i < buttons; ++i) { Uint8 new_button = SDL_JoystickGetButton(joystick[j].handle, i), changed = button[i] ^ new_button; if (!changed) continue; if (new_button == 0) // button was released { button[i] = new_button; } else // button was pressed { assignment->type = BUTTON; assignment->num = i; detected = true; break; } } for (int i = 0; i < hats; ++i) { Uint8 new_hat = SDL_JoystickGetHat(joystick[j].handle, i), changed = hat[i] ^ new_hat; if (!changed) continue; if ((new_hat & changed) == SDL_HAT_CENTERED) // hat was centered { hat[i] = new_hat; } else { assignment->type = HAT; assignment->num = i; assignment->x_axis = changed & (SDL_HAT_LEFT | SDL_HAT_RIGHT); assignment->negative_axis = changed & (SDL_HAT_LEFT | SDL_HAT_UP); detected = true; } } service_SDL_events(true); JE_showVGA(); wait_delay(); } while (!detected && !newkey && !newmouse); free(axis); free(button); free(hat); return detected; }
void input_sdl_init() { if (SDL_WasInit(SDL_INIT_JOYSTICK) == 0) { if(SDL_InitSubSystem(SDL_INIT_JOYSTICK) < 0) { die("error initializing SDL Joystick subsystem"); } } // Open joystick device int numjoys = SDL_NumJoysticks(); printf("Number of Joysticks found = %i\n", numjoys); if (numjoys > 0) { JoySDL = SDL_JoystickOpen(0); } printf("Joystick opened\n"); if(JoySDL) { int AxisCount,ButtonCount; const char* Name; AxisCount = 0; ButtonCount = 0; //Name[0] = '\0'; AxisCount = SDL_JoystickNumAxes(JoySDL); ButtonCount = SDL_JoystickNumButtons(JoySDL); Name = SDL_JoystickName(0); printf("SDK: Found '%s' joystick with %d axes and %d buttons\n", Name, AxisCount, ButtonCount); if (strcmp(Name,"Microsoft X-Box 360 pad")==0) { sdl_map_btn = sdl_map_btn_xbox360; sdl_map_axis = sdl_map_axis_xbox360; printf("Using Xbox 360 map\n"); } } else { printf("SDK: No Joystick Found\n"); } #ifdef TARGET_PANDORA float v; int j; for (int i=0; i<128; i++) { v = ((float)i)/127.0f; v = (v+v*v)/2.0f; j = (int)(v*127.0f); if (j > 127) { j = 127; } JSensitivity[128-i] = -j; JSensitivity[128+i] = j; } #endif SDL_ShowCursor(0); if (SDL_WM_GrabInput( SDL_GRAB_ON ) != SDL_GRAB_ON) { printf("SDK: Error while grabbing mouse\n"); } }
static void IN_JoyMove(void) { unsigned int axes = 0; unsigned int hats = 0; int total = 0; int i = 0; if (!stick) { return; } SDL_JoystickUpdate(); // update the ball state. total = SDL_JoystickNumBalls(stick); if (total > 0) { int balldx = 0; int balldy = 0; int dx; int dy; for (i = 0; i < total; i++) { dx = 0; dy = 0; SDL_JoystickGetBall(stick, i, &dx, &dy); balldx += dx; balldy += dy; } if (balldx || balldy) { // !!! FIXME: is this good for stick balls, or just mice? // Scale like the mouse input... if (abs(balldx) > 1) { balldx *= 2; } if (abs(balldy) > 1) { balldy *= 2; } Com_QueueEvent(0, SE_MOUSE, balldx, balldy, 0, NULL); } } // now query the stick buttons... total = SDL_JoystickNumButtons(stick); if (total > 0) { if (total > ARRAY_LEN(stick_state.buttons)) { total = ARRAY_LEN(stick_state.buttons); } for (i = 0; i < total; i++) { qboolean pressed = (SDL_JoystickGetButton(stick, i) != 0); if (pressed != stick_state.buttons[i]) { Com_QueueEvent(0, SE_KEY, K_JOY1 + i, pressed, 0, NULL); stick_state.buttons[i] = pressed; } } } // look at the hats... total = SDL_JoystickNumHats(stick); if (total > 0) { if (total > 4) { total = 4; } for (i = 0; i < total; i++) { ((Uint8 *)&hats)[i] = SDL_JoystickGetHat(stick, i); } } // update hat state if (hats != stick_state.oldhats) { for (i = 0; i < 4; i++) { if (((Uint8 *)&hats)[i] != ((Uint8 *)&stick_state.oldhats)[i]) { // release event switch (((Uint8 *)&stick_state.oldhats)[i]) { case SDL_HAT_UP: Com_QueueEvent(0, SE_KEY, hat_keys[4 * i + 0], qfalse, 0, NULL); break; case SDL_HAT_RIGHT: Com_QueueEvent(0, SE_KEY, hat_keys[4 * i + 1], qfalse, 0, NULL); break; case SDL_HAT_DOWN: Com_QueueEvent(0, SE_KEY, hat_keys[4 * i + 2], qfalse, 0, NULL); break; case SDL_HAT_LEFT: Com_QueueEvent(0, SE_KEY, hat_keys[4 * i + 3], qfalse, 0, NULL); break; case SDL_HAT_RIGHTUP: Com_QueueEvent(0, SE_KEY, hat_keys[4 * i + 0], qfalse, 0, NULL); Com_QueueEvent(0, SE_KEY, hat_keys[4 * i + 1], qfalse, 0, NULL); break; case SDL_HAT_RIGHTDOWN: Com_QueueEvent(0, SE_KEY, hat_keys[4 * i + 2], qfalse, 0, NULL); Com_QueueEvent(0, SE_KEY, hat_keys[4 * i + 1], qfalse, 0, NULL); break; case SDL_HAT_LEFTUP: Com_QueueEvent(0, SE_KEY, hat_keys[4 * i + 0], qfalse, 0, NULL); Com_QueueEvent(0, SE_KEY, hat_keys[4 * i + 3], qfalse, 0, NULL); break; case SDL_HAT_LEFTDOWN: Com_QueueEvent(0, SE_KEY, hat_keys[4 * i + 2], qfalse, 0, NULL); Com_QueueEvent(0, SE_KEY, hat_keys[4 * i + 3], qfalse, 0, NULL); break; default: break; } // press event switch (((Uint8 *)&hats)[i]) { case SDL_HAT_UP: Com_QueueEvent(0, SE_KEY, hat_keys[4 * i + 0], qtrue, 0, NULL); break; case SDL_HAT_RIGHT: Com_QueueEvent(0, SE_KEY, hat_keys[4 * i + 1], qtrue, 0, NULL); break; case SDL_HAT_DOWN: Com_QueueEvent(0, SE_KEY, hat_keys[4 * i + 2], qtrue, 0, NULL); break; case SDL_HAT_LEFT: Com_QueueEvent(0, SE_KEY, hat_keys[4 * i + 3], qtrue, 0, NULL); break; case SDL_HAT_RIGHTUP: Com_QueueEvent(0, SE_KEY, hat_keys[4 * i + 0], qtrue, 0, NULL); Com_QueueEvent(0, SE_KEY, hat_keys[4 * i + 1], qtrue, 0, NULL); break; case SDL_HAT_RIGHTDOWN: Com_QueueEvent(0, SE_KEY, hat_keys[4 * i + 2], qtrue, 0, NULL); Com_QueueEvent(0, SE_KEY, hat_keys[4 * i + 1], qtrue, 0, NULL); break; case SDL_HAT_LEFTUP: Com_QueueEvent(0, SE_KEY, hat_keys[4 * i + 0], qtrue, 0, NULL); Com_QueueEvent(0, SE_KEY, hat_keys[4 * i + 3], qtrue, 0, NULL); break; case SDL_HAT_LEFTDOWN: Com_QueueEvent(0, SE_KEY, hat_keys[4 * i + 2], qtrue, 0, NULL); Com_QueueEvent(0, SE_KEY, hat_keys[4 * i + 3], qtrue, 0, NULL); break; default: break; } } } } // save hat state stick_state.oldhats = hats; // finally, look at the axes... total = SDL_JoystickNumAxes(stick); if (total > 0) { if (total > 16) { total = 16; } for (i = 0; i < total; i++) { Sint16 axis = SDL_JoystickGetAxis(stick, i); if (in_joystickUseAnalog->integer) { float f = ((float) abs(axis)) / 32767.0f; if (f < in_joystickThreshold->value) { axis = 0; } if (axis != stick_state.oldaaxes[i]) { Com_QueueEvent(0, SE_JOYSTICK_AXIS, i, axis, 0, NULL); stick_state.oldaaxes[i] = axis; } } else { float f = ((float) axis) / 32767.0f; if (f < -in_joystickThreshold->value) { axes |= (1 << (i * 2)); } else if (f > in_joystickThreshold->value) { axes |= (1 << ((i * 2) + 1)); } } } } // Time to update axes state based on old vs. new. if (axes != stick_state.oldaxes) { for (i = 0; i < 16; i++) { if ((axes & (1 << i)) && !(stick_state.oldaxes & (1 << i))) { Com_QueueEvent(0, SE_KEY, joy_keys[i], qtrue, 0, NULL); } if (!(axes & (1 << i)) && (stick_state.oldaxes & (1 << i))) { Com_QueueEvent(0, SE_KEY, joy_keys[i], qfalse, 0, NULL); } } } // Save for future generations. stick_state.oldaxes = axes; }
static void IN_InitJoystick(void) { int i = 0; int total = 0; char buf[16384] = ""; if (stick != NULL) { SDL_JoystickClose(stick); } stick = NULL; memset(&stick_state, '\0', sizeof(stick_state)); if (!SDL_WasInit(SDL_INIT_JOYSTICK)) { Com_Printf("Initializing joystick devices\n"); if (SDL_Init(SDL_INIT_JOYSTICK) < 0) { Com_Printf("SDL_Init(SDL_INIT_JOYSTICK) failed: %s\n", SDL_GetError()); return; } Com_Printf("...joysticks initialized\n"); } total = SDL_NumJoysticks(); Com_Printf("...available joysticks: %d\n", total); // Print list and build cvar to allow ui to select joystick. for (i = 0; i < total; i++) { Q_strcat(buf, sizeof(buf), SDL_JoystickNameForIndex(i)); Q_strcat(buf, sizeof(buf), "\n"); } Cvar_Get("in_availableJoysticks", buf, CVAR_ROM); if (!in_joystick->integer) { Com_Printf("...no active joystick set\n"); SDL_QuitSubSystem(SDL_INIT_JOYSTICK); return; } in_joystickNo = Cvar_Get("in_joystickNo", "0", CVAR_ARCHIVE); if (in_joystickNo->integer < 0 || in_joystickNo->integer >= total) { Cvar_Set("in_joystickNo", "0"); } in_joystickUseAnalog = Cvar_Get("in_joystickUseAnalog", "0", CVAR_ARCHIVE); stick = SDL_JoystickOpen(in_joystickNo->integer); if (stick == NULL) { Com_Printf("No joystick opened.\n"); return; } Com_DPrintf("Joystick %d opened\n", in_joystickNo->integer); Com_DPrintf("Name: %s\n", SDL_JoystickNameForIndex(in_joystickNo->integer)); Com_DPrintf("Axes: %d\n", SDL_JoystickNumAxes(stick)); Com_DPrintf("Hats: %d\n", SDL_JoystickNumHats(stick)); Com_DPrintf("Buttons: %d\n", SDL_JoystickNumButtons(stick)); Com_DPrintf("Balls: %d\n", SDL_JoystickNumBalls(stick)); Com_DPrintf("Use Analog: %s\n", in_joystickUseAnalog->integer ? "Yes" : "No"); SDL_JoystickEventState(SDL_QUERY); }
int Joystick::getAxisCount() const { if (!_sdlJoy) return 0; return SDL_JoystickNumAxes(_sdlJoy); }
int main(int argc, char *argv[]) { SDL_Window *window; /* main window */ SDL_Renderer *renderer; Uint32 startFrame; /* time frame began to process */ Uint32 endFrame; /* time frame ended processing */ Uint32 delay; /* time to pause waiting to draw next frame */ int done; /* should we clean up and exit? */ /* initialize SDL */ if (SDL_Init(SDL_INIT_VIDEO | SDL_INIT_JOYSTICK) < 0) { fatalError("Could not initialize SDL"); } /* create main window and renderer */ // int bbp = SDL_VideoModeOK(SCREEN_WIDTH, SCREEN_HEIGHT, 32, SDL_FULLSCREEN); window = SDL_CreateWindow(NULL, 0, 0, SCREEN_WIDTH, SCREEN_HEIGHT, SDL_WINDOW_OPENGL | SDL_WINDOW_SHOWN | SDL_WINDOW_BORDERLESS); renderer = SDL_CreateRenderer(window, 0, 0); /* print out some info about joysticks and try to open accelerometer for use */ printf("There are %d joysticks available\n", SDL_NumJoysticks()); printf("Default joystick (index 0) is %s\n", SDL_JoystickName(0)); accelerometer = SDL_JoystickOpen(0); if (accelerometer == NULL) { fatalError("Could not open joystick (accelerometer)"); } printf("joystick number of axis = %d\n", SDL_JoystickNumAxes(accelerometer)); printf("joystick number of hats = %d\n", SDL_JoystickNumHats(accelerometer)); printf("joystick number of balls = %d\n", SDL_JoystickNumBalls(accelerometer)); printf("joystick number of buttons = %d\n", SDL_JoystickNumButtons(accelerometer)); /* load graphics */ initializeTextures(renderer); /* setup ship */ shipData.x = (SCREEN_WIDTH - shipData.rect.w) / 2; shipData.y = (SCREEN_HEIGHT - shipData.rect.h) / 2; shipData.vx = 0.0f; shipData.vy = 0.0f; done = 0; /* enter main loop */ while (!done) { startFrame = SDL_GetTicks(); SDL_Event event; while (SDL_PollEvent(&event)) { if (event.type == SDL_QUIT) { done = 1; } } render(renderer); endFrame = SDL_GetTicks(); /* figure out how much time we have left, and then sleep */ delay = MILLESECONDS_PER_FRAME - (endFrame - startFrame); if (delay < 0) { delay = 0; } else if (delay > MILLESECONDS_PER_FRAME) { delay = MILLESECONDS_PER_FRAME; } SDL_Delay(delay); } /* delete textures */ SDL_DestroyTexture(ship); SDL_DestroyTexture(space); /* shutdown SDL */ SDL_Quit(); return 0; }
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; }
static SDL_bool WatchJoystick(SDL_Joystick * joystick) { SDL_Window *window = NULL; SDL_Renderer *screen = NULL; SDL_Texture *background, *button, *axis, *marker; const char *name = NULL; SDL_bool retval = SDL_FALSE; SDL_bool done = SDL_FALSE, next=SDL_FALSE; SDL_Event event; SDL_Rect dst; int s, _s; Uint8 alpha=200, alpha_step = -1; Uint32 alpha_ticks; char mapping[4096], temp[4096]; MappingStep *step; MappingStep steps[] = { {342, 132, 0.0, MARKER_BUTTON, "x", -1, -1, -1, -1, ""}, {387, 167, 0.0, MARKER_BUTTON, "a", -1, -1, -1, -1, ""}, {431, 132, 0.0, MARKER_BUTTON, "b", -1, -1, -1, -1, ""}, {389, 101, 0.0, MARKER_BUTTON, "y", -1, -1, -1, -1, ""}, {174, 132, 0.0, MARKER_BUTTON, "back", -1, -1, -1, -1, ""}, {233, 132, 0.0, MARKER_BUTTON, "guide", -1, -1, -1, -1, ""}, {289, 132, 0.0, MARKER_BUTTON, "start", -1, -1, -1, -1, ""}, {116, 217, 0.0, MARKER_BUTTON, "dpleft", -1, -1, -1, -1, ""}, {154, 249, 0.0, MARKER_BUTTON, "dpdown", -1, -1, -1, -1, ""}, {186, 217, 0.0, MARKER_BUTTON, "dpright", -1, -1, -1, -1, ""}, {154, 188, 0.0, MARKER_BUTTON, "dpup", -1, -1, -1, -1, ""}, {77, 40, 0.0, MARKER_BUTTON, "leftshoulder", -1, -1, -1, -1, ""}, {91, 0, 0.0, MARKER_BUTTON, "lefttrigger", -1, -1, -1, -1, ""}, {396, 36, 0.0, MARKER_BUTTON, "rightshoulder", -1, -1, -1, -1, ""}, {375, 0, 0.0, MARKER_BUTTON, "righttrigger", -1, -1, -1, -1, ""}, {75, 154, 0.0, MARKER_BUTTON, "leftstick", -1, -1, -1, -1, ""}, {305, 230, 0.0, MARKER_BUTTON, "rightstick", -1, -1, -1, -1, ""}, {75, 154, 0.0, MARKER_AXIS, "leftx", -1, -1, -1, -1, ""}, {75, 154, 90.0, MARKER_AXIS, "lefty", -1, -1, -1, -1, ""}, {305, 230, 0.0, MARKER_AXIS, "rightx", -1, -1, -1, -1, ""}, {305, 230, 90.0, MARKER_AXIS, "righty", -1, -1, -1, -1, ""}, }; /* Create a window to display joystick axis position */ window = SDL_CreateWindow("Game Controller Map", 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; } background = LoadTexture(screen, "controllermap.bmp", SDL_FALSE); button = LoadTexture(screen, "button.bmp", SDL_TRUE); axis = LoadTexture(screen, "axis.bmp", SDL_TRUE); SDL_RaiseWindow(window); /* scale for platforms that don't give you the window size you asked for. */ SDL_RenderSetLogicalSize(screen, SCREEN_WIDTH, SCREEN_HEIGHT); /* Print info about the joystick we are watching */ name = SDL_JoystickName(joystick); SDL_Log("Watching joystick %d: (%s)\n", SDL_JoystickInstanceID(joystick), name ? name : "Unknown Joystick"); SDL_Log("Joystick has %d axes, %d hats, %d balls, and %d buttons\n", SDL_JoystickNumAxes(joystick), SDL_JoystickNumHats(joystick), SDL_JoystickNumBalls(joystick), SDL_JoystickNumButtons(joystick)); SDL_Log("\n\n\ ====================================================================================\n\ Press the buttons on your controller when indicated\n\ (Your controller may look different than the picture)\n\ If you want to correct a mistake, press backspace or the back button on your device\n\ To skip a button, press SPACE or click/touch the screen\n\ To exit, press ESC\n\ ====================================================================================\n"); /* Initialize mapping with GUID and name */ SDL_JoystickGetGUIDString(SDL_JoystickGetGUID(joystick), temp, SDL_arraysize(temp)); SDL_snprintf(mapping, SDL_arraysize(mapping), "%s,%s,platform:%s,", temp, name ? name : "Unknown Joystick", SDL_GetPlatform()); /* Loop, getting joystick events! */ for(s=0; s<SDL_arraysize(steps) && !done;) { /* blank screen, set up for drawing this frame. */ step = &steps[s]; SDL_strlcpy(step->mapping, mapping, SDL_arraysize(step->mapping)); step->axis = -1; step->button = -1; step->hat = -1; step->hat_value = -1; SDL_SetClipboardText("TESTING TESTING 123"); switch(step->marker) { case MARKER_AXIS: marker = axis; break; case MARKER_BUTTON: marker = button; break; default: break; } dst.x = step->x; dst.y = step->y; SDL_QueryTexture(marker, NULL, NULL, &dst.w, &dst.h); next=SDL_FALSE; SDL_SetRenderDrawColor(screen, 0xFF, 0xFF, 0xFF, SDL_ALPHA_OPAQUE); while (!done && !next) { if (SDL_GetTicks() - alpha_ticks > 5) { alpha_ticks = SDL_GetTicks(); alpha += alpha_step; if (alpha == 255) { alpha_step = -1; } if (alpha < 128) { alpha_step = 1; } } SDL_RenderClear(screen); SDL_RenderCopy(screen, background, NULL, NULL); SDL_SetTextureAlphaMod(marker, alpha); SDL_SetTextureColorMod(marker, 10, 255, 21); SDL_RenderCopyEx(screen, marker, NULL, &dst, step->angle, NULL, 0); SDL_RenderPresent(screen); if (SDL_PollEvent(&event)) { switch (event.type) { case SDL_JOYAXISMOTION: if (event.jaxis.value > 20000 || event.jaxis.value < -20000) { for (_s = 0; _s < s; _s++) { if (steps[_s].axis == event.jaxis.axis) { break; } } if (_s == s) { step->axis = event.jaxis.axis; SDL_strlcat(mapping, step->field, SDL_arraysize(mapping)); SDL_snprintf(temp, SDL_arraysize(temp), ":a%u,", event.jaxis.axis); SDL_strlcat(mapping, temp, SDL_arraysize(mapping)); s++; next=SDL_TRUE; } } break; case SDL_JOYHATMOTION: if (event.jhat.value == SDL_HAT_CENTERED) { break; /* ignore centering, we're probably just coming back to the center from the previous item we set. */ } for (_s = 0; _s < s; _s++) { if (steps[_s].hat == event.jhat.hat && steps[_s].hat_value == event.jhat.value) { break; } } if (_s == s) { step->hat = event.jhat.hat; step->hat_value = event.jhat.value; SDL_strlcat(mapping, step->field, SDL_arraysize(mapping)); SDL_snprintf(temp, SDL_arraysize(temp), ":h%u.%u,", event.jhat.hat, event.jhat.value ); SDL_strlcat(mapping, temp, SDL_arraysize(mapping)); s++; next=SDL_TRUE; } break; case SDL_JOYBALLMOTION: break; case SDL_JOYBUTTONUP: for (_s = 0; _s < s; _s++) { if (steps[_s].button == event.jbutton.button) { break; } } if (_s == s) { step->button = event.jbutton.button; SDL_strlcat(mapping, step->field, SDL_arraysize(mapping)); SDL_snprintf(temp, SDL_arraysize(temp), ":b%u,", event.jbutton.button); SDL_strlcat(mapping, temp, SDL_arraysize(mapping)); s++; next=SDL_TRUE; } break; case SDL_FINGERDOWN: case SDL_MOUSEBUTTONDOWN: /* Skip this step */ s++; next=SDL_TRUE; break; case SDL_KEYDOWN: if (event.key.keysym.sym == SDLK_BACKSPACE || event.key.keysym.sym == SDLK_AC_BACK) { /* Undo! */ if (s > 0) { SDL_strlcpy(mapping, step->mapping, SDL_arraysize(step->mapping)); s--; next = SDL_TRUE; } break; } if (event.key.keysym.sym == SDLK_SPACE) { /* Skip this step */ s++; next=SDL_TRUE; break; } if ((event.key.keysym.sym != SDLK_ESCAPE)) { break; } /* Fall through to signal quit */ case SDL_QUIT: done = SDL_TRUE; break; default: break; } } } } if (s == SDL_arraysize(steps) ) { SDL_Log("Mapping:\n\n%s\n\n", mapping); /* Print to stdout as well so the user can cat the output somewhere */ printf("%s\n", mapping); } while(SDL_PollEvent(&event)) {}; SDL_DestroyRenderer(screen); SDL_DestroyWindow(window); return retval; }
string SDLInit(const char *title, int2 &screensize, bool fullscreen) { //SDL_SetMainReady(); if (SDL_Init(SDL_INIT_VIDEO | SDL_INIT_JOYSTICK | SDL_INIT_GAMECONTROLLER /* | SDL_INIT_AUDIO*/) < 0) { return SDLError("Unable to initialize SDL"); } SDL_SetEventFilter(SDLHandleAppEvents, nullptr); DebugLog(-1, "SDL initialized..."); SDL_LogSetAllPriority(SDL_LOG_PRIORITY_WARN); // on demand now //extern bool sfxr_init(); //if (!sfxr_init()) // return SDLError("Unable to initialize audio"); #ifdef PLATFORM_MOBILE SDL_GL_SetAttribute(SDL_GL_CONTEXT_MAJOR_VERSION, 2); #else //certain older Intel HD GPUs and also Nvidia Quadro 1000M don't support 3.1 ? the 1000M is supposed to support 4.2 //SDL_GL_SetAttribute(SDL_GL_CONTEXT_MAJOR_VERSION, 3); //SDL_GL_SetAttribute(SDL_GL_CONTEXT_MINOR_VERSION, 1); #ifndef WIN32 SDL_GL_SetAttribute(SDL_GL_CONTEXT_PROFILE_MASK, SDL_GL_CONTEXT_PROFILE_CORE); SDL_GL_SetAttribute(SDL_GL_CONTEXT_FLAGS, SDL_GL_CONTEXT_FORWARD_COMPATIBLE_FLAG); #endif SDL_GL_SetAttribute(SDL_GL_MULTISAMPLEBUFFERS, 1); SDL_GL_SetAttribute(SDL_GL_MULTISAMPLESAMPLES, 4); #endif //SDL_GL_SetAttribute(SDL_GL_DEPTH_SIZE, 0); // set this if we're in 2D mode for speed on mobile? SDL_GL_SetAttribute(SDL_GL_RETAINED_BACKING, 1); // because we redraw the screen each frame SDL_GL_SetAttribute(SDL_GL_DOUBLEBUFFER, 1); DebugLog(-1, "SDL about to figure out display mode..."); #ifdef PLATFORM_MOBILE landscape = screensize.x() >= screensize.y(); int modes = SDL_GetNumDisplayModes(0); screensize = int2(0); for (int i = 0; i < modes; i++) { SDL_DisplayMode mode; SDL_GetDisplayMode(0, i, &mode); //printf("mode: %d %d\n", mode.w, mode.h); if (landscape ? mode.w > screensize.x() : mode.h > screensize.y()) { screensize = int2(mode.w, mode.h); } } DebugLog(-1, inttoa(screensize.x())); DebugLog(-1, inttoa(screensize.y())); DebugLog(-1, "SDL about to create window..."); _sdl_window = SDL_CreateWindow(title, 0, 0, screensize.x(), screensize.y(), SDL_WINDOW_OPENGL | SDL_WINDOW_SHOWN | SDL_WINDOW_BORDERLESS); DebugLog(-1, _sdl_window ? "SDL window passed..." : "SDL window FAILED..."); if (landscape) SDL_SetHint("SDL_HINT_ORIENTATIONS", "LandscapeLeft LandscapeRight"); int ax = 0, ay = 0; SDL_GetWindowSize(_sdl_window, &ax, &ay); int2 actualscreensize(ax, ay); //screenscalefactor = screensize.x / actualscreensize.x; // should be 2 on retina #ifdef __IOS__ assert(actualscreensize == screensize); screensize = actualscreensize; #else screensize = actualscreensize; // __ANDROID__ DebugLog(-1, inttoa(screensize.x())); DebugLog(-1, inttoa(screensize.y())); #endif #else _sdl_window = SDL_CreateWindow(title, SDL_WINDOWPOS_CENTERED, SDL_WINDOWPOS_CENTERED, screensize.x(), screensize.y(), SDL_WINDOW_OPENGL | SDL_WINDOW_SHOWN | SDL_WINDOW_RESIZABLE | (fullscreen ? SDL_WINDOW_FULLSCREEN_DESKTOP : 0)); #endif if (!_sdl_window) return SDLError("Unable to create window"); DebugLog(-1, "SDL window opened..."); _sdl_context = SDL_GL_CreateContext(_sdl_window); DebugLog(-1, _sdl_context ? "SDL context passed..." : "SDL context FAILED..."); if (!_sdl_context) return SDLError("Unable to create OpenGL context"); DebugLog(-1, "SDL OpenGL context created..."); /* SDL_GL_SetAttribute(SDL_GL_MULTISAMPLEBUFFERS, 1); SDL_GL_SetAttribute(SDL_GL_MULTISAMPLESAMPLES, 4); */ #ifndef __IOS__ SDL_GL_SetSwapInterval(1); // vsync on #endif SDL_JoystickEventState(SDL_ENABLE); SDL_JoystickUpdate(); for(int i = 0; i < SDL_NumJoysticks(); i++) { SDL_Joystick *joy; if (joy = SDL_JoystickOpen(i)) { DebugLog(-1, "Detected joystick: %s (%d axes, %d buttons, %d balls, %d hats)\n", SDL_JoystickName(joy), SDL_JoystickNumAxes(joy), SDL_JoystickNumButtons(joy), SDL_JoystickNumBalls(joy), SDL_JoystickNumHats(joy)); }; }; starttime = SDL_GetTicks(); lastmillis = starttime - 16; // ensure first frame doesn't get a crazy delta return ""; }
int main(int argc, char **argv) { SDL_Surface *screen; SDL_AudioSpec audio_wanted; int frame; int evfd; int x, y; evfd = open("/dev/ps2event", O_RDONLY); if (evfd < 0) { perror("/dev/ps2event: open"); return 1; } ioctl(evfd, PS2IOC_ENABLEEVENT, PS2EV_VSYNC); dx = get_dx(); dy = get_dy(); SDL_Init(SDL_INIT_VIDEO | SDL_INIT_AUDIO | SDL_INIT_JOYSTICK); atexit(cleanup); if (argc > 1 && !strcmp(argv[1], "-j")) { int i; SDL_Event event; SDL_Joystick *joystick; printf("%d joysticks were found.\n\n", SDL_NumJoysticks() ); printf("The names of the joysticks are:\n"); for (i=0; i < SDL_NumJoysticks(); i++) { printf(" %s\n", SDL_JoystickName(i)); } joystick = SDL_JoystickOpen(0); printf("Joystick 0 has %d axes\n", SDL_JoystickNumAxes(joystick)); printf("Joystick 0 has %d buttons\n", SDL_JoystickNumButtons(joystick)); printf("Joystick 0 has %d balls\n", SDL_JoystickNumBalls(joystick)); printf("Joystick 0 has %d hats\n", SDL_JoystickNumHats(joystick)); while(SDL_WaitEvent(&event)) { switch(event.type) { case SDL_JOYAXISMOTION: printf("Axis %d %d\n", event.jaxis.axis, event.jaxis.value); break; case SDL_JOYBUTTONDOWN: printf("Button %d down\n", event.jbutton.button); break; case SDL_JOYBUTTONUP: printf("Button %d up\n", event.jbutton.button); break; case SDL_KEYDOWN: goto done; break; } } done: return 0; } /* * Set the audio device up. */ audio_wanted.freq = 22050; audio_wanted.format = AUDIO_S8; audio_wanted.channels = 1; /* 1 = mono, 2 = stereo */ audio_wanted.samples = 1024; /* Good low-latency value for callback */ audio_wanted.callback = fill_audio; audio_wanted.userdata = NULL; if ( SDL_OpenAudio(&audio_wanted, NULL) < 0 ) { fprintf(stderr, "Couldn't open audio: %s\n", SDL_GetError()); return 1; } /* * Set the video mode up. */ screen = SDL_SetVideoMode(SCR_WIDTH*XMULT, SCR_HEIGHT*YMULT, 8, SDL_SWSURFACE); if (!screen) { printf("SDL screen initialisation error: %s\n", SDL_GetError()); return 1; } SDL_ShowCursor(SDL_DISABLE); if (SDL_MUSTLOCK(screen)) SDL_LockSurface(screen); for (x = 0; x < SCR_WIDTH*XMULT; x++) { for (y = 0; y < SCR_HEIGHT*YMULT; y++) { putpixel(screen, x, y, SDL_MapRGB(screen->format, (x*10)&255, (y*10)&255, ((x+y+frame)*10)&255)); } } if (SDL_MUSTLOCK(screen)) SDL_UnlockSurface(screen); SDL_PauseAudio(0); for (frame = 1; frame < 256; frame++) { SDL_Rect r1 = { 0, 0, SCR_WIDTH*XMULT-1, SCR_HEIGHT*YMULT }; SDL_Rect r2 = { 1, 0, SCR_WIDTH*XMULT-1, SCR_HEIGHT*YMULT }; if (SDL_MUSTLOCK(screen)) SDL_LockSurface(screen); // for (x = 0; x < SCR_WIDTH*XMULT; x++) { for (y = 0; y < SCR_HEIGHT*YMULT; y++) { memmove(screen->pixels + y * screen->pitch, screen->pixels + y * screen->pitch + screen->format->BytesPerPixel, (SCR_WIDTH*XMULT-1) * screen->format->BytesPerPixel); putpixel(screen, SCR_WIDTH*XMULT-1, y, 0); //putpixel(screen, x, y, (x==SCR_WIDTH*XMULT-1 ? 0 : // getpixel(screen, x+1, y))); } // } if (SDL_MUSTLOCK(screen)) SDL_UnlockSurface(screen); //SDL_UpdateRect(screen, frame*2, 0, 2, SCR_HEIGHT*YMULT); SDL_Flip(screen); { long long t = bigclock(); ioctl(evfd, PS2IOC_WAITEVENT, PS2EV_VSYNC); sparetime += bigclock() - t; } } return 0; }
BCPLWORD sdlfn(BCPLWORD *a, BCPLWORD *g, BCPLWORD *W) { char tmpstr[256]; //printf("sdlfn: fno=%d a1=%d a2=%d a3=%d a4=%d\n", // a[0], a[1], a[2], a[3], a[4]); switch(a[0]) { default: printf("sdlfn: Unknown op: fno=%d a1=%d a2=%d a3=%d a4=%d\n", a[0], a[1], a[2], a[3], a[4]); return 0; case sdl_avail: // Test whether SDL is available return -1; // SDL is available case gl_avail: // Test whether OpenGL is available #ifdef GLavail return -1; // OpenGL is available #else return 0; // OpenGL is not available #endif case sdl_init: // Initialise all SDL features { BCPLWORD res = (BCPLWORD) SDL_Init(SDL_INIT_EVERYTHING); // Enable Unicode translation of keyboard events. SDL_EnableUNICODE(1); SDL_JoystickEventState(SDL_ENABLE); //printf("sdl_init\n"); return res; } case sdl_setvideomode: // width, height, bbp, flags { SDL_Surface *scr; //printf("Calling SetVideoMode(%d, %d, %d, %8x)\n", a[1], a[2], a[3], a[4]); scr = SDL_SetVideoMode((int)a[1], (int)a[2], (int)a[3], (Uint32)a[4]); SDL_Flip(scr); return (BCPLWORD) scr; //return (BCPLWORD) SDL_SetVideoMode((int)a[1], (int)a[2], (int)a[3], (Uint32)a[4]); } case sdl_quit: // Shut down SDL printf("sdl_quit\n"); SDL_Quit(); return -1; case sdl_locksurface: // surf // Return 0 on success // Return -1 on failure return (BCPLWORD) SDL_LockSurface((SDL_Surface*) a[1]); case sdl_unlocksurface: // surf SDL_UnlockSurface((SDL_Surface*) a[1]); return 0; case sdl_getsurfaceinfo: // surf, surfinfo -> [flag, format, w, h, pitch, pixels, cliprect, refcount] { SDL_Surface *surf = (SDL_Surface*)a[1]; BCPLWORD *info = &W[a[2]]; info[ 0] = (BCPLWORD) (surf->flags); info[ 1] = (BCPLWORD) (surf->format); info[ 2] = (BCPLWORD) (surf->w); info[ 3] = (BCPLWORD) (surf->h); info[ 4] = (BCPLWORD) (surf->pitch); info[ 5] = (BCPLWORD) (surf->pixels); //info[ 6] = (BCPLWORD) (surf->clip_rect); // fields: x,y, w, h info[ 7] = (BCPLWORD) (surf->refcount); //printf("getsurfaceinfo: format=%d\n", info[1]); return 0; } case sdl_getfmtinfo: // fmt, pxlinfo -> [palette, bitspp, bytespp, rmask, gmask, rmask, amask, // rloss, rshift, gloss, gshift, bloss, bshift, aloss, ashift, // colorkey, alpha] { SDL_PixelFormat *fmt = (SDL_PixelFormat*)(a[1]); BCPLWORD *info = &(W[a[2]]); //printf("getfmtinfo: format=%d\n", (BCPLWORD)fmt); info[ 0] = (BCPLWORD) (fmt->palette); info[ 1] = (BCPLWORD) (fmt->BitsPerPixel); info[ 2] = (BCPLWORD) (fmt->BytesPerPixel); info[ 3] = (BCPLWORD) (fmt->Rmask); info[ 4] = (BCPLWORD) (fmt->Gmask); info[ 5] = (BCPLWORD) (fmt->Bmask); info[ 6] = (BCPLWORD) (fmt->Amask); info[ 7] = (BCPLWORD) (fmt->Rshift); info[ 8] = (BCPLWORD) (fmt->Gshift); info[ 9] = (BCPLWORD) (fmt->Bshift); info[10] = (BCPLWORD) (fmt->Ashift); info[11] = (BCPLWORD) (fmt->Rloss); info[12] = (BCPLWORD) (fmt->Gloss); info[13] = (BCPLWORD) (fmt->Rloss); info[14] = (BCPLWORD) (fmt->Aloss); info[15] = (BCPLWORD) (fmt->colorkey); info[16] = (BCPLWORD) (fmt->alpha); return 0; } case sdl_geterror: // str -- fill str with BCPL string for the latest SDL error { char *str = SDL_GetError(); printf("sdl_geterror: %s\n", str); return c2b_str(str, a[1]); // Convert to BCPL string format } case sdl_updaterect: // surf, left, top, right, bottom return 0; // Not yet available case sdl_loadbmp: // filename of a .bmp image { char tmpstr[256]; b2c_str(a[1], tmpstr); return (BCPLWORD) SDL_LoadBMP(tmpstr); } case sdl_mksurface: //(format, w, h) { SDL_PixelFormat *fmt = (SDL_PixelFormat*)(a[1]); Uint32 rmask = fmt->Rmask; Uint32 gmask = fmt->Gmask; Uint32 bmask = fmt->Bmask; Uint32 amask = fmt->Amask; //printf("rmask=%8x gmask=%8x bmask=%8x amask=%8x\n", rmask, gmask, bmask, amask); return (BCPLWORD)SDL_CreateRGBSurface( SDL_SWSURFACE, a[2], a[3], // Width, Height 32, // Not using a palette rmask, gmask, bmask, amask); } case sdl_blitsurface: // src, srcrect, dest, destrect //printf("blitsurface: %d, %d, %d, %d)\n", a[1], a[2], a[3], a[4]); { BCPLWORD *p = &W[a[4]]; SDL_Rect dstrect = {p[0],p[1],p[2],p[3]}; //printf("x=%d, y=%d, w=%d, h=%d\n", p[0], p[1], p[2], p[3]); return (BCPLWORD) SDL_BlitSurface((SDL_Surface*) a[1], (SDL_Rect*) 0, (SDL_Surface*) a[3], &dstrect); } case sdl_setcolourkey: //(surf, key) // If key=-1 unset colour key // otherwise set colour key to given value. // key must be in the pixel format of the given surface //printf("sdl_setcolourkey: %8x\n", a[2]); if(a[2]==-1) { return (BCPLWORD)SDL_SetColorKey((SDL_Surface*)a[1], 0, (Uint32)a[2]); } else { return (BCPLWORD)SDL_SetColorKey((SDL_Surface*)a[1], SDL_SRCCOLORKEY, (Uint32)a[2]); } case sdl_freesurface: // surf SDL_FreeSurface((SDL_Surface*)a[1]); return 0; case sdl_setalpha: // surf, flags, alpha return 0; // Not yet available case sdl_imgload: // filename -- using the SDL_image library return 0; // Not yet available case sdl_delay: // msecs -- the SDL delay function SDL_Delay((int)a[1]); return 0; case sdl_getticks: // return msecs since initialisation return (BCPLWORD)SDL_GetTicks(); case sdl_showcursor: // Show the cursor return (BCPLWORD)SDL_ShowCursor(SDL_ENABLE); case sdl_hidecursor: // Hide the cursor return (BCPLWORD)SDL_ShowCursor(SDL_DISABLE); case sdl_flip: // surf -- Double buffered update of the screen return (BCPLWORD) SDL_Flip((SDL_Surface*)a[1]); case sdl_displayformat: // surf -- convert surf to display format return 0; // Not yet available case sdl_waitevent: // (pointer) to [type, args, ... ] to hold details of the next event // return 0 if no events available return 0; // Not yet available case sdl_pollevent: // (pointer) to [type, args, ... ] to hold details of // the next event { SDL_Event test_event; if (SDL_PollEvent(&test_event)) { decodeevent(&test_event, &W[a[1]]); return -1; } decodeevent(0, &W[a[1]]); return 0; } case sdl_getmousestate: // pointer to [x, y] returns bit pattern of buttons currently pressed return 0; // Not yet available case sdl_loadwav: // file, spec, buff, len return 0; // Not yet available case sdl_freewav: // buffer return 0; // Not yet available case sdl_wm_setcaption: // surf, string { char tmpstr[256]; b2c_str(a[1], tmpstr); SDL_WM_SetCaption(tmpstr, 0); return 0; } case sdl_videoinfo: // buffer { const SDL_VideoInfo* p = SDL_GetVideoInfo(); BCPLWORD *info = &W[a[1]]; info[ 0] = (BCPLWORD) ((p->hw_available) | (p->hw_available)<<1 | (p->blit_hw)<<2 | (p->blit_hw_CC)<<3 | (p->blit_hw_A)<<4 | (p->blit_sw)<<5 | (p->blit_sw_CC)<<6 | (p->blit_sw_A)<<7 ); info[ 1] = (BCPLWORD) (p->blit_fill); info[ 2] = (BCPLWORD) (p->video_mem); info[ 3] = (BCPLWORD) (p->vfmt); info[ 4] = (BCPLWORD) (p->vfmt->BitsPerPixel); //printf("videoinfo: a[2]=%d %8X %8X %d %d %d\n", // a[2], info[0], info[1], info[2], info[3], info[4]); return 0; } case sdl_maprgb: // format, r, g, b { return (BCPLWORD) SDL_MapRGB((SDL_PixelFormat*)(a[1]), a[2], a[3], a[4]); } case sdl_drawline: { SDL_Surface *surf = (SDL_Surface*)(a[1]); //printf("\nDraw Line: %d %d %d %d %d %8x\n", a[1], a[2], a[3], a[4], a[5], a[6]); Draw_Line(surf, a[2], a[3], a[4], a[5], a[6]); return 0; } case sdl_drawhline: case sdl_drawvline: case sdl_drawcircle: case sdl_drawrect: case sdl_drawpixel: case sdl_drawellipse: case sdl_drawfillellipse: case sdl_drawround: case sdl_drawfillround: return 0; case sdl_drawfillcircle: { SDL_Surface *surf = (SDL_Surface*)(a[1]); Draw_FillCircle(surf, a[2], a[3], a[4], a[5]); return 0; } // case sdl_drawfillrect: //return Draw_FillRect((SDL_Surface*)a[1], 500,200, 50,70, 0xF0FF00); case sdl_fillrect: { SDL_Rect rect = {a[2],a[3],a[4],a[5]}; //printf("\nfillrect: surface=%d rect=(%d,%d,%d,%d) col=%8x\n", // a[1], a[2], a[3], a[4], a[5], a[6]); SDL_FillRect((SDL_Surface*)(a[1]), &rect, a[6]); return 0; } case sdl_fillsurf: //printf("\nfillsurf: surface=%d col=%8x\n", // a[1], a[2]); SDL_FillRect((SDL_Surface*)(a[1]), 0, a[2]); return 0; // Joystick functions case sdl_numjoysticks: return SDL_NumJoysticks(); case sdl_joystickopen: // 42 (index) => joy return (BCPLWORD)SDL_JoystickOpen(a[1]); case sdl_joystickclose: // 43 (joy) SDL_JoystickClose((SDL_Joystick *)a[1]); return 0; case sdl_joystickname: // 44 (index) { const char *name = SDL_JoystickName(a[1]); return c2b_str(name, a[1]); } case sdl_joysticknumaxes: // 45 (joy) return SDL_JoystickNumAxes((SDL_Joystick*)a[1]); case sdl_joysticknumbuttons: // 46 (joy) return SDL_JoystickNumButtons((SDL_Joystick*)a[1]); case sdl_joysticknumballs: // 47 (joy) return SDL_JoystickNumBalls((SDL_Joystick*)a[1]); case sdl_joysticknumhats: // 47 (joy) return SDL_JoystickNumHats((SDL_Joystick*)a[1]); case sdl_joystickeventstate: //49 sdl_enable=1 or sdl_ignore=0 return SDL_JoystickEventState(a[1]); case sdl_joystickgetbutton: // 55 (joy) return SDL_JoystickGetButton((SDL_Joystick*)a[1], a[2]); case sdl_joystickgetaxis: // 56 (joy) return SDL_JoystickGetAxis((SDL_Joystick*)a[1], a[2]); case sdl_joystickgethat: // 58 (joy) return SDL_JoystickGetHat((SDL_Joystick*)a[1], a[2]); case gl_setvideomode: // 200 (width, height) { // Setup minimum bit sizes, a depth buffer and double buffering. const SDL_VideoInfo* info = NULL; int bpp = 0; SDL_Surface *scr; info = SDL_GetVideoInfo(); if(!info) return 0; bpp = info->vfmt->BitsPerPixel; printf("bpp=%d width=%d height=%d\n", bpp, a[1], a[2]); SDL_GL_SetAttribute(SDL_GL_RED_SIZE, 5); SDL_GL_SetAttribute(SDL_GL_GREEN_SIZE, 5); SDL_GL_SetAttribute(SDL_GL_BLUE_SIZE, 5); SDL_GL_SetAttribute(SDL_GL_DEPTH_SIZE, 16); SDL_GL_SetAttribute(SDL_GL_DOUBLEBUFFER, 1); printf("Calling SDL_SetVideoMode\n"); scr = SDL_SetVideoMode((int)a[1], (int)a[2], bpp, SDL_OPENGL); return (BCPLWORD)scr; } #ifdef GLavail case gl_ShadeModel: //printf("gl_ShadeModel: a[1]=%d GL_SMOOTH=%d\n", a[1], GL_SMOOTH); //glShadeModel((int)a[1]); //glShadeModel(GL_SMOOTH); return 0; case gl_CullFace: //printf("gl_CullFace: %d GL_BACK=%d\n", a[1], GL_BACK); //glCullFace(a[1]); glCullFace(GL_BACK); return 0; case gl_FrontFace: //printf("gl_FrontFace: %d\n", a[1]); //printf(" GL_CCW=%d\n", GL_CCW); //glFrontFace(a[1]); glFrontFace(GL_CCW); return 0; case gl_Enable: //printf("gl_Enable: %d\n", a[1]); //printf(" GL_CULLFACE=%d\n", GL_CULL_FACE); glEnable(a[1]); return 0; case gl_ClearColor: //printf("gl_ClearColor: %d %d %d %d\n", a[1], a[2], a[3], a[4]); glClearColor(a[1]/255.0, a[2]/255.0, a[3]/255.0, a[4]/255.0); return 0; case gl_ViewPort: //printf("gl_Viewport: %d %d %d %d\n", a[1], a[2], a[3], a[4]); glViewport(a[1], a[2], a[3], a[4]); //glViewport(0, 0, 800, 500); return 0; case gl_MatrixMode: //printf("gl_MatrixMode: %d\n", a[1]); //printf(" GL_PROJECTION=%d\n", GL_PROJECTION); //printf(" GL_MODELVIEW=%d\n", GL_MODELVIEW); glMatrixMode(a[1]); return 0; case gl_LoadIdentity: //printf("gl_LoadIdentity:\n"); glLoadIdentity(); return 0; case glu_Perspective: //printf("gl_Perspective: %d %d %d %d\n", a[1], a[2], a[3], a[4]); gluPerspective(((float)a[1])/1000000, ((float)a[2])/1000000, ((float)a[3])/1000, ((float)a[4])/1000); //gluPerspective(60.0, 800.0/500.0, 1.0, 1024.0); return 0; case gl_Clear: //printf("gl_Clear: #x%8X\n", a[1]); //printf(" GL_COLOR_BUFFER_BIT=%8X\n", GL_COLOR_BUFFER_BIT); //printf(" GL_DEPTH_BUFFER_BIT=%8X\n", GL_DEPTH_BUFFER_BIT); glClear(a[1]); //glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); return 0; case gl_Translate: //printf("gl_Translate: %d %d %d\n", a[1], a[2], a[3]); glTranslatef(a[1]/1000.0, a[2]/1000.0, a[3]/1000.0); return 0; case gl_Rotate: //printf("gl_Rotate: %d %d %d %d\n", a[1], a[2], a[3], a[4]); glRotatef(a[1]/1000000.0, a[2]/1000.0, a[3]/1000.0, a[4]/1000.0); return 0; case gl_Begin: //printf("gl_Begin: %d\n", a[1]); //printf(" GL_TRIANGLES=%d\n", GL_TRIANGLES); glBegin(a[1]); return 0; case gl_End: //printf("gl_End:\n"); glEnd(); return 0; case gl_Color4v: //printf("gl_Color4v: %d\n", a[1]); glColor4ub(W[a[1]], W[a[1]+1], W[a[1]+2], W[a[1]+3]); return 0; case gl_Vertex3v: //printf("gl_Vertex3v: %d -> [%d %d %d]\n", a[1], W[a[1]], W[a[1]+1], W[a[1]+2]); glVertex3f(W[a[1]]/1000.0, W[a[1]+1]/1000.0, W[a[1]+2]/1000.0); return 0; case gl_SwapBuffers: //printf("gl_SwapBuffers:\n"); SDL_GL_SwapBuffers(); return 0; #endif // more to come ... } }
/* * Initializes the backend */ void IN_Init(void) { Com_Printf("------- input initialization -------\n"); mouse_x = mouse_y = 0; #if SDL_VERSION_ATLEAST(2, 0, 0) joystick_yaw = joystick_pitch = joystick_forwardmove = joystick_sidemove = 0; #endif exponential_speedup = Cvar_Get("exponential_speedup", "0", CVAR_ARCHIVE); freelook = Cvar_Get("freelook", "1", 0); in_grab = Cvar_Get("in_grab", "2", CVAR_ARCHIVE); lookstrafe = Cvar_Get("lookstrafe", "0", 0); m_filter = Cvar_Get("m_filter", "0", CVAR_ARCHIVE); m_up = Cvar_Get("m_up", "1", 0); m_forward = Cvar_Get("m_forward", "1", 0); m_pitch = Cvar_Get("m_pitch", "0.022", 0); m_side = Cvar_Get("m_side", "0.8", 0); m_yaw = Cvar_Get("m_yaw", "0.022", 0); sensitivity = Cvar_Get("sensitivity", "3", 0); #if SDL_VERSION_ATLEAST(2, 0, 0) joy_haptic_magnitude = Cvar_Get("joy_haptic_magnitude", "0.0", CVAR_ARCHIVE); joy_yawsensitivity = Cvar_Get("joy_yawsensitivity", "1.0", CVAR_ARCHIVE); joy_pitchsensitivity = Cvar_Get("joy_pitchsensitivity", "1.0", CVAR_ARCHIVE); joy_forwardsensitivity = Cvar_Get("joy_forwardsensitivity", "1.0", CVAR_ARCHIVE); joy_sidesensitivity = Cvar_Get("joy_sidesensitivity", "1.0", CVAR_ARCHIVE); joy_upsensitivity = Cvar_Get("joy_upsensitivity", "1.0", CVAR_ARCHIVE); joy_axis_leftx = Cvar_Get("joy_axis_leftx", "sidemove", CVAR_ARCHIVE); joy_axis_lefty = Cvar_Get("joy_axis_lefty", "forwardmove", CVAR_ARCHIVE); joy_axis_rightx = Cvar_Get("joy_axis_rightx", "yaw", CVAR_ARCHIVE); joy_axis_righty = Cvar_Get("joy_axis_righty", "pitch", CVAR_ARCHIVE); joy_axis_triggerleft = Cvar_Get("joy_axis_triggerleft", "triggerleft", CVAR_ARCHIVE); joy_axis_triggerright = Cvar_Get("joy_axis_triggerright", "triggerright", CVAR_ARCHIVE); joy_axis_leftx_threshold = Cvar_Get("joy_axis_leftx_threshold", "0.15", CVAR_ARCHIVE); joy_axis_lefty_threshold = Cvar_Get("joy_axis_lefty_threshold", "0.15", CVAR_ARCHIVE); joy_axis_rightx_threshold = Cvar_Get("joy_axis_rightx_threshold", "0.15", CVAR_ARCHIVE); joy_axis_righty_threshold = Cvar_Get("joy_axis_righty_threshold", "0.15", CVAR_ARCHIVE); joy_axis_triggerleft_threshold = Cvar_Get("joy_axis_triggerleft_threshold", "0.15", CVAR_ARCHIVE); joy_axis_triggerright_threshold = Cvar_Get("joy_axis_triggerright_threshold", "0.15", CVAR_ARCHIVE); #endif vid_fullscreen = Cvar_Get("vid_fullscreen", "0", CVAR_ARCHIVE); windowed_mouse = Cvar_Get("windowed_mouse", "1", CVAR_USERINFO | CVAR_ARCHIVE); Cmd_AddCommand("+mlook", IN_MLookDown); Cmd_AddCommand("-mlook", IN_MLookUp); #if SDL_VERSION_ATLEAST(2, 0, 0) SDL_StartTextInput(); #else SDL_EnableKeyRepeat(SDL_DEFAULT_REPEAT_DELAY, SDL_DEFAULT_REPEAT_INTERVAL); #endif #if SDL_VERSION_ATLEAST(2, 0, 0) /* joystik init */ if (!SDL_WasInit(SDL_INIT_GAMECONTROLLER | SDL_INIT_HAPTIC)) { if (SDL_Init(SDL_INIT_GAMECONTROLLER | SDL_INIT_HAPTIC) == -1) { Com_Printf ("Couldn't init SDL joystick: %s.\n", SDL_GetError ()); } else { Com_Printf ("%i joysticks were found.\n", SDL_NumJoysticks()); if (SDL_NumJoysticks() > 0) { int i; for (i=0; i<SDL_NumJoysticks(); i ++) { joystick = SDL_JoystickOpen(i); Com_Printf ("The name of the joystick is '%s'\n", SDL_JoystickName(joystick)); Com_Printf ("Number of Axes: %d\n", SDL_JoystickNumAxes(joystick)); Com_Printf ("Number of Buttons: %d\n", SDL_JoystickNumButtons(joystick)); Com_Printf ("Number of Balls: %d\n", SDL_JoystickNumBalls(joystick)); Com_Printf ("Number of Hats: %d\n", SDL_JoystickNumHats(joystick)); joystick_haptic = SDL_HapticOpenFromJoystick(joystick); if (joystick_haptic == NULL) Com_Printf ("Most likely joystick isn't haptic\n"); else IN_Haptic_Effects_Info(); if(SDL_IsGameController(i)) { SDL_GameControllerButtonBind backBind; controller = SDL_GameControllerOpen(i); Com_Printf ("Controller settings: %s\n", SDL_GameControllerMapping(controller)); Com_Printf ("Controller axis: \n"); Com_Printf (" * leftx = %s\n", joy_axis_leftx->string); Com_Printf (" * lefty = %s\n", joy_axis_lefty->string); Com_Printf (" * rightx = %s\n", joy_axis_rightx->string); Com_Printf (" * righty = %s\n", joy_axis_righty->string); Com_Printf (" * triggerleft = %s\n", joy_axis_triggerleft->string); Com_Printf (" * triggerright = %s\n", joy_axis_triggerright->string); Com_Printf ("Controller thresholds: \n"); Com_Printf (" * leftx = %f\n", joy_axis_leftx_threshold->value); Com_Printf (" * lefty = %f\n", joy_axis_lefty_threshold->value); Com_Printf (" * rightx = %f\n", joy_axis_rightx_threshold->value); Com_Printf (" * righty = %f\n", joy_axis_righty_threshold->value); Com_Printf (" * triggerleft = %f\n", joy_axis_triggerleft_threshold->value); Com_Printf (" * triggerright = %f\n", joy_axis_triggerright_threshold->value); backBind = SDL_GameControllerGetBindForButton(controller, SDL_CONTROLLER_BUTTON_BACK); if (backBind.bindType == SDL_CONTROLLER_BINDTYPE_BUTTON) { back_button_id = backBind.value.button; Com_Printf ("\nBack button JOY%d will be unbindable.\n", back_button_id+1); } break; } else { char joystick_guid[256] = {0}; SDL_JoystickGUID guid; guid = SDL_JoystickGetDeviceGUID(i); SDL_JoystickGetGUIDString(guid, joystick_guid, 255); Com_Printf ("For use joystic as game contoller please set SDL_GAMECONTROLLERCONFIG:\n"); Com_Printf ("e.g.: SDL_GAMECONTROLLERCONFIG='%s,%s,leftx:a0,lefty:a1,rightx:a2,righty:a3,back:b1,...\n", joystick_guid, SDL_JoystickName(joystick)); } } } else { joystick_haptic = SDL_HapticOpenFromMouse(); if (joystick_haptic == NULL) Com_Printf ("Most likely mouse isn't haptic\n"); else IN_Haptic_Effects_Info(); } } } #endif Com_Printf("------------------------------------\n\n"); }