Ejemplo n.º 1
0
    def __init__(self, controller_id, axis_deadzone=10000, trigger_deadzone=0):

        # Make sure we get joystick events even if in window mode and not focused.
        sdl2.SDL_SetHint(sdl2.SDL_HINT_JOYSTICK_ALLOW_BACKGROUND_EVENTS, b"1")

        sdl2.SDL_Init(sdl2.SDL_INIT_GAMECONTROLLER)

        # Mapping for X-box S Controller
        sdl2.SDL_GameControllerAddMapping(
            b"030000005e0400008902000021010000,Classic XBOX Controller,"
            b"a:b0,b:b1,y:b4,x:b3,start:b7,guide:,back:b6,leftstick:b8,"
            b"rightstick:b9,dpup:h0.1,dpleft:h0.8,dpdown:h0.4,dpright:h0.2,"
            b"leftx:a0,lefty:a1,rightx:a3,righty:a4,lefttrigger:a2,"
            b"righttrigger:a5,leftshoulder:b5,rightshoulder:b2,")

        # Mapping for 8bitdo
        sdl2.SDL_GameControllerAddMapping(
            b"05000000c82d00002038000000010000,8Bitdo NES30 Pro,"
            b"a:b1,b:b0,back:b10,dpdown:h0.4,dpleft:h0.8,"
            b"dpright:h0.2,dpup:h0.1,guide:b2,leftshoulder:b6,"
            b"leftstick:b13,lefttrigger:a5,leftx:a0,lefty:a1,"
            b"rightshoulder:b7,rightstick:b14,righttrigger:a4,"
            b"rightx:a2,righty:a3,start:b11,x:b4,y:b3,platform:Linux,")

        self.controller = None
        self.name = 'controller {:s}'.format(controller_id)
        self.which = None

        try:
            n = int(controller_id, 10)
            if n < sdl2.SDL_NumJoysticks():
                self.controller = sdl2.SDL_GameControllerOpen(n)
                self.which = n
        except ValueError:
            for n in range(sdl2.SDL_NumJoysticks()):
                name = sdl2.SDL_JoystickNameForIndex(n)
                if name is not None:
                    name = name.decode('utf8')
                    if name == controller_id:
                        self.controller = sdl2.SDL_GameControllerOpen(n)
                        self.which = n

        if self.controller is None:
            raise Exception('Controller not found: {:s}'.format(controller_id))

        try:
            self.name = sdl2.SDL_JoystickName(
                sdl2.SDL_GameControllerGetJoystick(
                    self.controller)).decode('utf8')
        except AttributeError:
            pass

        logger.info('Using {:s} for input.'.format(self.name))

        self.axis_deadzone = axis_deadzone
        self.trigger_deadzone = trigger_deadzone

        self.previous_state = State()
Ejemplo n.º 2
0
def get_controller(c):
    try:
        n = int(c, 10)
        return sdl2.SDL_GameControllerOpen(n)
    except ValueError:
        for n in range(sdl2.SDL_NumJoysticks()):
            name = sdl2.SDL_JoystickNameForIndex(n)
            if name is not None:
                name = name.decode('utf8')
                if name == c:
                    return sdl2.SDL_GameControllerOpen(n)
        raise Exception('Controller not found: %s'.format(c))
Ejemplo n.º 3
0
    def pump(self):
        for event in sdl2.ext.get_events():
            if event.type == sdl2.SDL_CONTROLLERDEVICEADDED:
                controller = event.cdevice.which
                log.debug('Controller added: %i' % controller)
                self.controller_added(controller)
                sdl2.SDL_GameControllerOpen(event.cdevice.which)

            elif event.type == sdl2.SDL_CONTROLLERDEVICEREMOVED:
                controller = event.cdevice.which
                log.debug('Controller removed: %i' % controller)
                self.controller_removed(controller)
                # sdl2.SDL_GameControllerClose(event.cdevice.which)

            elif event.type == sdl2.SDL_CONTROLLERBUTTONDOWN:
                button = event.cbutton.button
                self.set_button(
                    SDL_BUTTON_MAP[button], GamepadButtonState.Pressed
                )

            elif event.type == sdl2.SDL_CONTROLLERBUTTONUP:
                button = event.cbutton.button
                self.set_button(
                    SDL_BUTTON_MAP[button], GamepadButtonState.Released
                )

            elif event.type == sdl2.SDL_CONTROLLERAXISMOTION:
                axis = event.caxis.axis
                value = event.caxis.value
                self.set_axis(SDL_AXIS_MAP[axis], value)
Ejemplo n.º 4
0
 def ev_controllerdeviceadded(
         self, event: ControllerDeviceAdded) -> Optional[Action]:
     # `which` contains the joystick index of the added controller
     i = event.which
     assert i not in self.controllers
     controller = sdl2.SDL_GameControllerOpen(i)
     self.controllers[i] = controller
     print("Added controller {} {}".format(i, controller))
     return None
Ejemplo n.º 5
0
def sdl2_event_pump(events):
    global _sdlcontroller
    # Feed events into the loop
    for event in sdl2.ext.get_events():
        if event.type == sdl2.SDL_QUIT:
            events.append(WindowEvent(WindowEvent.QUIT))
        elif event.type == sdl2.SDL_KEYDOWN:
            events.append(
                WindowEvent(
                    KEY_DOWN.get(event.key.keysym.sym, WindowEvent.PASS)))
        elif event.type == sdl2.SDL_KEYUP:
            events.append(
                WindowEvent(KEY_UP.get(event.key.keysym.sym,
                                       WindowEvent.PASS)))
        elif event.type == sdl2.SDL_WINDOWEVENT:
            if event.window.windowID == 1:
                if event.window.event == sdl2.SDL_WINDOWEVENT_FOCUS_LOST:
                    events.append(WindowEvent(WindowEvent.WINDOW_UNFOCUS))
                elif event.window.event == sdl2.SDL_WINDOWEVENT_FOCUS_GAINED:
                    events.append(WindowEvent(WindowEvent.WINDOW_FOCUS))
        elif event.type == sdl2.SDL_MOUSEWHEEL:
            events.append(
                WindowEventMouse(WindowEvent._INTERNAL_MOUSE,
                                 window_id=event.motion.windowID,
                                 mouse_scroll_x=event.wheel.x,
                                 mouse_scroll_y=event.wheel.y))
        elif event.type == sdl2.SDL_MOUSEMOTION or event.type == sdl2.SDL_MOUSEBUTTONUP:
            mouse_button = -1
            if event.type == sdl2.SDL_MOUSEBUTTONUP:
                if event.button.button == sdl2.SDL_BUTTON_LEFT:
                    mouse_button = 0
                elif event.button.button == sdl2.SDL_BUTTON_RIGHT:
                    mouse_button = 1

            events.append(
                WindowEventMouse(WindowEvent._INTERNAL_MOUSE,
                                 window_id=event.motion.windowID,
                                 mouse_x=event.motion.x,
                                 mouse_y=event.motion.y,
                                 mouse_button=mouse_button))
        elif event.type == sdl2.SDL_CONTROLLERDEVICEADDED:
            _sdlcontroller = sdl2.SDL_GameControllerOpen(event.cdevice.which)
        elif event.type == sdl2.SDL_CONTROLLERDEVICEREMOVED:
            sdl2.SDL_GameControllerClose(_sdlcontroller)
        elif event.type == sdl2.SDL_CONTROLLERBUTTONDOWN:
            events.append(
                WindowEvent(
                    CONTROLLER_DOWN.get(event.cbutton.button,
                                        WindowEvent.PASS)))
        elif event.type == sdl2.SDL_CONTROLLERBUTTONUP:
            events.append(
                WindowEvent(
                    CONTROLLER_UP.get(event.cbutton.button, WindowEvent.PASS)))
    return events
Ejemplo n.º 6
0
 def open(self, client):
     super(SDLInputHandler, self).open(client)
     # Enumerate already plugged controllers
     for i in range(sdl2.SDL_NumJoysticks()):
         if sdl2.SDL_IsGameController(i):
             if sdl2.SDL_GameControllerOpen(i):
                 log.info("Opened controller: %i", i)
                 self.client.controller_added(i)
             else:
                 log.error("Unable to open controller: %i", i)
         else:
             log.error("Not a gamecontroller: %i", i)
Ejemplo n.º 7
0
    def __init__(self, sdl_controller_id):
        self.sdl_controller_id = sdl_controller_id
        self.sdl_controller = sdl2.SDL_GameControllerOpen(sdl_controller_id)

        self.sdl_joy = sdl2.SDL_GameControllerGetJoystick(self.sdl_controller)
        self.sdl_joy_id = sdl2.SDL_JoystickInstanceID(self.sdl_joy)

        guid = sdl2.SDL_JoystickGetDeviceGUID(self.sdl_joy_id)
        logging.log(logging.INFO, "Joystick GUID: %s " % guid)
        logging.log(
            logging.INFO,
            "Mapping: %s" % sdl2.SDL_GameControllerMappingForGUID(guid))
Ejemplo n.º 8
0
 def __init__(self, joystick_index):
     self.game_controller = None
     self.joystick = None
     self.joystick_id = None
     if sdl2.SDL_IsGameController(joystick_index):
         self.game_controller = sdl2.SDL_GameControllerOpen(joystick_index)
         self.joystick = sdl2.SDL_GameControllerGetJoystick(
             self.game_controller)
         self.joystick_id = sdl2.SDL_JoystickInstanceID(self.joystick)
         self.name = sdl2.SDL_GameControllerName(self.game_controller)
     else:
         self.joystick = sdl2.SDL_JoystickOpen(joystick_index)
         self.joystick_id = sdl2.SDL_JoystickInstanceID(self.joystick)
         self.name = sdl2.SDL_JoystickName(self.joystick)
Ejemplo n.º 9
0
    def open(self, device_index):
        self._sdl_controller = sdl2.SDL_GameControllerOpen(device_index)
        self._sdl_joystick = sdl2.SDL_GameControllerGetJoystick(self._sdl_controller)
        self._sdl_joystick_id = sdl2.SDL_JoystickInstanceID(self._sdl_joystick)

        self._controller_name = sdl2.SDL_JoystickName(self._sdl_joystick)
        self._num_axis = sdl2.SDL_JoystickNumAxes(self._sdl_joystick),
        self._num_buttons = sdl2.SDL_JoystickNumButtons(self._sdl_joystick)
        self._num_balls = sdl2.SDL_JoystickNumBalls(self._sdl_joystick)

        for btn_index in range(0, self.MAX_BUTTONS):
            self._button_down[btn_index] = 0
            self._button_pressed[btn_index] = 0
            self._button_released[btn_index] = 0

        if self._sdl_joystick_id != -1:
            self._connected = True
Ejemplo n.º 10
0
    def __init__(self, controller_id: int, **kwargs):
        self.ser = serial.Serial(**kwargs)

        sdl2.SDL_Init(sdl2.SDL_INIT_GAMECONTROLLER)
        self.controller = sdl2.SDL_GameControllerOpen(int(controller_id))
        try:
            print('Using "{:s}" for input.'.format(
                sdl2.SDL_JoystickName(
                    sdl2.SDL_GameControllerGetJoystick(
                        self.controller)).decode('utf8')))
        except AttributeError:
            print(f'Using controller {controller_id} for input.')

        self.input_stack = []
        self.recording = None
        self.start_dttm = None
        self.prev_msg_stamp = None
Ejemplo n.º 11
0
    def pump(self):
        for event in sdl2.ext.get_events():
            if event.type == sdl2.SDL_CONTROLLERDEVICEADDED:
                controller = event.cdevice.which
                log.debug('Controller added: %i' % controller)
                self.controller_added(controller)
                sdl2.SDL_GameControllerOpen(event.cdevice.which)

            elif event.type == sdl2.SDL_CONTROLLERDEVICEREMOVED:
                controller = event.cdevice.which
                log.debug('Controller removed: %i' % controller)
                self.controller_removed(controller)
                # sdl2.SDL_GameControllerClose(event.cdevice.which)

            elif event.type == sdl2.SDL_CONTROLLERBUTTONDOWN:
                button = event.cbutton.button
                self.set_button(SDL_BUTTON_MAP[button],
                                GamepadButtonState.Pressed)

            elif event.type == sdl2.SDL_CONTROLLERBUTTONUP:
                button = event.cbutton.button
                self.set_button(SDL_BUTTON_MAP[button],
                                GamepadButtonState.Released)

            elif event.type == sdl2.SDL_CONTROLLERAXISMOTION:
                axis = event.caxis.axis
                value = event.caxis.value
                if axis in (sdl2.SDL_CONTROLLER_AXIS_LEFTY,
                            sdl2.SDL_CONTROLLER_AXIS_RIGHTY):
                    value = -value
                if axis in (sdl2.SDL_CONTROLLER_AXIS_LEFTX,
                            sdl2.SDL_CONTROLLER_AXIS_LEFTY,
                            sdl2.SDL_CONTROLLER_AXIS_RIGHTX,
                            sdl2.SDL_CONTROLLER_AXIS_RIGHTY):
                    if value >= 32768:
                        value = 32767
                    elif value <= -32768:
                        value = -32768
                if axis in (sdl2.SDL_CONTROLLER_AXIS_TRIGGERLEFT,
                            sdl2.SDL_CONTROLLER_AXIS_TRIGGERRIGHT):
                    value = int(value / 32767 * 255)

                self.set_axis(SDL_AXIS_MAP[axis], value)
Ejemplo n.º 12
0
    def __init__(self, game):
        if sdl2.SDL_Init(sdl2.SDL_INIT_JOYSTICK) != 0:
            raise ("Coudldn't initialise joysticks")

        self.quit = False
        self.game_pads = [GamePad(game), GamePad(game)]

        self.key_map = {}
        self.key_map[eActions.up] = [sdl2.SDLK_UP]
        self.key_map[eActions.right] = [sdl2.SDLK_RIGHT]
        self.key_map[eActions.down] = [sdl2.SDLK_DOWN]
        self.key_map[eActions.left] = [sdl2.SDLK_LEFT]

        self.key_map[eActions.up1] = [sdl2.SDLK_w]
        self.key_map[eActions.right1] = [sdl2.SDLK_d]
        self.key_map[eActions.down1] = [sdl2.SDLK_s]
        self.key_map[eActions.left1] = [sdl2.SDLK_a]

        self.key_map[eActions.jump] = [sdl2.SDLK_SPACE]
        self.key_map[eActions.attack_small] = [sdl2.SDLK_g]
        self.key_map[eActions.attack_big] = [sdl2.SDLK_b]
        self.key_map[eActions.block] = [sdl2.SDLK_f]

        self.key_map[eActions.pause] = [sdl2.SDLK_p, sdl2.SDLK_ESCAPE]
        self.key_map[eActions.quit] = [sdl2.SDLK_q, sdl2.SDLK_ESCAPE]
        self.key_map[eActions.fullscreen] = [sdl2.SDLK_f]
        self.key_map[eActions.select] = [sdl2.SDLK_TAB, sdl2.SDLK_o]

        self.controllers = {}

        if sdl2.SDL_NumJoysticks() > 0:
            for joy in range(sdl2.SDL_NumJoysticks()):
                if sdl2.SDL_IsGameController(joy):
                    self.controllers[joy] = (GameController(
                        handler=sdl2.SDL_GameControllerOpen(joy),
                        joy_number=joy))
            if len(self.controllers) > 2:
                self.game_pads.append(GamePad(game))
Ejemplo n.º 13
0
    print("Unable to open device")
    sdl2.SDL_Quit()
    exit(0)
else:
    mappings = sdl2.SDL_GameControllerAddMappingsFromFile(
        b'gamecontrollerdb.txt')

    if sdl2.SDL_IsGameController(index) == 0:
        print("Device", index, "does not support GameController Mode")
        sdl2.SDL_Quit()
        exit(0)

    name = sdl2.SDL_GameControllerNameForIndex(index)
    print("Using Device", index, ":", name)

    gamecontroller = sdl2.SDL_GameControllerOpen(index)
    if gamecontroller == None:
        print("Unable to open gamecontroller")
        sdl2.SDL_Quit()
        exit(0)

# -------------------------------
# connect to the control channel
print("Connecting to", addr)
ctx = zmq.Context()

master = ctx.socket(zmq.REQ)
master.connect(addr)

master.send_json({"ProtocolVersion": 1, "Code": 2})
answer = master.recv_json()
Ejemplo n.º 14
0
    def __new__(cls, identifier=None, instance_id=None, *args, **kwargs):
        # Check init
        if not get_init():
            init()

        # Create the object
        joy = super().__new__(cls)

        if instance_id is not None:
            # Create the underlying joystick from the instance id.
            # SDL_JOYDEVICEREMOVED and all other SDL_JOY#### events give the instance id
            joy.joystick = sdl2.SDL_JoystickFromInstanceID(instance_id)
            # print('Instance ID:', raw_joystick, SDL_JoystickGetAttached(raw_joystick))
        else:
            # Create the underlying joystick from the enumerated identifier
            # SDL_JOYDEVICEADDED and SDL_NumJoysticks use open
            if identifier is None:
                identifier = 0
            if isinstance(identifier, str):
                # Get the joystick from the name or None if not found!
                for i in range(sdl2.SDL_NumJoysticks()):
                    raw_joystick = sdl2.SDL_JoystickOpen(i)
                    try:
                        if sdl2.SDL_JoystickName(raw_joystick).decode(
                                'utf-8') == identifier:
                            joy.joystick = raw_joystick
                            break
                    except:
                        pass
            else:
                joy.joystick = sdl2.SDL_JoystickOpen(identifier)
            # print('ID:', raw_joystick, SDL_JoystickGetAttached(raw_joystick))

        try:
            joy.identifier = sdl2.SDL_JoystickID(
                sdl2.SDL_JoystickInstanceID(joy.joystick)).value
            # joy.identifier = SDL_JoystickInstanceID(raw_joystick)
            joy.name = sdl2.SDL_JoystickName(joy.joystick).decode('utf-8')
            joy.numaxes = sdl2.SDL_JoystickNumAxes(joy.joystick)
            joy.numbuttons = sdl2.SDL_JoystickNumButtons(joy.joystick)
            joy.numhats = sdl2.SDL_JoystickNumHats(joy.joystick)
            joy.numballs = sdl2.SDL_JoystickNumBalls(joy.joystick)
            joy.init_keys()
        except:
            pass

        # Try to get the gamepad object
        try:
            joy.gamecontroller = sdl2.SDL_GameControllerOpen(joy.identifier)
            # FromInstanceId does not Attach!
            # joy.gamecontroller = SDL_GameControllerFromInstanceID(SDL_JoystickInstanceID(joy.joystick)
            # print('ID:', SDL_GameControllerGetAttached(joy.gamecontroller))
        except:
            joy.gamecontroller = None

        try:
            joy.guid = get_guid(
                joy.joystick
            )  # Using this is more reliable for the GameController stuff
        except:
            pass

        return joy