Esempio n. 1
0
def video_autoinit():
    if not sdl.SDL_WasInit(sdl.SDL_INIT_VIDEO):
        pre_video_init()
        if sdl.SDL_InitSubSystem(sdl.SDL_INIT_VIDEO):
            return False
        sdl.SDL_EnableUNICODE(1)
    return True
Esempio n. 2
0
    def set_palette(self, colors):
        """ set_palette([RGB, RGB, RGB, ...]) -> None
        set the color palette for an 8bit Surface
        """
        palette = self._format.palette
        if not palette:
            raise SDLError("Surface has no palette")
        if not hasattr(colors, '__iter__'):
            raise ValueError("Argument must be a sequence type")
        if not sdl.SDL_WasInit(sdl.SDL_INIT_VIDEO):
            raise SDLError(
                "cannot set palette without pygame.display initialized")

        length = min(palette.ncolors, len(colors))
        c_colors = ffi.new('SDL_Color[]', length)
        for i in range(length):
            rgb = colors[i]
            if (not hasattr(rgb, '__iter__')) or len(rgb) < 3 or len(rgb) > 4:
                raise ValueError("takes a sequence of integers of RGB")
            c_colors[i].r = rgb[0]
            c_colors[i].g = rgb[1]
            c_colors[i].b = rgb[2]
            if len(rgb) == 4 and rgb[3] != 255:
                raise ValueError("takes an alpha value of 255")
        sdl.SDL_SetColors(self._c_surface, c_colors, 0, length)
Esempio n. 3
0
def get_busy():
    """get_busy(): return bool

       test if any sound is being mixed"""
    if not sdl.SDL_WasInit(sdl.SDL_INIT_AUDIO):
        return False
    return sdl.Mix_Playing(-1) != 0
Esempio n. 4
0
def autoinit():
    if not sdl.SDL_WasInit(sdl.SDL_INIT_JOYSTICK):
        if sdl.SDL_InitSubSystem(sdl.SDL_INIT_JOYSTICK):
            return False
        sdl.SDL_JoystickEventState(sdl.SDL_ENABLE)
        register_quit(autoquit)
    return True
Esempio n. 5
0
 def __del__(self):
     if self._c_surface and (sdl.SDL_WasInit(sdl.SDL_INIT_VIDEO) or not \
                             (self._c_surface.flags & sdl.SDL_HWSURFACE)):
         sdl.SDL_FreeSurface(self._c_surface)
     self._c_surface = None
     self._format = None
     self._w = None
     self._h = None
Esempio n. 6
0
def autoquit():
    for joydata in Joystick._OPEN_JOYSTICKS:
        sdl.SDL_JoystickClose(joydata)
    Joystick._OPEN_JOYSTICKS.clear()

    if sdl.SDL_WasInit(sdl.SDL_INIT_JOYSTICK):
        sdl.SDL_JoystickEventState(sdl.SDL_DISABLE)
        sdl.SDL_QuitSubSystem(sdl.SDL_INIT_JOYSTICK)
Esempio n. 7
0
def _timer_callback(interval, param):
    if sdl.SDL_WasInit(sdl.SDL_INIT_VIDEO):
        event = ffi.new("SDL_Event*")
        event.type = ffi.cast("intptr_t", param)
        # SDL will make a copy of the event while handling SDL_PushEvent,
        # so we don't need to hold the allocated memory after this call.
        sdl.SDL_PushEvent(event)
    return interval
Esempio n. 8
0
def autoinit(frequency=None, size=None, channels=None, chunksize=None):
    if not frequency:
        frequency = _request_frequency
    if not size:
        size = _request_size
    if not channels:
        channels = _request_stereo
    if not chunksize:
        chunksize = _request_chunksize

    if channels >= 2:
        channels = 2
    else:
        channels = 1

    # chunk must be a power of 2
    chunksize = int(math.log(chunksize, 2))
    chunksize = 2**chunksize
    if chunksize < buffer:
        chunksize *= 2

    # fmt is a bunch of flags
    if size == 8:
        fmt = sdl.AUDIO_U8
    elif size == -8:
        fmt = sdl.AUDIO_S8
    elif size == 16:
        fmt = sdl.AUDIO_U16SYS
    elif size == -16:
        fmt = sdl.AUDIO_S16SYS
    else:
        raise ValueError("unsupported size %d" % size)

    global _numchanneldata, _channeldata
    if not sdl.SDL_WasInit(sdl.SDL_INIT_AUDIO):
        register_quit(autoquit)
        # channel stuff
        if not _channeldata:
            _numchanneldata = sdl.MIX_CHANNELS
            _channeldata = [ChannelData() for i in range(_numchanneldata)]

        if sdl.SDL_InitSubSystem(sdl.SDL_INIT_AUDIO) == -1:
            return False

        if sdl.Mix_OpenAudio(frequency, fmt, channels, chunksize) == -1:
            sdl.SDL_QuitSubSystem(sdl.SDL_INIT_AUDIO)
            return False
        sdl.Mix_ChannelFinished(_endsound_callback)
        # TODO: reverse stereo for 8-bit below SDL 1.2.8
        sdl.Mix_VolumeMusic(127)
    return True
Esempio n. 9
0
def _endmusic_callback():
    global _current_music, _queue_music, _music_pos, _music_pos_time
    if _endmusic_event is not None and sdl.SDL_WasInit(sdl.SDL_INIT_AUDIO):
        event.post(event.Event(_endmusic_event))

    if _queue_music:
        if _current_music:
            sdl.Mix_FreeMusic(_current_music)
        _current_music = _queue_music
        _queue_music = None
        sdl.Mix_HookMusicFinished(_endmusic_callback)
        _music_pos = 0
        sdl.Mix_PlayMusic(_current_music, 0)
    else:
        _music_pos_time = -1
        sdl.Mix_SetPostMix(ffi.NULL, ffi.NULL)
Esempio n. 10
0
def get_init():
    """get_init(): return (frequency, format, channels)

       test if the mixer is initialized"""
    if not sdl.SDL_WasInit(sdl.SDL_INIT_AUDIO):
        return None

    freq = ffi.new("int *")
    audioformat = ffi.new("uint16_t *")
    chan = ffi.new("int *")
    if not sdl.Mix_QuerySpec(freq, audioformat, chan):
        return None
    if audioformat[0] & ~0xff:
        format_in_bits = -(audioformat[0] & 0xff)
    else:
        format_in_bits = audioformat[0] & 0xff
    return (int(freq[0]), format_in_bits, int(chan[0]))
Esempio n. 11
0
def autoquit():
    global _channeldata, _numchanneldata, _current_music, \
           _queue_music
    if sdl.SDL_WasInit(sdl.SDL_INIT_AUDIO):
        sdl.Mix_HaltMusic()
        # cleanup
        if _channeldata:
            _channeldata = None
            _numchanneldata = 0
        if _current_music:
            sdl.Mix_FreeMusic(_current_music)
            _current_music = None
        if _queue_music:
            sdl.Mix_FreeMusic(_queue_music)
            _queue_music = None

        sdl.Mix_CloseAudio()
        sdl.SDL_QuitSubSystem(sdl.SDL_INIT_AUDIO)
Esempio n. 12
0
 def convert(self, arg=None, flags=0):
     with locked(self._c_surface):
         if isinstance(arg, Surface):
             flags = arg._c_surface.flags | (
                 self._c_surface.flags &
                 (sdl.SDL_SRCCOLORKEY | sdl.SDL_SRCALPHA))
             newsurf = sdl.SDL_ConvertSurface(self._c_surface, arg._format,
                                              flags)
         elif arg is None:
             if sdl.SDL_WasInit(sdl.SDL_INIT_VIDEO):
                 newsurf = sdl.SDL_DisplayFormat(self._c_surface)
             else:
                 newsurf = sdl.SDL_ConvertSurface(self._c_surface,
                                                  self._format,
                                                  self._c_surface.flags)
         else:
             xxx
     return Surface._from_sdl_surface(newsurf)
Esempio n. 13
0
    def set_palette_at(self, index, rgb):
        """ set_palette_at(index, RGB) -> None
        set the color for a single index in an 8bit Surface palette
        """
        palette = self._format.palette
        if not palette:
            raise SDLError("Surface has no palette")
        if index < 0 or index >= palette.ncolors:
            raise IndexError("index out of bounds")
        if not sdl.SDL_WasInit(sdl.SDL_INIT_VIDEO):
            raise SDLError("cannot set palette without pygame.display initialized")
        if (not hasattr(rgb, '__iter__')) or len(rgb) < 3 or len(rgb) > 4:
            raise ValueError("takes a sequence of integers of RGB for argument 2")

        color = ffi.new('SDL_Color*')
        color[0].r = rgb[0]
        color[0].g = rgb[1]
        color[0].b = rgb[2]
        sdl.SDL_SetColors(self._c_surface, color, index, 1)
Esempio n. 14
0
def _endmusic_callback():
    global _current_music, _queue_music, _music_pos, _music_pos_time
    if _endmusic_event is not None and sdl.SDL_WasInit(sdl.SDL_INIT_AUDIO):
        # Pygame doesn't do the same checks for this path as in
        # event.post, and people rely on that, so we also duplicate
        # the logic
        event = ffi.new('SDL_Event*')
        event.type = _endmusic_event
        sdl.SDL_PushEvent(event)

    if _queue_music:
        if _current_music:
            sdl.Mix_FreeMusic(_current_music)
        _current_music = _queue_music
        _queue_music = None
        sdl.Mix_HookMusicFinished(_endmusic_callback)
        _music_pos = 0
        sdl.Mix_PlayMusic(_current_music, 0)
    else:
        _music_pos_time = -1
        sdl.Mix_SetPostMix(ffi.NULL, ffi.NULL)
Esempio n. 15
0
def _endsound_callback(channelnum):
    if not _channeldata:
        return

    data = _channeldata[channelnum]
    # post sound ending event
    if data.endevent != sdl.SDL_NOEVENT and sdl.SDL_WasInit(sdl.SDL_INIT_VIDEO):
        event = ffi.new('SDL_Event*')
        event.type = data.endevent
        if event.type >= sdl.SDL_USEREVENT and event.type < sdl.SDL_NUMEVENTS:
            event.user.code = channelnum
        sdl.SDL_PushEvent(event)

    if data.queue:
        sound_chunk = data.sound.chunk
        data.sound = data.queue
        data.queue = None
        channelnum = sdl.Mix_PlayChannelTimed(channelnum, sound_chunk, 0, -1)
        if channelnum != -1:
            sdl.Mix_GroupChannel(channelnum, data.sound._chunk_tag)
    else:
        data.sound = None
Esempio n. 16
0
def _get_init():
    return sdl.SDL_WasInit(sdl.SDL_INIT_TIMER)
Esempio n. 17
0
def _check_init():
    if not sdl.SDL_WasInit(sdl.SDL_INIT_JOYSTICK):
        raise SDLError("joystick system not initialized")
Esempio n. 18
0
def get_init():
    """ get_init() -> bool
    Returns True if the joystick module is initialized.
    """
    return sdl.SDL_WasInit(sdl.SDL_INIT_JOYSTICK) != 0
Esempio n. 19
0
def get_init():
    """ get_init() -> bool
    Returns True if the display module has been initialized
    """
    return sdl.SDL_WasInit(sdl.SDL_INIT_VIDEO) != 0
Esempio n. 20
0
    def __init__(self, size, flags=0, depth=0, masks=None):
        w, h = unpack_rect(size)

        if isinstance(depth, Surface):
            if masks:
                raise ValueError(
                    "cannot pass surface for depth and color masks")
            surface = depth
            depth = 0
        else:
            surface = None
            depth = int(depth)

        if depth and masks:
            Rmask, Gmask, Bmask, Amask = masks
            bpp = depth

        elif surface is None:
            if depth:
                bpp = depth
                Rmask, Gmask, Bmask, Amask = \
                    self._get_default_masks(bpp, False)
            elif sdl.SDL_GetVideoSurface():
                pix = sdl.SDL_GetVideoSurface().format
                bpp = pix.BitsPerPixel
                Amask = pix.Amask
                Rmask = pix.Rmask
                Gmask = pix.Gmask
                Bmask = pix.Bmask
            elif sdl.SDL_WasInit(sdl.SDL_INIT_VIDEO):
                pix = sdl.SDL_GetVideoInfo().vfmt
                bpp = pix.BitsPerPixel
                Amask = pix.Amask
                Rmask = pix.Rmask
                Gmask = pix.Gmask
                Bmask = pix.Bmask
            else:
                bpp = 32
                Rmask, Gmask, Bmask, Amask = \
                    self._get_default_masks(32, False)
            # the alpha mask might be different - must update
            if flags & sdl.SDL_SRCALPHA:
                Rmask, Gmask, Bmask, Amask = \
                    self._get_default_masks(bpp, True)

        # depth argument was a Surface object
        else:
            pix = surface._c_surface.format
            bpp = pix.BitsPerPixel
            if flags & sdl.SDL_SRCALPHA:
                Rmask, Gmask, Bmask, Amask = \
                    self._get_default_masks(bpp, True)
            else:
                Amask = pix.Amask
                Rmask = pix.Rmask
                Gmask = pix.Gmask
                Bmask = pix.Bmask

        self._c_surface = sdl.SDL_CreateRGBSurface(flags, w, h, bpp, Rmask,
                                                   Gmask, Bmask, Amask)
        self._format = self._c_surface.format
        self._w = self._c_surface.w
        self._h = self._c_surface.h

        if not self._c_surface:
            raise SDLError.from_sdl_error()

        if masks:
            """
            Confirm the surface was created correctly (masks were valid).
            Also ensure that 24 and 32 bit surfaces have 8 bit fields
            (no losses).
            """
            format = self._format
            Rmask = (0xFF >> format.Rloss) << format.Rshift
            Gmask = (0xFF >> format.Gloss) << format.Gshift
            Bmask = (0xFF >> format.Bloss) << format.Bshift
            Amask = (0xFF >> format.Aloss) << format.Ashift
            bad_loss = format.Rloss or format.Gloss or format.Bloss
            if flags & sdl.SDL_SRCALPHA:
                bad_loss = bad_loss or format.Aloss
            else:
                bad_loss = bad_loss or format.Aloss != 8
            if (format.Rmask != Rmask or format.Gmask != Gmask
                    or format.Bmask != Bmask or format.Amask != Amask
                    or (format.BytesPerPixel >= 3 and bad_loss)):
                # Note: don't free _c_surface here. It will
                # be done in __del__.
                raise ValueError("Invalid mask values")
Esempio n. 21
0
    def blit(self, source, dest, area=None, special_flags=0):
        """ blit(source, dest, area=None, special_flags = 0) -> Rect
        draw one image onto another
        """
        if not self._c_surface or not source._c_surface:
            raise SDLError("display Surface quit")
        if self.is_pure_opengl():
            raise SDLError("Cannot blit to OPENGL Surfaces (OPENGLBLIT is ok)")

        srcrect = ffi.new('SDL_Rect*')
        destrect = ffi.new('SDL_Rect*')
        if area is not None:
            srcrect.x, srcrect.y, srcrect.w, srcrect.h = \
                    rect_vals_from_obj(area)
        else:
            srcrect.w = source._w
            srcrect.h = source._h
        if isinstance(dest, tuple) and len(dest) == 2:
            destrect.x = int(dest[0])
            destrect.y = int(dest[1])
            destrect.w = source._w
            destrect.h = source._h
        else:
            destrect.x, destrect.y, destrect.w, destrect.h = \
                    rect_vals_from_obj(dest)

        c_dest = self._c_surface
        c_src = source._c_surface
        c_subsurface = None
        flags = special_flags

        if self.subsurfacedata:
            owner = self.subsurfacedata.owner
            c_subsurface = owner._c_surface
            suboffsetx = self.subsurfacedata.xoffset
            suboffsety = self.subsurfacedata.yoffset
            while owner.subsurfacedata:
                subdata = owner.subsurfacedata
                owner = subdata.owner
                c_subsurface = owner._c_surface
                suboffsetx += subdata.xoffset
                suboffsety += subdata.yoffset

            orig_clip = ffi.new('SDL_Rect*')
            sub_clip = ffi.new('SDL_Rect*')
            sdl.SDL_GetClipRect(c_subsurface, orig_clip)
            sdl.SDL_GetClipRect(self._c_surface, sub_clip)
            sub_clip[0].x += suboffsetx
            sub_clip[0].y += suboffsety
            sdl.SDL_SetClipRect(c_subsurface, sub_clip)
            destrect.x += suboffsetx
            destrect.y += suboffsety
            c_dest = c_subsurface

        # TODO: implement special blend flags
        # these checks come straight from pygame - copied comments
        if (c_dest.format.Amask and (c_dest.flags & sdl.SDL_SRCALPHA)
                and not (c_src.format.Amask
                         and not (c_src.flags & sdl.SDL_SRCALPHA))
                and (c_dest.format.BytesPerPixel == 2
                     or c_dest.format.BytesPerPixel == 4)):
            # SDL works for 2 and 4 bytes
            res = sdl.pygame_Blit(c_src, srcrect, c_dest, destrect, flags)
        elif flags or (c_src.flags & (sdl.SDL_SRCALPHA | sdl.SDL_SRCCOLORKEY)
                       and c_dest.pixels == c_src.pixels
                       and check_surface_overlap(c_src, srcrect, c_dest,
                                                 destrect)):
            '''
            This simplification is possible because a source subsurface
            is converted to its owner with a clip rect and a dst
            subsurface cannot be blitted to its owner because the
            owner is locked.
            '''
            res = sdl.pygame_Blit(c_src, srcrect, c_dest, destrect, flags)
        # can't blit alpha to 8bit, crashes SDL
        elif (c_dest.format.BytesPerPixel == 1
              and (c_src.format.Amask or c_src.flags & sdl.SDL_SRCALPHA)):
            if c_src.format.BytesPerPixel == 1:
                res = sdl.pygame_Blit(c_src, srcrect, c_dest, destrect, 0)
            elif sdl.SDL_WasInit(sdl.SDL_INIT_VIDEO):
                # TODO: SDL_DisplayFormat segfaults
                c_src = sdl.SDL_DisplayFormat(c_src)
                if c_src:
                    res = sdl.SDL_BlitSurface(c_src, srcrect, c_dest, destrect)
                    sdl.SDL_FreeSurface(c_src)
                else:
                    res = -1
            else:
                raise NotImplementedError()
        else:
            res = sdl.SDL_BlitSurface(c_src, srcrect, c_dest, destrect)

        if c_subsurface:
            sdl.SDL_SetClipRect(c_subsurface, orig_clip)
            destrect.x -= suboffsetx
            destrect.y -= suboffsety
        else:
            # TODO: prep/unprep
            pass

        if res == -1:
            raise SDLError.from_sdl_error()
        elif res == -2:
            raise SDLError("Surface was lost")

        return Rect._from4(destrect.x, destrect.y, destrect.w, destrect.h)
Esempio n. 22
0
def check_mixer():
    """Helper function to check if sound was initialised"""
    # Defined here so we don't need circular imports between
    # mixer and this
    if not sdl.SDL_WasInit(sdl.SDL_INIT_AUDIO):
        raise SDLError("mixer system not initialized")
Esempio n. 23
0
def video_autoquit():
    if sdl.SDL_WasInit(sdl.SDL_INIT_VIDEO):
        sdl.SDL_QuitSubSystem(sdl.SDL_INIT_VIDEO)
Esempio n. 24
0
def _timer_callback(interval, param):
    if sdl.SDL_WasInit(sdl.SDL_INIT_VIDEO):
        event = ffi.new("SDL_Event")
        event.type = ffi.cast("intptr_t", param)
        sdl.SDL_PushEvent(event)
    return interval