Exemplo n.º 1
0
/*
 * Open controllers and joysticks
 */
void S2D_OpenControllers() {

  char guid_str[33];

  // Enumerate joysticks
  for (int device_index = 0; device_index < SDL_NumJoysticks(); ++device_index) {

    // Check if joystick supports SDL's game controller interface (a mapping is available)
    if (SDL_IsGameController(device_index)) {
      SDL_GameController *controller = SDL_GameControllerOpen(device_index);
      SDL_JoystickID intance_id = SDL_JoystickInstanceID(SDL_GameControllerGetJoystick(controller));

      SDL_JoystickGetGUIDString(
        SDL_JoystickGetGUID(SDL_GameControllerGetJoystick(controller)),
        guid_str, 33
      );

      if (intance_id > last_intance_id) {
        if (controller) {
          S2D_Log(S2D_INFO, "Controller #%i: %s\n      GUID: %s", intance_id, SDL_GameControllerName(controller), guid_str);
        } else {
          S2D_Log(S2D_ERROR, "Could not open controller #%i: %s", intance_id, SDL_GetError());
        }
        last_intance_id = intance_id;
      }

    // Controller interface not supported, try to open as joystick
    } else {
      SDL_Joystick *joy = SDL_JoystickOpen(device_index);
      SDL_JoystickID intance_id = SDL_JoystickInstanceID(joy);

      if (!joy) {
        S2D_Log(S2D_ERROR, "Could not open controller");
      } else if(intance_id > last_intance_id) {
        SDL_JoystickGetGUIDString(
          SDL_JoystickGetGUID(joy),
          guid_str, 33
        );
        S2D_Log(S2D_INFO,
          "Controller #%i: %s\n      GUID: %s\n      Axes: %d\n      Buttons: %d\n      Balls: %d",
          intance_id, SDL_JoystickName(joy), guid_str, SDL_JoystickNumAxes(joy),
          SDL_JoystickNumButtons(joy), SDL_JoystickNumBalls(joy)
        );
        S2D_Log(S2D_WARN, "Controller #%i does not have a mapping available", intance_id);
        last_intance_id = intance_id;
      }
    }
  }
}
Exemplo n.º 2
0
SDL_JoystickID get_joystick_id(SDL_GameController* controller) {
    // Get the joystick underlying the controller
    SDL_Joystick* joystick = SDL_GameControllerGetJoystick(controller);

    // Return the instance ID of the joystick
    return SDL_JoystickInstanceID(joystick);
}
Exemplo n.º 3
0
Joystick::Joystick(SDL_JoystickID instanceId, const QString& name, SDL_GameController* sdlGameController) :
    _sdlGameController(sdlGameController),
    _sdlJoystick(SDL_GameControllerGetJoystick(_sdlGameController)),
    _instanceId(instanceId)
{
    
}
Exemplo n.º 4
0
	void refresh_controllers()
	{
		for (s32 i = 0; i < MAX_GAMEPADS; i++)
		{
			if (haptics[i])
			{
				SDL_HapticClose(haptics[i]);
				haptics[i] = nullptr;
			}

			if (controllers[i])
			{
				SDL_GameControllerClose(controllers[i]);
				controllers[i] = nullptr;
			}
		}

		for (s32 i = 0; i < SDL_NumJoysticks(); i++)
		{
			if (SDL_IsGameController(i))
			{
				controllers[i] = SDL_GameControllerOpen(i);
				SDL_Joystick* joystick = SDL_GameControllerGetJoystick(controllers[i]);
				if (SDL_JoystickIsHaptic(joystick))
				{
					haptics[i] = SDL_HapticOpenFromJoystick(joystick);
					if (SDL_HapticRumbleInit(haptics[i])) // failed
					{
						SDL_HapticClose(haptics[i]);
						haptics[i] = nullptr;
					}
				}
			}
		}
	}
Exemplo n.º 5
0
void InputDaemon::addInputDevice(int index)
{
    SDL_Joystick *joystick = SDL_JoystickOpen(index);
    if (joystick)
    {
        SDL_JoystickID tempJoystickID = SDL_JoystickInstanceID(joystick);

        if (!joysticks->contains(tempJoystickID))
        {
            QSettings *settings = new QSettings(PadderCommon::configFilePath, QSettings::IniFormat);
            settings->beginGroup("Mappings");

            QString temp;
            SDL_JoystickGUID tempGUID = SDL_JoystickGetGUID(joystick);
            char guidString[65] = {'0'};
            SDL_JoystickGetGUIDString(tempGUID, guidString, sizeof(guidString));
            temp = QString(guidString);

            bool disableGameController = settings->value(QString("%1Disable").arg(temp), false).toBool();

            if (SDL_IsGameController(index) && !disableGameController)
            {
                SDL_GameController *controller = SDL_GameControllerOpen(index);
                if (controller)
                {
                    SDL_Joystick *sdlStick = SDL_GameControllerGetJoystick(controller);
                    SDL_JoystickID tempJoystickID = SDL_JoystickInstanceID(sdlStick);
                    if (!joysticks->contains(tempJoystickID))
                    {
                        GameController *damncontroller = new GameController(controller, index, this);
                        joysticks->insert(tempJoystickID, damncontroller);
                        trackcontrollers.insert(tempJoystickID, damncontroller);

                        // Force close of settings file.
                        settings->endGroup();
                        delete settings;
                        settings = 0;

                        emit deviceAdded(damncontroller);
                    }
                }
            }
            else
            {
                Joystick *curJoystick = new Joystick(joystick, index, this);
                joysticks->insert(tempJoystickID, curJoystick);
                trackjoysticks.insert(tempJoystickID, curJoystick);

                // Force close of settings file.
                settings->endGroup();
                delete settings;
                settings = 0;

                emit deviceAdded(curJoystick);
            }
        }
    }
}
Exemplo n.º 6
0
void IN_StartupJoystick (void)
{
	int i;
	int nummappings;
	char controllerdb[MAX_OSPATH];
	SDL_GameController *gamecontroller;
	
	if (COM_CheckParm("-nojoy"))
		return;
	
	if (SDL_InitSubSystem(SDL_INIT_GAMECONTROLLER) == -1 )
	{
		Con_Warning("could not initialize SDL Game Controller\n");
		return;
	}
	
	// Load additional SDL2 controller definitions from gamecontrollerdb.txt
	q_snprintf (controllerdb, sizeof(controllerdb), "%s/gamecontrollerdb.txt", com_basedir);
	nummappings = SDL_GameControllerAddMappingsFromFile(controllerdb);
	if (nummappings > 0)
		Con_Printf("%d mappings loaded from gamecontrollerdb.txt\n", nummappings);
	
	// Also try host_parms->userdir
	if (host_parms->userdir != host_parms->basedir)
	{
		q_snprintf (controllerdb, sizeof(controllerdb), "%s/gamecontrollerdb.txt", host_parms->userdir);
		nummappings = SDL_GameControllerAddMappingsFromFile(controllerdb);
		if (nummappings > 0)
			Con_Printf("%d mappings loaded from gamecontrollerdb.txt\n", nummappings);
	}

	for (i = 0; i < SDL_NumJoysticks(); i++)
	{
		const char *joyname = SDL_JoystickNameForIndex(i);
		if ( SDL_IsGameController(i) )
		{
			const char *controllername = SDL_GameControllerNameForIndex(i);
			gamecontroller = SDL_GameControllerOpen(i);
			if (gamecontroller)
			{
				Con_Printf("detected controller: %s\n", controllername != NULL ? controllername : "NULL");
				
				joy_active_instaceid = SDL_JoystickInstanceID(SDL_GameControllerGetJoystick(gamecontroller));
				joy_active_controller = gamecontroller;
				break;
			}
			else
			{
				Con_Warning("failed to open controller: %s\n", controllername != NULL ? controllername : "NULL");
			}
		}
		else
		{
			Con_Warning("joystick missing controller mappings: %s\n", joyname != NULL ? joyname : "NULL" );
		}
	}
}
Exemplo n.º 7
0
static int
getJoystickAxisState(const config::input::InputDevice *device,
                     SDL_GameController *controller,
                     vpad::Channel channel,
                     vpad::CoreAxis axis)
{
   decaf_check(device);
   decaf_check(controller);

   auto joystick = SDL_GameControllerGetJoystick(controller);
   decaf_check(joystick);

   auto index = -1;
   auto name = SDL_CONTROLLER_AXIS_INVALID;
   auto invert = false;

   switch (axis) {
   case vpad::CoreAxis::LeftStickX:
      index = device->joystick.left_stick_x;
      name = SDL_CONTROLLER_AXIS_LEFTX;
      invert = device->joystick.left_stick_x_invert;
      break;
   case vpad::CoreAxis::LeftStickY:
      index = device->joystick.left_stick_y;
      name = SDL_CONTROLLER_AXIS_LEFTY;
      invert = device->joystick.left_stick_y_invert;
      break;
   case vpad::CoreAxis::RightStickX:
      index = device->joystick.right_stick_x;
      name = SDL_CONTROLLER_AXIS_RIGHTX;
      invert = device->joystick.right_stick_x_invert;
      break;
   case vpad::CoreAxis::RightStickY:
      index = device->joystick.right_stick_y;
      name = SDL_CONTROLLER_AXIS_RIGHTY;
      invert = device->joystick.right_stick_y_invert;
      break;
   }

   auto value = 0;

   if (index >= 0) {
      value = SDL_JoystickGetAxis(joystick, index);
   } else if (index == -2) {
      if (name != SDL_CONTROLLER_AXIS_INVALID) {
         value = SDL_GameControllerGetAxis(controller, name);
      }
   }

   if (invert) {
      value = -value;
   }

   return value;
}
Exemplo n.º 8
0
	int GameController::getJoystick(State & state, SDL_GameController * gamecontroller){
		Stack * stack = state.stack;
		Joystick * interfaceJoystick = state.getInterface<Joystick>("LuaSDL_Joystick");
		SDL_Joystick * joystick = SDL_GameControllerGetJoystick(gamecontroller);
		if (joystick){
			interfaceJoystick->push(joystick);
			return 1;
		}
		else{
			return 0;
		}
	}
Exemplo n.º 9
0
GameController::GameController(SDL_GameController *controller, int deviceIndex, QObject *parent) :
    InputDevice(deviceIndex, parent)
{
    this->controller = controller;
    SDL_Joystick *joyhandle = SDL_GameControllerGetJoystick(controller);
    joystickID = SDL_JoystickInstanceID(joyhandle);

    for (int i=0; i < NUMBER_JOYSETS; i++)
    {
        GameControllerSet *controllerset = new GameControllerSet(this, i, this);
        joystick_sets.insert(i, controllerset);
        enableSetConnections(controllerset);
    }
}
Exemplo n.º 10
0
void InputDaemon::refreshMapping(QString mapping, InputDevice *device)
{
    bool found = false;

    for (int i=0; i < SDL_NumJoysticks() && !found; i++)
    {
        SDL_Joystick *joystick = SDL_JoystickOpen(i);
        SDL_JoystickID joystickID = SDL_JoystickInstanceID(joystick);

        if (device->getSDLJoystickID() == joystickID)
        {
            found = true;

            if (SDL_IsGameController(i))
            {
                // Mapping string updated. Perform basic refresh
                QByteArray tempbarray = mapping.toUtf8();
                SDL_GameControllerAddMapping(tempbarray.data());
            }
            else
            {
                // Previously registered as a plain joystick. Add
                // mapping and check for validity. If SDL accepts it,
                // close current device and re-open as
                // a game controller.
                SDL_GameControllerAddMapping(mapping.toUtf8().constData());

                if (SDL_IsGameController(i))
                {
                    device->closeSDLDevice();
                    trackjoysticks.remove(joystickID);
                    joysticks->remove(joystickID);

                    SDL_GameController *controller = SDL_GameControllerOpen(i);
                    GameController *damncontroller = new GameController(controller, i, settings, this);
                    connect(damncontroller, SIGNAL(requestWait()), eventWorker, SLOT(haltServices()));
                    SDL_Joystick *sdlStick = SDL_GameControllerGetJoystick(controller);
                    joystickID = SDL_JoystickInstanceID(sdlStick);
                    joysticks->insert(joystickID, damncontroller);
                    trackcontrollers.insert(joystickID, damncontroller);
                    emit deviceUpdated(i, damncontroller);
                }
            }
        }

        // Make sure to decrement reference count
        SDL_JoystickClose(joystick);
    }
}
Exemplo n.º 11
0
	const char* Gamepad::GetDeviceGUID (int id) {

		SDL_Joystick* joystick = SDL_GameControllerGetJoystick (gameControllers[id]);

		if (joystick) {

			char* guid = new char[64];
			SDL_JoystickGetGUIDString (SDL_JoystickGetGUID (joystick), guid, 64);
			return guid;

		}

		return 0;

	}
Exemplo n.º 12
0
QString GameController::getGUIDString()
{
    QString temp;
    if (controller)
    {
        SDL_Joystick *joyhandle = SDL_GameControllerGetJoystick(controller);
        if (joyhandle)
        {
            SDL_JoystickGUID tempGUID = SDL_JoystickGetGUID(joyhandle);
            char guidString[65] = {'0'};
            SDL_JoystickGetGUIDString(tempGUID, guidString, sizeof(guidString));
            temp = QString(guidString);
        }
    }

    return temp;
}
void
GameControllerManager::on_controller_removed(int instance_id)
{
  for(auto& controller : m_game_controllers)
  {
    auto joy = SDL_GameControllerGetJoystick(controller);
    SDL_JoystickID id = SDL_JoystickInstanceID(joy);
    if (id == instance_id)
    {
      SDL_GameControllerClose(controller);
      controller = nullptr;
    }
  }

  m_game_controllers.erase(std::remove(m_game_controllers.begin(), m_game_controllers.end(), nullptr),
                           m_game_controllers.end());
}
Exemplo n.º 14
0
C4GamePadOpener::C4GamePadOpener(int iGamepad)
{
	int n = iGamepad;
	for (int i = 0; i < SDL_NumJoysticks(); i++)
		if (SDL_IsGameController(i) && n-- == 0)
		{
			controller = SDL_GameControllerOpen(i);
			if (!controller) LogF("SDL: %s", SDL_GetError());
			SDL_Joystick *joystick = SDL_GameControllerGetJoystick(controller);
			haptic = SDL_HapticOpenFromJoystick(joystick);
			if (haptic && SDL_HapticRumbleSupported(haptic))
				SDL_HapticRumbleInit(haptic);
			else
				LogF("Gamepad #%d %s does not support rumbling.", SDL_JoystickInstanceID(joystick), SDL_JoystickName(joystick));
			break;
		}

	if (!controller) LogF("Gamepad %d not available", iGamepad);
}
Exemplo n.º 15
0
//===========================================================================
// XJoystickInit
//
// Creates and initializes joysticks.
//
// Parameters:
//
// Returns:
//
//===========================================================================
bool XJoystickInit() {
	int i;
	
	SDL_InitSubSystem(SDL_INIT_JOYSTICK);
	SDL_InitSubSystem(SDL_INIT_GAMECONTROLLER);
	SDL_JoystickEventState(SDL_ENABLE);
	SDL_GameControllerEventState(SDL_ENABLE);
	
	if(!SDL_WasInit(SDL_INIT_JOYSTICK) && SDL_InitSubSystem(SDL_INIT_JOYSTICK)) {
		std::cout<<"Unable to initialize the joystick subsystem"<<std::endl;
		return false;
	}
	
	for(i = 0; i < SDL_NumJoysticks(); ++i) {
		if (SDL_IsGameController(i)) {
			printf("Index \'%i\' is a compatible controller, named \'%s\'\n", i, SDL_GameControllerNameForIndex(i));
			ctrl = SDL_GameControllerOpen(i);
			joy = SDL_GameControllerGetJoystick(ctrl);
			break;
		} else {
			printf("Index \'%s\' is not a compatible controller.\n", SDL_JoystickNameForIndex(i));
		}
	}
	if (ctrl) {
		JoystickAvailable = 1;
		return true;
	}
	for(i = 0; i < SDL_NumJoysticks(); ++i) {
		joy = SDL_JoystickOpen(i);
		if (joy) {
			printf("Index \'%i\' is a compatible joystick, named \'%s\'\n", i, SDL_JoystickNameForIndex(i));
			break;
		}
	}
	if (joy) {
		JoystickAvailable = 1;
		return true;
	} else {
		return false;
	}
}
Exemplo n.º 16
0
int _create_controler(int i) {
    SDL_GameController *controller = SDL_GameControllerOpen(i);
    SDL_Joystick *joy = SDL_GameControllerGetJoystick(controller);

    int idx = _new_controler();

    _G.controller[idx] = controller;

    memory_set(_G.state[idx], 0, sizeof(int) * GAMEPAD_BTN_MAX);

    if (SDL_JoystickIsHaptic(joy) == 1) {
        SDL_Haptic *haptic = SDL_HapticOpenFromJoystick(joy);
        SDL_HapticRumbleInit(haptic);
        _G.haptic[idx] = haptic;

        log_info("input.gamepad", "Gamepad %d has haptic support", i);
    } else {
        _G.haptic[idx] = NULL;
    }

    return idx;
}
Exemplo n.º 17
0
	bool SDLGamepad::Connect (int deviceID) {

		if (SDL_IsGameController (deviceID)) {

			SDL_GameController *gameController = SDL_GameControllerOpen (deviceID);

			if (gameController) {

				SDL_Joystick *joystick = SDL_GameControllerGetJoystick (gameController);
				int id = SDL_JoystickInstanceID (joystick);

				gameControllers[id] = gameController;
				gameControllerIDs[deviceID] = id;

				return true;

			}

		}

		return false;

	}
Exemplo n.º 18
0
internal void sdl_init_joysticks(struct sdl_event_context *ctx)
{
	unsigned int player;
	int num_joy_sticks, jsi;
	SDL_GameController *controller;
	SDL_Joystick *joystick;
	SDL_Haptic *rumble;

	for (player = 0; player < MAX_CONTROLLERS; ++player) {
		ctx->players[player].controller = NULL;
		ctx->players[player].rumble = NULL;
	}

	num_joy_sticks = SDL_NumJoysticks();
	debug(0, "SDL_NumJoysticks() == %d\n", num_joy_sticks);
	player = 0;
	for (jsi = 0; jsi < num_joy_sticks && player < MAX_CONTROLLERS; ++jsi) {
		if (!SDL_IsGameController(jsi)) {
			debug(0, "SDL_IsGameController(%d) == 0\n", jsi);
			continue;
		}
		controller = SDL_GameControllerOpen(jsi);
		ctx->players[player].controller = controller;
		debug(0, "ctx->players[%u].controller = %p\n", player,
		      (void *)controller);

		joystick = SDL_GameControllerGetJoystick(controller);
		rumble = SDL_HapticOpenFromJoystick(joystick);
		if (SDL_HapticRumbleInit(rumble)) {
			ctx->players[player].rumble = rumble;
		} else {
			SDL_HapticClose(rumble);
		}

		++player;
	}
}
Exemplo n.º 19
0
SDL_JoystickID SDLController::InstanceID()
{
    SDL_Joystick* joy = SDL_GameControllerGetJoystick(m_Ctrl);
    return SDL_JoystickInstanceID(joy);
}
Exemplo n.º 20
0
void PIN_GameControllerManager::AddGameController(int joy_index)
{
    printf("Checking joystick #%d...\n",joy_index);
    printf("Name: %s\n",SDL_JoystickNameForIndex(joy_index));

    if(SDL_IsGameController(joy_index))
    {
        printf("This joystick is a gamecontroller. Adding to controller pool...\n");
        printf("Game controller name: %s\n",SDL_GameControllerNameForIndex(joy_index));

        PIN_GameControllerEntry* newEntry = CreateGameControllerEntry();

        SDL_GameController* ctrl =  SDL_GameControllerOpen(joy_index);
        SDL_Joystick* joy = SDL_GameControllerGetJoystick(ctrl);

        SDL_JoystickGUID joyGUID = SDL_JoystickGetGUID(joy);
        char strGUID[PIN_BUFFER_SIZE];
        SDL_JoystickGetGUIDString(joyGUID,strGUID, PIN_BUFFER_SIZE);

        printf("Controller GUID: %s\n",strGUID);
        SDL_JoystickID joyID  = SDL_JoystickInstanceID(joy);
        if(joyID < 0)
        {
            printf("Error: %s\n",SDL_GetError());
            delete newEntry;
            return;
        }
        else
        {
            newEntry->ControllerID = joyID + PIN_ID_JOYSTICK;
        }

        newEntry->Controller = ctrl;
        newEntry->Joystick = joy;

        newEntry->AxisDeadZone = 8000;

        newEntry->GlobalKeys[PIN_GK_UP]     = BuildComboSet(newEntry,SDL_GameControllerGetStringForButton(SDL_CONTROLLER_BUTTON_DPAD_UP));
        newEntry->GlobalKeys[PIN_GK_DOWN]   = BuildComboSet(newEntry,SDL_GameControllerGetStringForButton(SDL_CONTROLLER_BUTTON_DPAD_DOWN));
        newEntry->GlobalKeys[PIN_GK_LEFT]   = BuildComboSet(newEntry,SDL_GameControllerGetStringForButton(SDL_CONTROLLER_BUTTON_DPAD_LEFT));
        newEntry->GlobalKeys[PIN_GK_RIGHT]  = BuildComboSet(newEntry,SDL_GameControllerGetStringForButton(SDL_CONTROLLER_BUTTON_DPAD_RIGHT));
        newEntry->GlobalKeys[PIN_GK_ENTER]  = BuildComboSet(newEntry,SDL_GameControllerGetStringForButton(SDL_CONTROLLER_BUTTON_A));
        newEntry->GlobalKeys[PIN_GK_BACK]   = BuildComboSet(newEntry,SDL_GameControllerGetStringForButton(SDL_CONTROLLER_BUTTON_B));

        PIN_KeyList lstDef = _controlType->DEFAULT_KEYS;

        printf("Setting control type definitions...\n");

        AssignKey(newEntry, &(newEntry->GlobalKeys),PIN_GK_UP,lstDef,PIN_KEY_UP);
        AssignKey(newEntry, &(newEntry->GlobalKeys),PIN_GK_DOWN,lstDef,PIN_KEY_DOWN);
        AssignKey(newEntry, &(newEntry->GlobalKeys),PIN_GK_LEFT,lstDef,PIN_KEY_LEFT);
        AssignKey(newEntry, &(newEntry->GlobalKeys),PIN_GK_RIGHT,lstDef,PIN_KEY_RIGHT);
        AssignKey(newEntry, &(newEntry->GlobalKeys),PIN_GK_ENTER,lstDef,PIN_KEY_ENTER);
        AssignKey(newEntry, &(newEntry->GlobalKeys),PIN_GK_BACK,lstDef,PIN_KEY_BACK);

        for(PIN_MappingList::iterator it = _mappingList->begin(); it!= _mappingList->end(); ++it)
        {
            PIN_Mapping* m = *it;
            if(boost::equals(m->GUID,strGUID))
            {
                printf("Setting mapping-specific definitions...\n");
                printf("Mapping name: '%s'\n",m->NAME);

                PIN_KeyList m_keys = m->DEFAULT_KEYS;

                newEntry->SourceMapping = m;

                newEntry->AxisDeadZone = m->DEADZONE;

                AssignKey(newEntry, &(newEntry->GlobalKeys),PIN_GK_UP,m_keys,PIN_KEY_UP);
                AssignKey(newEntry, &(newEntry->GlobalKeys),PIN_GK_DOWN,m_keys,PIN_KEY_DOWN);
                AssignKey(newEntry, &(newEntry->GlobalKeys),PIN_GK_LEFT,m_keys,PIN_KEY_LEFT);
                AssignKey(newEntry, &(newEntry->GlobalKeys),PIN_GK_RIGHT,m_keys,PIN_KEY_RIGHT);
                AssignKey(newEntry, &(newEntry->GlobalKeys),PIN_GK_ENTER,m_keys,PIN_KEY_ENTER);
                AssignKey(newEntry, &(newEntry->GlobalKeys),PIN_GK_BACK,m_keys,PIN_KEY_BACK);

                break;
            }
        }

        if(_currentGameMode != NULL)
        {
            UpdateControllerGameMode(newEntry);
        }

        //_controllerList.push_back(newEntry);
        AddController(newEntry);
    }
    else
    {
        printf("This joystick is NOT a gamecontroller. It can't be used.\n");
    }
}
Exemplo n.º 21
0
int main(int argc, char *argv[]) {
  int opt;
  struct sockaddr_can addr;
  struct canfd_frame frame;
  int running = 1;
  int enable_canfd = 1;
  int play_traffic = 1;
  struct stat st;
  SDL_Event event;

  while ((opt = getopt(argc, argv, "Xdl:s:t:h?")) != -1) {
    switch(opt) {
	case 'l':
		difficulty = atoi(optarg);
		break;
	case 's':
		seed = atoi(optarg);
		break;
	case 't':
		traffic_log = optarg;
		break;
	case 'd':
		debug = 1;
		break;
	case 'X':
		play_traffic = 0;
		break;
	case 'h':
	case '?':
	default:
		usage(NULL);
		break;
    }
  }

  if (optind >= argc) usage("You must specify at least one can device");

  if(stat(traffic_log, &st) == -1) {
	char msg[256];
	snprintf(msg, 255, "CAN Traffic file not found: %s\n", traffic_log);
	usage(msg);
  }

  /* open socket */
  if ((s = socket(PF_CAN, SOCK_RAW, CAN_RAW)) < 0) {
       perror("socket");
       return 1;
  }

  addr.can_family = AF_CAN;

  strcpy(ifr.ifr_name, argv[optind]);
  if (ioctl(s, SIOCGIFINDEX, &ifr) < 0) {
       perror("SIOCGIFINDEX");
       return 1;
  }
  addr.can_ifindex = ifr.ifr_ifindex;

  if (setsockopt(s, SOL_CAN_RAW, CAN_RAW_FD_FRAMES,
                 &enable_canfd, sizeof(enable_canfd))){
       printf("error when enabling CAN FD support\n");
       return 1;
  }

  if (bind(s, (struct sockaddr *)&addr, sizeof(addr)) < 0) {
       perror("bind");
       return 1;
  }

  door_id = DEFAULT_DOOR_ID;
  signal_id = DEFAULT_SIGNAL_ID;
  speed_id = DEFAULT_SPEED_ID;

  if (seed) {
	srand(seed);
        door_id = (rand() % 2046) + 1;
        signal_id = (rand() % 2046) + 1;
        speed_id = (rand() % 2046) + 1;
        door_pos = rand() % 9;
        signal_pos = rand() % 9;
        speed_pos = rand() % 8;
        printf("Seed: %d\n", seed);
	door_len = door_pos + 1;
	signal_len = signal_pos + 1;
	speed_len = speed_len + 2;
  }

  if(difficulty > 0) {
	if (door_len < 8) {
		door_len += rand() % (8 - door_len);
	} else {
		door_len = 0;
	}
	if (signal_len < 8) {
		signal_len += rand() % (8 - signal_len);
	} else {
		signal_len = 0;
	}
	if (speed_len < 8) {
		speed_len += rand() % (8 - speed_len);
	} else {
		speed_len = 0;
	}
  }

  if(play_traffic) {
	signal(SIGALRM,(void (*)(int))kill_child);
	play_id = fork();
	if((int)play_id == -1) {
		printf("Error: Couldn't fork bg player\n");
		exit(-1);
	} else if (play_id != 0) {
		play_can_traffic();
	}
  }

  // GUI Setup
  SDL_Window *window = NULL;
  SDL_Surface *screenSurface = NULL;
  if(SDL_Init ( SDL_INIT_VIDEO | SDL_INIT_JOYSTICK ) < 0 ) {
        printf("SDL Could not initializes\n");
        exit(40);
  }
  if( SDL_NumJoysticks() < 1) {
	printf(" Warning: No joysticks connected\n");
  } else {
	if(SDL_IsGameController(0)) {
	  gGameController = SDL_GameControllerOpen(0);
	  if(gGameController == NULL) {
		printf(" Warning: Unable to open game controller. %s\n", SDL_GetError() );
	  } else {
		gJoystick = SDL_GameControllerGetJoystick(gGameController);
		gHaptic = SDL_HapticOpenFromJoystick(gJoystick);
		print_joy_info();
	  }
        } else {
		gJoystick = SDL_JoystickOpen(0);
		if(gJoystick == NULL) {
			printf(" Warning: Could not open joystick\n");
		} else {
			gHaptic = SDL_HapticOpenFromJoystick(gJoystick);
			if (gHaptic == NULL) printf("No Haptic support\n");
			print_joy_info();
		}
	}
  }
  window = SDL_CreateWindow("CANBus Control Panel", SDL_WINDOWPOS_UNDEFINED, SDL_WINDOWPOS_UNDEFINED, SCREEN_WIDTH, SCREEN_HEIGHT, SDL_WINDOW_SHOWN | SDL_WINDOW_RESIZABLE);
  if(window == NULL) {
        printf("Window could not be shown\n");
  }
  renderer = SDL_CreateRenderer(window, -1, 0);
  SDL_Surface *image = IMG_Load(get_data("joypad.png"));
  base_texture = SDL_CreateTextureFromSurface(renderer, image);
  SDL_RenderCopy(renderer, base_texture, NULL, NULL);
  SDL_RenderPresent(renderer);
  int button, axis; // Used for checking dynamic joystick mappings

  while(running) {
    while( SDL_PollEvent(&event) != 0 ) {
        switch(event.type) {
            case SDL_QUIT:
                running = 0;
                break;
	    case SDL_WINDOWEVENT:
		switch(event.window.event) {
		case SDL_WINDOWEVENT_ENTER:
		case SDL_WINDOWEVENT_RESIZED:
			redraw_screen();
			break;
		}
	    case SDL_KEYDOWN:
		switch(event.key.keysym.sym) {
		    case SDLK_UP:
			throttle = 1;
			break;
		    case SDLK_LEFT:
			turning = -1;
			break;
		    case SDLK_RIGHT:
			turning = 1;
			break;
		    case SDLK_LSHIFT:
			lock_enabled = 1;
			if(unlock_enabled) send_lock(CAN_DOOR1_LOCK | CAN_DOOR2_LOCK | CAN_DOOR3_LOCK | CAN_DOOR4_LOCK);
			break;
		    case SDLK_RSHIFT:
			unlock_enabled = 1;
			if(lock_enabled) send_unlock(CAN_DOOR1_LOCK | CAN_DOOR2_LOCK | CAN_DOOR3_LOCK | CAN_DOOR4_LOCK);
			break;
		    case SDLK_a:
			if(lock_enabled) {
				send_lock(CAN_DOOR1_LOCK);
			} else if(unlock_enabled) {
				send_unlock(CAN_DOOR1_LOCK);
			}
			break;
		    case SDLK_b:
			if(lock_enabled) {
				send_lock(CAN_DOOR2_LOCK);
			} else if(unlock_enabled) {
				send_unlock(CAN_DOOR2_LOCK);
			}
			break;
		    case SDLK_x:
			if(lock_enabled) {
				send_lock(CAN_DOOR3_LOCK);
			} else if(unlock_enabled) {
				send_unlock(CAN_DOOR3_LOCK);
			}
			break;
		    case SDLK_y:
			if(lock_enabled) {
				send_lock(CAN_DOOR4_LOCK);
			} else if(unlock_enabled) {
				send_unlock(CAN_DOOR4_LOCK);
			}
			break;
		}
		kk_check(event.key.keysym.sym);
	   	break;
	    case SDL_KEYUP:
		switch(event.key.keysym.sym) {
		    case SDLK_UP:
			throttle = -1;
			break;
		    case SDLK_LEFT:
		    case SDLK_RIGHT:
			turning = 0;
			break;
		    case SDLK_LSHIFT:
			lock_enabled = 0;
			break;
		    case SDLK_RSHIFT:
			unlock_enabled = 0;
			break;
		}
		break;
	    case SDL_JOYAXISMOTION:
		axis = event.jaxis.axis;
		if(axis == gAxisLeftH) {
			ud(event.jaxis.value);
		} else if(axis == gAxisLeftV) {
			turn(event.jaxis.value);
		} else if(axis == gAxisR2) {
			accelerate(event.jaxis.value);
		} else if(axis == gAxisRightH ||
			  axis == gAxisRightV ||
			  axis == gAxisL2 ||
			  axis == gJoyX ||
			  axis == gJoyY ||
			  axis == gJoyZ) {
			// Do nothing, the axis is known just not connected
		} else {
			if (debug) printf("Unkown axis: %d\n", event.jaxis.axis);
		}
		break;
	    case SDL_JOYBUTTONDOWN:
                button = event.jbutton.button;
		if(button == gButtonLock) {
			lock_enabled = 1;
			if(unlock_enabled) send_lock(CAN_DOOR1_LOCK | CAN_DOOR2_LOCK | CAN_DOOR3_LOCK | CAN_DOOR4_LOCK);
		} else if(button == gButtonUnlock) {
			unlock_enabled = 1;
			if(lock_enabled) send_unlock(CAN_DOOR1_LOCK | CAN_DOOR2_LOCK | CAN_DOOR3_LOCK | CAN_DOOR4_LOCK);
		} else if(button == gButtonA) {
			if(lock_enabled) {
				send_lock(CAN_DOOR1_LOCK);
			} else if(unlock_enabled) {
				send_unlock(CAN_DOOR1_LOCK);
			}
			kk_check(SDLK_a);
		} else if (button == gButtonB) {
			if(lock_enabled) {
				send_lock(CAN_DOOR2_LOCK);
			} else if(unlock_enabled) {
				send_unlock(CAN_DOOR2_LOCK);
			}
			kk_check(SDLK_b);
		} else if (button == gButtonX) {
			if(lock_enabled) {
				send_lock(CAN_DOOR3_LOCK);
			} else if(unlock_enabled) {
				send_unlock(CAN_DOOR3_LOCK);
			}
			kk_check(SDLK_x);
		} else if (button == gButtonY) {
			if(lock_enabled) {
				send_lock(CAN_DOOR4_LOCK);
			} else if(unlock_enabled) {
				send_unlock(CAN_DOOR4_LOCK);
			}
			kk_check(SDLK_y);
		} else if (button == gButtonStart) {
			kk_check(SDLK_RETURN);
		} else {
			if(debug) printf("Unassigned button: %d\n", event.jbutton.button);
		}
		break;
	    case SDL_JOYBUTTONUP:
		button = event.jbutton.button;
		if(button == gButtonLock) {
			lock_enabled = 0;
		} else if(button == gButtonUnlock) {
			unlock_enabled = 0;
		} else {
			//if(debug) printf("Unassigned button: %d\n", event.jbutton.button);
		}
		break;
	    case SDL_JOYDEVICEADDED:
		// Only use the first controller
		if(event.cdevice.which == 0) {
			gJoystick = SDL_JoystickOpen(0);
			if(gJoystick) {
				gHaptic = SDL_HapticOpenFromJoystick(gJoystick);
				print_joy_info();
			}
		}
		break;
	    case SDL_JOYDEVICEREMOVED:
		if(event.cdevice.which == 0) {
			SDL_JoystickClose(gJoystick);
			gJoystick = NULL;
		}
		break;
	    case SDL_CONTROLLERDEVICEADDED:
		// Only use the first controller
		if(gGameController == NULL) {
			gGameController = SDL_GameControllerOpen(0);
			gJoystick = SDL_GameControllerGetJoystick(gGameController);
			gHaptic = SDL_HapticOpenFromJoystick(gJoystick);
			print_joy_info();
		}
		break;
	    case SDL_CONTROLLERDEVICEREMOVED:
		if(event.cdevice.which == 0) {
			SDL_GameControllerClose(gGameController);
			gGameController = NULL;
		}
		break;
        }
    }
    currentTime = SDL_GetTicks();
    checkAccel();
    checkTurn();
    SDL_Delay(5);
  }

  kill_child(SIGKILL);
  close(s);
  SDL_DestroyTexture(base_texture);
  SDL_FreeSurface(image);
  SDL_GameControllerClose(gGameController);
  SDL_DestroyRenderer(renderer);
  SDL_DestroyWindow(window);
  SDL_Quit();

}
Exemplo n.º 22
0
static void sdl_pad_connect(unsigned id)
{
   sdl_joypad_t *pad          = (sdl_joypad_t*)&sdl_pads[id];
   bool success               = false;
   int32_t product            = 0;
   int32_t vendor             = 0;

#ifdef HAVE_SDL2
   SDL_JoystickGUID guid;
   uint16_t *guid_ptr;

   if (SDL_IsGameController(id))
   {
      pad->controller = SDL_GameControllerOpen(id);
      pad->joypad     = SDL_GameControllerGetJoystick(pad->controller);

      success = pad->joypad != NULL && pad->controller != NULL;
   }
   else
#endif
   {
      pad->joypad = SDL_JoystickOpen(id);
      success = pad->joypad != NULL;
   }

   if (!success)
   {
      RARCH_ERR("[SDL]: Couldn't open joystick #%u: %s.\n", id, SDL_GetError());

      if (pad->joypad)
         SDL_JoystickClose(pad->joypad);

      pad->joypad = NULL;

      return;
   }

#ifdef HAVE_SDL2
   guid       = SDL_JoystickGetGUID(pad->joypad);
   guid_ptr   = (uint16_t*)guid.data;
#ifdef __linux
   vendor     = guid_ptr[2];
   product    = guid_ptr[4];
#elif _WIN32
   vendor     = guid_ptr[0];
   product    = guid_ptr[1];
#endif
#endif

   if (!input_autoconfigure_connect(
         sdl_joypad_name(id),
         NULL,
         sdl_joypad.ident,
         id,
         vendor,
         product))
      input_config_set_device_name(id, sdl_joypad_name(id));

   RARCH_LOG("[SDL]: Device #%u (%04x:%04x) connected: %s.\n", id, vendor,
             product, sdl_joypad_name(id));

#ifdef HAVE_SDL2
   if (pad->controller)
   {
      /* SDL_GameController internally supports all axis/button IDs, even if
       * the controller's mapping does not have a binding for it.
       *
       * So, we can claim to support all axes/buttons, and when we try to poll
       * an unbound ID, SDL simply returns the correct unpressed value.
       *
       * Note that, in addition to 0 trackballs, we also have 0 hats. This is
       * because the d-pad is in the button list, as the last 4 enum entries.
       *
       * -flibit
       */
      pad->num_axes    = SDL_CONTROLLER_AXIS_MAX;
      pad->num_buttons = SDL_CONTROLLER_BUTTON_MAX;
      pad->num_hats    = 0;
      pad->num_balls   = 0;

      RARCH_LOG("[SDL]: Device #%u supports game controller api.\n", id);
   }
   else
   {
      pad->num_axes    = SDL_JoystickNumAxes(pad->joypad);
      pad->num_buttons = SDL_JoystickNumButtons(pad->joypad);
      pad->num_hats    = SDL_JoystickNumHats(pad->joypad);
      pad->num_balls   = SDL_JoystickNumBalls(pad->joypad);

      RARCH_LOG("[SDL]: Device #%u has: %u axes, %u buttons, %u hats and %u trackballs.\n",
                id, pad->num_axes, pad->num_buttons, pad->num_hats, pad->num_balls);
   }

   pad->haptic = g_has_haptic ? SDL_HapticOpenFromJoystick(pad->joypad) : NULL;

   if (g_has_haptic && !pad->haptic)
      RARCH_WARN("[SDL]: Couldn't open haptic device of the joypad #%u: %s\n",
                 id, SDL_GetError());

   pad->rumble_effect = -1;

   if (pad->haptic)
   {
      SDL_HapticEffect efx;
      efx.type = SDL_HAPTIC_LEFTRIGHT;
      efx.leftright.type = SDL_HAPTIC_LEFTRIGHT;
      efx.leftright.large_magnitude = efx.leftright.small_magnitude = 0x4000;
      efx.leftright.length = 5000;

      if (SDL_HapticEffectSupported(pad->haptic, &efx) == SDL_FALSE)
      {
         pad->rumble_effect = -2;
         RARCH_WARN("[SDL]: Device #%u does not support rumble.\n", id);
      }
   }
#else
   pad->num_axes    = SDL_JoystickNumAxes(pad->joypad);
   pad->num_buttons = SDL_JoystickNumButtons(pad->joypad);
   pad->num_hats    = SDL_JoystickNumHats(pad->joypad);

   RARCH_LOG("[SDL]: Device #%u has: %u axes, %u buttons, %u hats.\n",
             id, pad->num_axes, pad->num_buttons, pad->num_hats);
#endif
}
Exemplo n.º 23
0
void Engine_InitSDLControls()
{
    int    NumJoysticks;
    Uint32 init_flags    = SDL_INIT_VIDEO | SDL_INIT_EVENTS;                    // These flags are used in any case.

    if(control_mapper.use_joy == 1)
    {
        init_flags |= SDL_INIT_GAMECONTROLLER;                                  // Update init flags for joystick.

        if(control_mapper.joy_rumble)
        {
            init_flags |= SDL_INIT_HAPTIC;                                      // Update init flags for force feedback.
        }

        SDL_Init(init_flags);

        NumJoysticks = SDL_NumJoysticks();
        if((NumJoysticks < 1) || ((NumJoysticks - 1) < control_mapper.joy_number))
        {
            Sys_DebugLog(LOG_FILENAME, "Error: there is no joystick #%d present.", control_mapper.joy_number);
            return;
        }

        if(SDL_IsGameController(control_mapper.joy_number))                     // If joystick has mapping (e.g. X360 controller)
        {
            SDL_GameControllerEventState(SDL_ENABLE);                           // Use GameController API
            sdl_controller = SDL_GameControllerOpen(control_mapper.joy_number);

            if(!sdl_controller)
            {
                Sys_DebugLog(LOG_FILENAME, "Error: can't open game controller #%d.", control_mapper.joy_number);
                SDL_GameControllerEventState(SDL_DISABLE);                      // If controller init failed, close state.
                control_mapper.use_joy = 0;
            }
            else if(control_mapper.joy_rumble)                                  // Create force feedback interface.
            {
                sdl_haptic = SDL_HapticOpenFromJoystick(SDL_GameControllerGetJoystick(sdl_controller));
                if(!sdl_haptic)
                {
                    Sys_DebugLog(LOG_FILENAME, "Error: can't initialize haptic from game controller #%d.", control_mapper.joy_number);
                }
            }
        }
        else
        {
            SDL_JoystickEventState(SDL_ENABLE);                                 // If joystick isn't mapped, use generic API.
            sdl_joystick = SDL_JoystickOpen(control_mapper.joy_number);

            if(!sdl_joystick)
            {
                Sys_DebugLog(LOG_FILENAME, "Error: can't open joystick #%d.", control_mapper.joy_number);
                SDL_JoystickEventState(SDL_DISABLE);                            // If joystick init failed, close state.
                control_mapper.use_joy = 0;
            }
            else if(control_mapper.joy_rumble)                                  // Create force feedback interface.
            {
                sdl_haptic = SDL_HapticOpenFromJoystick(sdl_joystick);
                if(!sdl_haptic)
                {
                    Sys_DebugLog(LOG_FILENAME, "Error: can't initialize haptic from joystick #%d.", control_mapper.joy_number);
                }
            }
        }

        if(sdl_haptic)                                                          // To check if force feedback is working or not.
        {
            SDL_HapticRumbleInit(sdl_haptic);
            SDL_HapticRumblePlay(sdl_haptic, 1.0, 300);
        }
    }
    else
    {
        SDL_Init(init_flags);
    }
}
Exemplo n.º 24
0
SDL_JoystickID SDL2Manager::getInstanceId(SDL_GameController* controller) {
    SDL_Joystick* joystick = SDL_GameControllerGetJoystick(controller);
    return SDL_JoystickInstanceID(joystick);
}
Exemplo n.º 25
0
SdlManager::SdlController::SdlController(SDL_GameController* controller)
: SdlController(controller, SDL_GameControllerGetJoystick(controller))
{}
Exemplo n.º 26
0
bool DEV_Joystick::CreateJoystickDevice(void)
{
	bool joy_error = false;

#ifndef WITH_SDL
	m_isinit = true;
	joy_error = true;
#else /* WITH_SDL */
	if (!m_isinit) {

		if (!(SDL_CHECK(SDL_IsGameController) &&
			SDL_CHECK(SDL_GameControllerOpen) &&
			SDL_CHECK(SDL_GameControllerEventState) &&
			SDL_CHECK(SDL_GameControllerGetJoystick) &&
			SDL_CHECK(SDL_JoystickInstanceID)))
		{
			joy_error = true;
		}

		if (!joy_error && !SDL_IsGameController(m_joyindex)) {
			/* mapping instruccions if joystick is not a game controller */
			CM_Error("Game Controller index " << m_joyindex << ": Could not be initialized\n"
			<< "Please, generate Xbox360 compatible mapping using antimicro or Steam big mode application\n"
			<< "and after set, the SDL controller variable before you launch the executable, i.e:\n"
			<< "export SDL_GAMECONTROLLERCONFIG=\"[the string you received from controllermap]\"");
			/* Need this so python args can return empty lists */
			joy_error = true;
		}

		if (!joy_error) {
			m_private->m_gamecontroller = SDL_GameControllerOpen(m_joyindex);
			if (!m_private->m_gamecontroller) {
				joy_error = true;
			}
		}

		SDL_Joystick *joy;
		if (!joy_error) {
			joy = SDL_GameControllerGetJoystick(m_private->m_gamecontroller);
			if (!joy) {
				joy_error = true;
			}
		}

		if (!joy_error) {
			m_private->m_instance_id = SDL_JoystickInstanceID(joy);
			if (m_private->m_instance_id < 0){
				joy_error = true;
				CM_Error("joystick instanced failed: " << SDL_GetError());
			}
		}

		if (!joy_error) {
			CM_Debug("Game Controller (" << GetName() << ") with index " << m_joyindex << " initialized");

			/* A Game Controller has:
			 *
			 * 6 axis availables:	   AXIS_LEFTSTICK_X, AXIS_LEFTSTICK_Y,
			 * (in order from 0 to 5)  AXIS_RIGHTSTICK_X, AXIS_RIGHTSTICK_Y,
			 *						   AXIS_TRIGGERLEFT and AXIS_TRIGGERRIGHT.
			 *
			 * 15 buttons availables:  BUTTON_A, BUTTON_B, BUTTON_X, BUTTON_Y,
			 * (in order from 0 to 14) BUTTON_BACK, BUTTON_GUIDE, BUTTON_START,
			 *						   BUTTON_LEFTSTICK, BUTTON_RIGHTSTICK,
			 *						   BUTTON_LEFTSHOULDER, BUTTON_RIGHTSHOULDER,
			 *						   BUTTON_DPAD_UP, BUTTON_DPAD_DOWN,
			 *						   BUTTON_DPAD_LEFT and BUTTON_DPAD_RIGHT.
			 */
			m_axismax = SDL_CONTROLLER_AXIS_MAX;
			m_buttonmax = SDL_CONTROLLER_BUTTON_MAX;
		}

		/* Haptic configuration */
		if (!joy_error && SDL_CHECK(SDL_HapticOpen)) {
			m_private->m_haptic = SDL_HapticOpen(m_joyindex);
			if (!m_private->m_haptic) {
				CM_Warning("Game Controller (" << GetName() << ") with index " << m_joyindex
					<< " has not force feedback (vibration) available");
			}
		}
	}
#endif /* WITH_SDL */

	if (joy_error) {
		m_axismax = m_buttonmax = 0;
		return false;
	}
	else {
		m_isinit = true;
		return true;
	}
}
Exemplo n.º 27
0
void InputDaemon::refreshJoysticks()
{
    QMapIterator<SDL_JoystickID, InputDevice*> iter(*joysticks);

    while (iter.hasNext())
    {
        InputDevice *joystick = iter.next().value();
        if (joystick)
        {
            delete joystick;
            joystick = 0;
        }
    }

    joysticks->clear();
#ifdef USE_SDL_2
    trackjoysticks.clear();
    trackcontrollers.clear();
#endif

#ifdef USE_SDL_2
    settings->getLock()->lock();
    settings->beginGroup("Mappings");
#endif

    for (int i=0; i < SDL_NumJoysticks(); i++)
    {
#ifdef USE_SDL_2

        SDL_Joystick *joystick = SDL_JoystickOpen(i);

        QString temp;
        SDL_JoystickGUID tempGUID = SDL_JoystickGetGUID(joystick);
        char guidString[65] = {'0'};
        SDL_JoystickGetGUIDString(tempGUID, guidString, sizeof(guidString));
        temp = QString(guidString);

        bool disableGameController = settings->value(QString("%1Disable").arg(temp), false).toBool();

        if (SDL_IsGameController(i) && !disableGameController)
        {
            SDL_GameController *controller = SDL_GameControllerOpen(i);
            GameController *damncontroller = new GameController(controller, i, settings, this);
            connect(damncontroller, SIGNAL(requestWait()), eventWorker, SLOT(haltServices()));
            SDL_Joystick *sdlStick = SDL_GameControllerGetJoystick(controller);
            SDL_JoystickID joystickID = SDL_JoystickInstanceID(sdlStick);
            joysticks->insert(joystickID, damncontroller);
            trackcontrollers.insert(joystickID, damncontroller);
        }
        else
        {
            Joystick *curJoystick = new Joystick(joystick, i, settings, this);
            connect(curJoystick, SIGNAL(requestWait()), eventWorker, SLOT(haltServices()));
            SDL_JoystickID joystickID = SDL_JoystickInstanceID(joystick);
            joysticks->insert(joystickID, curJoystick);
            trackjoysticks.insert(joystickID, curJoystick);
        }
#else
        SDL_Joystick *joystick = SDL_JoystickOpen(i);
        Joystick *curJoystick = new Joystick(joystick, i, settings, this);
        connect(curJoystick, SIGNAL(requestWait()), eventWorker, SLOT(haltServices()));
        joysticks->insert(i, curJoystick);
#endif
    }

#ifdef USE_SDL_2
    settings->endGroup();
    settings->getLock()->unlock();
#endif

    emit joysticksRefreshed(joysticks);
}
Exemplo n.º 28
0
int32_t C4GamePadOpener::GetID()
{
	return SDL_JoystickInstanceID(SDL_GameControllerGetJoystick(controller));
}
Exemplo n.º 29
0
void InputDaemon::addInputDevice(int index)
{
    SDL_Joystick *joystick = SDL_JoystickOpen(index);
    if (joystick)
    {
        SDL_JoystickID tempJoystickID = SDL_JoystickInstanceID(joystick);

        if (!joysticks->contains(tempJoystickID))
        {
            settings->getLock()->lock();
            settings->beginGroup("Mappings");

            QString temp;
            SDL_JoystickGUID tempGUID = SDL_JoystickGetGUID(joystick);
            char guidString[65] = {'0'};
            SDL_JoystickGetGUIDString(tempGUID, guidString, sizeof(guidString));
            temp = QString(guidString);

            bool disableGameController = settings->value(QString("%1Disable").arg(temp), false).toBool();

            if (SDL_IsGameController(index) && !disableGameController)
            {
                // Make sure to decrement reference count
                SDL_JoystickClose(joystick);

                SDL_GameController *controller = SDL_GameControllerOpen(index);
                if (controller)
                {
                    SDL_Joystick *sdlStick = SDL_GameControllerGetJoystick(controller);
                    SDL_JoystickID tempJoystickID = SDL_JoystickInstanceID(sdlStick);
                    if (!joysticks->contains(tempJoystickID))
                    {
                        GameController *damncontroller = new GameController(controller, index, settings, this);
                        connect(damncontroller, SIGNAL(requestWait()), eventWorker, SLOT(haltServices()));
                        joysticks->insert(tempJoystickID, damncontroller);
                        trackcontrollers.insert(tempJoystickID, damncontroller);

                        settings->endGroup();
                        settings->getLock()->unlock();

                        emit deviceAdded(damncontroller);
                    }
                }
                else
                {
                    settings->endGroup();
                    settings->getLock()->unlock();
                }
            }
            else
            {
                Joystick *curJoystick = new Joystick(joystick, index, settings, this);
                joysticks->insert(tempJoystickID, curJoystick);
                trackjoysticks.insert(tempJoystickID, curJoystick);

                settings->endGroup();
                settings->getLock()->unlock();

                emit deviceAdded(curJoystick);
            }
        }
        else
        {
            // Make sure to decrement reference count
            SDL_JoystickClose(joystick);
        }
    }
}
Exemplo n.º 30
0
static void sdl_pad_connect(unsigned id)
{
   sdl_joypad_t *pad          = (sdl_joypad_t*)&sdl_pads[id];
   bool success               = false;
   int32_t product            = 0;
   int32_t vendor             = 0;
   settings_t *settings       = config_get_ptr();
   autoconfig_params_t params = {{0}};

#ifdef HAVE_SDL2
   SDL_JoystickGUID guid;
   uint16_t *guid_ptr;

   if (SDL_IsGameController(id))
   {
      pad->controller = SDL_GameControllerOpen(id);
      pad->joypad     = SDL_GameControllerGetJoystick(pad->controller);

      success = pad->joypad != NULL && pad->controller != NULL;
   }
   else
#endif
   {
      pad->joypad = SDL_JoystickOpen(id);
      success = pad->joypad != NULL;
   }

   if (!success)
   {
      RARCH_ERR("[SDL]: Couldn't open joystick #%u: %s.\n", id, SDL_GetError());

      if (pad->joypad)
         SDL_JoystickClose(pad->joypad);

      pad->joypad = NULL;

      return;
   }

   strlcpy(settings->input.device_names[id], sdl_pad_name(id), sizeof(settings->input.device_names[id]));

#ifdef HAVE_SDL2
   guid       = SDL_JoystickGetGUID(pad->joypad);
   guid_ptr   = (uint16_t*)guid.data;
#ifdef __linux
   vendor     = guid_ptr[2];
   product    = guid_ptr[4];
#elif _WIN32
   vendor     = guid_ptr[0];
   product    = guid_ptr[1];
#endif
#endif
   params.idx = id;
   strlcpy(params.name, sdl_pad_name(id), sizeof(params.name));
   params.vid = vendor;
   params.pid = product;
   strlcpy(params.driver, sdl_joypad.ident, sizeof(params.driver));

   input_config_autoconfigure_joypad(&params);

   RARCH_LOG("[SDL]: Device #%u (%04x:%04x) connected: %s.\n", id, vendor,
             product, sdl_pad_name(id));

#ifdef HAVE_SDL2

   if (pad->controller)
      RARCH_LOG("[SDL]: Device #%u supports game controller api.\n", id);

   pad->haptic = g_has_haptic ? SDL_HapticOpenFromJoystick(pad->joypad) : NULL;

   if (g_has_haptic && !pad->haptic)
      RARCH_WARN("[SDL]: Couldn't open haptic device of the joypad #%u: %s\n",
                 id, SDL_GetError());

   pad->rumble_effect = -1;

   if (pad->haptic)
   {
      SDL_HapticEffect efx;
      efx.type = SDL_HAPTIC_LEFTRIGHT;
      efx.leftright.type = SDL_HAPTIC_LEFTRIGHT;
      efx.leftright.large_magnitude = efx.leftright.small_magnitude = 0x4000;
      efx.leftright.length = 5000;

      if (SDL_HapticEffectSupported(pad->haptic, &efx) == SDL_FALSE)
      {
         pad->rumble_effect = -2;
         RARCH_WARN("[SDL]: Device #%u does not support rumble.\n", id);
      }
   }
#endif

   pad->num_axes    = SDL_JoystickNumAxes(pad->joypad);
   pad->num_buttons = SDL_JoystickNumButtons(pad->joypad);
   pad->num_hats    = SDL_JoystickNumHats(pad->joypad);

#ifdef HAVE_SDL2
   pad->num_balls   = SDL_JoystickNumBalls(pad->joypad);

   RARCH_LOG("[SDL]: Device #%u has: %u axes, %u buttons, %u hats and %u trackballs.\n",
             id, pad->num_axes, pad->num_buttons, pad->num_hats, pad->num_balls);
#else
   RARCH_LOG("[SDL]: Device #%u has: %u axes, %u buttons, %u hats.\n",
             id, pad->num_axes, pad->num_buttons, pad->num_hats);
#endif
}