Beispiel #1
0
    def input_config(self):
        self.pages_list = [None, None, None, None, None]
        self.gamepads_stored = [None, None, None, None, None]

        input_notebook = Gtk.Notebook()
        input_notebook.set_vexpand(True)
        input_notebook.connect("switch-page", self.on_change_page)

        # Tab "Player 1"#
        player1_tab = Gtk.Label(label="Player1")
        player1_box = Gtk.VBox()

        area_input1 = self.input_page('Input-SDL-Control1')
        player1_box.pack_start(area_input1, False, False, 0)

        input_notebook.append_page(player1_box, player1_tab)

        # Tab "Player 2"
        player2_tab = Gtk.Label(label="Player2")
        player2_box = Gtk.VBox()

        area_input2 = self.input_page('Input-SDL-Control2')
        player2_box.pack_start(area_input2, False, False, 0)

        input_notebook.append_page(player2_box, player2_tab)

        # Tab "Player 3"
        player3_tab = Gtk.Label(label="Player3")
        player3_box = Gtk.VBox()

        area_input3 = self.input_page('Input-SDL-Control3')
        player3_box.pack_start(area_input3, False, False, 0)

        input_notebook.append_page(player3_box, player3_tab)

        # Tab "Player 4"
        player4_tab = Gtk.Label(label="Player4")
        player4_box = Gtk.VBox()

        area_input4 = self.input_page('Input-SDL-Control4')
        player4_box.pack_start(area_input4, False, False, 0)

        input_notebook.append_page(player4_box, player4_tab)

        dialog_box = self.plugin_window.get_content_area()
        dialog_box.add(input_notebook)

        #sdl.SDL_SetHint(sdl.SDL_HINT_JOYSTICK_ALLOW_BACKGROUND_EVENTS, b"1")
        sdl.SDL_InitSubSystem(
            sdl.SDL_INIT_VIDEO)  #necessary for SDL_GetKeyFromScancode
        sdl.SDL_InitSubSystem(sdl.SDL_INIT_JOYSTICK)
        thread = threading.Thread(name="Polling", target=self.poll_sdl_events)
        try:
            thread.start()
        except:
            log.error("The polling thread has encountered an unexpected error")
            threading.main_thread()
Beispiel #2
0
    def _init_audio(self):
        if sdl2.SDL_InitSubSystem(sdl2.SDL_INIT_AUDIO) != 0:
            raise RuntimeError("Failed to init audio")

        nsamples = self.chunksize * self.nchannels
        # For some reason, on OS X, this is 2x bigger than expected.
        # HACK!
        import sys

        if sys.platform == "darwin":
            nsamples = int(nsamples / 2)

        self._audio_spec = sdl2.SDL_AudioSpec(
            self.R,
            # sdl2.AUDIO_S16MSB,
            sdl2.AUDIO_S16LSB,  # endianness eek!
            self.nchannels,
            nsamples,
            sdl2.SDL_AudioCallback(self._handle_audio_cb),
        )

        self._devid = sdl2.SDL_OpenAudioDevice(None, 0, self._audio_spec, None,
                                               0)
        # start playing (well-named function!)
        sdl2.SDL_PauseAudioDevice(self._devid, 0)
Beispiel #3
0
    def __init__(self):
        super(SDLInputHandler, self).__init__()

        sdl2.SDL_InitSubSystem(sdl2.SDL_INIT_GAMECONTROLLER)
        ret = sdl2.SDL_GameControllerAddMappingsFromFile(
            os.path.join(os.path.dirname(__file__),
                         'controller_db.txt').encode('utf-8'))

        if ret == -1:
            raise InputError("Failed to load GameControllerDB, %s",
                             sdl2.SDL_GetError())
Beispiel #4
0
    def open(self, configuration):
        '''Open the SDL2 Window

        *Parameters:*

        - `configuration`: Configurations parameters from Application
        '''
        if sdl2.SDL_InitSubSystem(sdl2.SDL_INIT_VIDEO) != 0:
            msg = "Can't open window: %s" % sdl2.SDL_GetError()
            logger.critical(msg)
            raise SDL2Error(msg)

        flags = 0
        if configuration.fullscreen and \
           configuration.width and configuration.height:
            flags |= sdl2.SDL_WINDOW_FULLSCREEN
        elif configuration.fullscreen:
            flags |= sdl2.SDL_WINDOW_FULLSCREEN_DESKTOP
        if not configuration.decorated:
            flags |= sdl2.SDL_WINDOW_BORDERLESS
        if configuration.resizable:
            flags |= sdl2.SDL_WINDOW_RESIZABLE
        if configuration.highdpi:
            flags |= sdl2.SDL_WINDOW_ALLOW_HIGHDPI

        self.window = sdl2.SDL_CreateWindow(configuration.name.encode('ascii'),
                                            configuration.x, configuration.y,
                                            configuration.width,
                                            configuration.height, flags)

        if not self.window:
            msg = "Can't open window: %s" % sdl2.SDL_GetError()
            logger.critical(msg)
            raise SDL2Error(msg)

        logger.debug("SDL2 window opened with configuration: %s",
                     (configuration, ))

        self.info = sdl2.SDL_SysWMinfo()
        sdl2.SDL_VERSION(self.info.version)
        sdl2.SDL_GetWindowWMInfo(self.window, ctypes.byref(self.info))
Beispiel #5
0
    def open(self, configuration):
        '''Open and configure audio system

        *Parameters:*

        - `configuration`: Configuration parameters from Application
        '''
        if sdl2.SDL_InitSubSystem(sdl2.SDL_INIT_AUDIO) != 0:
            msg = "Cannot initialize audio system: %s" % sdl2.SDL_GetError()
            logger.critical(msg)
            raise SDL2Error(msg)

        if mixer.Mix_OpenAudio(mixer.MIX_DEFAULT_FREQUENCY,
                               mixer.MIX_DEFAULT_FORMAT, 2, 1024):
            msg = "Cannot open mixed audio: %s" % mixer.Mix_GetError()
            logger.critical(msg)
            raise SDL2Error(msg)

        mixer.Mix_AllocateChannels(configuration.audio_channel)

        logger.info("Audio initialized")
 def open(self, client):
     sdl2.SDL_InitSubSystem(sdl2.SDL_INIT_AUDIO)
Beispiel #7
0
    def __init__(self,
                 perhiperal_type=Input.Type.JOYSTICK,
                 verbosity=0,
                 silent=False):
        self.atari = jigo2600.Atari2600()
        self.speed = 1
        self.max_fps = 60.
        self.aspect = 1.8
        self.paused = False
        self.done = False
        self.verbosity = verbosity
        self.cart_db = None
        self.cart_sha1 = None
        self.cart_meta = None
        self.peripheral_type = Input.Type.JOYSTICK
        self.switches_interface = SwitchesInterface()
        self.joysticks_interface = JoystickInterface()
        self.paddles_interface = PaddleInterface()
        self.input_stream = InputStream()
        self.has_sdl_audio = False
        self.has_sdl_gamecontroller = False
        self.has_sdl_joystick = False

        # Load the cartridge database.
        try:
            data = pkgutil.get_data('jigo2600',
                                    'cartridges.json').decode("utf8")
            self.cart_db = json.loads(data)
            del data
        except FileNotFoundError:
            if self.verbosity > 0:
                print(f'Warning: could not open the cartridge metadata file')

        # Setup the graphics.
        frame = self.atari.get_current_frame()
        if sdl2.SDL_Init(sdl2.SDL_INIT_VIDEO) != 0:
            print(sdl2.SDL_GetError())
            sys.exit(-1)
        self.screen = sdl2.SDL_CreateWindow(
            b"Atari2600", sdl2.SDL_WINDOWPOS_UNDEFINED,
            sdl2.SDL_WINDOWPOS_UNDEFINED, int(frame.width * self.aspect * 2),
            int(frame.height * 2),
            sdl2.SDL_WINDOW_SHOWN | sdl2.SDL_WINDOW_RESIZABLE)
        if not self.screen:
            print(sdl2.SDL_GetError())
            sys.exit(-1)
        self.renderer = sdl2.SDL_CreateRenderer(self.screen, -1,
                                                sdl2.SDL_RENDERER_PRESENTVSYNC)
        self.texture = sdl2.SDL_CreateTexture(self.renderer,
                                              sdl2.SDL_PIXELFORMAT_BGRA32,
                                              sdl2.SDL_TEXTUREACCESS_STREAMING,
                                              frame.width, frame.height)

        # Setup the audio.
        self.has_sdl_audio = not silent and (sdl2.SDL_InitSubSystem(
            sdl2.SDL_INIT_AUDIO) == 0)
        if self.has_sdl_audio:
            self.audio_spec = sdl2.SDL_AudioSpec(
                44100, sdl2.AUDIO_U8, 1, 1024,
                sdl2.SDL_AudioCallback(self.play_audio))
            self.audio_dev = sdl2.SDL_OpenAudioDevice(None, 0, self.audio_spec,
                                                      self.audio_spec, 0)
            self.audio_buffer_rate = self.audio_spec.freq / self.audio_spec.samples
            assert self.audio_spec.channels == 1

        # Setup the joysticks.
        self.has_sdl_joystick = (sdl2.SDL_InitSubSystem(
            sdl2.SDL_INIT_JOYSTICK) == 0)
        if self.has_sdl_joystick:
            sdl2.SDL_SetHint(sdl2.SDL_HINT_JOYSTICK_ALLOW_BACKGROUND_EVENTS,
                             b"1")
            sdl2.SDL_JoystickEventState(sdl2.SDL_ENABLE)

        # Setup the game controllers.
        self.has_sdl_gamecontroller = (sdl2.SDL_InitSubSystem(
            sdl2.SDL_INIT_GAMECONTROLLER) == 0)
        if self.has_sdl_gamecontroller:
            sdl2.SDL_GameControllerEventState(sdl2.SDL_ENABLE)
            data = pkgutil.get_data("jigo2600", "gamecontrollerdb.txt")
            rw = sdl2.SDL_RWFromConstMem(data, len(data))
            n = sdl2.SDL_GameControllerAddMappingsFromRW(rw, False)
            if self.verbosity > 0:
                if n == -1:
                    print(
                        f"Warning: could not load the controller database file"
                    )
                else:
                    print(f"Loaded {n} game controller mappings")
Beispiel #8
0
 def __init__(self, app):
     self.app = app
     self.ui = self.app.ui
     # read from binds.cfg file or create it from template
     # exec results in edit_binds, a dict whose keys are keys+mods
     # and whose values are bound functions
     self.edit_bind_src = None
     # bad probs if a command isn't in binds.cfg, so just blow it away
     # if the template is newer than it
     # TODO: better solution is find any binds in template but not binds.cfg
     # and add em
     binds_filename = self.app.config_dir + BINDS_FILENAME
     binds_outdated = not os.path.exists(
         binds_filename) or os.path.getmtime(
             binds_filename) < os.path.getmtime(BINDS_TEMPLATE_FILENAME)
     if not binds_outdated and os.path.exists(binds_filename):
         exec(open(binds_filename).read())
         self.app.log('Loaded key binds from %s' % binds_filename)
     else:
         default_data = open(BINDS_TEMPLATE_FILENAME).readlines()[1:]
         new_binds = open(binds_filename, 'w')
         new_binds.writelines(default_data)
         new_binds.close()
         self.app.log('Created new key binds file %s' % binds_filename)
         exec(''.join(default_data))
     if not self.edit_bind_src:
         self.app.log('No bind data found, Is binds.cfg.default present?')
         exit()
     # associate key + mod combos with methods
     self.edit_binds = {}
     for bind_string in self.edit_bind_src:
         bind = self.parse_key_bind(bind_string)
         if not bind:
             continue
         # bind data could be a single item (string) or a list/tuple
         bind_data = self.edit_bind_src[bind_string]
         if type(bind_data) is str:
             bind_fnames = ['BIND_%s' % bind_data]
         else:
             bind_fnames = ['BIND_%s' % s for s in bind_data]
         bind_functions = []
         for bind_fname in bind_fnames:
             if not hasattr(self, bind_fname):
                 continue
             bind_functions.append(getattr(self, bind_fname))
         self.edit_binds[bind] = bind_functions
     # get controller(s)
     # TODO: use kewl SDL2 gamepad system
     js_init = sdl2.SDL_InitSubSystem(sdl2.SDL_INIT_JOYSTICK)
     if js_init != 0:
         self.app.log(
             "SDL2: Couldn't initialize joystick subsystem, code %s" %
             js_init)
         return
     sticks = sdl2.SDL_NumJoysticks()
     #self.app.log('%s gamepads found' % sticks)
     self.gamepad = None
     self.gamepad_left_x, self.gamepad_left_y = 0, 0
     # for now, just grab first pad
     if sticks > 0:
         pad = sdl2.SDL_JoystickOpen(0)
         pad_name = sdl2.SDL_JoystickName(pad).decode('utf-8')
         pad_axes = sdl2.SDL_JoystickNumAxes(pad)
         pad_buttons = sdl2.SDL_JoystickNumButtons(pad)
         self.app.log('Gamepad found: %s with %s axes, %s buttons' %
                      (pad_name, pad_axes, pad_buttons))
         self.gamepad = pad
     # before main loop begins, set initial mouse position -
     # SDL_GetMouseState returns 0,0 if the mouse hasn't yet moved
     # in the new window!
     wx, wy = ctypes.c_int(0), ctypes.c_int(0)
     sdl2.SDL_GetWindowPosition(self.app.window, wx, wy)
     wx, wy = int(wx.value), int(wy.value)
     mx, my = ctypes.c_int(0), ctypes.c_int(0)
     sdl2.mouse.SDL_GetGlobalMouseState(mx, my)
     mx, my = int(mx.value), int(my.value)
     self.app.mouse_x, self.app.mouse_y = mx - wx, my - wy
     # set flag so we know whether handle_input's SDL_GetMouseState result
     # is accurate :/
     self.mouse_has_moved = False