Exemple #1
0
  int JoystickInput::getEvent(bool ignoreConfig, bool checkLock)
  {
#ifdef HAVE_SDL_H
    if (!haveJoystick)
      return 0;
    mutex_.lock();
    if ((!ignoreConfig && !config.enableJoystick) || (checkLock && lockFlag)) {
      mutex_.unlock();
      return 0;
    }
    if (eventIndex < eventCnt) {
      // consume any buffered events first
      int     retval = events[eventIndex];
      if (++eventIndex == eventCnt) {
        eventCnt = 0;
        eventIndex = 0;
      }
      mutex_.unlock();
      return retval;
    }
    {
      double  t = updateTimer.getRealTime();
      if (t < 0.005) {
        mutex_.unlock();
        return 0;
      }
      // poll joystick input at 5 ms intervals
      updateTimer.reset((t - 0.005) * 0.5);
    }
    SDL_JoystickUpdate();
    eventCnt = 0;
    eventIndex = 0;
    if (!ignoreConfig) {
      int     thresholdInt = int(config.axisThreshold * 32767.0 + 0.5);
      bool    autoFireState = false;
      double  pwmPhase = 0.0;
      if (config.enablePWM) {
        double  tt = 1.0 / config.pwmFrequency;
        double  t = pwmTimer.getRealTime();
        if (t >= tt) {
          t = std::fmod(t, tt);
          pwmTimer.reset(t);
        }
        pwmPhase = t * config.pwmFrequency;
        pwmPhase *= (1.0 - config.axisThreshold);
        pwmPhase += (config.axisThreshold * 0.5);
      }
      if (config.enableAutoFire) {
        double  tt = 1.0 / config.autoFireFrequency;
        double  t = autoFireTimer.getRealTime();
        if (t >= tt) {
          t = std::fmod(t, tt);
          autoFireTimer.reset(t);
        }
        autoFireState = (t < (tt * config.autoFirePulseWidth));
      }
      for (int i = 0; i < axisCnt; i++) {
        int     newState =
            int(SDL_JoystickGetAxis(reinterpret_cast<SDL_Joystick *>(
                                        sdlDevices[axes[i].devNum]),
                                    axes[i].axisNum));
        if (!config.enablePWM) {
          if (newState > axes[i].prvInputState) {
            if (newState >= (-thresholdInt)) {
              if (axes[i].prvOutputState < 0)
                events[eventCnt++] = -(keyCodeBase + (i << 1));
              if (newState >= thresholdInt) {
                if (axes[i].prvOutputState <= 0)
                  events[eventCnt++] = (keyCodeBase + (i << 1) + 1);
                axes[i].prvOutputState = 1;
              }
              else
                axes[i].prvOutputState = 0;
            }
          }
          else if (newState < axes[i].prvInputState) {
            if (newState < thresholdInt) {
              if (axes[i].prvOutputState > 0)
                events[eventCnt++] = -(keyCodeBase + (i << 1) + 1);
              if (newState < (-thresholdInt)) {
                if (axes[i].prvOutputState >= 0)
                  events[eventCnt++] = (keyCodeBase + (i << 1));
                axes[i].prvOutputState = -1;
              }
              else
                axes[i].prvOutputState = 0;
            }
          }
        }
        else {
          int     newOutputState = 0;
          if (newState > 0) {
            if ((double(newState) * (1.0 / 32768.0)) >= pwmPhase)
              newOutputState = 1;
          }
          else if (newState < 0) {
            if ((double(newState) * (-1.0 / 32768.0)) > pwmPhase)
              newOutputState = -1;
          }
          if (newOutputState != axes[i].prvOutputState) {
            if (axes[i].prvOutputState < 0)
              events[eventCnt++] = -(keyCodeBase + (i << 1));
            else if (axes[i].prvOutputState > 0)
              events[eventCnt++] = -(keyCodeBase + (i << 1) + 1);
            if (newOutputState < 0)
              events[eventCnt++] = (keyCodeBase + (i << 1));
            else if (newOutputState > 0)
              events[eventCnt++] = (keyCodeBase + (i << 1) + 1);
            axes[i].prvOutputState = newOutputState;
          }
        }
        axes[i].prvInputState = newState;
      }
      for (int i = 0; i < buttonCnt; i++) {
        bool    newState =
            bool(SDL_JoystickGetButton(reinterpret_cast<SDL_Joystick *>(
                                           sdlDevices[buttons[i].devNum]),
                                       buttons[i].buttonNum));
        if (config.enableAutoFire) {
          if (newState && !buttons[i].prvInputState) {
            autoFireState = true;
            autoFireTimer.reset();
          }
          buttons[i].prvInputState = newState;
          newState = newState && autoFireState;
        }
        else
          buttons[i].prvInputState = newState;
        if (newState != buttons[i].prvOutputState) {
          if (newState)
            events[eventCnt++] = (keyCodeBase + 16 + i);
          else
            events[eventCnt++] = -(keyCodeBase + 16 + i);
          buttons[i].prvOutputState = newState;
        }
      }
    }
    else {
      // special mode with high threshold and hysteresis, no pulse width
      // modulation and auto fire; used when defining the keyboard map, as
      // stable input is required
      for (int i = 0; i < axisCnt; i++) {
        int     newState =
            int(SDL_JoystickGetAxis(reinterpret_cast<SDL_Joystick *>(
                                        sdlDevices[axes[i].devNum]),
                                    axes[i].axisNum));
        if (newState > axes[i].prvInputState) {
          if (newState >= -8192) {
            if (axes[i].prvOutputState < 0)
              events[eventCnt++] = -(keyCodeBase + (i << 1));
            if (newState >= 24576) {
              if (axes[i].prvOutputState <= 0)
                events[eventCnt++] = (keyCodeBase + (i << 1) + 1);
              axes[i].prvOutputState = 1;
            }
            else if (newState < 8192)
              axes[i].prvOutputState = 0;
          }
        }
        else if (newState < axes[i].prvInputState) {
          if (newState < 8192) {
            if (axes[i].prvOutputState > 0)
              events[eventCnt++] = -(keyCodeBase + (i << 1) + 1);
            if (newState < -24576) {
              if (axes[i].prvOutputState >= 0)
                events[eventCnt++] = (keyCodeBase + (i << 1));
              axes[i].prvOutputState = -1;
            }
            else if (newState >= -8192)
              axes[i].prvOutputState = 0;
          }
        }
        axes[i].prvInputState = newState;
      }
      for (int i = 0; i < buttonCnt; i++) {
        bool    newState =
            bool(SDL_JoystickGetButton(reinterpret_cast<SDL_Joystick *>(
                                           sdlDevices[buttons[i].devNum]),
                                       buttons[i].buttonNum));
        if (newState != buttons[i].prvInputState) {
          if (newState)
            events[eventCnt++] = (keyCodeBase + 16 + i);
          else
            events[eventCnt++] = -(keyCodeBase + 16 + i);
          buttons[i].prvInputState = newState;
          buttons[i].prvOutputState = newState;
        }
      }
    }
    for (int i = 0; i < hatCnt; i++) {
      int     newState =
          int(SDL_JoystickGetHat(reinterpret_cast<SDL_Joystick *>(
                                     sdlDevices[povHats[i].devNum]),
                                 povHats[i].hatNum));
      int     changeMask = newState ^ povHats[i].prvState;
      if (changeMask) {
        if (changeMask & int(SDL_HAT_RIGHT)) {
          if (newState & int(SDL_HAT_RIGHT))
            events[eventCnt++] = (keyCodeBase + 32 + (i << 2));
          else
            events[eventCnt++] = -(keyCodeBase + 32 + (i << 2));
        }
        if (changeMask & int(SDL_HAT_UP)) {
          if (newState & int(SDL_HAT_UP))
            events[eventCnt++] = (keyCodeBase + 32 + (i << 2) + 1);
          else
            events[eventCnt++] = -(keyCodeBase + 32 + (i << 2) + 1);
        }
        if (changeMask & int(SDL_HAT_LEFT)) {
          if (newState & int(SDL_HAT_LEFT))
            events[eventCnt++] = (keyCodeBase + 32 + (i << 2) + 2);
          else
            events[eventCnt++] = -(keyCodeBase + 32 + (i << 2) + 2);
        }
        if (changeMask & int(SDL_HAT_DOWN)) {
          if (newState & int(SDL_HAT_DOWN))
            events[eventCnt++] = (keyCodeBase + 32 + (i << 2) + 3);
          else
            events[eventCnt++] = -(keyCodeBase + 32 + (i << 2) + 3);
        }
        povHats[i].prvState = newState;
      }
    }
    int     retval = 0;
    if (eventCnt) {
      // return first event from buffer
      retval = events[0];
      if (++eventIndex == eventCnt) {
        eventCnt = 0;
        eventIndex = 0;
      }
    }
    mutex_.unlock();
    return retval;
#else
    (void) ignoreConfig;
    (void) checkLock;
    return 0;
#endif  // HAVE_SDL_H
  }
Exemple #2
0
/* update joystick states */
void update_joysticks(void)
{
  SDL_JoystickUpdate();
}
static void get_binds(config_file_t *conf, int player, int joypad)
{
   if (SDL_Init(SDL_INIT_JOYSTICK | SDL_INIT_VIDEO) < 0)
   {
      fprintf(stderr, "Failed to init joystick subsystem.\n");
      exit(1);
   }

   SDL_Joystick *joystick;
   int num = SDL_NumJoysticks();
   if (joypad >= num)
   {
      fprintf(stderr, "Cannot find joystick at index #%d, only have %d joystick(s) available ...\n", joypad, num);
      exit(1);
   }

   joystick = SDL_JoystickOpen(joypad);
   if (!joystick)
   {
      fprintf(stderr, "Cannot open joystick.\n");
      exit(1);
   }

   int last_axis = -1;
   bool block_axis = false;

   int num_axes = SDL_JoystickNumAxes(joystick);
   int *initial_axes = (int*)calloc(num_axes, sizeof(int));
   assert(initial_axes);

   SDL_PumpEvents();
   SDL_JoystickUpdate();
   for (int i = 0; i < num_axes; i++)
   {
      Sint16 initial = SDL_JoystickGetAxis(joystick, i);
      if (abs(initial) < 20000)
         initial = 0;

      // Certain joypads (such as XBox360 controller on Linux) has a default negative axis for shoulder triggers,
      // which makes configuration very awkward.
      // If default negative, we can't trigger on the negative axis, and similar with defaulted positive axes.

      if (initial)
         fprintf(stderr, "Axis %d is defaulted to %s axis value of %d\n", i, initial > 0 ? "positive" : "negative", (int)initial);

      initial_axes[i] = initial;
   }

   fprintf(stderr, "Configuring binds for player #%d on joypad #%d (%s)\n",
         player + 1, joypad, SDL_JoystickName(joypad));
   fprintf(stderr, "Press Ctrl-C to exit early.\n");
   fprintf(stderr, "\n");

   for (unsigned i = 0; i < sizeof(binds) / sizeof(struct bind) && (g_use_misc || !binds[i].is_misc) ; i++)
   {
      fprintf(stderr, "%s\n", binds[i].keystr);

      bool done = false;
      SDL_Event event;
      int value;
      const char *quark;
      unsigned player_index = binds[i].is_misc ? 0 : player;

      while (SDL_WaitEvent(&event) && !done)
      {
         switch (event.type)
         {
            case SDL_JOYBUTTONDOWN:
               fprintf(stderr, "\tJoybutton pressed: %d\n", (int)event.jbutton.button);
               done = true;
               config_set_int(conf, binds[i].confbtn[player_index], event.jbutton.button);
               break;

            case SDL_JOYAXISMOTION:
            {
               bool same_axis        = last_axis == event.jaxis.axis;
               bool require_negative = initial_axes[event.jaxis.axis] > 0;
               bool require_positive = initial_axes[event.jaxis.axis] < 0;

               // Block the axis config until we're sure axes have returned to their neutral state.
               if (same_axis)
               {
                  if (abs(event.jaxis.value) < 10000 ||
                        (require_positive && event.jaxis.value < 0) ||
                        (require_negative && event.jaxis.value > 0))
                     block_axis = false;
               }

               // If axes are in their neutral state, we can't allow it.
               if (require_negative && event.jaxis.value >= 0)
                  break;
               if (require_positive && event.jaxis.value <= 0)
                  break;

               if (block_axis)
                  break;

               if (abs(event.jaxis.value) > 20000)
               {
                  last_axis = event.jaxis.axis;
                  fprintf(stderr, "\tJoyaxis moved: Axis %d, Value %d\n", (int)event.jaxis.axis, (int)event.jaxis.value);

                  done       = true;
                  block_axis = true;

                  char buf[8];
                  snprintf(buf, sizeof(buf), event.jaxis.value > 0 ? "+%d" : "-%d", event.jaxis.axis);
                  config_set_string(conf, binds[i].confaxis[player_index], buf);
               }

               break;
            }

            case SDL_KEYDOWN:
               fprintf(stderr, ":V\n");
               break;

            case SDL_JOYHATMOTION:
               value = event.jhat.value;
               if (value & SDL_HAT_UP)
                  quark = "up";
               else if (value & SDL_HAT_DOWN)
                  quark = "down";
               else if (value & SDL_HAT_LEFT)
                  quark = "left";
               else if (value & SDL_HAT_RIGHT)
                  quark = "right";
               else
                  break;

               fprintf(stderr, "\tJoyhat moved: Hat %d, direction %s\n", (int)event.jhat.hat, quark);

               done = true;
               char buf[16];
               snprintf(buf, sizeof(buf), "h%d%s", event.jhat.hat, quark);
               config_set_string(conf, binds[i].confbtn[player_index], buf);
               break;


            case SDL_QUIT:
               goto end;

            default:
               break;
         }
      }
   }

   free(initial_axes);

end:
   SDL_JoystickClose(joystick);
   SDL_Quit();
}
int
configure()
{
	SDL_Event mevent;
	int option=1,i;

	drawConfigure(option);

	while(1) {
		while(SDL_PollEvent(&mevent)) {
    			if (mevent.type==SDL_QUIT)
    				return 0;

			/* joystick control for the menu */
			if(joy[0])
			{
				SDL_JoystickUpdate();

				i=SDL_JoystickGetAxis(joy[0],1);
				if(i>4200)
				{
					mevent.type=SDL_KEYDOWN;
					mevent.key.keysym.sym=SDLK_DOWN;
				}
				if(i<-4200)
				{
					mevent.type=SDL_KEYDOWN;
					mevent.key.keysym.sym=SDLK_UP;
				}

				if(SDL_JoystickGetButton(joy[0], 0))
				{
					mevent.type=SDL_KEYDOWN;
					mevent.key.keysym.sym=SDLK_RETURN;
				}

				if(SDL_JoystickGetButton(joy[0], 1))
				{
					mevent.type=SDL_KEYDOWN;
					mevent.key.keysym.sym=SDLK_ESCAPE;
				}
			}

			if(mevent.type==SDL_KEYDOWN) {
				if(mevent.key.keysym.sym==SDLK_ESCAPE)
					return 1;
				if(mevent.key.keysym.sym==SDLK_DOWN ||
					mevent.key.keysym.sym==SDLK_s) {
					option++;
					if(option>4)
						option=1;
					drawConfigure(option);
				}
				if(mevent.key.keysym.sym==SDLK_UP ||
					mevent.key.keysym.sym==SDLK_w) {
					option--;
					if(option<1)
						option=4;
					drawConfigure(option);
				}
				if(mevent.key.keysym.sym==SDLK_RETURN) {
					switch(option) {
						default:
						break;
						case 1:
							if(joy[0]) {
								conf.control[0]=conf.control[0] ? 0 : 1;
								drawConfigure(option);
							}
						break;
						case 2:
							if(joy[1]) {
								conf.control[1]=conf.control[1] ? 0 : 1;
								drawConfigure(option);
							}
						break;
						case 3:
							conf.sound--;
							if(conf.sound<0)
								conf.sound=3;

							if(sound) {
								if(bgm) {
									Mix_FreeMusic(bgm);
									bgm=NULL;
								}

								for(i=0;i<NUM_EFX;i++)
									if(efx[i]) {
										Mix_FreeChunk(efx[i]);
										efx[i]=NULL;
									}
								Mix_CloseAudio();
							}

							if(conf.sound!=NO_SOUND) {
								switch(conf.sound) {
										default:
										case SOUND_HI:
											i=44100;
										break;
										case SOUND_MED:
											i=22050;
										break;
										case SOUND_LOW:
											i=16000;
										break;
								}
								if(Mix_OpenAudio(i, MIX_DEFAULT_FORMAT, 2, 2048)<0) {
									fprintf(stderr, "Unable to set audio: %s\n", SDL_GetError());
									sound=0;
								} else {
									soundLoad();
									if(efx[7])
										Mix_PlayChannel(-1,efx[7],0);
									sound=1;
								}
							}
							drawConfigure(option);
						break;
						case 4:
							conf.fullscreen=conf.fullscreen ? 0 : 1;
							drawConfigure(option);
						break;
					}
				}
			}
		}
	}

	return 0;
}
int
getName(char *name, int place, int playern)
{
	Uint32 tick;
	SDL_Event mevent;
	int pos=0, i=0;
	char ckey='a';

	if(joy[playern-1] && player[playern-1].joy)
	{
		name[pos]=ckey;
		name[pos+1]=0;
	}

	drawGetName(name,place,playern);

	tick=SDL_GetTicks();
	while(1) {
		while(SDL_PollEvent(&mevent)) {
    			if (mevent.type==SDL_QUIT)
    				return 0;

			/* joystick control */
			if(joy[playern-1] && player[playern-1].joy)
			{
				SDL_JoystickUpdate();

				i=SDL_JoystickGetAxis(joy[playern-1],1);
				if(i>4200)
				{
					mevent.type=SDL_KEYDOWN;
					mevent.key.keysym.sym=SDLK_DOWN;
				}
				if(i<-4200)
				{
					mevent.type=SDL_KEYDOWN;
					mevent.key.keysym.sym=SDLK_UP;
				}
				i=SDL_JoystickGetAxis(joy[playern-1],0);
				if(i>4200)
				{
					mevent.type=SDL_KEYDOWN;
					mevent.key.keysym.sym=SDLK_RIGHT;
				}

				if(SDL_JoystickGetButton(joy[playern-1], 0))
				{
					mevent.type=SDL_KEYDOWN;
					mevent.key.keysym.sym=SDLK_RETURN;
				}

				if(SDL_JoystickGetButton(joy[playern-1], 1))
				{
					pos++;
					mevent.type=SDL_KEYDOWN;
					mevent.key.keysym.sym=SDLK_BACKSPACE;
				}
			}

		
			if(mevent.type==SDL_KEYDOWN) {
				if(mevent.key.keysym.sym==SDLK_ESCAPE) {
					if(!name[0])
						strcpy(name,"nobody");
					return 1;
				}

				if(mevent.key.keysym.sym==SDLK_DOWN)
				{
					ckey--;

					if(ckey<'0')
						ckey='z';
					if(ckey+1=='a')
						ckey='9';

					name[pos]=ckey;
					name[pos+1]=0;
					drawGetName(name,place,playern);

					continue;
				}

				if(mevent.key.keysym.sym==SDLK_UP)
				{
					ckey++;

					if(ckey>'z')
						ckey='0';
					if(ckey-1=='9')
						ckey='a';

					name[pos]=ckey;
					name[pos+1]=0;
					drawGetName(name,place,playern);

					continue;
				}
			
				if(mevent.key.keysym.sym==SDLK_RIGHT)
				{
					if(pos<8) {
						name[pos]=ckey;
						pos++;
						name[pos]=0;
						drawGetName(name,place,playern);

						ckey='a';
						continue;
					}
				}
				
				if(mevent.key.keysym.sym==SDLK_RETURN)
					if(name[0]) {
						/* pirutupiiii */
						if(sound && efx[7])
							Mix_PlayChannel(-1,efx[7],0);
						return 1;
					}

				if(mevent.key.keysym.sym==SDLK_BACKSPACE) {
						if(pos>0) {
							pos--;
							name[pos]=0;
							drawGetName(name,place,playern);
						}
						continue;
				}

				/* I don't know if this will work ever, in my system does */
				if((mevent.key.keysym.sym>=SDLK_a &&
					mevent.key.keysym.sym<=SDLK_z) ||
					(mevent.key.keysym.sym>=SDLK_0 &&
					mevent.key.keysym.sym<=SDLK_9)) {
						if(pos<8) {
							name[pos]=SDLK2ascii(mevent.key.keysym.sym);
							pos++;
							name[pos]=0;
							drawGetName(name,place,playern);

							ckey='a';
						}
				}
			}
		}
	}

	return 0;
}
Exemple #6
0
int state_main_menu(SDL_Surface *screen)
{
    TTF_Font *font_menu = font_load("res/asia.ttf", 50);
    TTF_Font *font_credit = font_load("res/asia.ttf", 20);
    image *bg_image = image_load("res/main.jpg");
    Mix_Chunk *select = sample_load("res/select.wav");

    int i;
    const int item_nb = 2;
    int font_quality = SOLID;
    int choice_current=1;
    SDL_Rect cur_pos;
    bool done = false;
	//bool is_in_game = false;

    cur_pos.x = 10;
    cur_pos.y = 0;
    char sz_choice[20];

    #ifdef GEKKO
    bool timerset = false;
    #endif

    while (!done)
    {
        #ifdef GEKKO
       unsigned int start=0;
       if (!timerset) {
            timerset=true;
            start=SDL_GetTicks();
        }

       unsigned int now=SDL_GetTicks();
       if ((now-start)>50) {
            timerset=false;
            SDL_JoystickUpdate();
            int joystate = SDL_JoystickGetHat(g_game.v_unit[0].joystick, 0);
            switch (joystate){
                case SDL_HAT_DOWN:
                    if (choice_current < item_nb){
                        choice_current++;
                        sample_play(select);
                    }
                break;
                case SDL_HAT_UP:
                    if (choice_current > 1){
                        choice_current--;
                        sample_play(select);
                    }
                break;
            }
       }
       #endif



        SDL_Event event;
        while (SDL_PollEvent(&event))
        {
            switch ( event.type )
            {
            case SDL_QUIT:
                done = true;
                break;
            case SDL_KEYUP:
                switch ( event.key.keysym.sym )
                {
                case SDLK_DOWN:
                    if (choice_current < item_nb){
                        choice_current++;
                        sample_play(select);
                    }
                    break;
                case SDLK_UP:
                    if (choice_current > 1){
                        choice_current--;
                        sample_play(select);
                    }
                    break;
                case SDLK_RETURN:
                    while (choice_current == IN_GAME)
                    {
                        unit_default_param(g_game.v_unit, g_game.unit_nb);
                        choice_current = state_in_game(screen);
                        if (choice_current == MAIN_MENU)    //The current state is main menu, select in game as default choice and quit
                        {
                            choice_current = IN_GAME;
                            break;
                        }
                    }
                    if (choice_current == OPTION)state_options(screen);
                    break;

                default:
                    break;
                }
            break;
            case SDL_JOYBUTTONDOWN:
                switch(event.jbutton.button)
                {
                    case 0:
                    break;
                    case 1:
                    break;

                    case 2:
                        while (choice_current == IN_GAME)
                        {
                            unit_default_param(g_game.v_unit, g_game.unit_nb);
                            choice_current = state_in_game(screen);
                            if (choice_current == MAIN_MENU)    //The current state is main menu, select in game as default choice and quit
                            {
                                choice_current = IN_GAME;
                                break;
                            }
                        }
                        if (choice_current == OPTION)state_options(screen);
                    break;

                    case 3:
                    break;

                    case 4:
                    break;

                    case 5:
                    break;

                    case 6:
                        done = true;
                    break;
                }
            break;
            default:
            break;
            }
        }

        SDL_FillRect(screen, 0, SDL_MapRGB(screen->format, 0, 0, 0));
        image_draw(bg_image, screen, 0, 0);

        int top_shift = 150;

        for (i=1;i<=2;i++)
        {
            if (i == 1)
            {
                strncpy(sz_choice, "Play", 20);
                sz_choice[19] = '\0';
            }
            else if ( i == 2)
            {
                strncpy(sz_choice, "Options", 20);
                sz_choice[19] = '\0';
            }

            if (choice_current == i)
            {
                font_quality = SHADED;
            }
            else font_quality = SOLID;

            cur_pos.y = top_shift + i*50;
            SDL_Surface *font_surface= font_create_surface(font_menu, 250, 120, 35, 10, 100, 100, 100, 0, sz_choice, font_quality);
            SDL_BlitSurface(font_surface, NULL, screen, &cur_pos);
            SDL_FreeSurface (font_surface);
        }

        cur_pos.y = 450;
        SDL_Surface *font_surface= font_create_surface(font_credit, 250, 120, 35, 10, 100, 100, 100, 0, "2010 - 2015 TheDrev", SOLID);
        SDL_BlitSurface(font_surface, NULL, screen, &cur_pos);
        SDL_FreeSurface (font_surface);

        SDL_Flip(screen);
    }

    //free font
    if(font_menu != NULL)TTF_CloseFont(font_menu);
    if(font_credit != NULL)TTF_CloseFont(font_credit);
    SDL_FreeSurface(bg_image->surface);
    Mix_FreeChunk(select);

    //free ressouces
    element* p_browse = images;
    while (p_browse) {
        ressource *res = p_browse->data;
        free(res->name);
        image_free(res->data);
        p_browse = p_browse->next;
    }

    linked_list_clear(&images);

    return EXIT_SUCCESS;
}
Exemple #7
0
int state_options(SDL_Surface *screen)
{
    TTF_Font *font_menu = font_load("res/asia.ttf", 50);
    image *bg_image = image_load("res/options.jpg");
    Mix_Chunk *select = sample_load("res/select.wav");

    int i;
	//int initial_unit_nb = g_game.unit_nb;
    int font_quality = SOLID;
    int choice_current=1;
    SDL_Rect cur_pos;
    bool done = false;

    cur_pos.x = 10;
    cur_pos.y = 0;
    char sz_choice[20];

    #ifdef GEKKO
        unsigned int start=0;
        int timerset = false;
    #endif
SDL_EnableKeyRepeat(50, 10);
    while (!done)
    {
        #ifdef GEKKO
       unsigned int start=0;
       if (!timerset) {
            timerset=true;
            start=SDL_GetTicks();
        }

       unsigned int now=SDL_GetTicks();
           if ((now-start)>50) {
                timerset=false;
                SDL_JoystickUpdate();
                int joystate = SDL_JoystickGetHat(g_game.v_unit[0].joystick, 0);
                switch (joystate){
                    case SDL_HAT_DOWN:
                       if (choice_current <= 1){
                        sample_play(select);
                        choice_current++;
                        }
                    break;
                    case SDL_HAT_UP:
                        if (choice_current > 1){
                            sample_play(select);
                            choice_current--;
                        }
                    break;
                    case SDL_HAT_LEFT:
                        if (choice_current == 2)
                        {
                            if (g_game.block_fill >= 0.01)
                                g_game.block_fill -= 0.01;
                        }
                        else if (choice_current == 1)
                        {
                            if (g_game.unit_nb > 2)
                            {
                                g_game.unit_nb -= 1;
                            }
                        }
                    break;
                    case SDL_HAT_RIGHT:
                        if (choice_current == 2)
                        {
                            if (g_game.block_fill < 0.99)
                                g_game.block_fill += 0.01;
                        }
                        else if (choice_current == 1)
                        {
                            if (g_game.unit_nb < UNIT_MAX)
                            {
                                g_game.unit_nb++;
                            }
                        }
                    break;
                    default:
                    break;
                }
           }
        #endif


        SDL_Event event;
        while (SDL_PollEvent(&event))
        {
            switch ( event.type )
            {
            case SDL_QUIT:
                exit(EXIT_SUCCESS);
                break;
                case SDL_JOYBUTTONDOWN:
                    if(event.jbutton.button == 6){
                        done = true;
                    }
                break;
            case SDL_KEYDOWN:
                switch ( event.key.keysym.sym )
                {
                case SDLK_DOWN:
                    if (choice_current <= 1){
                        sample_play(select);
                        choice_current++;
                    }
                    break;
                case SDLK_UP:
                    if (choice_current > 1)
                    {
                        sample_play(select);
                        choice_current--;
                    }
                    break;
                case SDLK_LEFT:
                    if (choice_current == 2)
                    {
                        if (g_game.block_fill >= 0.01)
                            g_game.block_fill -= 0.01;
                    }
                    else if (choice_current == 1)
                    {
                        if (g_game.unit_nb > 2)
                        {
                            g_game.unit_nb--;
                        }
                    }
                    break;
                case SDLK_RIGHT:
                    if (choice_current == 2)
                    {
                        if (g_game.block_fill < 0.99)
                            g_game.block_fill += 0.01;
                    }
                    else if (choice_current == 1)
                    {
                        if (g_game.unit_nb < UNIT_MAX)
                        {
                            g_game.unit_nb++;
                        }
                    }
                    break;
                case SDLK_ESCAPE:
                    done = true;
                    break;
                default:
                    break;
                }
                break;
            }

            if(event.type == SDL_JOYBUTTONDOWN && event.jbutton.button == 6)done=true;
        }

        SDL_FillRect(screen, 0, SDL_MapRGB(screen->format, 20, 20, 20));
        image_draw(bg_image, screen, 0, 0);


        for (i=1;i<=2;i++)
        {
            if (i == 1)
            {
                sprintf(sz_choice, "%s < %.d >", "Player", g_game.unit_nb);
            }
            else if ( i == 2)
            {

                sprintf(sz_choice, "%s < %.0f%% >", "Block fill", g_game.block_fill * 100);
            }

            if (choice_current == i)
            {
                font_quality = SHADED;
            }
            else font_quality = SOLID;

            cur_pos.y = i*100;
            SDL_Surface *font_surface;
            font_surface = font_create_surface(font_menu, 250, 120, 35, 10, 100, 100, 100, 0, sz_choice, font_quality);
            SDL_BlitSurface(font_surface, NULL, screen, &cur_pos);
            SDL_FreeSurface(font_surface);
        }
        SDL_Flip(screen);
    }
    TTF_CloseFont(font_menu);
    SDL_FreeSurface(bg_image->surface);
    SDL_EnableKeyRepeat(0, 0);
    return OPTION;
}
Exemple #8
0
static mrb_value
mrb_sdl2_joystick_joystick_update(mrb_state *mrb, mrb_value self)
{
  SDL_JoystickUpdate();
  return self;
}
Exemple #9
0
//
// UpdateJoystick
//
uint32_t Xbox::UpdateJoystick(void *obj, uint32_t ival, void *arg)
{
	int16_t     axis_x = 0, axis_y = 0;
	int16_t     move_x = 0, move_y = 0;
	int         mouse_x, mouse_y;
	uint8_t     button;
	uint8_t     hat;

	if(!SDL_JoystickOpened(JOYPAD1) || !OpenedJoy)
		return false;

	// Get the cursor position
	SDL_GetMouseState(&mouse_x, &mouse_y);

	// Get the current joystick state
	SDL_JoystickUpdate();

	// Left Stick X Axis
	axis_x = SDL_JoystickGetAxis(OpenedJoy, JOY_AXIS_LX);
	// Left Stick Y Axis
	axis_y = SDL_JoystickGetAxis(OpenedJoy, JOY_AXIS_LY);

	if(axis_x || axis_y)
	{
		if(axis_x > JOY_DEADZONE)
			axis_x -= JOY_DEADZONE;
		else if(axis_x < -JOY_DEADZONE)
			axis_x += JOY_DEADZONE;
		else
			axis_x = 0;

		if(axis_y > JOY_DEADZONE)
			axis_y -= JOY_DEADZONE;
		else if(axis_y < -JOY_DEADZONE)
			axis_y += JOY_DEADZONE;
		else
			axis_y = 0;

		move_x = mouse_x;
		move_y = mouse_y;

		if(axis_x)
			move_x += axis_x / 2000;
		if(axis_y)
			move_y += axis_y / 2000;

		// Move the cursor
		if(move_x != mouse_x || move_y != mouse_y)
			SDL_WarpMouse(move_x, move_y);
	}

	// Get all the button states
	for(int i = 0; i < JOY_BTTN_TOTAL; i++)
	{
		SDL_Event ev;

		button = SDL_JoystickGetButton(OpenedJoy, i);

		// Mouse Button Translations
		if(i == JOY_BTTN_A)
		{
			if(button && !BPressed[i])
			{
				ev.button.type = SDL_MOUSEBUTTONDOWN;
				ev.button.state = SDL_PRESSED;
			}
			else if(!button && BPressed[i])
			{
				ev.button.type = SDL_MOUSEBUTTONUP;
				ev.button.state = SDL_RELEASED;
			}
			else
				continue;

			ev.button.which = 0;
			ev.button.button = SDL_BUTTON_LEFT;
			ev.button.x = mouse_x;
			ev.button.y = mouse_y;
		}
		// Keyboard Translations
		else if(i == JOY_BTTN_B || i == JOY_BTTN_LTRIG || i == JOY_BTTN_RTRIG)
		{
			if(button && !BPressed[i])
			{
				ev.key.type = SDL_KEYDOWN;
				ev.key.state = SDL_PRESSED;
			}
			else if(!button && BPressed[i])
			{
				ev.key.type = SDL_KEYUP;
				ev.key.state = SDL_RELEASED;
			}
			else
				continue;

			if(i == JOY_BTTN_B)
				ev.key.keysym.sym = SDLK_RETURN;
			else if(i == JOY_BTTN_LTRIG)
				ev.key.keysym.sym = SDLK_PAGEUP;
			else
				ev.key.keysym.sym = SDLK_PAGEDOWN;
		}
		else
			continue;

		BPressed[i] = !BPressed[i];

		// Push the translated event
		SDL_PushEvent(&ev);
	}

	// Hat (D-Pad)
	hat = SDL_JoystickGetHat(OpenedJoy, 0);
	if(HPressed) // A hat position is recorded
	{
		if(!(hat & HPressed))
		{
			SDL_Event ev;

			ev.key.type = SDL_KEYUP;
			ev.key.state = SDL_RELEASED;

			if(HPressed == SDL_HAT_UP)
				ev.key.keysym.sym = SDLK_UP;
			else if(HPressed == SDL_HAT_DOWN)
				ev.key.keysym.sym = SDLK_DOWN;
			else
				ev.key.keysym.sym = SDLK_TAB;

			SDL_PushEvent(&ev);

			// In the Agar tabcycle code the action is taken when the tab keyup
			// event is received and it is then that the shift modifier is tested
			// so shift needs to be released after the tab event has been pushed or
			// the modifier will not be active when the test occurs.
			if(HPressed == SDL_HAT_LEFT)
			{
				// Push the mod keyup event
				ev.key.keysym.sym = SDLK_LSHIFT;
				SDL_PushEvent(&ev);
			}

			HPressed = 0;
		}
	}
	if(!HPressed) // Either nothing was pushed before or the state has changed
	{
		SDL_Event ev;

		ev.key.type = SDL_KEYDOWN;
		ev.key.state = SDL_PRESSED;

		if(hat & SDL_HAT_UP)
		{
			ev.key.keysym.sym = SDLK_UP;
			HPressed = SDL_HAT_UP;
		}
		else if(hat & SDL_HAT_DOWN)
		{
			ev.key.keysym.sym = SDLK_DOWN;
			HPressed = SDL_HAT_DOWN;
		}
		else if(hat & SDL_HAT_RIGHT)
		{
			ev.key.keysym.sym = SDLK_TAB;
			HPressed = SDL_HAT_RIGHT;
		}
		else if(hat & SDL_HAT_LEFT)
		{
			// Push the mod keydown event
			ev.key.keysym.sym = SDLK_LSHIFT;
			SDL_PushEvent(&ev);

			ev.key.keysym.sym = SDLK_TAB;
			HPressed = SDL_HAT_LEFT;
		}

		if(HPressed)
			SDL_PushEvent(&ev);
	}

	// Repeat after interval
	return ival;
}
Exemple #10
0
void handleInput(Ogre::Real elapsedRealTime)
{
	// This variable can be used to keep keys from repeating too fast.
	static Ogre::Real toggleTimer = 0;
	if (toggleTimer >= 0)
	{
		toggleTimer -= elapsedRealTime;
	}

	OIS::Keyboard* keyboard = gEngine.getKeyboard();

	if (keyboard->isKeyDown(OIS::KC_W))
	{
		gCar->forward();
	}
	else if (keyboard->isKeyDown(OIS::KC_S))
	{
		gCar->reverse();
	}
	else
	{
		gCar->idle();
	}

	if (keyboard->isKeyDown(OIS::KC_A))
	{
		gCar->setSteering(-1);
	}
	else if (keyboard->isKeyDown(OIS::KC_D))
	{
		gCar->setSteering(1);
	}
	else
	{
		gCar->setSteering(0);
	}

	// If available, get data from the game controller.
	if (gGamePad)
	{
		// Update the game controller state.
		SDL_JoystickUpdate();

		Ogre::Real joy0X = (Ogre::Real)SDL_JoystickGetAxis(gGamePad, 0) / 
			(Ogre::Real)32768;
		Ogre::Real joy0Y = (Ogre::Real)SDL_JoystickGetAxis(gGamePad, 1) / 
			(Ogre::Real)32768;
		Ogre::Real joy1X = (Ogre::Real)SDL_JoystickGetAxis(gGamePad, 4) / 
			(Ogre::Real)32768;
		Ogre::Real joy1Y = (Ogre::Real)SDL_JoystickGetAxis(gGamePad, 3) / 
			(Ogre::Real)32768;

		if (fabs(joy0Y) > 0.1)
		{
			gCar->setThrottle(-joy0Y);
		}
		else
		{
			gCar->idle();
		}

		if (fabs(joy0X) > 0.1)
		{
			gCar->setSteering(joy0X);
		}
		else
		{
			gCar->setSteering(0);
		}

		if (joy1X > 0.2 || joy1X < -0.2)
		{
			Ogre::Degree rotAroundY = -Ogre::Degree(joy1X);
			gEngine.getCamera()->yawRelative(rotAroundY.valueDegrees());
		}

		if (joy1Y > 0.2 || joy1Y < -0.2)
		{
			Ogre::Degree rotAroundX = -Ogre::Degree(joy1Y);
			gEngine.getCamera()->pitchRelative(rotAroundX.valueDegrees());
		}
	}

	// Toggle GUI.
	if (keyboard->isKeyDown(OIS::KC_G) && toggleTimer <= 0)
	{
		Ogre::Overlay* debugOverlay = Ogre::OverlayManager::getSingleton().
			getByName("Verve/Debug");

		if (debugOverlay->isVisible())
        {
			debugOverlay->hide();
			gAgentDebugger->setDisplayEnabled(false);
		}
		else
		{
			debugOverlay->show();
			gAgentDebugger->setDisplayEnabled(true);
		}

		toggleTimer = 0.5;
	}
}
Exemple #11
0
int ReadAnalogEvent(int padnum, int analognum, int analogdir)
{
	SDL_Joystick *js;
	int i, changed = 0, t;
	Sint16 axis;
	
	if (g.cfg.PadDef[padnum].DevNum >= 0) {
		js = SDL_JoystickOpen(g.cfg.PadDef[padnum].DevNum);
		SDL_JoystickEventState(SDL_IGNORE);
	} else {
		js = NULL;
	}
	
	for (t = 0; t < 1000000 / 1000; t++) {
		// check joystick events
		if (js != NULL) {
			SDL_JoystickUpdate();
			
			for (i = 0; i < SDL_JoystickNumButtons(js); i++) {
				if (SDL_JoystickGetButton(js, i)) {
					g.cfg.PadDef[padnum].AnalogDef[analognum][analogdir].JoyEvType = BUTTON;
					g.cfg.PadDef[padnum].AnalogDef[analognum][analogdir].J.Button = i;
					changed = 1;
					goto end;
				}
			}
			
			for (i = 0; i < NUM_AXES(js); i++) {
				axis = SDL_JoystickGetAxis(js, i);
				if (abs(axis) > 16383 && (abs(axis - PrevAxisPos[i]) > 4096 || abs(axis - InitialAxisPos[i]) > 4096)) {
					g.cfg.PadDef[padnum].AnalogDef[analognum][analogdir].JoyEvType = AXIS;
					g.cfg.PadDef[padnum].AnalogDef[analognum][analogdir].J.Axis = (i + 1) * (axis > 0 ? 1 : -1);
					changed = 1;
					goto end;
				}
				PrevAxisPos[i] = axis;
			}
			
			for (i = 0; i < SDL_JoystickNumHats(js); i++) {
				axis = SDL_JoystickGetHat(js, i);
				if (axis != SDL_HAT_CENTERED) {
					g.cfg.PadDef[padnum].AnalogDef[analognum][analogdir].JoyEvType = HAT;
					
					if (axis & SDL_HAT_UP) {
						g.cfg.PadDef[padnum].AnalogDef[analognum][analogdir].J.Hat = ((i << 8) | SDL_HAT_UP);
					} else if (axis & SDL_HAT_DOWN) {
						g.cfg.PadDef[padnum].AnalogDef[analognum][analogdir].J.Hat = ((i << 8) | SDL_HAT_DOWN);
					} else if (axis & SDL_HAT_LEFT) {
						g.cfg.PadDef[padnum].AnalogDef[analognum][analogdir].J.Hat = ((i << 8) | SDL_HAT_LEFT);
					} else if (axis & SDL_HAT_RIGHT) {
						g.cfg.PadDef[padnum].AnalogDef[analognum][analogdir].J.Hat = ((i << 8) | SDL_HAT_RIGHT);
					}
					
					changed = 1;
					goto end;
				}
			}
		}
		
		// check keyboard events
		i = CheckKeyDown();
		if (i != 0) {
			if (i != (kVK_Escape + 1)) g.cfg.PadDef[padnum].AnalogDef[analognum][analogdir].Key = i;
			changed = 1;
			goto end;
		}
		
		// check mouse events
		if (GetCurrentButtonState()) {
			changed = 2;
			goto end;
		}
		
		usleep(1000);
	}
	
end:
	if (js != NULL) {
		SDL_JoystickClose(js);
	}
	
	return changed;
}
Exemple #12
0
static void sdl_joypad_poll(void)
{
   SDL_JoystickUpdate();
}
Exemple #13
0
static u32 sal_Input(int held)
{
#if 1
    SDL_Event event;
    int i=0;
    u32 timer=0;
#ifdef GCW_JOYSTICK
    int    deadzone = 10000;
    Sint32 x_move   = 0;
    Sint32 y_move   = 0;

#endif

    if (!SDL_PollEvent(&event))
    {
        if (held)
            return inputHeld;
        return 0;
    }

    Uint8 type = (event.key.state == SDL_PRESSED);
    switch(event.key.keysym.sym)
    {
        CASE( LCTRL,     A      );
        CASE( LALT,      B      );
        CASE( SPACE,     X      );//this triggers for some reason on the gcw0 when analogue joystick is on and in a diagonal position if sdl_updatejoystick is called before this point.
        CASE( LSHIFT,    Y      );
        CASE( TAB,       L      );
        CASE( BACKSPACE, R      );
        CASE( RETURN,    START  );
        CASE( ESCAPE,    SELECT );
        CASE( UP,        UP     );
        CASE( DOWN,      DOWN   );
        CASE( LEFT,      LEFT   );
        CASE( RIGHT,     RIGHT  );
        CASE( HOME,      MENU   );
    default:
        break;
    }
#ifdef GCW_JOYSTICK
    if(analogJoy && !key_repeat_enabled)
    {
        static int j_left = 0;
        static int j_right = 0;
        static int j_up = 0;
        static int j_down = 0;

        //Update joystick position
        if (SDL_NumJoysticks() > 0)
        {
            SDL_Joystick *joy;
            joy    = SDL_JoystickOpen(0);
            SDL_JoystickUpdate();
            x_move = SDL_JoystickGetAxis(joy, 0);
            y_move = SDL_JoystickGetAxis(joy, 1);
        }

        //Emulate keypresses with joystick
        if (x_move < -deadzone || x_move > deadzone)
        {
            if (x_move < -deadzone) inputHeld |= SAL_INPUT_LEFT;
            if (x_move >  deadzone) inputHeld |= SAL_INPUT_RIGHT;
            if (x_move < -deadzone) j_left     = 1;
            if (x_move >  deadzone) j_right    = 1;
        } else
        {
            //stop movement if previously triggered by analogue stick
            if (j_left)
            {
                j_left = 0;
                inputHeld &= ~(SAL_INPUT_LEFT );
            }
            if (j_right)
            {
                j_right = 0;
                inputHeld &= ~(SAL_INPUT_RIGHT );
            }
        }

        if (y_move < -deadzone || y_move > deadzone)
        {
            if (y_move < -deadzone) inputHeld |= SAL_INPUT_UP;
            if (y_move >  deadzone) inputHeld |= SAL_INPUT_DOWN;
            if (y_move < -deadzone) j_up       = 1;
            if (y_move >  deadzone) j_down     = 1;
        } else
        {
            //stop movement if previously triggered by analogue stick
            if (j_up)
            {
                j_up = 0;
                inputHeld &= ~(SAL_INPUT_UP );
            }
            if (j_down)
            {
                j_down = 0;
                inputHeld &= ~(SAL_INPUT_DOWN );
            }
        }
    }
#endif

    mInputRepeat = inputHeld;

#else
    int i=0;
    u32 inputHeld=0;
    u32 timer=0;
    u8 *keystate;

    SDL_PumpEvents();

    keystate = SDL_GetKeyState(NULL);

    if ( keystate[SDLK_LCTRL] ) inputHeld|=SAL_INPUT_A;
    if ( keystate[SDLK_LALT] ) inputHeld|=SAL_INPUT_B;
    if ( keystate[SDLK_SPACE] ) inputHeld|=SAL_INPUT_X;
    if ( keystate[SDLK_LSHIFT] ) inputHeld|=SAL_INPUT_Y;
    if ( keystate[SDLK_TAB] ) inputHeld|=SAL_INPUT_L;
    if ( keystate[SDLK_BACKSPACE] ) inputHeld|=SAL_INPUT_R;
    if ( keystate[SDLK_RETURN] ) inputHeld|=SAL_INPUT_START;
    if ( keystate[SDLK_ESCAPE] ) inputHeld|=SAL_INPUT_SELECT;
    if ( keystate[SDLK_UP] ) inputHeld|=SAL_INPUT_UP;
    if ( keystate[SDLK_DOWN] ) inputHeld|=SAL_INPUT_DOWN;
    if ( keystate[SDLK_LEFT] ) inputHeld|=SAL_INPUT_LEFT;
    if ( keystate[SDLK_RIGHT] ) inputHeld|=SAL_INPUT_RIGHT;

    // Process key repeats
    timer=sal_TimerRead();
    for (i=0; i<32; i++)
    {
        if (inputHeld&(1<<i))
        {
            if(mInputFirst&(1<<i))
            {
                if (mInputRepeatTimer[i]<timer)
                {
                    mInputRepeat|=1<<i;
                    mInputRepeatTimer[i]=timer+10;
                }
                else
                {
                    mInputRepeat&=~(1<<i);
                }
            }
            else
            {
                //First press of button
                //set timer to expire later than usual
                mInputFirst|=(1<<i);
                mInputRepeat|=1<<i;
                mInputRepeatTimer[i]=timer+50;
            }
        }
        else
        {
            mInputRepeatTimer[i]=timer-10;
            mInputRepeat&=~(1<<i);
            mInputFirst&=~(1<<i);
        }

    }

    if(mInputIgnore)
    {
        //A request to ignore all key presses until all keys have been released has been made
        //check for release and clear flag, otherwise clear inputHeld and mInputRepeat
        if (inputHeld == 0)
        {
            mInputIgnore=0;
        }
        inputHeld=0;
        mInputRepeat=0;
    }
#endif

    return inputHeld;
}
Exemple #14
0
EXPORT_C_(void) PADupdate(int pad)
{
	// Poll keyboard.
	PollForKeyboardInput(pad);

	// joystick info
	SDL_JoystickUpdate();

	for (int i = 0; i < MAX_KEYS; i++)
	{
		int cpad = PadEnum[pad][0];

		if (JoystickIdWithinBounds(key_to_joystick_id(cpad, i)))
		{
			JoystickInfo* pjoy = s_vjoysticks[key_to_joystick_id(cpad, i)];
			int pad = (pjoy)->GetPAD();

			switch (type_of_key(cpad, i))
			{
				case PAD_JOYBUTTONS:
				{
					int value = SDL_JoystickGetButton((pjoy)->GetJoy(), key_to_button(cpad, i));

					if (value)
						clear_bit(status[pad], i); // released
					else
						set_bit(status[pad], i); // pressed
					break;
				}
			case PAD_HAT:
				{
					int value = SDL_JoystickGetHat((pjoy)->GetJoy(), key_to_axis(cpad, i));

					if (key_to_hat_dir(cpad, i) == value)
					{
						clear_bit(status[pad], i);
						//PAD_LOG("Registered %s\n", HatName(value), i);
						//PAD_LOG("%s\n", KeyName(cpad, i).c_str());
					}
					else
					{
						set_bit(status[pad], i);
					}
					break;
				}
			case PAD_POV:
				{
					int value = pjoy->GetAxisFromKey(cpad, i);

					PAD_LOG("%s: %d (%d)\n", KeyName(cpad, i).c_str(), value, key_to_pov_sign(cpad, i));
					if (key_to_pov_sign(cpad, i) && (value < -2048))
					{
						//PAD_LOG("%s Released+.\n", KeyName(cpad, i).c_str());
						clear_bit(status[pad], i);
					}
					else if (!key_to_pov_sign(cpad, i) && (value > 2048))
					{
						//PAD_LOG("%s Released-\n", KeyName(cpad, i).c_str());
						clear_bit(status[pad], i);
					}
					else
					{
						//PAD_LOG("%s Pressed.\n", KeyName(cpad, i).c_str());
						set_bit(status[pad], i);
					}
					break;
				}
				case PAD_JOYSTICK:
				{
					int value = pjoy->GetAxisFromKey(cpad, i);

					switch (i)
					{
						case PAD_LX:
						case PAD_LY:
						case PAD_RX:
						case PAD_RY:
							if (abs(value) > (pjoy)->GetDeadzone(value))
								Analog::ConfigurePad(pad, i, value);
							else
								Analog::ResetPad(pad, i);
							break;
					}
					break;
				}
			default: break;
			}
		}
	}
}
/*
===============
IN_Xbox360ControllerMove
===============
*/
static void IN_Xbox360ControllerMove()
{
	bool     joy_pressed[ ARRAY_LEN( joy_keys ) ];
	unsigned int axes = 0;
	unsigned int hat = 0;
	int          total = 0;
	int          i = 0;

	if ( !stick )
	{
		return;
	}

	if ( !in_joystick->integer )
	{
		return;
	}

	SDL_JoystickUpdate();

	memset( joy_pressed, '\0', sizeof( joy_pressed ) );

	// query the stick buttons...
	total = SDL_JoystickNumButtons( stick );

	if ( total > 0 )
	{
		if ( total > (int) ARRAY_LEN( stick_state.buttons ) )
		{
			total = ARRAY_LEN( stick_state.buttons );
		}

		for ( i = 0; i < total; i++ )
		{
			bool pressed = ( SDL_JoystickGetButton( stick, i ) != 0 );

			if ( pressed != stick_state.buttons[ i ] )
			{
				Com_QueueEvent( 0, sysEventType_t::SE_KEY, K_XBOX360_A + i, pressed, 0, nullptr );

				if ( in_xbox360ControllerDebug->integer )
				{
					Log::Notice( "xbox button = %i to key = Q:0x%02x(%s)\n", i, K_XBOX360_A + i, Key_KeynumToString( K_XBOX360_A + i ) );
				}

				stick_state.buttons[ i ] = pressed;
			}
		}
	}

	// look at the hats...
	total = SDL_JoystickNumHats( stick );
	hat = SDL_JoystickGetHat( stick, 0 );

	// update hat state
	if ( hat != stick_state.oldhats )
	{
		if ( hat != stick_state.oldhats )
		{
			int       key;

			const int allHatDirections = ( SDL_HAT_UP |
			                               SDL_HAT_RIGHT |
			                               SDL_HAT_DOWN |
			                               SDL_HAT_LEFT );

			if ( in_xbox360ControllerDebug->integer )
			{
				switch ( hat & allHatDirections )
				{
					case SDL_HAT_UP:
						key = K_XBOX360_DPAD_UP;
						break;

					case SDL_HAT_RIGHT:
						key = K_XBOX360_DPAD_RIGHT;
						break;

					case SDL_HAT_DOWN:
						key = K_XBOX360_DPAD_DOWN;
						break;

					case SDL_HAT_LEFT:
						key = K_XBOX360_DPAD_LEFT;
						break;

					case SDL_HAT_RIGHTUP:
						key = K_XBOX360_DPAD_RIGHTUP;
						break;

					case SDL_HAT_RIGHTDOWN:
						key = K_XBOX360_DPAD_RIGHTDOWN;
						break;

					case SDL_HAT_LEFTUP:
						key = K_XBOX360_DPAD_LEFTUP;
						break;

					case SDL_HAT_LEFTDOWN:
						key = K_XBOX360_DPAD_LEFTDOWN;
						break;

					default:
						key = 0;
						break;
				}

				if ( hat != SDL_HAT_CENTERED )
				{
					Log::Notice( "xbox hat bits = %i to key = Q:0x%02x(%s)\n", hat, key, Key_KeynumToString( key ) );
				}
			}

			// release event
			switch ( stick_state.oldhats & allHatDirections )
			{
				case SDL_HAT_UP:
					Com_QueueEvent( 0, sysEventType_t::SE_KEY, K_XBOX360_DPAD_UP, false, 0, nullptr );
					break;

				case SDL_HAT_RIGHT:
					Com_QueueEvent( 0, sysEventType_t::SE_KEY, K_XBOX360_DPAD_RIGHT, false, 0, nullptr );
					break;

				case SDL_HAT_DOWN:
					Com_QueueEvent( 0, sysEventType_t::SE_KEY, K_XBOX360_DPAD_DOWN, false, 0, nullptr );
					break;

				case SDL_HAT_LEFT:
					Com_QueueEvent( 0, sysEventType_t::SE_KEY, K_XBOX360_DPAD_LEFT, false, 0, nullptr );
					break;

				case SDL_HAT_RIGHTUP:
					Com_QueueEvent( 0, sysEventType_t::SE_KEY, K_XBOX360_DPAD_RIGHTUP, false, 0, nullptr );
					break;

				case SDL_HAT_RIGHTDOWN:
					Com_QueueEvent( 0, sysEventType_t::SE_KEY, K_XBOX360_DPAD_RIGHTDOWN, false, 0, nullptr );
					break;

				case SDL_HAT_LEFTUP:
					Com_QueueEvent( 0, sysEventType_t::SE_KEY, K_XBOX360_DPAD_LEFTUP, false, 0, nullptr );
					break;

				case SDL_HAT_LEFTDOWN:
					Com_QueueEvent( 0, sysEventType_t::SE_KEY, K_XBOX360_DPAD_LEFTDOWN, false, 0, nullptr );
					break;

				default:
					break;
			}

			// press event
			switch ( hat & allHatDirections )
			{
				case SDL_HAT_UP:
					Com_QueueEvent( 0, sysEventType_t::SE_KEY, K_XBOX360_DPAD_UP, true, 0, nullptr );
					break;

				case SDL_HAT_RIGHT:
					Com_QueueEvent( 0, sysEventType_t::SE_KEY, K_XBOX360_DPAD_RIGHT, true, 0, nullptr );
					break;

				case SDL_HAT_DOWN:
					Com_QueueEvent( 0, sysEventType_t::SE_KEY, K_XBOX360_DPAD_DOWN, true, 0, nullptr );
					break;

				case SDL_HAT_LEFT:
					Com_QueueEvent( 0, sysEventType_t::SE_KEY, K_XBOX360_DPAD_LEFT, true, 0, nullptr );
					break;

				case SDL_HAT_RIGHTUP:
					Com_QueueEvent( 0, sysEventType_t::SE_KEY, K_XBOX360_DPAD_RIGHTUP, true, 0, nullptr );
					break;

				case SDL_HAT_RIGHTDOWN:
					Com_QueueEvent( 0, sysEventType_t::SE_KEY, K_XBOX360_DPAD_RIGHTDOWN, true, 0, nullptr );
					break;

				case SDL_HAT_LEFTUP:
					Com_QueueEvent( 0, sysEventType_t::SE_KEY, K_XBOX360_DPAD_LEFTUP, true, 0, nullptr );
					break;

				case SDL_HAT_LEFTDOWN:
					Com_QueueEvent( 0, sysEventType_t::SE_KEY, K_XBOX360_DPAD_LEFTDOWN, true, 0, nullptr );
					break;

				default:
					break;
			}
		}
	}

	// save hat state
	stick_state.oldhats = hat;

#if defined( WIN32 )
	// use left stick for strafing
	IN_XBox360Axis( 0, joystickAxis_t::AXIS_SIDE, 127 );
	IN_XBox360Axis( 1, joystickAxis_t::AXIS_FORWARD, -127 );

	// use right stick for viewing
	IN_XBox360Axis( 4, joystickAxis_t::AXIS_YAW, -127 );
	IN_XBox360Axis( 3, joystickAxis_t::AXIS_PITCH, 127 );

	axes |= IN_XBox360AxisToButton( 2, K_XBOX360_LT, -1, 0 );
	axes |= IN_XBox360AxisToButton( 5, K_XBOX360_RT, -1, 0 );
#else
	// use left stick for strafing
	IN_XBox360Axis( 0, joystickAxis_t::AXIS_SIDE, 127 );
	IN_XBox360Axis( 1, joystickAxis_t::AXIS_FORWARD, -127 );

	// use right stick for viewing
	IN_XBox360Axis( 3, joystickAxis_t::AXIS_YAW, -127 );
	IN_XBox360Axis( 4, joystickAxis_t::AXIS_PITCH, 127 );

	axes |= IN_XBox360AxisToButton( 2, K_XBOX360_LT, -1, 0 );
	axes |= IN_XBox360AxisToButton( 5, K_XBOX360_RT, -1, 0 );
#endif

	/* Save for future generations. */
	stick_state.oldaxes = axes;
}
Exemple #16
0
void
game_loop ()
{
    SDL_Event event;
    int done = 0,
        eventstate;

    if (GT_MP)
        net_game_fillsockaddr ();
    if ( SDL_InitSubSystem ( SDL_INIT_JOYSTICK ) < 0 ) {
        fprintf ( stderr, "Unable to initialize Joystick: %s\n", SDL_GetError() );
    }
    printf ( "%i joysticks found\n", SDL_NumJoysticks () );

    menu = NULL;
    bman.updatestatusbar = 1;   // force an update
    timestamp = SDL_GetTicks (); // needed for time sync.
    d_gamedetail ("GAME START");

    gfx_blitupdaterectclear ();
    draw_logo ();
    draw_field ();
    SDL_Flip (gfx.screen);
    draw_players ();

    if (bman.p_nr >= 0 && bman.p_nr < MAX_PLAYERS) {
        players[bman.p_nr].ready = 1;
        if (GT_MP_PTPS)
            send_playerdata (&players[bman.p_servnr].net.addr, bman.p_nr, &players[bman.p_nr]);
    }
    if (bman.p2_nr >= 0 && bman.p2_nr < MAX_PLAYERS) {
        players[bman.p2_nr].ready = 1;
        if (GT_MP_PTPS)
            send_playerdata (&players[bman.p_servnr].net.addr, bman.p2_nr, &players[bman.p2_nr]);
    }
	fire_init();
    while (!done && (bman.state == GS_running || bman.state == GS_ready)) {
        SDL_JoystickUpdate ();
        if ((eventstate = SDL_PollEvent (&event)) != 0)
            switch (event.type) {
            case (SDL_QUIT):
                done = 1;
                bman.state = GS_quit;
            }

        /*
         * input handling
         */
        keyb_loop (&event);

        game_keys_loop ();

        if (GT_MP)
            chat_loop (&event);

        if ((!IS_LPLAYER2) && (!chat.active))
            chat_setactive (1, 1);

        restore_players_screen ();

        player_check (bman.p_nr);
        if (IS_LPLAYER2)
            player_check (bman.p2_nr);

        dead_playerani ();

        special_loop ();

        player_move (bman.p_nr);
        if (IS_LPLAYER2)
            player_move (bman.p2_nr);

        if (GT_MP) {
            player_calcpos ();
            network_loop ();
        }

        if (bman.state == GS_running)
            single_loop ();

        bomb_loop ();
		/* wind_loop (); SOON */
		fire_loop ();
        field_loop ();
        flitems_loop ();

        draw_players ();
        game_draw_info ();      // will set the var bman.player_nr

        /* check if there is only one player left and the game is in multiplayer mode
           and if there the last dieing animation is done */
        if (game_check_endgame () && bman.timeout >= 0.0f)
            bman.timeout = 0.0f;

        if ((GT_SP || GT_MP_PTPM) && bman.timeout < -GAME_OVERTIMEOUT) {
            d_printf ("GAME: Game Over\n");
            done = 1;
        }

        stonelist_draw ();

        /* if there is any menu displayed do so */
        if (menu != NULL)
            game_menu_loop (&event, eventstate);

        gfx_blitdraw ();

        s_calctimesync ();
        bman.timeout -= timediff;

    }

    if (menu != NULL) {
        menu_delete (menu);
        menu = NULL;
    }

    gfx_blitdraw ();

    chat_show (-1, -1, -1, -1);
    draw_logo ();
    gfx_blitupdaterectclear ();
    SDL_Flip (gfx.screen);

    d_gamedetail ("GAME END");
    d_printf ("done = %d\n", done);
};
Exemple #17
0
// drive with joystick
int driveJoy(int deadzone_pct) {
	
	// Initialise Variables
	deadzone_pct /= 100;
    SDL_Joystick *joy;
	
	
	// Show window
	echo();
	clear();
	ev3->status(true);
	ev3->stop(false);
	refresh();
	
	// Init joystick
	if ( SDL_InitSubSystem ( SDL_INIT_JOYSTICK ) < 0 )
	{
		mvprintw(4, 2, "Unable to initialize Joystick: %s\n", SDL_GetError() );
		return -1;
	}
	
	// if joysticks available
	if(SDL_NumJoysticks()>0)
    {
        // Open joystick
        joy=SDL_JoystickOpen(0);
        
        // Manually update joystick status
		SDL_JoystickEventState ( SDL_QUERY );
		
		// Initialise variables
		int x = 0,
			y = 0,
			cmd_counter = 0;
		
		// debouncing variables
		bool	btn_brake_mode	= false,
				btn_brakes		= false,
				btn_acc_steering= false,
				send 		= false;	// send command?
		
		// set default values
		drive_t drv;
			drv.speed = 0;
			drv.turn = 0;
			drv.brakes = false;			// Don't turn brakes on at startup
			drv.brake_mode = false; 	// Coast
			drv.acc_steering = false; 	// Use full steering while driving
			
		
		// Main loop
		while( true ) {	
			
			// Show driving information
			clear();
			mvprintw(2, 2, "Speed:  %2d  Turn:  %2d  CS: %3d\n", drv.speed, drv.turn, drv.convSpeed);
			mvprintw(3, 2, "LX: %5d  RY: %5d", x, y );
			ev3->status(true);
			refresh();
			
			// Initialise variables
			int tmpx = 0,
				tmpy = 0,
				tol  = 32768 * deadzone_pct; // determine controller tolerance
			int button[4];	
			send = false;
			
			// Update joystick status
			SDL_JoystickUpdate ();
			
			// read buttons
			button[0] = SDL_JoystickGetButton( joy, BTN_BRAKE );
			button[1] = SDL_JoystickGetButton( joy, BTN_BRAKE_MODE );
			button[2] = SDL_JoystickGetButton( joy, BTN_ACC_STEERING );
			button[3] = SDL_JoystickGetButton( joy, BTN_QUIT );
			
			// show button information
			mvprintw(5,2,"Brake:   %d", (int)(drv.brakes), button[0]);
			mvprintw(6,2,"BrMode:  %d", (int)(drv.brakes), button[1]);
			mvprintw(7,2,"AccMode: %d", (int)(drv.acc_steering), button[2]);
			mvprintw(9,2,"Sent %d commands",cmd_counter);
			refresh();
			
			// don't drive the EV3 mad
			usleep(10000);
			
			// check for active brakes
			if(!drv.brakes) {
				
				// read axis for speed control
				tmpy = SDL_JoystickGetAxis(joy, JS_AXIS_SPEED);
				
				// check for significant change
				if( (tmpy + tol) < y || (tmpy - tol) > y ) {
					y = tmpy;
					
					// use full speed while driving backwards
					if(y == 32767)
						y++;
					
					// some deadzone
					if(y >= 768 || y <= -768) {
						
						// convert speed
						drv.speed = (int)(y / -32768.0 * 100.0);
					
					} else // set speed to 0 if value is in deadzone
						drv.speed = 0;
					
					// register for sending command to EV3
					send = true;
				}
				
				// read turn axis
				tmpx = SDL_JoystickGetAxis(joy, JS_AXIS_TURN);
				
				// check for significant change
				if( (tmpx + tol) < x  || (tmpx - tol) > x ) {
					x = tmpx;
					
					// use full turn
					if(x == 32767)
						x++;
					
					// some deadzone
					if(x >= 768 || x <= -768) {
						
						// convert speed
						drv.turn = (int)(x / 32768.0 * 100.0);
						if(drv.acc_steering)
							drv.turn *= 2;
					
					} else // set turn to 0 if value is in deadzone
						drv.turn = 0;
					
					// register for sending command to EV3
					send = true;
				}	
			} // if !brakes
			
			
			
			
			// check debouncer and brake mode button
			if( !(btn_brake_mode) && button[1] ) {
				
				// switch brake mode
				drv.brake_mode = !(drv.brake_mode);
				
				// apply new brake mode if necessary
				if(drv.brakes)
					send = true;
					
				// debounce on
				btn_brake_mode = true;
			}
			// debounce off
			else if( btn_brake_mode && !(button[1]) )
				btn_brake_mode = false;
			
			
			
			// check debouncer and brake button
			if( !(btn_brakes) && button[0] ) {
				
				// switch brake state
				drv.brakes = !(drv.brakes);
				
				// apply brake state
				send = true;
					
				// debounce on
				btn_brakes = true;
			}
			// debounce off
			else if( btn_brakes && !(button[0]) )
				btn_brakes = false;
				
			
			// check debouncer and acc steering button
			if( !(btn_acc_steering) && button[2] ) {
				
				// switch steering behaviour
				drv.acc_steering = !drv.acc_steering;
				
				// debounce on
				btn_acc_steering = true;
			}
			// debounce off
			else if( btn_acc_steering && !(button[2]) )
				btn_acc_steering = false;
				

			
			
			// exit loop on quit button
			if(button[3])
				break;
				
			// send data if available
			if(send) {
				ev3->drive(drv);
				cmd_counter++;
			}
			
		} // while(jsOpen)
		
		// refresh window
		refresh();
		
		// Close if joystick opened
		if(SDL_JoystickOpened(0))
			SDL_JoystickClose(joy);
		
	} // fail w/o joysticks
	
	return 0;
}
Exemple #18
0
void HandleGamepad (int key_held[])
{
	static char state = '0';
#define MAX 32
	static int axes[MAX];
	static int buttons[MAX];
	static int num_axes;
	static int num_buttons;
	static SDL_Joystick* joy;

	if (state == '0') {
		state = '?';
		memset (joy_held, 0, sizeof(joy_held));

		if (SDL_Init(SDL_INIT_JOYSTICK) < 0) {
			fprintf (stderr, "SDL_init(): %s\n", SDL_GetError());
			return;
		}

		// select joystick
		int num_joysticks = SDL_NumJoysticks();
		int i;
		for (i = 0; i < num_joysticks; i++)
			printf ("joystick %d = \"%s\"\n", i, SDL_JoystickName (i));

		if (num_joysticks != 1) {
			printf ("error: %d joysticks detected\n", num_joysticks);
			return;
		}
		int joystick_index = 0;

		joy = SDL_JoystickOpen (joystick_index);
		if (joy == NULL) {
			fprintf (stderr, "SDL_JoystickOpen(): %s\n", SDL_GetError());
			return;
		}

		printf ("Number of Axes: %d\n", num_axes = SDL_JoystickNumAxes(joy));
		printf ("Number of Buttons: %d\n", num_buttons = SDL_JoystickNumButtons(joy));
		printf ("Number of Balls: %d\n", SDL_JoystickNumBalls(joy));
		printf ("Number of Hats: %d\n", SDL_JoystickNumHats(joy));

		state = '1';
	}
	else if (state == '1') {

		SDL_JoystickUpdate();

		int i;
		for (i = 0;  i < num_axes && i < MAX;  ++i)
			axes[i] = SDL_JoystickGetAxis (joy, i);

		for (i = 0;  i < num_buttons && i < MAX;  ++i)
			buttons[i] = SDL_JoystickGetButton (joy, i);

		hold (key_held, K_UP, axes[1] < -1000 || axes[3] < -1000 || buttons[4]);
		hold (key_held, K_RT, axes[0] >  1000 || axes[2] >  1000 || buttons[5]);
		hold (key_held, K_DN, axes[1] >  1000 || axes[3] >  1000 || buttons[6]);
		hold (key_held, K_LT, axes[0] < -1000 || axes[2] < -1000 || buttons[7]);
		hold (key_held, K_SP, buttons[14]);
	}
}
Exemple #19
0
int state_in_game(SDL_Surface *screen)
{
    SDL_Rect srcrect = {0, 0, 480, 480};                      //the part of the screen to be stretched, must be sup 0 and inf screen surface Height and Width
    SDL_Rect dstrect = set_rect(0, 0, SCREEN_HEIGHT, SCREEN_WIDTH);    //equals screen resolution

    int bomb_nb=0;
    int flame_nb=0;
    bool done = false;
    int i=0;                     //generic accumulator 1
    int j=0;                     //generic accumulator 2
    int k=0;                     //unit accumulator
    int tick_count=0;
    int tick_trigger=0;
    int time_elapsed=0;         //time elapsed in this round (in secondes)
    int last_time=0;
    int current_game_status=-1;

    timer *timer_battle = timer_init();
    timer_start(timer_battle);

    // load sample.wav in to sample
    Mix_Chunk *sample = sample_load("res/boom.wav");
    Mix_Music* music = music_load("res/music.xm");
    music_play(music);

    //initialize map
    map *p_map = malloc(sizeof(map));
    p_map->tile_height = 32;
    p_map->tile_width = 32;
    map_load_level(p_map, "res/level_01.map");
    p_map->p_chipset = image_load("res/classic.png");
    SDL_Surface* surface_menu = IMG_Load("./res/menu.png");
    SDL_SetColorKey(surface_menu, SDL_SRCCOLORKEY, SDL_MapRGB(surface_menu->format, 255, 0, 255));

    for (k=0;k<g_game.unit_nb;k++)
    {
        unit_tile_protect(g_game.v_unit+k, p_map);
    }

    int block_nb = map_block_add(p_map, g_game.block_fill, .5);         ///@todo the disp % is not implemented yet
    int panel_nb = panel_add(g_game.v_panel, p_map, block_nb);

    int random_comment = rand() % 9;
    char sz_comment[32];
    SDL_Rect pos_comment = set_rect(10, 465, 0, 0);
    int comment_time_elapsed;
    timer *timer_comment = timer_init();

    //Menu
    TTF_Font *font_menu = font_load("res/asia.ttf", 20);
    TTF_Font *font_result = font_load("res/asia.ttf", 75);

    SDL_Rect cur_pos;
    cur_pos.x = 42;
    cur_pos.y = 425;

    char sz_time[10];

    while (!done)
    {
        SDL_Event event;
        SDL_JoystickUpdate();
        while(SDL_PollEvent(&event)){
            for (k=0;k<g_game.unit_nb;k++)
            {
                if (!g_game.v_unit[k].is_dead)
                {
                    unit_handle_key(g_game.v_unit+k, &event, k, g_game.v_bomb, p_map, &bomb_nb);
                }
            }
           if(event.type == SDL_QUIT || ((event.type == SDL_KEYDOWN) && (event.key.keysym.sym == SDLK_ESCAPE)) || (event.type == SDL_JOYBUTTONDOWN && event.jbutton.button == 6)){
                    done = true;
                    current_game_status = MAIN_MENU;
            }
            else if((event.type == SDL_KEYDOWN && event.key.keysym.sym == SDLK_RETURN)|| (event.type == SDL_JOYBUTTONDOWN && event.jbutton.button == 5)){
                    Mix_PauseMusic();
                    state_paused(screen);
                    Mix_ResumeMusic();
            }
        }

        for (k=0;k<g_game.unit_nb;k++){
            if(!g_game.v_unit[k].use_keyboard){
                int joystate = SDL_JoystickGetHat(g_game.v_unit[k].joystick, 0);
                switch (joystate){
                    case SDL_HAT_DOWN:
                        unit_set_vel_y(g_game.v_unit+k, g_game.v_unit[k].speed);
                        unit_set_vel_x(g_game.v_unit+k, 0);
                        g_game.v_unit[k].p_sprite->animation_current = DOWN;
                    break;
                    case SDL_HAT_UP:
                        unit_set_vel_y(g_game.v_unit+k, -g_game.v_unit[k].speed);
                        unit_set_vel_x(g_game.v_unit+k, 0);
                        g_game.v_unit[k].p_sprite->animation_current = UP;
                    break;
                    case SDL_HAT_RIGHT:
                        unit_set_vel_x(g_game.v_unit+k, g_game.v_unit[k].speed);
                        unit_set_vel_y(g_game.v_unit+k, 0);
                        g_game.v_unit[k].p_sprite->animation_current = RIGHT;
                    break;
                    case SDL_HAT_LEFT:
                        unit_set_vel_x(g_game.v_unit+k, -g_game.v_unit[k].speed);
                        unit_set_vel_y(g_game.v_unit+k, 0);
                        g_game.v_unit[k].p_sprite->animation_current = LEFT;
                    break;
                    default:
                        if ( g_game.v_unit[k].vel_x != 0 ){
                            unit_set_vel_x(g_game.v_unit+k, 0);
                            g_game.v_unit[k].p_sprite->v_anim[g_game.v_unit[k].p_sprite->animation_current].frame_current = 1;
                        }
                        if ( g_game.v_unit[k].vel_y != 0 ){
                            unit_set_vel_y(g_game.v_unit+k, 0);
                            g_game.v_unit[k].p_sprite->v_anim[g_game.v_unit[k].p_sprite->animation_current].frame_current = 1;
                        }

                    break;
                }
            }
        }

        tick_count = SDL_GetTicks();
        if (tick_count > tick_trigger / 60){
            tick_trigger = tick_count;
            SDL_FillRect(backbuffer, 0, SDL_MapRGB(backbuffer->format, 10, 20, 80));


            //draw the map
            map_draw(p_map, backbuffer);
            for (i=0;i<panel_nb;i++)
            {
                if(p_map->pp_tile[g_game.v_panel[i]->p_sprite->y / TILE_SIZE][g_game.v_panel[i]->p_sprite->x / TILE_SIZE].type != BLOCK)panel_draw(g_game.v_panel[i], backbuffer);
            }


            //check panels
            for (i=0;i<panel_nb;i++)
            {
                // for all units
                for (k=0;k<g_game.unit_nb;k++)
                {
                    //Check for bonus
                    if (g_game.v_panel[i]->p_sprite->y / TILE_SIZE == unit_get_bounding_index_center_y(g_game.v_unit+k)
                            && (g_game.v_panel[i]->p_sprite->x / TILE_SIZE == unit_get_bounding_index_center_x(g_game.v_unit+k)))
                    {
                        panel_apply(g_game.v_panel[i], g_game.v_unit+k);

                        panel_free(g_game.v_panel[i]);
                        panel_nb--;

                        //Left shift the vector
                        for (j=i;j<panel_nb;j++)
                        {
                            g_game.v_panel[j] = g_game.v_panel[j+1];
                        }
                    }
                }
            }

            //Draw and update bombs
            for (i=0;i<bomb_nb;i++)
            {
                bomb_draw(g_game.v_bomb[i], backbuffer);
                anim_sprite_update_frame(g_game.v_bomb[i]->p_sprite);
                bomb_update_timer(g_game.v_bomb[i]);

                if ((g_game.v_bomb[i]->time_left <= 0) || (p_map->pp_tile[g_game.v_bomb[i]->p_sprite->y / TILE_SIZE][g_game.v_bomb[i]->p_sprite->x / TILE_SIZE].type == FLAME))
                {
                    sample_play(sample);
                    bomb_explode(g_game.v_bomb[i], p_map, g_game.v_flame, &flame_nb);
                    bomb_nb--;

                    bomb_free(g_game.v_bomb[i]);

                    //Left shift the vector
                    for (j=i;j<bomb_nb;j++)
                    {
                        g_game.v_bomb[j] = g_game.v_bomb[j+1];
                    }
                }
            }

            //Check flame
            for (i=0;i<p_map->height;i++)
            {
                for (j=0;j<p_map->width[i];j++)
                {
                    // for all units, check if hitten (if unit center is on a tile with a flame flag)
                    for (k=0;k<g_game.unit_nb;k++)
                    {
                        if ((p_map->pp_tile[i][j].type == FLAME) &&
                                ((unit_get_index_x(g_game.v_unit+k) == j) &&
                                (unit_get_index_y(g_game.v_unit+k) == i)) &&
                                g_game.v_unit[k].is_dead == false)
                        {
                            g_game.v_unit[k].is_dead = true;
                            timer_start(timer_comment);

                            switch(random_comment)
                            {
                                case(0):sprintf(sz_comment, "Say goodbye, %s ", g_game.v_unit[k].name);
                                break;
                                case(1):sprintf(sz_comment, "burn %s, burn ! ", g_game.v_unit[k].name);
                                break;
                                case(2):sprintf(sz_comment, "%s vanished !!!!!! ", g_game.v_unit[k].name);
                                break;
                                case(3):sprintf(sz_comment, "unit_free(%s); //^^ ", g_game.v_unit[k].name);
                                break;
                                case(4):sprintf(sz_comment, "%s ? Where are you ? ", g_game.v_unit[k].name);
                                break;
                                case(5):sprintf(sz_comment, "%s was a good guy ", g_game.v_unit[k].name);
                                break;
                                case(6):sprintf(sz_comment, "HE says : \"HELLO, %s\" ", g_game.v_unit[k].name);
                                break;
                                case(7):sprintf(sz_comment, "%s has meet his programmer ", g_game.v_unit[k].name);
                                break;
                                case(8):sprintf(sz_comment, "$ %s>/dev/null ", g_game.v_unit[k].name);
                                break;
                                case(9):sprintf(sz_comment, "%s was not ignifugated ", g_game.v_unit[k].name);
                                break;
                            }
                        }
                    }
                }
            }

            //Draw and update flames
            for (i=0;i<flame_nb;i++)
            {
                flame_draw(g_game.v_flame[i], p_map, backbuffer);
                g_game.v_flame[i]->time_left--;
                if (g_game.v_flame[i]->time_left <= 0)
                {
                    flame_free(g_game.v_flame[i], p_map);
                    flame_nb--;

                    //Left shift the vector
                    for (j=i;j<flame_nb;j++)
                    {
                        g_game.v_flame[j] = g_game.v_flame[j+1];
                    }
                }
            }



            for (k=0;k<g_game.unit_nb;k++)
            {
                if (!g_game.v_unit[k].is_dead)
                {
                    unit_calc_bounding_box(g_game.v_unit+k);
                    unit_update(g_game.v_unit+k, p_map);
                }
            }
            // draw and update units
            unit_draw_from_z_index(g_game.v_unit, g_game.unit_nb, backbuffer);

            //Change every 1 second
            time_elapsed = timer_get_ticks (timer_battle) / 1000;
            if (time_elapsed != last_time){
                last_time = time_elapsed;       //Update current time

        /* Check if any unit won
                    This function is performed every second in order to dont call it to often, and
                    have a little delay if two or more units died almost in the same time (even ms, in the case
                    a unit is at the left of a bomb and an other at the right, the right unit win because the
                    flame is first put to the left...)
                */

                int unit_win;
                unit_win = unit_check_victory(g_game.v_unit, g_game.unit_nb);

                if (unit_win >= 0)
                {
                    //print win, sound, etc
                    g_game.v_unit[unit_win].victory++;
                    time_elapsed = 0;
                    ///@todo set a victories limit (from 1 to 5) and display a special image if win... for the moment, another battle
                    font_printf(font_result, TILE_SIZE * 2, TILE_SIZE * 5, 50, 150, 100, backbuffer, "%s wins", g_game.v_unit[unit_win].name);
                    done = true;
                    current_game_status = IN_GAME;
                    SDL_SoftStretch(backbuffer, &srcrect, screen, &dstrect);
                    SDL_Flip(screen);
                    SDL_Delay(2000);
                    break;
                }
                else if (unit_win == -1)
                {
                    font_printf(font_result, (3)*TILE_SIZE, (6)*TILE_SIZE, 50, 150, 100, backbuffer, "DRAW !");
                    done = true;
                    current_game_status = IN_GAME;
                    SDL_SoftStretch(backbuffer, &srcrect, screen, &dstrect);
                    SDL_Flip(screen);
                    SDL_Delay(2000);
                }

                if (g_game.time - time_elapsed <= 0)
                {
                    cur_pos.x = 240;
                    cur_pos.y = 140;
                    font_printf(font_result, (3)*TILE_SIZE, (6)*TILE_SIZE, 50, 150, 100, backbuffer, "TIMES UP !");
                    done = true;
                    ///@todo select action in times up (blocks falling, etc) for the moment, just a draw...
                    current_game_status = IN_GAME;
                    SDL_SoftStretch(backbuffer, &srcrect, screen, &dstrect);
                    SDL_Flip(screen);
                    SDL_Delay(2000);
                }

            }

            ////////////////////  MENU  ////////////////////
            //TIME
            sprintf(sz_time, "%.3d", g_game.time - time_elapsed);
            SDL_Surface *surface_time = font_create_surface(font_menu, 200, 200, 200, 10, 100, 100, 100, 0, sz_time, SOLID);
            SDL_BlitSurface(surface_time, NULL, backbuffer, &cur_pos);
            SDL_FreeSurface(surface_time);
            SDL_Rect menu_src, menu_dest;
            menu_src.h = 32;
            menu_src.w = 32;
            menu_src.x = 0;
            menu_src.y = 0;

            menu_dest.x = 5;
            menu_dest.y = 420;

            SDL_BlitSurface(surface_menu, &menu_src, backbuffer, &menu_dest);

            //VICTORIES
            for (k=0;k<g_game.unit_nb;k++)
            {
                char sz_victory_nb[20];
                SDL_Rect vic_pos = set_rect(10, 450, 0, 0);
                sprintf(sz_victory_nb, "%s: %d", g_game.v_unit[k].name, g_game.v_unit[k].victory);

                vic_pos.x += k * 100;
                SDL_Surface *surface_victory = font_create_surface(font_menu, 200, 200, 200, 10, 100, 100, 100, 0, sz_victory_nb, SOLID);
                SDL_BlitSurface(surface_victory, NULL, backbuffer, &vic_pos);
                SDL_FreeSurface(surface_victory);
            }

            //Comment
            if(timer_comment->started){
                comment_time_elapsed = timer_get_ticks(timer_comment) / 1000;
                if (comment_time_elapsed < 3)   //Display the comment 3 seconds
                {
                    font_printf(font_menu, pos_comment.x, pos_comment.y, 200, 200, 200, backbuffer, sz_comment);
                }
                else{   //done
                    timer_stop(timer_comment);
                    random_comment = rand() % 9;

                }
            }

            //DEBUG
#ifdef DEBUG
            font_printf(font_menu, 10, 10, 255, 255, 200, backbuffer, "flame nb : %d", flame_nb);
            font_printf(font_menu, 10, 30, 255, 255, 200, backbuffer, "bomb nb : %d", bomb_nb);
            font_printf(font_menu, 10, 50, 255, 255, 200, backbuffer, "unit nb : %d", g_game.unit_nb);
            font_printf(font_menu, 10, 70, 255, 255, 200, backbuffer, "fill nb : %.2f", g_game.block_fill);
            font_printf(font_menu, 10, 90, 255, 255, 200, backbuffer, "Blocks at startup : %d", block_nb);
            font_printf(font_menu, 10, 110, 255, 255, 200, backbuffer, "Time elapsed : %d", timer_get_ticks(timer_battle)/1000);
            font_printf(font_menu, 10, 130, 255, 255, 200, backbuffer, "unit 1 index: %d %d", unit_get_bounding_index_center_x(g_game.v_unit+0), unit_get_bounding_index_center_y(g_game.v_unit+0));


            SDL_Rect rect = unit_get_bounding_box(g_game.v_unit+0);
            SDL_FillRect(backbuffer, &rect, SDL_MapRGB(backbuffer->format, 255, 255, 0));
#endif

            SDL_SoftStretch(backbuffer, &srcrect, screen, &dstrect);
            SDL_Flip(screen);
        }//end thick
    }   //end while



    //Free the memory
    for (i=0;i<bomb_nb;i++)
    {
        bomb_free(g_game.v_bomb[i]);
    }
    for (i=0;i<panel_nb;i++)
    {
        panel_free(g_game.v_panel[i]);
    }
    for (i=0;i<flame_nb;i++)
    {
        flame_free(g_game.v_flame[i], p_map);
    }
    map_free(p_map);

    free(timer_battle);
    free(timer_comment);

    Mix_FreeChunk(sample);
    Mix_FreeMusic(music);

    TTF_CloseFont(font_menu);
    font_menu=NULL; // to be safe...

    TTF_CloseFont(font_result);
    font_result=NULL; // to be safe...

    return current_game_status;

}
Exemple #20
0
void GamePadDialog::pollJoystick()
{
#if QT_HAS_SDL
	if(!m_joystick)
		return;
	SDL_JoystickUpdate();

	// Update buttons state
	for(int i=0;i<14;i++)
	{
		float val = 0;
		if(GamepadPadMapping[i].mapping_type == 0)
			val = SDL_JoystickGetButton(m_joystick,GamepadPadMapping[i].mapping_in);
		else if(GamepadPadMapping[i].mapping_type == 1)
		{
			val = SDL_JoystickGetAxis(m_joystick,GamepadPadMapping[i].mapping_in);
			if(val*GamepadPadMapping[i].mapping_sign > 16384) val = 1;
			else val = 0;
		}
		else if(GamepadPadMapping[i].mapping_type == 2)
			val = SDL_JoystickGetHat(m_joystick,GamepadPadMapping[i].mapping_in);
		QLabel* labelPreview = findChild<QLabel*>(GamepadPadMapping[i].ViewLabelName);
		if(labelPreview)
		{
			labelPreview->setVisible(val != 0);
		}
		if(val)
		{
			m_inputState->pad_buttons |= (1<<i);
		}
		else
		{
			m_inputState->pad_buttons &= ~(1<<i);
		}
	}
	// Update analog stick
	m_inputState->pad_lstick_x = 0;
	m_inputState->pad_lstick_y = 0;
	for(int i = 14; i < 18; i++)
	{
		float val = 0;
		if(GamepadPadMapping[i].mapping_type == 0)
			val = SDL_JoystickGetButton(m_joystick,GamepadPadMapping[i].mapping_in);
		else if(GamepadPadMapping[i].mapping_type == 1)
		{
			val = SDL_JoystickGetAxis(m_joystick,GamepadPadMapping[i].mapping_in);
			if((val <= 0 && GamepadPadMapping[i].mapping_sign < 0) || (val >= 0 && GamepadPadMapping[i].mapping_sign > 0))
				val = abs(val) * 1.0f / 32767;
			else
				val = 0;
		}
		else if(GamepadPadMapping[i].mapping_type == 2)
			val = SDL_JoystickGetHat(m_joystick,GamepadPadMapping[i].mapping_in);
		QLabel* labelPreview = findChild<QLabel*>(GamepadPadMapping[i].ViewLabelName);
		if(labelPreview)
		{
			labelPreview->setVisible(val != 0);
		}
		switch(i)
		{
		case 14:
			m_inputState->pad_lstick_x -= val;
			break;
		case 15:
			m_inputState->pad_lstick_x += val;
			break;
		case 16:
			m_inputState->pad_lstick_y -= val;
			break;
		default:
			m_inputState->pad_lstick_y += val;
			break;
		}
	}

	if(isVisible())
	{
		for(int i = 0; i < ui->padValues->topLevelItemCount(); i++)
		{
			QTreeWidgetItem* item = ui->padValues->topLevelItem(i);
			for(int j = 0; j < item->childCount(); j++)
			{
				QTreeWidgetItem* item2 = item->child(j);
				if(item2->data(0,Qt::UserRole).toInt() == 0)
				{
					item2->setText(1,QVariant(SDL_JoystickGetButton(m_joystick,item2->data(0,Qt::UserRole+1).toInt())).toString());
				}
				else if(item2->data(0,Qt::UserRole).toInt() == 1)
				{
					int val = SDL_JoystickGetAxis(m_joystick,item2->data(0,Qt::UserRole+1).toInt());
					if((val <= 0 && item2->data(0,Qt::UserRole+2).toInt() < 0) || (val >= 0 && item2->data(0,Qt::UserRole+2).toInt() > 0))
						item2->setText(1,QVariant(val).toString());
				}
				else if(item2->data(0,Qt::UserRole).toInt() == 2)
				{
					item2->setText(1,QVariant(SDL_JoystickGetHat(m_joystick,item2->data(0,Qt::UserRole+1).toInt())).toString());
				}
			}
		}
	}
#endif
}
Exemple #21
0
//===========================================================================
// XJoystickInput
//
// Processes data from the input device.  Uses GetDeviceState().
//
// Returns: 1 if joysticks state was updated, 0 otherwise.
//
//===========================================================================
int XJoystickInput()
{
	std::cout<<"XJoystickInput"<<std::endl;
	if(!JoystickAvailable)
		return 0;

	SDL_JoystickUpdate(); // update all open joysticks

	for (int i = 0; i < SDL_JoystickNumButtons(joy) && i < 32; i++)
	    XJoystickState.rgbButtons[i] = SDL_JoystickGetButton(joy, i);

	for (int i = 0; i < SDL_JoystickNumAxes(joy) && i < 2; i++)
	{
	    if (i == 0)
		XJoystickState.lX = SDL_JoystickGetAxis(joy, i);
	    else if (i == 1)
		XJoystickState.lY = SDL_JoystickGetAxis(joy, i);
	}

	CurrentStickSwitchCode = 0;
	if(JoystickStickSwitchButton && XJoystickState.rgbButtons[JoystickStickSwitchButton - VK_BUTTON_1])
	{
		int dx = XJoystickState.lX;
		if(abs(dx) < RANGE_MAX/16)
			dx = 0;
		int dy = XJoystickState.lY;
		if(abs(dy) < RANGE_MAX/16)
			dy = 0;

		if(dy < 0){
			if(dx < 0)
				CurrentStickSwitchCode = VK_STICK_SWITCH_7;
			else
				if(dx > 0)
					CurrentStickSwitchCode = VK_STICK_SWITCH_9;
				else
					CurrentStickSwitchCode = VK_STICK_SWITCH_8;
			}
		else
			if(dy > 0){
				if(dx < 0)
					CurrentStickSwitchCode = VK_STICK_SWITCH_1;
				else
					if(dx > 0)
						CurrentStickSwitchCode = VK_STICK_SWITCH_3;
					else
						CurrentStickSwitchCode = VK_STICK_SWITCH_2;
				}
			else
				if(dx < 0)
					CurrentStickSwitchCode = VK_STICK_SWITCH_4;
				else
					if(dx > 0)
						CurrentStickSwitchCode = VK_STICK_SWITCH_6;
					else
						CurrentStickSwitchCode = VK_STICK_SWITCH_5;
		}

	return 1;

} //*** end XJoystickInput()
/*
 * Manually pump for controller updates.
 */
void
SDL_GameControllerUpdate(void)
{
    /* Just for API completeness; the joystick API does all the work. */
    SDL_JoystickUpdate();
}
int
menu()
{
	SDL_Event mevent;
	int option=1, i;

	/* pirutupiiii */
	if(efx[7])
		Mix_PlayChannel(-1,efx[7],0);

	drawMenu(option);

	/* some dirty init */
	scroll=scroll2=0;

	while(1) {
		while(SDL_PollEvent(&mevent)) {
			if (mevent.type==SDL_QUIT)
				return 0;

			/* joystick control for the menu */
			if(joy[0])
			{
				SDL_JoystickUpdate();

				i=SDL_JoystickGetAxis(joy[0],1);
				if(i>4200)
				{
					mevent.type=SDL_KEYDOWN;
					mevent.key.keysym.sym=SDLK_DOWN;
				}
				if(i<-4200)
				{
					mevent.type=SDL_KEYDOWN;
					mevent.key.keysym.sym=SDLK_UP;
				}

				if(SDL_JoystickGetButton(joy[0], 0))
				{
					mevent.type=SDL_KEYDOWN;
					mevent.key.keysym.sym=SDLK_RETURN;
				}

				if(SDL_JoystickGetButton(joy[0], 1))
				{
					mevent.type=SDL_KEYDOWN;
					mevent.key.keysym.sym=SDLK_ESCAPE;
				}
			}
			
			if(mevent.type==SDL_KEYDOWN) {
				if(mevent.key.keysym.sym==SDLK_ESCAPE)
					return 0;
				if(mevent.key.keysym.sym==SDLK_DOWN ||
					mevent.key.keysym.sym==SDLK_s) {
					option++;
					if(option>6)
						option=1;
					drawMenu(option);
				}
				if(mevent.key.keysym.sym==SDLK_UP ||
					mevent.key.keysym.sym==SDLK_w) {
					option--;
					if(option<1)
						option=6;
					drawMenu(option);
				}
				if(mevent.key.keysym.sym==SDLK_RETURN) {
					switch(option) {
						default:
						break;
						case 1:
							player[0].shield=10;
							player[1].shield=0;
							player[0].score=player[1].score=0;
							player[0].stage=player[1].stage=0;
							return 1;
						case 2:
							player[0].shield=10;
							player[1].shield=10;
							player[0].score=player[1].score=0;
							player[0].stage=player[1].stage=0;
							return 1;
						case 3:
							if(!hiscores())
								return 0;
							drawMenu(option);
						break;
						case 4:
							if(!configure())
								return 0;
							drawMenu(option);
						break;
						case 5:
							if(!credits())
								return 0;
							drawMenu(option);
						break;
						case 6:
							return 0;
						break;
					}
				}
			}
		}
	}

	return 0;
}
Exemple #24
0
JNIEXPORT jintArray JNICALL Java_at_wisch_joystick_EventPollThread_pollForEvent (JNIEnv *env, jobject){
	
	int returnArray[7] = { -8, -8, 0, 0, 0, 0};
	/* index 0: eventStored
	 * index 1: joystickIndex
	 * index 2: eventType
	 * index 3: componentIndex
	 * index 4: value1
	 * index 5: value2
	 */
	
	SDL_Event event;

	/*
	 * According to the SDL documentation it should not be necessary, but i did not get
	 * any events without calling JoystickUpdate manually here.
	 */
	SDL_JoystickUpdate();

	returnArray[0] = SDL_PeepEvents(&event, 1, SDL_GETEVENT, SDL_JOYEVENTMASK);
	
	if (returnArray[0]){
		if (!event.type) {
			throwException(env, SDL_GetError());
			returnArray[0] = -14;
		} else {
			switch (event.type) {
				case (SDL_JOYBUTTONDOWN): //see SDL_JOYBUTTONUP below
				case (SDL_JOYBUTTONUP) : {
					returnArray[1] = event.jbutton.which;
					returnArray[2] = 1;
					returnArray[3] = event.jbutton.button;
					returnArray[4] = event.jbutton.state;
					returnArray[5] = 0;
					break; }
				case SDL_JOYHATMOTION: {
					returnArray[1] = event.jhat.which;
					returnArray[2] = 5;
					returnArray[3] = event.jhat.hat;
					returnArray[4] = translateHatState(event.jhat.value);
					returnArray[5] = 0;
					break; }
				case SDL_JOYAXISMOTION: {
					returnArray[1] = event.jaxis.which;
					returnArray[2] = 2;
					returnArray[3] = event.jaxis.axis;
					if (INVERTAXISORDER) returnArray[3] = SDL_JoystickNumAxes(joysticks[returnArray[1]])-returnArray[3]-1;
					returnArray[4] = event.jaxis.value;
					returnArray[5] = 0;
					break; }
				case SDL_JOYBALLMOTION: {
					returnArray[1] = event.jball.which;
					returnArray[2] = 6;
					returnArray[3] = event.jball.ball;
					returnArray[4] = event.jball.xrel;
					returnArray[5] = event.jball.yrel;
					break; }
			}
		}
	}
	jintArray returnJArray = (jintArray)env->NewIntArray(6);
	env->SetIntArrayRegion(returnJArray, 0, 6, (jint *)returnArray);
	return (returnJArray);
}
Exemple #25
0
/* 
=============== 
IN_ReadJoystick
=============== 
*/  
int IN_ReadJoystick (void)
{
	SDL_JoystickUpdate();
	return 1;
}
Exemple #26
0
JNIEXPORT void JNICALL Java_at_wisch_joystick_Joystick_poll (JNIEnv *, jobject) {
	SDL_JoystickUpdate();
}
Exemple #27
0
void Joystick::UpdateInput()
{
	// each joystick is doin this, o well
	SDL_JoystickUpdate();
}
Exemple #28
0
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 = SDL_JoystickOpen(i);
        if (joy)
        {
            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 "";
}
Exemple #29
0
/*
===============
IN_JoyMove
===============
*/
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;
		for (i = 0; i < total; i++)
		{
			int dx = 0;
			int 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 (in_joystickUseAnalog->integer)
		{
			if (total > MAX_JOYSTICK_AXIS) total = MAX_JOYSTICK_AXIS;
			for (i = 0; i < total; i++)
			{
				Sint16 axis = SDL_JoystickGetAxis(stick, i);
				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
		{
			if (total > 16) total = 16;
			for (i = 0; i < total; i++)
			{
				Sint16 axis = SDL_JoystickGetAxis(stick, i);
				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;
}
Exemple #30
0
   void CQTOpenGLJoystick::processEvents()
   {
      if ( !isOpen() )
         return;

      SDL_JoystickUpdate();

      int i;
      for (i = 0; i < numAxes; i++) {
         Sint16 moved = SDL_JoystickGetAxis(joystick, i);
         if ( abs(moved) >= deadzones[i] ) {
            if ( (moved != axes[i]) ) {
               int deltaMoved = abs(axes[i] - moved);
               if ( deltaMoved >= sensitivities[i] )
                  emit axisValueChanged(i, moved);
               axes[i] = moved;
               axisRepeatTimers[i].restart();
            } else if (autoRepeat && moved != 0) {
               if ( axisRepeatTimers[i].elapsed() >= autoRepeatDelay ) {
                  emit axisValueChanged(i, moved);
                  axes[i] = moved;
               }
            } else
               axisRepeatTimers[i].restart();
         } else
            emit axisValueChanged(i, 0);
      }
      for (i = 0; i < numButtons; i++) {
         Uint8 changed = SDL_JoystickGetButton(joystick, i);
         if ( (changed != buttons[i]) ) {
            emit buttonValueChanged(i, (bool) changed);
            buttons[i] = changed;
            buttonRepeatTimers[i].restart();
         } else if (autoRepeat && changed != 0) {
            if ( buttonRepeatTimers[i].elapsed() >= autoRepeatDelay ) {
               emit buttonValueChanged(i, (bool) changed);
               buttons[i] = changed;
            }
         } else
            buttonRepeatTimers[i].restart();
      }
      for (i = 0; i < numHats; i++) {
         Uint8 changed = SDL_JoystickGetHat(joystick, i);
         if ( (changed != hats[i]) ) {
            emit hatValueChanged(i, changed);
            hats[i] = changed;
            hatRepeatTimers[i].restart();
         } else if (autoRepeat && changed != 0) {
            if ( hatRepeatTimers[i].elapsed() >= autoRepeatDelay ) {
               emit hatValueChanged(i, changed);
               hats[i] = changed;
            }
         } else
            hatRepeatTimers[i].restart();
      }

      for (i = 0; i < numTrackballs; i++) {
         int dx, dy;
         SDL_JoystickGetBall(joystick, i, &dx, &dy);
         if ( dx != 0 || dy != 0 )
            emit trackballValueChanged(i, dx, dy);
      }
   }