Beispiel #1
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);
            }
        }
    }
}
Beispiel #2
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);
    }
}
Beispiel #3
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;
      }
    }
  }
}
Beispiel #4
0
bool Joystick::open(int deviceindex)
{
	close();

	joyhandle = SDL_JoystickOpen(deviceindex);

	if (joyhandle)
	{
		instanceid = SDL_JoystickInstanceID(joyhandle);

		// SDL_JoystickGetGUIDString uses 32 bytes plus the null terminator.
		char cstr[33];

		SDL_JoystickGUID sdlguid = SDL_JoystickGetGUID(joyhandle);
		SDL_JoystickGetGUIDString(sdlguid, cstr, (int) sizeof(cstr));

		pguid = std::string(cstr);

		// See if SDL thinks this is a Game Controller.
		openGamepad(deviceindex);

		// Prefer the Joystick name for consistency.
		const char *joyname = SDL_JoystickName(joyhandle);
		if (!joyname && controller)
			joyname = SDL_GameControllerName(controller);

		if (joyname)
			name = joyname;
	}

	return isConnected();
}
Beispiel #5
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);
}
Beispiel #6
0
 joystick_id id() const {
     joystick_id result = SDL_JoystickInstanceID(ptr.get());
     if(result == 0) {
         GUM_ERROR_HANDLER(result);
     }
     return result;
 }
void InputManager::addJoystickByDeviceIndex(int id)
{
	assert(id >= 0 && id < SDL_NumJoysticks());
	
	// open joystick & add to our list
	SDL_Joystick* joy = SDL_JoystickOpen(id);
	assert(joy);

	// add it to our list so we can close it again later
	SDL_JoystickID joyId = SDL_JoystickInstanceID(joy);
	mJoysticks[joyId] = joy;

	char guid[65];
	SDL_JoystickGetGUIDString(SDL_JoystickGetGUID(joy), guid, 65);

	// create the InputConfig
	mInputConfigs[joyId] = new InputConfig(joyId, SDL_JoystickName(joy), guid);
	if(!loadInputConfig(mInputConfigs[joyId]))
	{
		LOG(LogInfo) << "Added unconfigured joystick " << SDL_JoystickName(joy) << " (GUID: " << guid << ", instance ID: " << joyId << ", device index: " << id << ").";
	}else{
		LOG(LogInfo) << "Added known joystick " << SDL_JoystickName(joy) << " (instance ID: " << joyId << ", device index: " << id << ")";
	}

	// set up the prevAxisValues
	int numAxes = SDL_JoystickNumAxes(joy);
	mPrevAxisValues[joyId] = new int[numAxes];
	std::fill(mPrevAxisValues[joyId], mPrevAxisValues[joyId] + numAxes, 0); //initialize array to 0
}
Beispiel #8
0
SDLApplication::SDLApplication () {

    if (SDL_Init (SDL_INIT_VIDEO | SDL_INIT_GAMECONTROLLER | SDL_INIT_TIMER | SDL_INIT_JOYSTICK) != 0) {

        printf ("Could not initialize SDL: %s.\n", SDL_GetError ());

    }

    currentApplication = this;

    framePeriod = 1000.0 / 60.0;

#ifdef EMSCRIPTEN
    emscripten_cancel_main_loop ();
    emscripten_set_main_loop (UpdateFrame, 0, 0);
    emscripten_set_main_loop_timing (EM_TIMING_RAF, 1);
#endif

    currentUpdate = 0;
    lastUpdate = 0;
    nextUpdate = 0;

    ApplicationEvent applicationEvent;
    GamepadEvent gamepadEvent;
    KeyEvent keyEvent;
    MouseEvent mouseEvent;
    RenderEvent renderEvent;
    SensorEvent sensorEvent;
    TextEvent textEvent;
    TouchEvent touchEvent;
    WindowEvent windowEvent;

#if defined(IOS) || defined(ANDROID)
    for (int i = 0; i < SDL_NumJoysticks (); i++) {

        if (strstr (SDL_JoystickNameForIndex (i), "Accelerometer")) {

            accelerometer = SDL_JoystickOpen (i);
            accelerometerID = SDL_JoystickInstanceID (accelerometer);

        }

    }
#endif

#ifdef HX_MACOS
    CFURLRef resourcesURL = CFBundleCopyResourcesDirectoryURL (CFBundleGetMainBundle ());
    char path[PATH_MAX];

    if (CFURLGetFileSystemRepresentation (resourcesURL, TRUE, (UInt8 *)path, PATH_MAX)) {

        chdir (path);

    }

    CFRelease (resourcesURL);
#endif

}
Beispiel #9
0
void Joypad::connect()
{
    joystick = SDL_JoystickOpen(index);
    joystickId = SDL_JoystickInstanceID(joystick);
    buttonCount = SDL_JoystickNumButtons(joystick);
    axisCount = SDL_JoystickNumAxes(joystick);
    hatCount = SDL_JoystickNumHats(joystick);
}
Beispiel #10
0
void JoystickPool::openJoystick(const int joyIndex)
{
    SDL_Joystick* joystickInstance = SDL_JoystickOpen(joyIndex);
    if (joystickInstance != NULL)
    {
        mJoyMap[SDL_JoystickInstanceID(joystickInstance)] = joystickInstance;
    }
}
Beispiel #11
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" );
		}
	}
}
Beispiel #12
0
static mrb_value
mrb_sdl2_joystick_joystick_get_id(mrb_state *mrb, mrb_value self)
{
  SDL_Joystick * joystick_p = mrb_sdl2_joystick_joystick_get_ptr(mrb, self);
  SDL_JoystickID result = SDL_JoystickInstanceID(joystick_p);
  if (result < 1) {
    mruby_sdl2_raise_error(mrb);
  }
  return mrb_fixnum_value(result);
}
static SDL_bool
WatchJoystick(SDL_Joystick * joystick)
{
    SDL_Window *window = NULL;
    const char *name = NULL;

    retval = SDL_FALSE;
    done = SDL_FALSE;

    /* Create a window to display joystick axis position */
    window = SDL_CreateWindow("Joystick Test", SDL_WINDOWPOS_CENTERED,
                              SDL_WINDOWPOS_CENTERED, SCREEN_WIDTH,
                              SCREEN_HEIGHT, 0);
    if (window == NULL) {
        SDL_LogError(SDL_LOG_CATEGORY_APPLICATION, "Couldn't create window: %s\n", SDL_GetError());
        return SDL_FALSE;
    }

    screen = SDL_CreateRenderer(window, -1, 0);
    if (screen == NULL) {
        SDL_LogError(SDL_LOG_CATEGORY_APPLICATION, "Couldn't create renderer: %s\n", SDL_GetError());
        SDL_DestroyWindow(window);
        return SDL_FALSE;
    }

    SDL_SetRenderDrawColor(screen, 0x00, 0x00, 0x00, SDL_ALPHA_OPAQUE);
    SDL_RenderClear(screen);
    SDL_RenderPresent(screen);
    SDL_RaiseWindow(window);

    /* Print info about the joystick we are watching */
    name = SDL_JoystickName(joystick);
    SDL_Log("Watching joystick %d: (%s)\n", SDL_JoystickInstanceID(joystick),
           name ? name : "Unknown Joystick");
    SDL_Log("Joystick has %d axes, %d hats, %d balls, and %d buttons\n",
           SDL_JoystickNumAxes(joystick), SDL_JoystickNumHats(joystick),
           SDL_JoystickNumBalls(joystick), SDL_JoystickNumButtons(joystick));

    /* Loop, getting joystick events! */
#ifdef __EMSCRIPTEN__
    emscripten_set_main_loop_arg(loop, joystick, 0, 1);
#else
    while (!done) {
        loop(joystick);
    }
#endif

    SDL_DestroyRenderer(screen);
    screen = NULL;
    SDL_DestroyWindow(window);
    return retval;
}
Beispiel #14
0
void InputDaemon::refreshIndexes()
{
    for (int i = 0; i < SDL_NumJoysticks(); i++)
    {
        SDL_Joystick *joystick = SDL_JoystickOpen(i);
        SDL_JoystickID joystickID = SDL_JoystickInstanceID(joystick);
        InputDevice *tempdevice = joysticks->value(joystickID);
        if (tempdevice)
        {
            tempdevice->setIndex(i);
        }
    }
}
Beispiel #15
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);
    }
}
Beispiel #16
0
	void SDLJoystick::Init () {

		#if defined(IPHONE) || defined(ANDROID) || defined(TVOS)
		for (int i = 0; i < SDL_NumJoysticks (); i++) {

			if (strstr (SDL_JoystickNameForIndex (i), "Accelerometer")) {

				accelerometer = SDL_JoystickOpen (i);
				accelerometerID = SDL_JoystickInstanceID (accelerometer);

			}

		}
		#endif

	}
Beispiel #17
0
void InputDaemon::refreshIndexes()
{
    for (int i = 0; i < SDL_NumJoysticks(); i++)
    {
        SDL_Joystick *joystick = SDL_JoystickOpen(i);
        SDL_JoystickID joystickID = SDL_JoystickInstanceID(joystick);
        // Make sure to decrement reference count
        SDL_JoystickClose(joystick);

        InputDevice *tempdevice = joysticks->value(joystickID);
        if (tempdevice)
        {
            tempdevice->setIndex(i);
        }
    }
}
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());
}
Beispiel #19
0
void
JoystickManager::on_joystick_removed(int instance_id)
{
  log_debug << "on_joystick_removed: " << static_cast<int>(instance_id) << std::endl;
  for(auto& joy : joysticks)
  {
    SDL_JoystickID id = SDL_JoystickInstanceID(joy);
    if (id == instance_id)
    {
      SDL_JoystickClose(joy);
      joy = nullptr;
    }
  }

  joysticks.erase(std::remove(joysticks.begin(), joysticks.end(), nullptr),
                  joysticks.end());
}
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);
}
Beispiel #21
0
void SdlContext::_addJoystick(Input &inputs, int joyIdx)
{
    SDL_Joystick *current = SDL_JoystickOpen(joyIdx);

    if (current)
    {
        SDL_JoystickID sdlJoyId = SDL_JoystickInstanceID(current);

        if (sdlJoyId != -1)
        {
            uint32_t currentId = 0;

            while (currentId != AGE_JOYSTICK_MAX_NUMBER &&
                    _joysticks[currentId].id != -1)
                ++currentId;
            assert(currentId != AGE_JOYSTICK_MAX_NUMBER && "AGE cannot handle more than 6 joysticks.");
            _joysticks[currentId].id = sdlJoyId;
            _joysticks[currentId].handler = current;
            inputs.addJoystick(SDL_JoystickName(current), currentId);
        }
    }
}
Beispiel #22
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;

	}
Beispiel #23
0
void Game::init()
{
    SDL_Init(SDL_INIT_EVERYTHING);
    isRunning = true;
    gameState = GameState::GAMEPLAY;

    InputHandler* inputHandler = new InputHandler(*this);
    this->inputHandler = inputHandler;
    int numJoysticks = SDL_NumJoysticks();
    if (numJoysticks > 0)
    {
        for (int i = 0; i < numJoysticks; ++i)
        {
            this->inputHandler->joysticks.push_back(SDL_JoystickOpen(i));
            this->inputHandler->joystickControls.push_back(JoystickControls());
            this->inputHandler->joystickControls[i].joystickID = SDL_JoystickInstanceID(inputHandler->joysticks[i]);
        }
    }

    Graphics* graphics = new Graphics();
    this->graphics = graphics;

    this->setupSpaces();
}
Beispiel #24
0
	void Joystick::open() {
		if (m_joystickHandle) {
			close();
		}

		m_joystickHandle = SDL_JoystickOpen(m_deviceIndex);
		if (m_joystickHandle) {
			m_instanceId = SDL_JoystickInstanceID(m_joystickHandle);

			char tmp[33];
			SDL_JoystickGUID guid = SDL_JoystickGetDeviceGUID(m_deviceIndex);
			SDL_JoystickGetGUIDString(guid, tmp, sizeof(tmp));
			m_guidStr = std::string(tmp);

			openController();
			const char* name = SDL_JoystickNameForIndex(m_deviceIndex);
			if (isController() && !name) {
				name = SDL_GameControllerNameForIndex(m_deviceIndex);
			}
			m_name = std::string(name);
		} else {
			throw SDLException(SDL_GetError());
		}
	}
Beispiel #25
0
void
InputDriver::update()
{
   SDL_Event event;

   while (SDL_PollEvent(&event)) {
      switch (event.type) {
      case SDL_JOYDEVICEADDED:
      {
         auto joystick = SDL_JoystickOpen(event.jdevice.which);
         auto guid = SDL_JoystickGetGUID(joystick);
         auto instanceId = SDL_JoystickInstanceID(joystick);

         {
            std::unique_lock lock { mConfigurationMutex };
            auto connected = ConnectedJoystick { };
            connected.joystick = joystick;
            connected.guid = guid;
            connected.instanceId = instanceId;
            connected.duplicateId = 0;

            for (auto &others : mJoysticks) {
               if (others.guid == connected.guid) {
                  connected.duplicateId = std::max(connected.duplicateId, others.duplicateId + 1);
               }
            }

            for (auto &controller : mConfiguration.controllers) {
               for (auto &input : controller.inputs) {
                  if (input.joystickGuid == guid && input.joystickDuplicateId == connected.duplicateId) {
                     input.joystick = joystick;
                     input.joystickInstanceId = instanceId;
                  }
               }
            }

            mJoysticks.push_back(connected);
         }

         emit joystickConnected(instanceId, guid, SDL_JoystickName(joystick));
         break;
      }
      case SDL_JOYDEVICEREMOVED:
      {
         auto joystick = SDL_JoystickFromInstanceID(event.jdevice.which);
         if (joystick) {
            joystickDisconnected(SDL_JoystickInstanceID(joystick), SDL_JoystickGetGUID(joystick));

            {
               std::unique_lock lock { mConfigurationMutex };
               for (auto itr = mJoysticks.begin(); itr != mJoysticks.end(); ++itr) {
                  if (itr->joystick == joystick) {
                     itr = mJoysticks.erase(itr);
                  }
               }

               for (auto &controller : mConfiguration.controllers) {
                  for (auto &input : controller.inputs) {
                     if (input.joystick == joystick) {
                        input.joystick = nullptr;
                     }
                  }
               }
            }

            SDL_JoystickClose(joystick);
         }
         break;
      }
      case SDL_JOYBUTTONDOWN:
      {
         if (mButtonEventsEnabled) {
            auto joystick = SDL_JoystickFromInstanceID(event.jdevice.which);
            if (joystick) {
               joystickButtonDown(SDL_JoystickInstanceID(joystick), SDL_JoystickGetGUID(joystick), event.jbutton.button);
            }
         }
         break;
      }
      case SDL_JOYAXISMOTION:
      {
         if (mButtonEventsEnabled) {
            auto joystick = SDL_JoystickFromInstanceID(event.jdevice.which);
            if (joystick) {
               joystickAxisMotion(SDL_JoystickInstanceID(joystick), SDL_JoystickGetGUID(joystick), event.jaxis.axis, translateAxisValue(event.jaxis.value));
            }
         }
         break;
      }
      case SDL_JOYHATMOTION:
      {
         if (mButtonEventsEnabled) {
            auto joystick = SDL_JoystickFromInstanceID(event.jdevice.which);
            if (joystick) {
               joystickHatMotion(SDL_JoystickInstanceID(joystick), SDL_JoystickGetGUID(joystick), event.jhat.hat, event.jhat.value);
            }
         }
         break;
      }

      // I don't think we actually care about game controllers?
      case SDL_CONTROLLERDEVICEADDED:
         qDebug("SDL_CONTROLLERDEVICEADDED");
         break;
      case SDL_CONTROLLERDEVICEREMAPPED:
         qDebug("SDL_CONTROLLERDEVICEREMAPPED");
         break;
      case SDL_CONTROLLERDEVICEREMOVED:
         qDebug("SDL_CONTROLLERDEVICEREMOVED");
         break;
      case SDL_CONTROLLERBUTTONDOWN:
         qDebug("SDL_CONTROLLERBUTTONDOWN");
         break;
      }
   }

   QTimer::singleShot(10, Qt::PreciseTimer, this, SLOT(update()));
}
Beispiel #26
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);
        }
    }
}
Beispiel #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);
}
Beispiel #28
0
SDL_JoystickID SDLController::InstanceID()
{
    SDL_Joystick* joy = SDL_GameControllerGetJoystick(m_Ctrl);
    return SDL_JoystickInstanceID(joy);
}
static SDL_bool
WatchJoystick(SDL_Joystick * joystick)
{
    SDL_Window *window = NULL;
    SDL_Renderer *screen = NULL;
    SDL_Texture *background, *button, *axis, *marker;
    const char *name = NULL;
    SDL_bool retval = SDL_FALSE;
    SDL_bool done = SDL_FALSE, next=SDL_FALSE;
    SDL_Event event;
    SDL_Rect dst;
    int s, _s;
    Uint8 alpha=200, alpha_step = -1;
    Uint32 alpha_ticks;
    char mapping[4096], temp[4096];
    MappingStep *step;
    MappingStep steps[] = {
        {342, 132,  0.0,  MARKER_BUTTON, "x", -1, -1, -1, -1, ""},
        {387, 167,  0.0,  MARKER_BUTTON, "a", -1, -1, -1, -1, ""},
        {431, 132,  0.0,  MARKER_BUTTON, "b", -1, -1, -1, -1, ""},
        {389, 101,  0.0,  MARKER_BUTTON, "y", -1, -1, -1, -1, ""},
        {174, 132,  0.0,  MARKER_BUTTON, "back", -1, -1, -1, -1, ""},
        {233, 132,  0.0,  MARKER_BUTTON, "guide", -1, -1, -1, -1, ""},
        {289, 132,  0.0,  MARKER_BUTTON, "start", -1, -1, -1, -1, ""},        
        {116, 217,  0.0,  MARKER_BUTTON, "dpleft", -1, -1, -1, -1, ""},
        {154, 249,  0.0,  MARKER_BUTTON, "dpdown", -1, -1, -1, -1, ""},
        {186, 217,  0.0,  MARKER_BUTTON, "dpright", -1, -1, -1, -1, ""},
        {154, 188,  0.0,  MARKER_BUTTON, "dpup", -1, -1, -1, -1, ""},
        {77,  40,   0.0,  MARKER_BUTTON, "leftshoulder", -1, -1, -1, -1, ""},
        {91, 0,    0.0,  MARKER_BUTTON, "lefttrigger", -1, -1, -1, -1, ""},
        {396, 36,   0.0,  MARKER_BUTTON, "rightshoulder", -1, -1, -1, -1, ""},
        {375, 0,    0.0,  MARKER_BUTTON, "righttrigger", -1, -1, -1, -1, ""},
        {75,  154,  0.0,  MARKER_BUTTON, "leftstick", -1, -1, -1, -1, ""},
        {305, 230,  0.0,  MARKER_BUTTON, "rightstick", -1, -1, -1, -1, ""},
        {75,  154,  0.0,  MARKER_AXIS,   "leftx", -1, -1, -1, -1, ""},
        {75,  154,  90.0, MARKER_AXIS,   "lefty", -1, -1, -1, -1, ""},        
        {305, 230,  0.0,  MARKER_AXIS,   "rightx", -1, -1, -1, -1, ""},
        {305, 230,  90.0, MARKER_AXIS,   "righty", -1, -1, -1, -1, ""},
    };

    /* Create a window to display joystick axis position */
    window = SDL_CreateWindow("Game Controller Map", SDL_WINDOWPOS_CENTERED,
                              SDL_WINDOWPOS_CENTERED, SCREEN_WIDTH,
                              SCREEN_HEIGHT, 0);
    if (window == NULL) {
        SDL_LogError(SDL_LOG_CATEGORY_APPLICATION, "Couldn't create window: %s\n", SDL_GetError());
        return SDL_FALSE;
    }

    screen = SDL_CreateRenderer(window, -1, 0);
    if (screen == NULL) {
        SDL_LogError(SDL_LOG_CATEGORY_APPLICATION, "Couldn't create renderer: %s\n", SDL_GetError());
        SDL_DestroyWindow(window);
        return SDL_FALSE;
    }
    
    background = LoadTexture(screen, "controllermap.bmp", SDL_FALSE);
    button = LoadTexture(screen, "button.bmp", SDL_TRUE);
    axis = LoadTexture(screen, "axis.bmp", SDL_TRUE);
    SDL_RaiseWindow(window);

    /* scale for platforms that don't give you the window size you asked for. */
    SDL_RenderSetLogicalSize(screen, SCREEN_WIDTH, SCREEN_HEIGHT);

    /* Print info about the joystick we are watching */
    name = SDL_JoystickName(joystick);
    SDL_Log("Watching joystick %d: (%s)\n", SDL_JoystickInstanceID(joystick),
           name ? name : "Unknown Joystick");
    SDL_Log("Joystick has %d axes, %d hats, %d balls, and %d buttons\n",
           SDL_JoystickNumAxes(joystick), SDL_JoystickNumHats(joystick),
           SDL_JoystickNumBalls(joystick), SDL_JoystickNumButtons(joystick));
    
    SDL_Log("\n\n\
    ====================================================================================\n\
    Press the buttons on your controller when indicated\n\
    (Your controller may look different than the picture)\n\
    If you want to correct a mistake, press backspace or the back button on your device\n\
    To skip a button, press SPACE or click/touch the screen\n\
    To exit, press ESC\n\
    ====================================================================================\n");
    
    /* Initialize mapping with GUID and name */
    SDL_JoystickGetGUIDString(SDL_JoystickGetGUID(joystick), temp, SDL_arraysize(temp));
    SDL_snprintf(mapping, SDL_arraysize(mapping), "%s,%s,platform:%s,",
        temp, name ? name : "Unknown Joystick", SDL_GetPlatform());

    /* Loop, getting joystick events! */
    for(s=0; s<SDL_arraysize(steps) && !done;) {
        /* blank screen, set up for drawing this frame. */
        step = &steps[s];
        SDL_strlcpy(step->mapping, mapping, SDL_arraysize(step->mapping));
        step->axis = -1;
        step->button = -1;
        step->hat = -1;
        step->hat_value = -1;
        SDL_SetClipboardText("TESTING TESTING 123");
        
        switch(step->marker) {
            case MARKER_AXIS:
                marker = axis;
                break;
            case MARKER_BUTTON:
                marker = button;
                break;
            default:
                break;
        }
        
        dst.x = step->x;
        dst.y = step->y;
        SDL_QueryTexture(marker, NULL, NULL, &dst.w, &dst.h);
        next=SDL_FALSE;

        SDL_SetRenderDrawColor(screen, 0xFF, 0xFF, 0xFF, SDL_ALPHA_OPAQUE);

        while (!done && !next) {
            if (SDL_GetTicks() - alpha_ticks > 5) {
                alpha_ticks = SDL_GetTicks();
                alpha += alpha_step;
                if (alpha == 255) {
                    alpha_step = -1;
                }
                if (alpha < 128) {
                    alpha_step = 1;
                }
            }
            
            SDL_RenderClear(screen);
            SDL_RenderCopy(screen, background, NULL, NULL);
            SDL_SetTextureAlphaMod(marker, alpha);
            SDL_SetTextureColorMod(marker, 10, 255, 21);
            SDL_RenderCopyEx(screen, marker, NULL, &dst, step->angle, NULL, 0);
            SDL_RenderPresent(screen);
            
            if (SDL_PollEvent(&event)) {
                switch (event.type) {
                case SDL_JOYAXISMOTION:
                    if (event.jaxis.value > 20000 || event.jaxis.value < -20000) {
                        for (_s = 0; _s < s; _s++) {
                            if (steps[_s].axis == event.jaxis.axis) {
                                break;
                            }
                        }
                        if (_s == s) {
                            step->axis = event.jaxis.axis;
                            SDL_strlcat(mapping, step->field, SDL_arraysize(mapping));
                            SDL_snprintf(temp, SDL_arraysize(temp), ":a%u,", event.jaxis.axis);
                            SDL_strlcat(mapping, temp, SDL_arraysize(mapping));
                            s++;
                            next=SDL_TRUE;
                        }
                    }
                    
                    break;
                case SDL_JOYHATMOTION:
                        if (event.jhat.value == SDL_HAT_CENTERED) {
                            break;  /* ignore centering, we're probably just coming back to the center from the previous item we set. */
                        }
                        for (_s = 0; _s < s; _s++) {
                            if (steps[_s].hat == event.jhat.hat && steps[_s].hat_value == event.jhat.value) {
                                break;
                            }
                        }
                        if (_s == s) {
                            step->hat = event.jhat.hat;
                            step->hat_value = event.jhat.value;
                            SDL_strlcat(mapping, step->field, SDL_arraysize(mapping));
                            SDL_snprintf(temp, SDL_arraysize(temp), ":h%u.%u,", event.jhat.hat, event.jhat.value );
                            SDL_strlcat(mapping, temp, SDL_arraysize(mapping));
                            s++;
                            next=SDL_TRUE;
                        }
                    break;
                case SDL_JOYBALLMOTION:
                    break;
                case SDL_JOYBUTTONUP:
                    for (_s = 0; _s < s; _s++) {
                        if (steps[_s].button == event.jbutton.button) {
                            break;
                        }
                    }
                    if (_s == s) {
                        step->button = event.jbutton.button;
                        SDL_strlcat(mapping, step->field, SDL_arraysize(mapping));
                        SDL_snprintf(temp, SDL_arraysize(temp), ":b%u,", event.jbutton.button);
                        SDL_strlcat(mapping, temp, SDL_arraysize(mapping));
                        s++;
                        next=SDL_TRUE;
                    }
                    break;
                case SDL_FINGERDOWN:
                case SDL_MOUSEBUTTONDOWN:
                    /* Skip this step */
                    s++;
                    next=SDL_TRUE;
                    break;
                case SDL_KEYDOWN:
                    if (event.key.keysym.sym == SDLK_BACKSPACE || event.key.keysym.sym == SDLK_AC_BACK) {
                        /* Undo! */
                        if (s > 0) {
                            SDL_strlcpy(mapping, step->mapping, SDL_arraysize(step->mapping));
                            s--;
                            next = SDL_TRUE;
                        }
                        break;
                    }
                    if (event.key.keysym.sym == SDLK_SPACE) {
                        /* Skip this step */
                        s++;
                        next=SDL_TRUE;
                        break;
                    }
                    
                    if ((event.key.keysym.sym != SDLK_ESCAPE)) {
                        break;
                    }
                    /* Fall through to signal quit */
                case SDL_QUIT:
                    done = SDL_TRUE;
                    break;
                default:
                    break;
                }
            }
        }

    }

    if (s == SDL_arraysize(steps) ) {
        SDL_Log("Mapping:\n\n%s\n\n", mapping);
        /* Print to stdout as well so the user can cat the output somewhere */
        printf("%s\n", mapping);
    }
    
    while(SDL_PollEvent(&event)) {};
    
    SDL_DestroyRenderer(screen);
    SDL_DestroyWindow(window);
    return retval;
}
int
main(int argc, char *argv[])
{
    const char *name;
    int i;
    SDL_Joystick *joystick;

    /* Enable standard application logging */
    SDL_LogSetPriority(SDL_LOG_CATEGORY_APPLICATION, SDL_LOG_PRIORITY_INFO);	

    /* Initialize SDL (Note: video is required to start event loop) */
    if (SDL_Init(SDL_INIT_VIDEO | SDL_INIT_JOYSTICK) < 0) {
        SDL_LogError(SDL_LOG_CATEGORY_APPLICATION, "Couldn't initialize SDL: %s\n", SDL_GetError());
        exit(1);
    }

    /* Print information about the joysticks */
    SDL_Log("There are %d joysticks attached\n", SDL_NumJoysticks());
    for (i = 0; i < SDL_NumJoysticks(); ++i) {
        name = SDL_JoystickNameForIndex(i);
        SDL_Log("Joystick %d: %s\n", i, name ? name : "Unknown Joystick");
        joystick = SDL_JoystickOpen(i);
        if (joystick == NULL) {
            SDL_LogError(SDL_LOG_CATEGORY_APPLICATION, "SDL_JoystickOpen(%d) failed: %s\n", i,
                    SDL_GetError());
        } else {
            char guid[64];
            SDL_JoystickGetGUIDString(SDL_JoystickGetGUID(joystick),
                                      guid, sizeof (guid));
            SDL_Log("       axes: %d\n", SDL_JoystickNumAxes(joystick));
            SDL_Log("      balls: %d\n", SDL_JoystickNumBalls(joystick));
            SDL_Log("       hats: %d\n", SDL_JoystickNumHats(joystick));
            SDL_Log("    buttons: %d\n", SDL_JoystickNumButtons(joystick));
            SDL_Log("instance id: %d\n", SDL_JoystickInstanceID(joystick));
            SDL_Log("       guid: %s\n", guid);
            SDL_JoystickClose(joystick);
        }
    }

#ifdef ANDROID
    if (SDL_NumJoysticks() > 0) {
#else
    if (argv[1]) {
#endif
        SDL_bool reportederror = SDL_FALSE;
        SDL_bool keepGoing = SDL_TRUE;
        SDL_Event event;
        int device;
#ifdef ANDROID
        device = 0;
#else
        device = atoi(argv[1]);
#endif
        joystick = SDL_JoystickOpen(device);

        while ( keepGoing ) {
            if (joystick == NULL) {
                if ( !reportederror ) {
                    SDL_Log("Couldn't open joystick %d: %s\n", device, SDL_GetError());
                    keepGoing = SDL_FALSE;
                    reportederror = SDL_TRUE;
                }
            } else {
                reportederror = SDL_FALSE;
                keepGoing = WatchJoystick(joystick);
                SDL_JoystickClose(joystick);
            }

            joystick = NULL;
            if (keepGoing) {
                SDL_Log("Waiting for attach\n");
            }
            while (keepGoing) {
                SDL_WaitEvent(&event);
                if ((event.type == SDL_QUIT) || (event.type == SDL_FINGERDOWN)
                    || (event.type == SDL_MOUSEBUTTONDOWN)) {
                    keepGoing = SDL_FALSE;
                } else if (event.type == SDL_JOYDEVICEADDED) {
                    joystick = SDL_JoystickOpen(device);
                    break;
                }
            }
        }
    }
    else {
        SDL_Log("\n\nUsage: ./controllermap number\nFor example: ./controllermap 0\nOr: ./controllermap 0 >> gamecontrollerdb.txt");
    }
    SDL_QuitSubSystem(SDL_INIT_VIDEO | SDL_INIT_JOYSTICK);

    return 0;
}

#else

int
main(int argc, char *argv[])
{
    SDL_LogError(SDL_LOG_CATEGORY_APPLICATION, "SDL compiled without Joystick support.\n");
    exit(1);
}