Skip to content

Instantly share code, notes, and snippets.

@dholth
Created April 7, 2019 00:59
Show Gist options
  • Save dholth/3e96ee718646bbe6b081a1a7a78c9268 to your computer and use it in GitHub Desktop.
Save dholth/3e96ee718646bbe6b081a1a7a78c9268 to your computer and use it in GitHub Desktop.
add gamecontroller to kivy?
"""
Game controller input for Kivy.
Open game controllers as they become available, expose with full SDL2 API.
"""
# special version of sdl (pysdl2-cffi) that doesn't explictly link to a particular version
import sdl
JOYSTICK_EVENTS = (
sdl.JoyDeviceEvent,
sdl.JoyAxisEvent,
sdl.JoyHatEvent,
sdl.JoyBallEvent,
sdl.JoyButtonEvent,
sdl.ControllerDeviceEvent,
sdl.ControllerAxisEvent,
sdl.ControllerButtonEvent,
)
@sdl.ffi.callback("int (void *, SDL_Event *)")
def eventWatch(data, event):
event = sdl.Event(event)
sdl.ffi.from_handle(data).event(event)
return 1
class KivyController:
"""
Manage SDL2 joysticks.
"""
def __init__(self):
self._handle = sdl.ffi.new_handle(self)
def install(self):
"""
Attach to SDL2 event loop
"""
sdl.init(sdl.INIT_GAMECONTROLLER|sdl.INIT_JOYSTICK)
sdl.addEventWatch(eventWatch, self._handle)
self.joysticks = {}
self.controllers = {}
def event(self, event: sdl.Event):
"""
Handle wrapped SDL2 event
"""
event = event.unwrapEvent()
if isinstance(event, JOYSTICK_EVENTS):
print(event)
if isinstance(event, sdl.ControllerDeviceEvent):
if event.type == sdl.CONTROLLERDEVICEADDED:
j = sdl.gameControllerOpen(event.which)
self.controllers[j.gameControllerGetJoystick().joystickInstanceID()] = j
elif event.type == sdl.CONTROLLERDEVICEREMOVED:
j = self.controllers.pop(event.which)
j.gameControllerClose()
elif isinstance(event, sdl.JoyDeviceEvent):
if event.type == sdl.JOYDEVICEADDED:
j = sdl.joystickOpen(event.which)
self.joysticks[j.joystickInstanceID()] = j
elif event.type == sdl.JOYDEVICEREMOVED:
j = self.joysticks.pop(event.which)
# need to close?
j.joystickClose()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment