diff --git a/LICENSES b/LICENSES index a38c955..d2b3bc3 100644 --- a/LICENSES +++ b/LICENSES @@ -1,9 +1,3 @@ -- Included SDL ctypes code is Copyright: Alex Holkner - - This code is licensed under the LGPL license, as found here: - - http://www.gnu.org/licenses/lgpl.html - - Included SDL2 ctypes code is Copyright: Marcus von Appen This software is distributed under the Public Domain. diff --git a/README.md b/README.md index 676d304..f616b2d 100644 --- a/README.md +++ b/README.md @@ -11,7 +11,7 @@ About ----- -M64Py is a Qt5 front-end (GUI) for Mupen64Plus 2.0, a cross-platform +M64Py is a Qt5 front-end (GUI) for Mupen64Plus, a cross-platform plugin-based Nintendo 64 emulator. Front-end is written in Python and it provides a user-friendly interface over Mupen64Plus shared library. @@ -28,7 +28,7 @@ Dependencies ------------ * PyQt5 -* SDL-1.2 or SDL-2.0 +* SDL-2.0 Install ------- diff --git a/dist/debian/m64py.6 b/dist/debian/m64py.6 index 19ad35e..3adc68e 100644 --- a/dist/debian/m64py.6 +++ b/dist/debian/m64py.6 @@ -28,16 +28,13 @@ m64py \- Mupen64plus 2.0 frontend .B m64py [\fIoptions\fP] .br .SH DESCRIPTION -m64py is a graphical Qt5 frontend for the Nintendo64 emulator mupen64plus 2.0 +m64py is a graphical Qt5 frontend for the Nintendo64 emulator mupen64plus .PP .PP .SH OPTIONS .TP \fB\-v\fP, \fB\-\-verbose\fP Show verbose output. -.TP -\fB\-\-sdl2\fP -Use SDL2 instead of auto-detecting the libmupen64plus2 build type. . .SH SEE ALSO .BR mupen64plus (6), diff --git a/dist/redhat/m64py.spec.in b/dist/redhat/m64py.spec.in index 5f2539c..ab6bb16 100644 --- a/dist/redhat/m64py.spec.in +++ b/dist/redhat/m64py.spec.in @@ -18,7 +18,7 @@ Url: http://m64py.sourceforge.net Requires: PyQt5 SDL %description -M64Py is a Qt5 front-end (GUI) for Mupen64Plus 2.0, a cross-platform plugin-based Nintendo 64 emulator. +M64Py is a Qt5 front-end (GUI) for Mupen64Plus, a cross-platform plugin-based Nintendo 64 emulator. %prep %setup -n %{name}-%{unmangled_version} diff --git a/setup.py b/setup.py index c4d2580..b0dde6a 100644 --- a/setup.py +++ b/setup.py @@ -154,7 +154,6 @@ class build_exe(Command): def run(self): self.run_command("build_qt") - set_sdl2() set_rthook() self.run_build() self.copy_emulator() @@ -194,7 +193,6 @@ class build_zip(build_exe): def run(self): self.run_command("build_qt") - set_sdl2() set_rthook() self.set_config_path() self.run_build() @@ -269,7 +267,6 @@ class build_dmg(Command): def run(self): self.run_command("build_qt") - set_sdl2() set_rthook() self.run_build() self.copy_files() @@ -279,18 +276,6 @@ class build_dmg(Command): self.run_build_dmg() -def set_sdl2(): - opts_file = "" - opts_path = join(BASE_DIR, "src", "m64py", "opts.py") - with open(opts_path, "r") as opts: data = opts.read() - lines = data.split("\n") - for line in lines: - if "sdl2" in line: - line = line.replace("default=False", "default=True") - opts_file += line + "\n" - with open(opts_path, "w") as opts: opts.write(opts_file) - - def set_rthook(): import PyInstaller hook_file = "" @@ -364,12 +349,12 @@ setup( name = "m64py", version = FRONTEND_VERSION, description = "M64Py - A frontend for Mupen64Plus", - long_description = "M64Py is a Qt5 front-end (GUI) for Mupen64Plus 2.0, a cross-platform plugin-based Nintendo 64 emulator.", + long_description = "M64Py is a Qt5 front-end (GUI) for Mupen64Plus, a cross-platform plugin-based Nintendo 64 emulator.", author = "Milan Nikolic", author_email = "gen2brain@gmail.com", license = "GNU GPLv3", url = "http://m64py.sourceforge.net", - packages = ["m64py", "m64py.core", "m64py.frontend", "m64py.ui", "m64py.SDL", "m64py.SDL2"], + packages = ["m64py", "m64py.core", "m64py.frontend", "m64py.ui", "m64py.SDL2"], package_dir = {"": "src"}, scripts = ["m64py"], requires = ["PyQt5"], diff --git a/src/m64py/SDL/__init__.py b/src/m64py/SDL/__init__.py deleted file mode 100644 index cb0d9e5..0000000 --- a/src/m64py/SDL/__init__.py +++ /dev/null @@ -1,139 +0,0 @@ -#!/usr/bin/env python - -'''Main module for importing SDL-ctypes. - -This module defines the intialization and cleanup functions: - - `SDL_Init` - - `SDL_InitSubSystem` - - `SDL_WasInit` - - `SDL_QuitSubSystem` - - `SDL_Quit` - -It also imports all functions, constants and classes from the package -submodules. Typical usage, then, is to just import this module directly -into your namespace:: - - from SDL import * - -This gives you access to all SDL names exactly as they appear in the C -header files. - -:group Non-core modules: ttf, mixer, image, sound -''' - -__docformat__ = 'restructuredtext' -__version__ = '$Id: $' - -import ctypes -import sys - -from .dll import private_function, function -from .active import * -from .audio import * -from .cdrom import * -from .constants import * -from .endian import * -from .error import * -from .events import * -from .joystick import * -from .keyboard import * -from .mouse import * -from .quit import * -from .rwops import * -from .timer import * -from .version import * -from .video import * - -# SDL.h - -_SDL_Init = private_function('SDL_Init', - arg_types=[ctypes.c_uint], - return_type=ctypes.c_int) - -def SDL_Init(flags): - '''Initialise the SDL library. - - This function loads the SDL dynamically linked library and initializes - the subsystems specified by `flags` (and those satisfying dependencies) - Unless the `SDL_INIT_NOPARACHUTE` flag is set, it will install cleanup - signal handlers for some commonly ignored fatal signals (like SIGSEGV). - - The following flags are recognised: - - - `SDL_INIT_TIMER` - - `SDL_INIT_AUDIO` - - `SDL_INIT_VIDEO` - - `SDL_INIT_CDROM` - - `SDL_INIT_JOYSTICK` - - `SDL_INIT_NOPARACHUTE` - - `SDL_INIT_EVENTTHREAD` - - `SDL_INIT_EVERYTHING` - - :Parameters: - - `flags`: int - - :rtype: int - :return: undocumented (FIXME) - :see: `SDL_Quit` - ''' - if sys.platform == 'darwin' and flags & SDL_INIT_VIDEO: - import SDL.darwin - SDL.darwin.init() - return _SDL_Init(flags) - -_SDL_InitSubSystem = private_function('SDL_InitSubSystem', - arg_types=[ctypes.c_uint], - return_type=ctypes.c_int) - -def SDL_InitSubSystem(flags): - '''Initialize specific SDL subsystems. - - :Parameters: - - `flags`: int - - :rtype: int - :return: undocumented (FIXME) - :see: `SDL_Init`, `SDL_QuitSubSystem` - ''' - if sys.platform == 'darwin' and flags & SDL_INIT_VIDEO: - import SDL.darwin - SDL.darwin.init() - return _SDL_InitSubSystem(flags) - -SDL_QuitSubSystem = function('SDL_QuitSubSystem', - '''Clean up specific SDL subsystems. - - :Parameters: - - `flags`: int - - :see: `SDL_InitSubSystem` - ''', - args=['flags'], - arg_types=[ctypes.c_uint], - return_type=None) - -SDL_WasInit = function('SDL_WasInit', - '''Return a mask of the specified subsystems which have been - initialized. - - If `flags` is 0, return a mask of all initialized subsystems. - - :Parameters: - - `flags`: int - - :rtype: int - :return: undocumented (FIXME) - :see: `SDL_Init` - ''', - args=['flags'], - arg_types=[ctypes.c_uint], - return_type=ctypes.c_int) - -SDL_Quit = function('SDL_Quit', - '''Clean up all initialized subsystems. - - You should call this function upon all exit conditions. - ''', - args=[], - arg_types=[], - return_type=None) diff --git a/src/m64py/SDL/active.py b/src/m64py/SDL/active.py deleted file mode 100644 index 1820b10..0000000 --- a/src/m64py/SDL/active.py +++ /dev/null @@ -1,31 +0,0 @@ -#!/usr/bin/env python - -'''SDL application focus event handling. -''' - -__docformat__ = 'restructuredtext' -__version__ = '$Id: $' - -from ctypes import * - -from .dll import function - -SDL_GetAppState = function('SDL_GetAppState', - '''Return the current state of the application. - - The return value is a bitwise combination of `SDL_APPMOUSEFOCUS`, - `SDL_APPINPUTFOCUS`, and `SDL_APPACTIVE`. The meanings are as follows: - - `SDL_APPMOUSEFOCUS` - The application has mouse coverage. - `SDL_APPINPUTFOCUS` - The application has input focus. - `SDL_APPACTIVATE` - The user is able to see your application, otherwise it has been - iconified or disabled - - :rtype: int - ''', - args=[], - arg_types=[], - return_type=c_int) diff --git a/src/m64py/SDL/array.py b/src/m64py/SDL/array.py deleted file mode 100644 index 1956dd3..0000000 --- a/src/m64py/SDL/array.py +++ /dev/null @@ -1,291 +0,0 @@ -#!/usr/bin/env python - -''' -''' - -__docformat__ = 'restructuredtext' -__version__ = '$Id: $' - -from ctypes import * - -# Arrange these in order of preference -_array_names = ('numpy') - -def _import_arrays(array_names, locals): - default_array = None - for array_name in array_names: - try: - array = __import__(array_name, globals(), locals, []) - typemap = { - c_ubyte: array.uint8, - c_ushort: array.uint16, - c_uint: array.uint32 - } - locals[array_name] = array - locals['_%s_typemap' % array_name] = typemap - locals['_have_%s' % array_name] = True - if not default_array: - default_array = array - locals['_default_array'] = array - locals['_default_typemap'] = typemap - except ImportError: - locals['_have_%s' % array_name] = False - locals['_have_array'] = default_array is not None - -# This sets up local names for the arrays. If numpy is -# available, the following local variables are defined: -# numpy, _numpy_typemap -# -# The following local variables will be set to True or False: -# _have_numpy -# -# If any of the array modules were imported, the following is True: -# _have_array -# -# And if _have_array is True, the following are defined: -# _default_array -# _default_typemap -_import_arrays(_array_names, locals()) - -class SDL_array: - def __init__(self, ptr, count, ctype): - '''Construct an array at memory location `ptr` with `count` elements - of type `ctype`. - - :Parameters: - `ptr` : ctypes.Array, POINTER(ctype) or POINTER(ctypes.Array) - Starting point of the array space. Don't use c_void_p; this - will not cast correctly. If `ptr` is None, the array - will be created (filled with random data). - `count` : int - Number of elements in the array. - `ctype` : type - ctypes type if each element, e.g., c_ubyte, c_int, etc. - - ''' - count = int(count) - if not ptr: - ptr = (ctype * count)() - self.ptr = ptr - self.count = count - self.ctype = ctype - self._ctypes_array = None - - # Casting methods - - def as_bytes(self): - '''Access the array as raw bytes, regardless of the underlying - data type. - - This can be useful, for example, in accessing a 32-bit colour - buffer by individual components rather than the encoded pixel. - - :rtype: SDL_array - ''' - return SDL_array(self.ptr, (self.count * sizeof(self.ctype)), c_ubyte) - - def as_int16(self): - '''Access the array as 16-bit integers, regardless of the underlying - data type. - - :rtype: SDL_array - ''' - return SDL_array(self.ptr, - self.count * sizeof(self.ctype) / 2, - c_ushort) - - def as_int32(self): - '''Access the array as 32-bit integers, regardless of the underlying - data type. - - :rtype: SDL_array - ''' - return SDL_array(self.ptr, - self.count * sizeof(self.ctype) / 4, - c_uint) - - def as_ctypes(self): - '''Access the array as a ctypes array. - - :rtype: ctypes.Array - ''' - if not self._ctypes_array: - self._ctypes_array = \ - cast(self.ptr, POINTER(self.ctype * self.count)).contents - return self._ctypes_array - - # numpy specific methods - - def have_numpy(cls): - '''Determine if the numpy array module is available. - - :rtype: bool - ''' - return _have_numpy - - def as_numpy(self, shape=None): - '''Access the array as a numpy array. - - The numpy array shares the same underlying memory buffer, so - changes are immediate, and you can use the numpy array as you would - normally. To set the entire contents of the array at once, use a - ``[:]`` slice. - - If numpy is not installed, an ImportError will be raised. - - :rtype: numpy.ndarray - ''' - if not _have_numpy: - raise ImportError('numpy could not be imported') - if self.ctype not in _numpy_typemap: - raise TypeError('%s has no numpy compatible type' % self.ctype) - if shape is None: - shape = (self.count,) - ar = numpy.frombuffer(self.as_ctypes(), _numpy_typemap[self.ctype]) - ar = ar.reshape(shape) - return ar - - # Generic array methods (numpy) - - def have_array(cls): - '''Determine if an array module is available. - - :rtype: bool - ''' - return _have_array - have_array = classmethod(have_array) - - def array_module(cls): - '''Determine the default array module. - - :rtype: module - :return: one of numpy or None - ''' - if _have_array: - return _default_array - else: - return None - array_module = classmethod(array_module) - - def to_array(self, shape=None): - '''Convert the array to a numpy array. - - The returned array will be a copy of the data. You can retrieve - the module used (numpy) using the `array_module` - method. - - If none of numpy could be imported, an - ImportError will be raised. - - :rtype: numpy.ndarray.array - ''' - if not _have_array: - raise ImportError('no array module could be imported') - if self.ctype not in _default_typemap: - raise TypeError('%s has no array compatible type' % self.ctype) - - s = self.to_string() - t = _default_typemap[self.ctype] - - if shape is None: - shape = (self.count,) - - # Each module has its own shaping interface - if _have_numpy and _default_array is numpy: - return _default_array.fromstring(s, t).reshape(shape) - - def from_array(self, array): - '''Copy data from the given numpy array into - this array. - - The array sizes must match exactly. No type checking is performed. - - :Parameters: - `array` : numpy array object - Array to copy. - ''' - s = array.tostring() - memmove(self.ptr, s, len(s)) - - # General interoperability (string) - - def to_string(self): - '''Return a string with the contents of this array. - - :rtype: string - ''' - count = sizeof(self.ctype) * self.count - s = create_string_buffer(count) - memmove(s, self.ptr, count) - return s.raw - - def from_string(self, data): - '''Copy string data into this array. - - The string must have exactly the same length of this array (in bytes). - No size checking is performed. - - :Parameters: - `data` : str - String data to copy. - ''' - memmove(self.ptr, data, len(data)) - - def __repr__(self): - return 'SDL_array(ctype=%s, count=%r)' % (self.ctype, self.count) - - def __len__(self): - return self.count - - def __getitem__(self, key): - if type(key) is slice: - if key.step: - raise TypeError('slice step not supported') - return self.as_ctypes()[key.start:key.stop] - else: - return self.as_ctypes()[key] - - def __setitem__(self, key, value): - if type(key) is slice: - if key.step: - raise TypeError('slice step not supported') - self.as_ctypes()[key.start:key.stop] = value - else: - self.as_ctypes()[key] = value - -def to_ctypes(values, count, ctype): - '''Create a ctypes array of the given count and type, with the contents - of sequence `values`. - - :Parameters: - - `values`: sequence of length `count`, or SDL_array instance, or - ctypes.Array, or POINTER(ctypes.Array) - - `count`: int - - `ctype`: type - - :rtype: object, ctypes.Array - :return: (ref, array), where ref is an object that must be retained - by the caller for as long as the array is used. - ''' - - ref = values - - # Convert SDL_array instances to ctypes array - if isinstance(values, SDL_array): - values = values.as_ctypes() - - # Cast ctypes array to correct type if necessary - if isinstance(values, Array): - if values._type_ is ctype: - return ref, values - else: - return ref, cast(values, POINTER(ctype * count)).contents - - # Convert string bytes to array - if type(values) == str: - ref = create_string_buffer(values) - return ref, cast(ref, POINTER(ctype * count)).contents - - # Otherwise assume sequence - ar = (ctype * count)(*values) - return ar, ar diff --git a/src/m64py/SDL/audio.py b/src/m64py/SDL/audio.py deleted file mode 100644 index 0535cdf..0000000 --- a/src/m64py/SDL/audio.py +++ /dev/null @@ -1,414 +0,0 @@ -#!/usr/bin/env python - -'''Access to the raw audio mixing buffer. -''' - -__docformat__ = 'restructuredtext' -__version__ = '$Id: $' - -from ctypes import * - -from .array import SDL_array, to_ctypes -from .constants import AUDIO_U8, AUDIO_S8, AUDIO_U16LSB, AUDIO_S16LSB, AUDIO_U16MSB, AUDIO_S16MSB -from .dll import function, private_function -from .rwops import SDL_RWops, SDL_RWFromFile - -_SDL_AudioSpec_fn = \ - CFUNCTYPE(POINTER(c_ubyte), POINTER(c_ubyte), POINTER(c_ubyte), c_int) - -class SDL_AudioSpec(Structure): - '''Audio format structure. - - The calculated values in this structure are calculated by `SDL_OpenAudio`. - - :Ivariables: - `freq` : int - DSP frequency, in samples per second - `format` : int - Audio data format. One of AUDIO_U8, AUDIO_S8, AUDIO_U16LSB, - AUDIO_S16LSB, AUDIO_U16MSB or AUDIO_S16MSB - `channels` : int - Number of channels; 1 for mono or 2 for stereo. - `silence` : int - Audio buffer silence value (calculated) - `samples` : int - Audio buffer size in samples (power of 2) - `size` : int - Audio buffer size in bytes (calculated) - - ''' - _fields_ = [('freq', c_int), - ('format', c_ushort), - ('channels', c_ubyte), - ('silence', c_ubyte), - ('samples', c_ushort), - ('_padding', c_ushort), - ('size', c_uint), - ('_callback', _SDL_AudioSpec_fn), - ('_userdata', c_void_p)] - -_SDL_AudioCVT_p = POINTER('SDL_AudioCVT') - -_SDL_AudioCVT_filter_fn = \ - CFUNCTYPE(POINTER(c_ubyte), _SDL_AudioCVT_p, c_ushort) - -class SDL_AudioCVT(Structure): - '''Set of audio conversion filters and buffers. - - :Ivariables: - `needed` : int - 1 if conversion is possible - `src_format` : int - Source audio format. See `SDL_AudioSpec.format` - `dst_format` : int - Destination audio format. See `SDL_AudioSpec.format` - `rate_incr` : float - Rate conversion increment - `len` : int - Length of original audio buffer - `len_cvt` : int - Length of converted audio buffer - `len_mult` : int - Buffer must be len * len_mult big - `len_ratio` : float - Given len, final size is len * len_ratio - `filter_index` : int - Current audio conversion function - - ''' - _fields_ = [('needed', c_int), - ('src_format', c_ushort), - ('dst_format', c_ushort), - ('rate_incr', c_double), - ('buf', POINTER(c_ubyte)), - ('len', c_int), - ('len_cvt', c_int), - ('len_mult', c_int), - ('len_ratio', c_double), - ('filters', _SDL_AudioCVT_filter_fn * 10), - ('filter_index', c_int)] - -SetPointerType(_SDL_AudioCVT_p, SDL_AudioCVT) - -# SDL_AudioInit and SDL_AudioQuit marked private - -_SDL_AudioDriverName = private_function('SDL_AudioDriverName', - arg_types=[c_char_p, c_int], - return_type=c_char_p) - -def SDL_AudioDriverName(maxlen=1024): - ''' - Returns the name of the audio driver. Returns None if no driver has - been initialised. - - :Parameters: - `maxlen` - Maximum length of the returned driver name; defaults to 1024. - - :rtype: string - ''' - buf = create_string_buffer(maxlen) - if _SDL_AudioDriverName(buf, maxlen): - return buf.value - return None - -def _ctype_audio_format(fmt): - if fmt == AUDIO_U8: - return c_ubyte - elif fmt == AUDIO_S8: - return c_char - elif fmt in (AUDIO_U16LSB, AUDIO_U16MSB): - return c_ushort - elif fmt in (AUDIO_S16LSB, AUDIO_S16MSB): - return c_short - else: - raise TypeError('Unsupported format %r' % fmt) - -_SDL_OpenAudio = private_function('SDL_OpenAudio', - arg_types=[POINTER(SDL_AudioSpec), POINTER(SDL_AudioSpec)], - return_type=c_int, - error_return=-1) - -def SDL_OpenAudio(desired, obtained): - '''Open the audio device with the desired parameters. - - If successful, the actual hardware parameters will be set in the - instance passed into `obtained`. If `obtained` is None, the audio - data passed to the callback function will be guaranteed to be in - the requested format, and will be automatically converted to the - hardware audio format if necessary. - - An exception will be raised if the audio device couldn't be opened, - or the audio thread could not be set up. - - The fields of `desired` are interpreted as follows: - - `desired.freq` - desired audio frequency in samples per second - `desired.format` - desired audio format, i.e., one of AUDIO_U8, AUDIO_S8, - AUDIO_U16LSB, AUDIO_S16LSB, AUDIO_U16MSB or AUDIO_S16MSB - `desired.samples` - size of the audio buffer, in samples. This number should - be a power of two, and may be adjusted by the audio driver - to a value more suitable for the hardware. Good values seem - to range between 512 and 8096 inclusive, depending on the - application and CPU speed. Smaller values yield faster response - time, but can lead to underflow if the application is doing - heavy processing and cannot fill the audio buffer in time. - A stereo sample consists of both right and left channels in - LR ordering. Note that the number of samples is directly - related to time by the following formula:: - - ms = (samples * 1000) / freq - - `desired.size` - size in bytes of the audio buffer; calculated by SDL_OpenAudio. - `desired.silence` - value used to set the buffer to silence; calculated by - SDL_OpenAudio. - `desired.callback` - a function that will be called when the audio device is ready - for more data. The signature of the function should be:: - - callback(userdata: any, stream: SDL_array) -> None - - The function is called with the userdata you specify (see below), - and an SDL_array of the obtained format which you must fill - with audio data. - - This function usually runs in a separate thread, so you should - protect data structures that it accesses by calling - `SDL_LockAudio` and `SDL_UnlockAudio` in your code. - `desired.userdata` - passed as the first parameter to your callback function. - - The audio device starts out playing silence when it's opened, and should - be enabled for playing by calling ``SDL_PauseAudio(False)`` when you are - ready for your audio callback function to be called. Since the audio - driver may modify the requested size of the audio buffer, you should - allocate any local mixing buffers after you open the audio device. - - :Parameters: - - `desired`: `SDL_AudioSpec` - - `obtained`: `SDL_AudioSpec` or None - - ''' - if not hasattr(desired, 'callback'): - raise TypeError('Attribute "callback" not set on "desired"') - userdata = getattr(desired, 'userdata', None) - callback = desired.callback - ctype = [_ctype_audio_format(desired.format)] # List, so mutable - - def cb(data, stream, len): - ar = SDL_array(stream, len/sizeof(ctype[0]), ctype[0]) - callback(userdata, ar) - - desired._callback = _SDL_AudioSpec_fn(cb) - _SDL_OpenAudio(desired, obtained) - if obtained: - obtained.userdata = desired.userdata - obtained.callback = desired.callback - ctype[0] = _ctype_audio_format(obtained.format) - -SDL_GetAudioStatus = function('SDL_GetAudioStatus', - '''Get the current audio state. - - :rtype: int - :return: one of SDL_AUDIO_STOPPED, SDL_AUDIO_PLAYING, SDL_AUDIO_PAUSED - ''', - args=[], - arg_types=[], - return_type=c_int) - -SDL_PauseAudio = function('SDL_PauseAudio', - '''Pause and unpause the audio callback processing. - - It should be called with a parameter of 0 after opening the audio - device to start playing sound. This is so you can safely initalize - data for your callback function after opening the audio device. - Silence will be written to the audio device during the pause. - - :Parameters: - - `pause_on`: int - - ''', - args=['pause_on'], - arg_types=[c_int], - return_type=None) - -_SDL_LoadWAV_RW = private_function('SDL_LoadWAV_RW', - arg_types=[POINTER(SDL_RWops), - c_int, - POINTER(SDL_AudioSpec), - POINTER(POINTER(c_ubyte)), - POINTER(c_uint)], - return_type=POINTER(SDL_AudioSpec), - require_return=True) - -def SDL_LoadWAV_RW(src, freesrc): - '''Load a WAVE from the data source. - - The source is automatically freed if `freesrc` is non-zero. For - example, to load a WAVE file, you could do:: - - SDL_LoadWAV_RW(SDL_RWFromFile('sample.wav', 'rb'), 1) - - You need to free the returned buffer with `SDL_FreeWAV` when you - are done with it. - - :Parameters: - - `src`: `SDL_RWops` - - `freesrc`: int - - :rtype: (`SDL_AudioSpec`, `SDL_array`) - :return: a tuple (`spec`, `audio_buf`) where `spec` describes the data - format and `audio_buf` is the buffer containing audio data. - ''' - spec = SDL_AudioSpec() - audio_buf = POINTER(c_ubyte)() - audio_len = c_uint() - _SDL_LoadWAV_RW(src, freesrc, spec, byref(audio_buf), byref(audio_len)) - ctype = _ctype_audio_format(spec.format) - return (spec, - SDL_array(audio_buf, audio_len.value/sizeof(ctype), ctype)) - -def SDL_LoadWAV(file): - '''Load a WAVE from a file. - - :Parameters: - - `file`: str - - :rtype: (`SDL_AudioSpec`, `SDL_array`) - :see: `SDL_LoadWAV_RW` - ''' - return SDL_LoadWAV_RW(SDL_RWFromFile(file, 'rb'), 1) - -_SDL_FreeWAV = private_function('SDL_FreeWAV', - arg_types=[POINTER(c_ubyte)], - return_type=None) - -def SDL_FreeWAV(audio_buf): - '''Free a buffer previously allocated with `SDL_LoadWAV_RW` or - `SDL_LoadWAV`. - - :Parameters: - - `audio_buf`: `SDL_array` - - ''' - _SDL_FreeWAV(audio_buf.as_bytes().as_ctypes()) - -_SDL_BuildAudioCVT = private_function('SDL_BuildAudioCVT', - arg_types=[POINTER(SDL_AudioCVT), c_ushort, c_ubyte, c_uint, - c_ushort, c_ubyte, c_uint], - return_type=c_int, - error_return=-1) - -def SDL_BuildAudioCVT(src_format, src_channels, src_rate, - dst_format, dst_channels, dst_rate): - '''Take a source format and rate and a destination format and rate, - and return a `SDL_AudioCVT` structure. - - The `SDL_AudioCVT` structure is used by `SDL_ConvertAudio` to convert - a buffer of audio data from one format to the other. - - :Parameters: - - `src_format`: int - - `src_channels`: int - - `src_rate`: int - - `dst_format`: int - - `dst_channels`: int - - `dst_rate`: int - - :rtype: `SDL_AudioCVT` - ''' - cvt = SDL_AudioCVT() - _SDL_BuildAudioCVT(cvt, src_format, src_channels, src_rate, - dst_format, dst_channels, dst_rate) - return cvt - -SDL_ConvertAudio = function('SDL_ConvertAudio', - '''Convert audio data in-place. - - Once you have initialized the 'cvt' structure using - `SDL_BuildAudioCVT`, created an audio buffer ``cvt.buf``, and filled it - with ``cvt.len`` bytes of audio data in the source format, this - function will convert it in-place to the desired format. The data - conversion may expand the size of the audio data, so the buffer - ``cvt.buf`` should be allocated after the cvt structure is initialized - by `SDL_BuildAudioCVT`, and should be ``cvt->len*cvt->len_mult`` bytes - long. - - Note that you are responsible for allocating the buffer. The - recommended way is to construct an `SDL_array` of the correct size, - and set ``cvt.buf`` to the result of `SDL_array.as_ctypes`. - - :Parameters: - - `cvt`: `SDL_AudioCVT` - - :rtype: int - :return: undocumented - ''', - args=['cvt'], - arg_types=[POINTER(SDL_AudioCVT)], - return_type=c_int) - -_SDL_MixAudio = private_function('SDL_MixAudio', - arg_types=[POINTER(c_ubyte), POINTER(c_ubyte), c_uint, c_int], - return_type=None) - -def SDL_MixAudio(dst, src, length, volume): - '''Mix two audio buffers. - - This takes two audio buffers of the playing audio format and mixes - them, performing addition, volume adjustment, and overflow clipping. - The volume ranges from 0 - 128, and should be set to SDL_MIX_MAXVOLUME - for full audio volume. Note this does not change hardware volume. - This is provided for convenience -- you can mix your own audio data. - - :note: SDL-ctypes doesn't know the current play format, so you must - always pass in byte buffers (SDL_array or sequence) to this function, - rather than of the native data type. - - :Parameters: - - `dst`: `SDL_array` - - `src`: `SDL_array` - - `length`: int - - `volume`: int - - ''' - dstref, dst = to_ctypes(dst, len(dst), c_ubyte) - srcref, src = to_ctypes(src, len(src), c_ubyte) - if len(dst) < length: - raise TypeError('Destination buffer too small') - elif len(src) < length: - raise TypeError('Source buffer too small') - _SDL_MixAudio(dst, src, length, volume) - -SDL_LockAudio = function('SDL_LockAudio', - '''Guarantee the callback function is not running. - - The lock manipulated by these functions protects the callback function. - During a LockAudio/UnlockAudio pair, you can be guaranteed that the - callback function is not running. Do not call these from the callback - function or you will cause deadlock. - ''', - args=[], - arg_types=[], - return_type=None) - -SDL_UnlockAudio = function('SDL_UnlockAudio', - '''Release the audio callback lock. - - :see: `SDL_LockAudio` - ''', - args=[], - arg_types=[], - return_type=None) - -SDL_CloseAudio = function('SDL_CloseAudio', - '''Shut down audio processing and close the audio device. - ''', - args=[], - arg_types=[], - return_type=None) diff --git a/src/m64py/SDL/cdrom.py b/src/m64py/SDL/cdrom.py deleted file mode 100644 index 1934d43..0000000 --- a/src/m64py/SDL/cdrom.py +++ /dev/null @@ -1,291 +0,0 @@ -#!/usr/bin/env python - -'''CD-audio control. - -In order to use these functions, `SDL_Init` must have been called with the -`SDL_INIT_CDROM` flag. This causes SDL to scan the system for CD-ROM -drives, and load appropriate drivers. -''' - -__docformat__ = 'restructuredtext' -__version__ = '$Id: $' - -from ctypes import * - -from .constants import SDL_MAX_TRACKS, CD_FPS -from .dll import function - -class SDL_CDtrack(Structure): - '''Structure describing a single CD track. - - :Ivariables: - `id` : int - Track number - `type` : int - One of SDL_AUDIO_TRACK or SDL_DATA_TRACK - `length` : int - Length, in frames, of this track - `offset` : int - Offset, in frames, from start of disk - - ''' - _fields_ = [('id', c_ubyte), - ('type', c_ubyte), - ('_unused', c_ushort), - ('length', c_uint), - ('offset', c_uint)] - -class SDL_CD(Structure): - '''Structure describing a CD. - - This structure is only current as of the last call to `SDL_CDStatus`. - - :Ivariables: - `id` : int - Private drive identifier - `status` : int - Current drive status. One of CD_TRAYEMPTY, CD_STOPPED, - CD_PLAYING, CD_PAUSED, CD_ERROR. - `numtracks` : int - Number of tracks on disk - `cur_track` : int - Current track position - `cur_frame` : int - Current frame offset within current track - `track` : sequence of `SDL_CDtrack` - Tracks on the disk. - - ''' - _fields_ = [('id', c_uint), - ('status', c_int), - ('numtracks', c_int), - ('cur_track', c_int), - ('cur_frame', c_int), - ('track', SDL_CDtrack * (SDL_MAX_TRACKS + 1))] - -def CD_INDRIVE(status): - '''Given a status, returns True if there's a disk in the drive. - - :Parameters: - - `status`: int - - :rtype: bool - ''' - return status > 0 - -def FRAMES_TO_MSF(frames): - '''Convert from frames to minute/second/frame - - :Parameters: - - `frames`: int - - :rtype: (int, int, int) - :return: tuple of (minutes, seconds, frames) - ''' - F = frames % CD_FPS - frames /= CD_FPS - S = frames % 60 - frames /= 60 - M = frames - return (M, S, F) - -def MSF_TO_FRAMES(minutes, seconds, frames): - '''Convert from minute/second/frame to frames - - :Parameters: - - `minutes`: int - - `seconds`: int - - `frames`: int - - :rtype: int - ''' - return CD_FPS(minutes * 60 + seconds) + frames - -SDL_CDNumDrives = function('SDL_CDNumDrives', - '''Return the number of CD-ROM drives on the system. - - :rtype: int - ''', - args=[], - arg_types=[], - return_type=c_int, - error_return=-1) - -SDL_CDName = function('SDL_CDName', - '''Return a human-readable, system-dependent identifier for the - CD-ROM. - - Example:: - - '/dev/cdrom' - 'E:' - '/dev/disk/ide/1/master' - - :Parameters: - `drive` : int - Drive number, starting with 0. Drive 0 is the system default - CD-ROM. - - :rtype: string - ''', - args=['drive'], - arg_types=[c_int], - return_type=c_char_p, - require_return=True) - -SDL_CDOpen = function('SDL_CDOpen', - '''Open a CD-ROM drive for access. - - It returns a drive handle on success, or raises an exception if the - drive was invalid or busy. This newly opened CD-ROM becomes the - default CD used when other CD functions are passed None as the CD-ROM - handle. - - Drives are numbered starting with 0. Drive 0 is the system default - CD-ROM. - - :Parameters: - - `drive`: int - - :rtype: `SDL_CD` - ''', - args=['drive'], - arg_types=[c_int], - return_type=POINTER(SDL_CD), - dereference_return=True, - require_return=True) - -SDL_CDStatus = function('SDL_CDStatus', - '''Return the current status of the given drive. - - If the drive has a CD in it, the table of contents of the CD and - current play position of the CD will be updated in the SDL_CD - instance. - - Possible return values are - - `CD_TRAYEMPTY` - - `CD_STOPPED` - - `CD_PLAYING` - - `CD_PAUSED` - - :Parameters: - - `cdrom`: `SDL_CD` - - :rtype: int - ''', - args=['cdrom'], - arg_types=[POINTER(SDL_CD)], - return_type=int, - error_return=-1) - -SDL_CDPlayTracks = function('SDL_CDPlayTracks', - '''Play the given CD. - - Plays the given CD starting at `start_track` and `start_frame` for - `ntracks` tracks and `nframes` frames. If both `ntracks` and `nframes` - are 0, play until the end of the CD. This function will skip data - tracks. This function should only be called after calling - `SDL_CDStatus` to get track information about the CD. - - For example:: - - # Play entire CD: - if CD_INDRIVE(SDL_CDStatus(cdrom)): - SDL_CDPlayTracks(cdrom, 0, 0, 0, 0) - - # Play last track: - if CD_INDRIVE(SDL_CDStatus(cdrom)): - SDL_CDPlayTracks(cdrom, cdrom.numtracks-1, 0, 0, 0) - - #Play first and second track and 10 seconds of third track: - if CD_INDRIVE(SDL_CDStatus(cdrom)): - SDL_CDPlayTracks(cdrom, 0, 0, 2, 10) - - :Parameters: - - `cdrom`: `SDL_CD` - - `start_track`: int - - `start_frame`: int - - `ntracks`: int - - `nframes`: int - - ''', - args=['cdrom', 'start_track', 'start_frame', 'ntracks', 'nframes'], - arg_types=[POINTER(SDL_CD), c_int, c_int, c_int, c_int], - return_type=c_int, - error_return=-1) - -SDL_CDPlay = function('SDL_CDPlay', - '''Play the given CD. - - Plays the given CD starting at `start` frame for `length` frames. - - :Parameters: - - `cdrom`: `SDL_CD` - - `start`: int - - `length`: int - - ''', - args=['cdrom', 'start', 'length'], - arg_types=[POINTER(SDL_CD), c_int, c_int], - return_type=c_int, - error_return=-1) - -SDL_CDPause = function('SDL_CDPause', - '''Pause play. - - :Parameters: - - `cdrom`: `SDL_CD` - - ''', - args=['cdrom'], - arg_types=[POINTER(SDL_CD)], - return_type=c_int, - error_return=-1) - -SDL_CDResume = function('SDL_CDResume', - '''Resume play. - - :Parameters: - - `cdrom`: `SDL_CD` - - ''', - args=['cdrom'], - arg_types=[POINTER(SDL_CD)], - return_type=c_int, - error_return=-1) - -SDL_CDStop = function('SDL_CDStop', - '''Stop play. - - :Parameters: - - `cdrom`: `SDL_CD` - - ''', - args=['cdrom'], - arg_types=[POINTER(SDL_CD)], - return_type=c_int, - error_return=-1) - -SDL_CDEject = function('SDL_CDEject', - '''Eject CD-ROM. - - :Parameters: - - `cdrom`: `SDL_CD` - - ''', - args=['cdrom'], - arg_types=[POINTER(SDL_CD)], - return_type=c_int, - error_return=-1) - -SDL_CDClose = function('SDL_CDClose', - '''Close the handle for the CD-ROM drive. - - :Parameters: - - `cdrom`: `SDL_CD` - - ''', - args=['cdrom'], - arg_types=[POINTER(SDL_CD)], - return_type=c_int, - error_return=-1) diff --git a/src/m64py/SDL/constants.py b/src/m64py/SDL/constants.py deleted file mode 100644 index f898434..0000000 --- a/src/m64py/SDL/constants.py +++ /dev/null @@ -1,565 +0,0 @@ -#!/usr/bin/env python - -'''Constants and enums for all SDL submodules. -''' - -__docformat__ = 'restructuredtext' -__version__ = '$Id: $' - -import sys - -# enum SDLKey { - -# The keyboard syms have been cleverly chosen to map to ASCII -SDLK_UNKNOWN = 0 -SDLK_FIRST = 0 -SDLK_BACKSPACE = 8 -SDLK_TAB = 9 -SDLK_CLEAR = 12 -SDLK_RETURN = 13 -SDLK_PAUSE = 19 -SDLK_ESCAPE = 27 -SDLK_SPACE = 32 -SDLK_EXCLAIM = 33 -SDLK_QUOTEDBL = 34 -SDLK_HASH = 35 -SDLK_DOLLAR = 36 -SDLK_AMPERSAND = 38 -SDLK_QUOTE = 39 -SDLK_LEFTPAREN = 40 -SDLK_RIGHTPAREN = 41 -SDLK_ASTERISK = 42 -SDLK_PLUS = 43 -SDLK_COMMA = 44 -SDLK_MINUS = 45 -SDLK_PERIOD = 46 -SDLK_SLASH = 47 -SDLK_0 = 48 -SDLK_1 = 49 -SDLK_2 = 50 -SDLK_3 = 51 -SDLK_4 = 52 -SDLK_5 = 53 -SDLK_6 = 54 -SDLK_7 = 55 -SDLK_8 = 56 -SDLK_9 = 57 -SDLK_COLON = 58 -SDLK_SEMICOLON = 59 -SDLK_LESS = 60 -SDLK_EQUALS = 61 -SDLK_GREATER = 62 -SDLK_QUESTION = 63 -SDLK_AT = 64 - -# Skip uppercase letters - -SDLK_LEFTBRACKET = 91 -SDLK_BACKSLASH = 92 -SDLK_RIGHTBRACKET = 93 -SDLK_CARET = 94 -SDLK_UNDERSCORE = 95 -SDLK_BACKQUOTE = 96 -SDLK_a = 97 -SDLK_b = 98 -SDLK_c = 99 -SDLK_d = 100 -SDLK_e = 101 -SDLK_f = 102 -SDLK_g = 103 -SDLK_h = 104 -SDLK_i = 105 -SDLK_j = 106 -SDLK_k = 107 -SDLK_l = 108 -SDLK_m = 109 -SDLK_n = 110 -SDLK_o = 111 -SDLK_p = 112 -SDLK_q = 113 -SDLK_r = 114 -SDLK_s = 115 -SDLK_t = 116 -SDLK_u = 117 -SDLK_v = 118 -SDLK_w = 119 -SDLK_x = 120 -SDLK_y = 121 -SDLK_z = 122 -SDLK_DELETE = 127 -# End of ASCII mapped keysyms - -# International keyboard syms -SDLK_WORLD_0 = 160 # 0xA0 -SDLK_WORLD_1 = 161 -SDLK_WORLD_2 = 162 -SDLK_WORLD_3 = 163 -SDLK_WORLD_4 = 164 -SDLK_WORLD_5 = 165 -SDLK_WORLD_6 = 166 -SDLK_WORLD_7 = 167 -SDLK_WORLD_8 = 168 -SDLK_WORLD_9 = 169 -SDLK_WORLD_10 = 170 -SDLK_WORLD_11 = 171 -SDLK_WORLD_12 = 172 -SDLK_WORLD_13 = 173 -SDLK_WORLD_14 = 174 -SDLK_WORLD_15 = 175 -SDLK_WORLD_16 = 176 -SDLK_WORLD_17 = 177 -SDLK_WORLD_18 = 178 -SDLK_WORLD_19 = 179 -SDLK_WORLD_20 = 180 -SDLK_WORLD_21 = 181 -SDLK_WORLD_22 = 182 -SDLK_WORLD_23 = 183 -SDLK_WORLD_24 = 184 -SDLK_WORLD_25 = 185 -SDLK_WORLD_26 = 186 -SDLK_WORLD_27 = 187 -SDLK_WORLD_28 = 188 -SDLK_WORLD_29 = 189 -SDLK_WORLD_30 = 190 -SDLK_WORLD_31 = 191 -SDLK_WORLD_32 = 192 -SDLK_WORLD_33 = 193 -SDLK_WORLD_34 = 194 -SDLK_WORLD_35 = 195 -SDLK_WORLD_36 = 196 -SDLK_WORLD_37 = 197 -SDLK_WORLD_38 = 198 -SDLK_WORLD_39 = 199 -SDLK_WORLD_40 = 200 -SDLK_WORLD_41 = 201 -SDLK_WORLD_42 = 202 -SDLK_WORLD_43 = 203 -SDLK_WORLD_44 = 204 -SDLK_WORLD_45 = 205 -SDLK_WORLD_46 = 206 -SDLK_WORLD_47 = 207 -SDLK_WORLD_48 = 208 -SDLK_WORLD_49 = 209 -SDLK_WORLD_50 = 210 -SDLK_WORLD_51 = 211 -SDLK_WORLD_52 = 212 -SDLK_WORLD_53 = 213 -SDLK_WORLD_54 = 214 -SDLK_WORLD_55 = 215 -SDLK_WORLD_56 = 216 -SDLK_WORLD_57 = 217 -SDLK_WORLD_58 = 218 -SDLK_WORLD_59 = 219 -SDLK_WORLD_60 = 220 -SDLK_WORLD_61 = 221 -SDLK_WORLD_62 = 222 -SDLK_WORLD_63 = 223 -SDLK_WORLD_64 = 224 -SDLK_WORLD_65 = 225 -SDLK_WORLD_66 = 226 -SDLK_WORLD_67 = 227 -SDLK_WORLD_68 = 228 -SDLK_WORLD_69 = 229 -SDLK_WORLD_70 = 230 -SDLK_WORLD_71 = 231 -SDLK_WORLD_72 = 232 -SDLK_WORLD_73 = 233 -SDLK_WORLD_74 = 234 -SDLK_WORLD_75 = 235 -SDLK_WORLD_76 = 236 -SDLK_WORLD_77 = 237 -SDLK_WORLD_78 = 238 -SDLK_WORLD_79 = 239 -SDLK_WORLD_80 = 240 -SDLK_WORLD_81 = 241 -SDLK_WORLD_82 = 242 -SDLK_WORLD_83 = 243 -SDLK_WORLD_84 = 244 -SDLK_WORLD_85 = 245 -SDLK_WORLD_86 = 246 -SDLK_WORLD_87 = 247 -SDLK_WORLD_88 = 248 -SDLK_WORLD_89 = 249 -SDLK_WORLD_90 = 250 -SDLK_WORLD_91 = 251 -SDLK_WORLD_92 = 252 -SDLK_WORLD_93 = 253 -SDLK_WORLD_94 = 254 -SDLK_WORLD_95 = 255 # 0xFF - -# Numeric keypad -SDLK_KP0 = 256 -SDLK_KP1 = 257 -SDLK_KP2 = 258 -SDLK_KP3 = 259 -SDLK_KP4 = 260 -SDLK_KP5 = 261 -SDLK_KP6 = 262 -SDLK_KP7 = 263 -SDLK_KP8 = 264 -SDLK_KP9 = 265 -SDLK_KP_PERIOD = 266 -SDLK_KP_DIVIDE = 267 -SDLK_KP_MULTIPLY = 268 -SDLK_KP_MINUS = 269 -SDLK_KP_PLUS = 270 -SDLK_KP_ENTER = 271 -SDLK_KP_EQUALS = 272 - -# Arrows + Home/End pad -SDLK_UP = 273 -SDLK_DOWN = 274 -SDLK_RIGHT = 275 -SDLK_LEFT = 276 -SDLK_INSERT = 277 -SDLK_HOME = 278 -SDLK_END = 279 -SDLK_PAGEUP = 280 -SDLK_PAGEDOWN = 281 - -# Function keys -SDLK_F1 = 282 -SDLK_F2 = 283 -SDLK_F3 = 284 -SDLK_F4 = 285 -SDLK_F5 = 286 -SDLK_F6 = 287 -SDLK_F7 = 288 -SDLK_F8 = 289 -SDLK_F9 = 290 -SDLK_F10 = 291 -SDLK_F11 = 292 -SDLK_F12 = 293 -SDLK_F13 = 294 -SDLK_F14 = 295 -SDLK_F15 = 296 - -# Key state modifier keys -SDLK_NUMLOCK = 300 -SDLK_CAPSLOCK = 301 -SDLK_SCROLLOCK = 302 -SDLK_RSHIFT = 303 -SDLK_LSHIFT = 304 -SDLK_RCTRL = 305 -SDLK_LCTRL = 306 -SDLK_RALT = 307 -SDLK_LALT = 308 -SDLK_RMETA = 309 -SDLK_LMETA = 310 -SDLK_LSUPER = 311 # Left "Windows" key -SDLK_RSUPER = 312 # Right "Windows" key -SDLK_MODE = 313 # "Alt Gr" key -SDLK_COMPOSE = 314 # Multi-key compose key - -# Miscellaneous function keys -SDLK_HELP = 315 -SDLK_PRINT = 316 -SDLK_SYSREQ = 317 -SDLK_BREAK = 318 -SDLK_MENU = 319 -SDLK_POWER = 320 # Power Macintosh power key -SDLK_EURO = 321 # Some european keyboards -SDLK_UNDO = 322 # Atari keyboard has Undo - -SDLK_LAST = 323 # Keep me updated please. - -# end of enum SDLKey - -# enum SDLMod - -KMOD_NONE = 0x0000 -KMOD_LSHIFT = 0x0001 -KMOD_RSHIFT = 0x0002 -KMOD_LCTRL = 0x0040 -KMOD_RCTRL = 0x0080 -KMOD_LALT = 0x0100 -KMOD_RALT = 0x0200 -KMOD_LMETA = 0x0400 -KMOD_RMETA = 0x0800 -KMOD_NUM = 0x1000 -KMOD_CAPS = 0x2000 -KMOD_MODE = 0x4000 -KMOD_RESERVED = 0x8000 - -# end of enum SDLMod - -KMOD_CTRL = KMOD_LCTRL | KMOD_RCTRL -KMOD_SHIFT = KMOD_LSHIFT | KMOD_RSHIFT -KMOD_ALT = KMOD_LALT | KMOD_RALT -KMOD_META = KMOD_LMETA | KMOD_RMETA - -#BEGIN GENERATED CONSTANTS; see support/make_constants.py - -#Constants from SDL_mouse.h: -SDL_BUTTON_LEFT = 0x00000001 -SDL_BUTTON_MIDDLE = 0x00000002 -SDL_BUTTON_RIGHT = 0x00000003 -SDL_BUTTON_WHEELUP = 0x00000004 -SDL_BUTTON_WHEELDOWN = 0x00000005 - -#Constants from SDL_version.h: -SDL_MAJOR_VERSION = 0x00000001 -SDL_MINOR_VERSION = 0x00000002 -SDL_PATCHLEVEL = 0x0000000a - -#Constants from SDL.h: -SDL_INIT_TIMER = 0x00000001 -SDL_INIT_AUDIO = 0x00000010 -SDL_INIT_VIDEO = 0x00000020 -SDL_INIT_CDROM = 0x00000100 -SDL_INIT_JOYSTICK = 0x00000200 -SDL_INIT_NOPARACHUTE = 0x00100000 -SDL_INIT_EVENTTHREAD = 0x01000000 -SDL_INIT_EVERYTHING = 0x0000ffff - -#Constants from SDL_mutex.h: -SDL_MUTEX_TIMEDOUT = 0x00000001 - -#Constants from SDL_video.h: -SDL_ALPHA_OPAQUE = 0x000000ff -SDL_ALPHA_TRANSPARENT = 0x00000000 -SDL_SWSURFACE = 0x00000000 -SDL_HWSURFACE = 0x00000001 -SDL_ASYNCBLIT = 0x00000004 -SDL_ANYFORMAT = 0x10000000 -SDL_HWPALETTE = 0x20000000 -SDL_DOUBLEBUF = 0x40000000 -SDL_FULLSCREEN = 0x80000000 -SDL_OPENGL = 0x00000002 -SDL_OPENGLBLIT = 0x0000000a -SDL_RESIZABLE = 0x00000010 -SDL_NOFRAME = 0x00000020 -SDL_HWACCEL = 0x00000100 -SDL_SRCCOLORKEY = 0x00001000 -SDL_RLEACCELOK = 0x00002000 -SDL_RLEACCEL = 0x00004000 -SDL_SRCALPHA = 0x00010000 -SDL_PREALLOC = 0x01000000 -SDL_YV12_OVERLAY = 0x32315659 -SDL_IYUV_OVERLAY = 0x56555949 -SDL_YUY2_OVERLAY = 0x32595559 -SDL_UYVY_OVERLAY = 0x59565955 -SDL_YVYU_OVERLAY = 0x55595659 -SDL_LOGPAL = 0x00000001 -SDL_PHYSPAL = 0x00000002 - -#Constants from SDL_name.h: -NeedFunctionPrototypes = 0x00000001 - -#Constants from SDL_endian.h: -SDL_LIL_ENDIAN = 0x000004d2 -SDL_BIG_ENDIAN = 0x000010e1 - -#Constants from SDL_audio.h: -AUDIO_U8 = 0x00000008 -AUDIO_S8 = 0x00008008 -AUDIO_U16LSB = 0x00000010 -AUDIO_S16LSB = 0x00008010 -AUDIO_U16MSB = 0x00001010 -AUDIO_S16MSB = 0x00009010 -SDL_MIX_MAXVOLUME = 0x00000080 - -#Constants from begin_code.h: -NULL = 0x00000000 - -#Constants from SDL_cdrom.h: -SDL_MAX_TRACKS = 0x00000063 -SDL_AUDIO_TRACK = 0x00000000 -SDL_DATA_TRACK = 0x00000004 -CD_FPS = 0x0000004b - -#Constants from SDL_events.h: -SDL_RELEASED = 0x00000000 -SDL_PRESSED = 0x00000001 -SDL_ALLEVENTS = 0xffffffff -SDL_IGNORE = 0x00000000 -SDL_DISABLE = 0x00000000 -SDL_ENABLE = 0x00000001 - -#Constants from SDL_active.h: -SDL_APPMOUSEFOCUS = 0x00000001 -SDL_APPINPUTFOCUS = 0x00000002 -SDL_APPACTIVE = 0x00000004 - -#Constants from SDL_joystick.h: -SDL_HAT_CENTERED = 0x00000000 -SDL_HAT_UP = 0x00000001 -SDL_HAT_RIGHT = 0x00000002 -SDL_HAT_DOWN = 0x00000004 -SDL_HAT_LEFT = 0x00000008 - -#Constants from SDL_keyboard.h: -SDL_ALL_HOTKEYS = 0xffffffff -SDL_DEFAULT_REPEAT_DELAY = 0x000001f4 -SDL_DEFAULT_REPEAT_INTERVAL = 0x0000001e - -#Constants from SDL_rwops.h: -RW_SEEK_SET = 0x00000000 -RW_SEEK_CUR = 0x00000001 -RW_SEEK_END = 0x00000002 - -#Constants from SDL_timer.h: -SDL_TIMESLICE = 0x0000000a -TIMER_RESOLUTION = 0x0000000a -#END GENERATED CONSTANTS - -# From SDL_audio.h (inserted manually) - -# enum SDL_audiostatus -(SDL_AUDIO_STOPPED, - SDL_AUDIO_PLAYING, - SDL_AUDIO_PAUSED) = range(3) - -if sys.byteorder == 'little': - AUDIO_U16SYS = AUDIO_U16LSB - AUDIO_S16SYS = AUDIO_S16LSB -else: - AUDIO_U16SYS = AUDIO_U16MSB - AUDIO_S16SYS = AUDIO_S16MSB -AUDIO_U16 = AUDIO_U16LSB -AUDIO_S16 = AUDIO_S16LSB - -# From SDL_cdrom.h (inserted manually) -# enum CDstatus -(CD_TRAYEMPTY, - CD_STOPPED, - CD_PLAYING, - CD_PAUSED) = range(4) -CD_ERROR = -1 - -# From SDL_events.h (inserted manually) -# enum SDL_EventType -(SDL_NOEVENT, - SDL_ACTIVEEVENT, - SDL_KEYDOWN, - SDL_KEYUP, - SDL_MOUSEMOTION, - SDL_MOUSEBUTTONDOWN, - SDL_MOUSEBUTTONUP, - SDL_JOYAXISMOTION, - SDL_JOYBALLMOTION, - SDL_JOYHATMOTION, - SDL_JOYBUTTONDOWN, - SDL_JOYBUTTONUP, - SDL_QUIT, - SDL_SYSWMEVENT, - SDL_EVENT_RESERVEDA, - SDL_EVENT_RESERVEDB, - SDL_VIDEORESIZE, - SDL_VIDEOEXPOSE, - SDL_EVENT_RESERVED2, - SDL_EVENT_RESERVED3, - SDL_EVENT_RESERVED4, - SDL_EVENT_RESERVED5, - SDL_EVENT_RESERVED6, - SDL_EVENT_RESERVED7) = range(24) -SDL_USEREVENT = 24 -SDL_NUMEVENTS = 32 - -def SDL_EVENTMASK(x): - '''Used for predefining event masks.''' - return 1 << x - -# enum SDL_EventMask -SDL_ACTIVEEVENTMASK = SDL_EVENTMASK(SDL_ACTIVEEVENT) -SDL_KEYDOWNMASK = SDL_EVENTMASK(SDL_KEYDOWN) -SDL_KEYUPMASK = SDL_EVENTMASK(SDL_KEYUP) -SDL_KEYEVENTMASK = SDL_KEYUPMASK | \ - SDL_KEYDOWNMASK -SDL_MOUSEMOTIONMASK = SDL_EVENTMASK(SDL_MOUSEMOTION) -SDL_MOUSEBUTTONDOWNMASK = SDL_EVENTMASK(SDL_MOUSEBUTTONDOWN) -SDL_MOUSEBUTTONUPMASK = SDL_EVENTMASK(SDL_MOUSEBUTTONUP) -SDL_MOUSEEVENTMASK = SDL_MOUSEMOTIONMASK | \ - SDL_MOUSEBUTTONDOWNMASK | \ - SDL_MOUSEBUTTONUPMASK -SDL_JOYAXISMOTIONMASK = SDL_EVENTMASK(SDL_JOYAXISMOTION) -SDL_JOYBALLMOTIONMASK = SDL_EVENTMASK(SDL_JOYBALLMOTION) -SDL_JOYHATMOTIONMASK = SDL_EVENTMASK(SDL_JOYHATMOTION) -SDL_JOYBUTTONDOWNMASK = SDL_EVENTMASK(SDL_JOYBUTTONDOWN) -SDL_JOYBUTTONUPMASK = SDL_EVENTMASK(SDL_JOYBUTTONUP) -SDL_JOYEVENTMASK = SDL_JOYAXISMOTIONMASK | \ - SDL_JOYBALLMOTIONMASK | \ - SDL_JOYHATMOTIONMASK | \ - SDL_JOYBUTTONDOWNMASK | \ - SDL_JOYBUTTONUPMASK -SDL_QUITMASK = SDL_EVENTMASK(SDL_QUIT) -SDL_SYSWMEVENTMASK = SDL_EVENTMASK(SDL_SYSWMEVENT) -SDL_VIDEORESIZEMASK = SDL_EVENTMASK(SDL_VIDEORESIZE) -SDL_VIDEOEXPOSEMASK = SDL_EVENTMASK(SDL_VIDEOEXPOSE) - -# enum SDL_eventaction -(SDL_ADDEVENT, - SDL_PEEKEVENT, - SDL_GETEVENT) = range(3) - -#From SDL_joystick.h (inserted manually) -SDL_HAT_RIGHTUP = SDL_HAT_RIGHT | SDL_HAT_UP -SDL_HAT_RIGHTDOWN = SDL_HAT_RIGHT | SDL_HAT_DOWN -SDL_HAT_LEFTUP = SDL_HAT_LEFT | SDL_HAT_UP -SDL_HAT_LEFTDOWN = SDL_HAT_LEFT | SDL_HAT_DOWN - -# From SDL_video.h (inserted manually) -# enum SDL_GLattr -(SDL_GL_RED_SIZE, - SDL_GL_GREEN_SIZE, - SDL_GL_BLUE_SIZE, - SDL_GL_ALPHA_SIZE, - SDL_GL_BUFFER_SIZE, - SDL_GL_DOUBLEBUFFER, - SDL_GL_DEPTH_SIZE, - SDL_GL_STENCIL_SIZE, - SDL_GL_ACCUM_RED_SIZE, - SDL_GL_ACCUM_GREEN_SIZE, - SDL_GL_ACCUM_BLUE_SIZE, - SDL_GL_ACCUM_ALPHA_SIZE, - SDL_GL_STEREO, - SDL_GL_MULTISAMPLEBUFFERS, - SDL_GL_MULTISAMPLESAMPLES, - SDL_GL_ACCELERATED_VISUAL, - SDL_GL_SWAP_CONTROL) = range(17) - -# enum SDL_GrabMode -(SDL_GRAB_QUERY, - SDL_GRAB_OFF, - SDL_GRAB_ON) = range(-1,2) - -# From SDL_ttf.h (inserted manually) -TTF_STYLE_NORMAL = 0x00 -TTF_STYLE_BOLD = 0x01 -TTF_STYLE_ITALIC = 0x02 -TTF_STYLE_UNDERLINE = 0x04 - -# From SDL_mixer.h (inserted manually) -MIX_CHANNELS = 8 -MIX_DEFAULT_FREQUENCY = 22050 -MIX_MAX_VOLUME = 128 -MIX_CHANNEL_POST = -2 -MIX_EFFECTSMAXSPEED = 'MIX_EFFECTSMAXSPEED' -MIX_DEFAULT_CHANNELS = 2 - -if sys.byteorder == 'little': - MIX_DEFAULT_FORMAT = AUDIO_S16LSB -else: - MIX_DEFAULT_FORMAT = AUDIO_S16MSB - -# enum Mix_Fading -(MIX_NO_FADING, - MIX_FADING_OUT, - MIX_FADING_IN) = range(3) - -# enum Mix_MusicType -(MUS_NONE, - MUS_CMD, - MUS_WAV, - MUS_MOD, - MUS_MID, - MUS_OGG, - MUS_MP3) = range(7) - -# From SDL_sound.h (inserted manually): -# enum Sound_SampleFlags -SOUND_SAMPLEFLAG_NONE = 0 -SOUND_SAMPLEFLAG_CANSEEK = 1 -SOUND_SAMPLEFLAG_EOF = 1 << 29 -SOUND_SAMPLEFLAG_ERROR = 1 << 30 -SOUND_SAMPLEFLAG_EGAIN = 1 << 31 diff --git a/src/m64py/SDL/darwin.py b/src/m64py/SDL/darwin.py deleted file mode 100644 index bf39104..0000000 --- a/src/m64py/SDL/darwin.py +++ /dev/null @@ -1,153 +0,0 @@ -#!/usr/bin/env python - -'''Darwin (OS X) support. - -Appropriated from pygame.macosx -''' - -__docformat__ = 'restructuredtext' -__version__ = '$Id: $' - -import os -import sys - -# SDL-ctypes on OS X requires PyObjC -from Foundation import * -from AppKit import * -import objc -import MacOS - -from .dll import version_compatible -from .events import SDL_Event, SDL_PushEvent - -__all__ = ['init'] - -# Need to do this if not running with a nib -def setupAppleMenu(app): - appleMenuController = NSAppleMenuController.alloc().init() - appleMenuController.retain() - appleMenu = NSMenu.alloc().initWithTitle_('') - appleMenuItem = NSMenuItem.alloc().initWithTitle_action_keyEquivalent_('', None, '') - appleMenuItem.setSubmenu_(appleMenu) - app.mainMenu().addItem_(appleMenuItem) - appleMenuController.controlMenu_(appleMenu) - app.mainMenu().removeItem_(appleMenuItem) - -# Need to do this if not running with a nib -def setupWindowMenu(app): - windowMenu = NSMenu.alloc().initWithTitle_('Window') - windowMenu.retain() - menuItem = NSMenuItem.alloc().initWithTitle_action_keyEquivalent_('Minimize', 'performMiniaturize:', 'm') - windowMenu.addItem_(menuItem) - windowMenuItem = NSMenuItem.alloc().initWithTitle_action_keyEquivalent_('Window', None, '') - windowMenuItem.setSubmenu_(windowMenu) - app.mainMenu().addItem_(windowMenuItem) - app.setWindowsMenu_(windowMenu) - -# Used to cleanly terminate -class SDLAppDelegate(NSObject): - def applicationShouldTerminate_(self, app): - event = SDL_Event() - event.type = SDL_QUIT - SDL_PushEvent(event) - return NSTerminateLater - - def windowUpdateNotification_(self, notification): - win = notification.object() - if not version_compatible((1, 2, 8)) and isinstance(win, objc.lookUpClass('SDL_QuartzWindow')): - # Seems to be a retain count bug in SDL.. workaround! - win.retain() - NSNotificationCenter.defaultCenter().removeObserver_name_object_( - self, NSWindowDidUpdateNotification, None) - self.release() - -def setIcon(app, icon_data): - data = NSData.dataWithBytes_length_(icon_data, len(icon_data)) - if data is None: - return - img = NSImage.alloc().initWithData_(data) - if img is None: - return - app.setApplicationIconImage_(img) - -def install(): - app = NSApplication.sharedApplication() - appDelegate = SDLAppDelegate.alloc().init() - app.setDelegate_(appDelegate) - appDelegate.retain() - NSNotificationCenter.defaultCenter().addObserver_selector_name_object_( - appDelegate, - 'windowUpdateNotification:', - NSWindowDidUpdateNotification, - None) - if not app.mainMenu(): - mainMenu = NSMenu.alloc().init() - app.setMainMenu_(mainMenu) - setupAppleMenu(app) - setupWindowMenu(app) - app.finishLaunching() - app.updateWindows() - app.activateIgnoringOtherApps_(True) - -def S(*args): - return ''.join(args) - -OSErr = objc._C_SHT -OUTPSN = 'o^{ProcessSerialNumber=LL}' -INPSN = 'n^{ProcessSerialNumber=LL}' - -FUNCTIONS=[ - # These two are public API - ( u'GetCurrentProcess', S(OSErr, OUTPSN) ), - ( u'SetFrontProcess', S(OSErr, INPSN) ), - # This is undocumented SPI - ( u'CPSSetProcessName', S(OSErr, INPSN, objc._C_CHARPTR) ), - ( u'CPSEnableForegroundOperation', S(OSErr, INPSN) ), -] - -def WMEnable(name=None): - if name is None: - name = os.path.splitext(os.path.basename(sys.argv[0]))[0] - if isinstance(name, unicode): - name = name.encode() - if not hasattr(objc, 'loadBundleFunctions'): - return False - bndl = NSBundle.bundleWithPath_(objc.pathForFramework('/System/Library/Frameworks/ApplicationServices.framework')) - if bndl is None: - print >>sys.stderr, 'ApplicationServices missing' - return False - d = {} - app = NSApplication.sharedApplication() - objc.loadBundleFunctions(bndl, d, FUNCTIONS) - for (fn, sig) in FUNCTIONS: - if fn not in d: - print >>sys.stderr, 'Missing', fn - return False - err, psn = d['GetCurrentProcess']() - if err: - print >>sys.stderr, 'GetCurrentProcess', (err, psn) - return False - err = d['CPSSetProcessName'](psn, name) - if err: - print >>sys.stderr, 'CPSSetProcessName', (err, psn) - return False - err = d['CPSEnableForegroundOperation'](psn) - if err: - print >>sys.stderr, 'CPSEnableForegroundOperation', (err, psn) - return False - err = d['SetFrontProcess'](psn) - if err: - print >>sys.stderr, 'SetFrontProcess', (err, psn) - return False - return True - -def init(): - if not (MacOS.WMAvailable() or WMEnable()): - raise ImportError("Can not access the window manager. Use py2app or execute with the pythonw script.") - if not NSApp(): - # running outside of a bundle - install() - # running inside a bundle, change dir - if (os.getcwd() == '/') and len(sys.argv) > 1: - os.chdir(os.path.dirname(sys.argv[0])) - return True diff --git a/src/m64py/SDL/dll.py b/src/m64py/SDL/dll.py deleted file mode 100644 index 49dd02a..0000000 --- a/src/m64py/SDL/dll.py +++ /dev/null @@ -1,230 +0,0 @@ -#!/usr/bin/env python - -''' -''' - -__docformat__ = 'restructuredtext' -__version__ = '$Id: $' - -from ctypes import * -#from ctypes.util import find_library -from m64py.loader import find_library -import sys - -# Private version checking declared before SDL.version can be -# imported. -class _SDL_version(Structure): - _fields_ = [('major', c_ubyte), - ('minor', c_ubyte), - ('patch', c_ubyte)] - - def __repr__(self): - return '%d.%d.%d' % \ - (self.major, self.minor, self.patch) - -def _version_parts(v): - '''Return a tuple (major, minor, patch) for `v`, which can be - an _SDL_version, string or tuple.''' - if hasattr(v, 'major') and hasattr(v, 'minor') and hasattr(v, 'patch'): - return v.major, v.minor, v.patch - elif type(v) == tuple: - return v - elif type(v) == str: - return tuple([int(i) for i in v.split('.')]) - else: - raise TypeError - -def _version_string(v): - return '%d.%d.%d' % _version_parts(v) - -def _platform_library_name(library): - if sys.platform[:5] == 'linux': - return 'lib%.so' % library - elif sys.platform == 'darwin': - return '%s.dylib' % library - elif sys.platform == 'windows': - return '%s.dll' % library - return library - -class SDL_DLL: - def __init__(self, library_name, version_function_name): - if sys.platform[:5] == 'linux': - library_name = '%s-1.2' % library_name - elif sys.platform == 'darwin': - library_name = '%s-1.2.0' % library_name - self.library_name = library_name - library = find_library(library_name) - if not library: - raise ImportError('Dynamic library "%s" was not found' % \ - _platform_library_name(library_name)) - self._dll = getattr(cdll, library) - - # Get the version of the DLL we're using - if version_function_name: - try: - version_function = getattr(self._dll, version_function_name) - version_function.restype = POINTER(_SDL_version) - self._version = _version_parts(version_function().contents) - except AttributeError: - self._version = (0, 0, 0) - else: - self._version = (0, 0, 0) - - def version_compatible(self, v): - '''Returns True iff `v` is equal to or later than the loaded library - version.''' - v = _version_parts(v) - for i in range(3): - if self._version[i] < v[i]: - return False - return True - - def assert_version_compatible(self, name, since): - '''Raises an exception if `since` is later than the loaded library.''' - if not version_compatible(since): - from .error import SDL_NotImplementedError - raise SDL_NotImplementedError \ - ('%s requires SDL version %s; currently using version %s' % \ - (name, _version_string(since), _version_string(self._version))) - - - - def private_function(self, name, **kwargs): - '''Construct a wrapper function for ctypes with internal documentation - and no argument names.''' - kwargs['doc'] = 'Private wrapper for %s' % name - kwargs['args'] = [] - return self.function(name, **kwargs) - - def function(self, name, doc, args=[], arg_types=[], - return_type=None, - dereference_return=False, - require_return=False, - success_return=None, - error_return=None, - since=None): - '''Construct a wrapper function for ctypes. - - :Parameters: - `name` - The name of the function as it appears in the shared library. - `doc` - Docstring to associate with the wrapper function. - `args` - List of strings giving the argument names. - `arg_types` - List of ctypes classes giving the argument types. - `return_type` - The ctypes class giving the wrapped function's native - return type. - `dereference_return` - If True, the return value is assumed to be a pointer and - will be dereferenced via ``.contents`` before being - returned to the user application. - `require_return` - Used in conjunction with `dereference_return`; if True, an - exception will be raised if the result is NULL; if False - None will be returned when the result is NULL. - `success_return` - If not None, the expected result of the wrapped function. - If the return value does not equal success_return, an - exception will be raised. - `error_return` - If not None, the error result of the wrapped function. If - the return value equals error_return, an exception will be - raised. Cannot be used in conjunction with - `success_return`. - `since` - Tuple (major, minor, patch) or string 'x.y.z' of the first - version of SDL in which this function appears. If the - loaded version predates it, a placeholder function that - raises `SDL_NotImplementedError` will be returned instead. - Set to None if the function is in all versions of SDL. - - ''' - # Check for version compatibility first - if since and not self.version_compatible(since): - def _f(*args, **kwargs): - from .error import SDL_NotImplementedError - raise SDL_NotImplementedError \ - ('%s requires %s %s; currently using version %s' % \ - (name, self.library_name, _version_string(since), - _version_string(self._version))) - if args: - _f._args = args - _f.__doc__ = doc - try: - _f.func_name = name - except TypeError: # read-only in Python 2.3 - pass - return _f - - # Ok, get function from ctypes - func = getattr(self._dll, name) - func.argtypes = arg_types - func.restype = return_type - if dereference_return: - if require_return: - # Construct a function which dereferences the pointer result, - # or raises an exception if NULL is returned. - def _f(*args, **kwargs): - result = func(*args, **kwargs) - if result: - return result.contents - from .error import SDL_Exception, SDL_GetError - raise SDL_Exception(SDL_GetError()) - else: - # Construct a function which dereferences the pointer result, - # or returns None if NULL is returned. - def _f(*args, **kwargs): - result = func(*args, **kwargs) - if result: - return result.contents - return None - elif success_return is not None: - # Construct a function which returns None, but raises an exception - # if the C function returns a failure code. - def _f(*args, **kwargs): - result = func(*args, **kwargs) - if result != success_return: - from .error import SDL_Exception, SDL_GetError - raise SDL_Exception(SDL_GetError()) - return result - elif error_return is not None: - # Construct a function which returns None, but raises an exception - # if the C function returns a failure code. - def _f(*args, **kwargs): - result = func(*args, **kwargs) - if result == error_return: - from .error import SDL_Exception, SDL_GetError - raise SDL_Exception(SDL_GetError()) - return result - elif require_return: - # Construct a function which returns the usual result, or returns - # None if NULL is returned. - def _f(*args, **kwargs): - result = func(*args, **kwargs) - if not result: - from .error import SDL_Exception, SDL_GetError - raise SDL_Exception(SDL_GetError()) - return result - else: - # Construct a function which returns the C function's return - # value. - def _f(*args, **kwargs): - return func(*args, **kwargs) - if args: - _f._args = args - _f.__doc__ = doc - try: - _f.func_name = name - except TypeError: # read-only in Python 2.3 - pass - return _f - -# Shortcuts to the SDL core library -_dll = SDL_DLL('SDL', 'SDL_Linked_Version') -version_compatible = _dll.version_compatible -assert_version_compatible = _dll.assert_version_compatible -private_function = _dll.private_function -function = _dll.function diff --git a/src/m64py/SDL/endian.py b/src/m64py/SDL/endian.py deleted file mode 100644 index 0428099..0000000 --- a/src/m64py/SDL/endian.py +++ /dev/null @@ -1,46 +0,0 @@ -#!/usr/bin/env python - -'''Functions for converting to native byte order -''' - -__docformat__ = 'restructuredtext' -__version__ = '$Id: $' - -import sys - -from .constants import SDL_BIG_ENDIAN, SDL_LIL_ENDIAN - -def SDL_Swap16(x): - return (x << 8 & 0xff00) | \ - (x >> 8 & 0x00ff) - -def SDL_Swap32(x): - return (x << 24 & 0xff000000) | \ - (x << 8 & 0x00ff0000) | \ - (x >> 8 & 0x0000ff00) | \ - (x >> 24 & 0x000000ff) - -def SDL_Swap64(x): - return (SDL_Swap32(x & 0xffffffff) << 32) | \ - (SDL_Swap32(x >> 32 & 0xffffffff)) - -def _noop(x): - return x - -if sys.byteorder == 'big': - SDL_BYTEORDER = SDL_BIG_ENDIAN - SDL_SwapLE16 = SDL_Swap16 - SDL_SwapLE32 = SDL_Swap32 - SDL_SwapLE64 = SDL_Swap64 - SDL_SwapBE16 = _noop - SDL_SwapBE32 = _noop - SDL_SwapBE64 = _noop -else: - SDL_BYTEORDER = SDL_LIL_ENDIAN - SDL_SwapLE16 = _noop - SDL_SwapLE32 = _noop - SDL_SwapLE64 = _noop - SDL_SwapBE16 = SDL_Swap16 - SDL_SwapBE32 = SDL_Swap32 - SDL_SwapBE64 = SDL_Swap64 - diff --git a/src/m64py/SDL/error.py b/src/m64py/SDL/error.py deleted file mode 100644 index 972ec20..0000000 --- a/src/m64py/SDL/error.py +++ /dev/null @@ -1,57 +0,0 @@ -#!/usr/bin/env python - -'''Error detection and error handling functions. -''' - -__docformat__ = 'restructuredtext' -__version__ = '$Id: $' - -from ctypes import * - -from .dll import function - -class SDL_Exception(Exception): - '''Exception raised for all SDL errors. - - The message is as returned by `SDL_GetError`. - ''' - def __init__(self, message): - self.message = message - - def __str__(self): - return self.message - -class SDL_NotImplementedError(NotImplementedError): - '''Exception raised when the available SDL library predates the - requested function.''' - pass - -SDL_SetError = function('SDL_SetError', - '''Set the static error string. - - :Parameters: - `fmt` - format string; subsequent integer and string arguments are - interpreted as in printf(). - ''', - args=['fmt'], - arg_types=[c_char_p], - return_type=None) - -SDL_GetError = function('SDL_GetError', - '''Return the last error string set. - - :rtype: string - ''', - args=[], - arg_types=[], - return_type=c_char_p) - -SDL_ClearError = function('SDL_ClearError', - '''Clear any error string set. - ''', - args=[], - arg_types=[], - return_type=None) - -# SDL_Error not implemented (marked private in SDL_error.h) diff --git a/src/m64py/SDL/events.py b/src/m64py/SDL/events.py deleted file mode 100644 index f732a54..0000000 --- a/src/m64py/SDL/events.py +++ /dev/null @@ -1,538 +0,0 @@ -#!/usr/bin/env python - -'''Event handling. -''' - -__docformat__ = 'restructuredtext' -__version__ = '$Id: $' - -from ctypes import * - -from .constants import * -from .dll import function, private_function -from .keyboard import SDL_keysym -from .error import SDL_Exception, SDL_GetError - -class SDL_ActiveEvent(Structure): - '''Application visibility event structure. - - :see: `SDL_GetAppState` - - :Ivariables: - `type` : int - SDL_ACTIVEEVENT - `gain` : int - 1 if states were gained, zero otherwise - `state` : int - A mask of the focus states. A bitwise OR combination of: - SDL_APPMOUSEFOCUS, SDL_APPINPUTFOCUS and SDL_APPACTIVE. - - ''' - _fields_ = [('type', c_ubyte), - ('gain', c_ubyte), - ('state', c_ubyte)] - -class SDL_KeyboardEvent(Structure): - '''Keyboard event structure. - - :Ivariables: - `type` : int - SDL_KEYDOWN or SDL_KEYUP - `which` : int - The keyboard device index - `state` : int - SDL_PRESSED or SDL_RELEASED - `keysym` : `SDL_keysym` - Decoded key information. - - ''' - _fields_ = [('type', c_ubyte), - ('which', c_ubyte), - ('state', c_ubyte), - ('keysym', SDL_keysym)] - -class SDL_MouseMotionEvent(Structure): - '''Mouse motion event structure. - - :Ivariables: - `type` : int - SDL_MOUSEMOTION - `which` : int - The mouse device index - `state` : int - The current button state - `x` : int - The X coordinate of the mouse pointer - `y` : int - The Y coordinate of the mouse pointer - `xrel` : int - The relative motion in the X direction - `yrel` : int - The relative motion in the Y direction - - ''' - _fields_ = [('type', c_ubyte), - ('which', c_ubyte), - ('state', c_ubyte), - ('x', c_ushort), - ('y', c_ushort), - ('xrel', c_short), - ('yrel', c_short)] - -class SDL_MouseButtonEvent(Structure): - '''Mouse button event structure. - - :Ivariables: - `type` : int - SDL_MOUSEBUTTONDOWN or SDL_MOUSEBUTTONUP - `which` : int - The mouse device index - `button` : int - The mouse button index - `state` : int - SDL_PRESSED or SDL_RELEASED - `x` : int - The X coordinate of the mouse pointer - `y` : int - The Y coordinate of the mouse pointer - - ''' - _fields_ = [('type', c_ubyte), - ('which', c_ubyte), - ('button', c_ubyte), - ('state', c_ubyte), - ('x', c_ushort), - ('y', c_ushort)] - -class SDL_JoyAxisEvent(Structure): - '''Joystick axis motion event structure. - - :Ivariables: - `type` : int - SDL_JOYAXISMOTION - `which` : int - The joystick device index - `axis` : int - The joystick axis index - `value` : int - The axis value, in range [-32768, 32767] - - ''' - _fields_ = [('type', c_ubyte), - ('which', c_ubyte), - ('axis', c_ubyte), - ('value', c_short)] - -class SDL_JoyBallEvent(Structure): - '''Joystick trackball motion event structure. - - :Ivariables: - `type` : int - SDL_JOYBALLMOTION - `which` : int - The joystick device index - `ball` : int - The joystick trackball index - `xrel` : int - The relative motion in the X direction - `yrel` : int - The relative motion in the Y direction - - ''' - _fields_ = [('type', c_ubyte), - ('which', c_ubyte), - ('ball', c_ubyte), - ('xrel', c_short), - ('yrel', c_short)] - -class SDL_JoyHatEvent(Structure): - '''Joystick hat position change event structure. - - :Ivariables: - `type` : int - SDL_JOYHATMOTION - `which` : int - The joystick device index - `hat` : int - The joystick hat index - `value` : int - The hat position value. One of: SDL_HAT_LEFTUP, SDL_HAT_UP, - SDL_HAT_RIGHTUP, SDL_HAT_LEFT, SDL_HAT_CENTERED, SDL_HAT_RIGHT, - SDL_HAT_LEFTDOWN, SDL_HAT_DOWN, SDL_HAT_RIGHTDOWN. Note that - zero means the POV is centered. - - ''' - _fields_ = [('type', c_ubyte), - ('which', c_ubyte), - ('hat', c_ubyte), - ('value', c_ubyte)] - -class SDL_JoyButtonEvent(Structure): - '''Joystick button event structure. - - :Ivariables: - `type` : int - SDL_JOYBUTTONDOWN or SDL_JOYBUTTONUP - `which` : int - The joystick device index - `button` : int - The joystick button index - `state` : int - SDL_PRESSED or SDL_RELEASED - - ''' - _fields_ = [('type', c_ubyte), - ('which', c_ubyte), - ('button', c_ubyte), - ('state', c_ubyte)] - -class SDL_ResizeEvent(Structure): - '''The window resized event structure. - - :Ivariables: - `type` : int - SDL_VIDEORESIZE - `w` : int - New width - `h` : int - New height - - ''' - _fields_ = [('type', c_ubyte), - ('w', c_int), - ('h', c_int)] - -class SDL_ExposeEvent(Structure): - '''The screen redraw event structure. - - :Ivariables: - `type` : int - SDL_VIDEOEXPOSE - - ''' - _fields_ = [('type', c_ubyte)] - -class SDL_QuitEvent(Structure): - '''The quit requested event structure - - :Ivariables: - `type` : int - SDL_QUIT - - ''' - _fields_ = [('type', c_ubyte)] - -class SDL_UserEvent(Structure): - '''A user-defined event structure. - - :Ivariables: - `type` : int - SDL_USEREVENT through SDL_NUMEVENTS - 1 - `code` : int - User defined event code - - ''' - # pygame-ctypes needs data1 and data2 to be c_void_p; POINTER(c_ubyte) - # or similar will break it (see pygame/event.py) unless another workaround - # can be found. - _fields_ = [('type', c_ubyte), - ('code', c_int), - ('data1', c_void_p), - ('data2', c_void_p)] - -class SDL_SysWMEvent(Structure): - '''System window management event structure. - - :Ivariables: - `type` : int - SDL_SYSWMEVENT - - ''' - _fields_ = [('type', c_ubyte), - ('msg', c_void_p)] # TODO with SDL_syswm.h - -class SDL_Event(Union): - '''Union event structure. - - Events returned from functions are always returned as the - specialised subclass; for example you will receive a - `SDL_MouseMotionEvent` rather than `SDL_Event`. This structure - therefore has limited application use, but is used internally. - - :Ivariables: - `type` : int - Type of event - - ''' - _fields_ = [('type', c_ubyte), - ('active', SDL_ActiveEvent), - ('key', SDL_KeyboardEvent), - ('motion', SDL_MouseMotionEvent), - ('button', SDL_MouseButtonEvent), - ('jaxis', SDL_JoyAxisEvent), - ('jball', SDL_JoyBallEvent), - ('jhat', SDL_JoyHatEvent), - ('jbutton', SDL_JoyButtonEvent), - ('resize', SDL_ResizeEvent), - ('expose', SDL_ExposeEvent), - ('quit', SDL_QuitEvent), - ('user', SDL_UserEvent), - ('syswm', SDL_SysWMEvent)] - - types = { - SDL_ACTIVEEVENT: (SDL_ActiveEvent, 'active'), - SDL_KEYDOWN: (SDL_KeyboardEvent, 'key'), - SDL_KEYUP: (SDL_KeyboardEvent, 'key'), - SDL_MOUSEMOTION: (SDL_MouseMotionEvent, 'motion'), - SDL_MOUSEBUTTONDOWN: (SDL_MouseButtonEvent, 'button'), - SDL_MOUSEBUTTONUP: (SDL_MouseButtonEvent, 'button'), - SDL_JOYAXISMOTION: (SDL_JoyAxisEvent, 'jaxis'), - SDL_JOYBALLMOTION: (SDL_JoyBallEvent, 'jball'), - SDL_JOYHATMOTION: (SDL_JoyHatEvent, 'jhat'), - SDL_JOYBUTTONDOWN: (SDL_JoyButtonEvent, 'jbutton'), - SDL_JOYBUTTONUP: (SDL_JoyButtonEvent, 'jbutton'), - SDL_VIDEORESIZE: (SDL_ResizeEvent, 'resize'), - SDL_VIDEOEXPOSE: (SDL_ExposeEvent, 'expose'), - SDL_QUIT: (SDL_QuitEvent, 'quit'), - SDL_SYSWMEVENT: (SDL_SysWMEvent, 'syswm') - } - - def __init__(self, typecode=0): - self.type = typecode - - def __repr__(self): - if self.type in self.types: - return self.types[self.type][0].__repr__(self) - elif self.type >= SDL_USEREVENT: - # SDL_MAXEVENTS not defined - return SDL_UserEvent.__repr__(self) - return 'SDLEvent(type=%d)' % self.type - - def specialize(self): - '''Get an instance of the specialized subclass for this event, - based on `self.type`. - - :rtype: `SDL_Event` subclass - ''' - if self.type in self.types: - return getattr(self, self.types[self.type][1]) - elif self.type >= SDL_USEREVENT: - # SDL_MAXEVENTS not defined - return self.user - return self - -SDL_PumpEvents = function('SDL_PumpEvents', - '''Pumps the event loop, gathering events from the input devices. - - This function updates the event queue and internal input device state. - This should only be run in the thread that sets the video mode. - ''', - args=[], - arg_types=[], - return_type=None) - -_SDL_PeepEvents = private_function('SDL_PeepEvents', - arg_types=[POINTER(SDL_Event), c_int, c_int, c_uint], - return_type=c_int) - -def SDL_PeepEvents(numevents, action, mask): - '''Check the event queue for messages and optionally return them. - - The behaviour depends on `action`: - - `SDL_ADDEVENT` - Not implemented; will raise an exception. See `SDL_PushEvent`. - `SDL_PEEKEVENT` - Up to `numevents` events at the front of the event queue, - matching `mask`, will be returned and will not be removed - from the queue. - `SDL_GETEVENT` - Up to `numevents` events at the front of the event queue, - matching `mask`, will be returned and will be removed from the - queue. - - :Parameters: - `numevents` : int - Maximum number of events to return - `action` : int - Either `SDL_PEEKEVENT` or `SDL_GETEVENT` - `mask` : int - Mask to match type of returned events with. - - :rtype: list - :return: list of SDL_Event (or subclass) - :see: `SDL_PushEvent`, `SDL_HaveEvents` - ''' - if action == SDL_ADDEVENT: - raise NotImplementedError('Use SDL_PushEvent to add events') - ar = (SDL_Event * numevents)() - num = _SDL_PeepEvents(ar, numevents, action, mask) - if num == -1: - raise SDL_Exception(SDL_GetError()) - return list([e.specialize() for e in ar[:num]]) - -def SDL_HaveEvents(mask): - '''Check the event queue for events matching the given mask. - - :note: This function replaces the C function - SDL_PeepEvents(NULL, ...), which had undocumented behaviour. - - :Parameters: - `mask` : int - Mask to match type of returned events with. - - :rtype: bool - :return: True if at least one event matches the mask in the event - queue. - ''' - num = _SDL_PeepEvents(None, 1, SDL_PEEKEVENT, mask) - return num > 0 - -_SDL_PollEvent = private_function('SDL_PollEvent', - arg_types=[POINTER(SDL_Event)], - return_type=c_int) - -def SDL_PollEvent(): - '''Poll for currently pending events. - - Returns True if there are any pending events, or False if there are none - available. - - :see: `SDL_PollEventAndReturn` - :rtype: bool - ''' - return _SDL_PollEvent(None) == 1 - -def SDL_PollEventAndReturn(): - '''Poll for currently pending events, and return one off the queue - if possible. - - :see: `SDL_PollEvent` - :rtype: `SDL_Event` or subclass - ''' - e = SDL_Event() - result = _SDL_PollEvent(byref(e)) - if result == 1: - return e.specialize() - return None - -_SDL_WaitEvent = private_function('SDL_WaitEvent', - arg_types=[POINTER(SDL_Event)], - return_type=c_int) - -def SDL_WaitEvent(): - '''Wait indefinitely for an event. - - Returns when an event is available on the queue, or raises an exception - if an error occurs while waiting. - - :see: `SDL_WaitEventAndReturn` - ''' - if _SDL_WaitEvent(None) == 0: - raise SDL_Exception(SDL_GetError()) - -def SDL_WaitEventAndReturn(): - '''Wait indefinitely for the next event and return it. - - :see: `SDL_WaitEvent` - :rtype: `SDL_Event` or subclass - ''' - ev = SDL_Event() - result = _SDL_WaitEvent(byref(ev)) - if result == 1: - return ev.specialize() - else: - raise SDL_Exception(SDL_GetError()) - -SDL_PushEvent = function('SDL_PushEvent', - '''Add an event to the event queue. - - :Parameters: - - `event`: `SDL_Event` - - ''', - args=['event'], - arg_types=[POINTER(SDL_Event)], - return_type=c_int, - error_return=-1) - - -_SDL_EventFilter = CFUNCTYPE(c_int, POINTER(SDL_Event)) -_SDL_SetEventFilter = private_function('SDL_SetEventFilter', - arg_types=[_SDL_EventFilter], - return_type=None) - -_eventfilter_ref = None # keep global to avoid GC of anon func - -def SDL_SetEventFilter(filter): - '''Set up a filter to process all events before they change internal - state and are posted to the internal event queue. - - :warning: Be very careful of what you do in the event filter function, - as it may run in a different thread. - - There is one caveat when dealing with the `SDL_QUITEVENT` event type. - The event filter is only called when the window manager desires to - close the application window. If the event filter returns 1, then the - window will be closed, otherwise the window will remain open if - possible. If the quit event is generated by an interrupt signal, it - will bypass the internal queue and be delivered to the application at - the next event poll. - - :Parameters: - `filter` : function - a function that takes an `SDL_Event` as a single argument. If - the function returns 1 the event will be added to the internal - queue. If it returns 0, the event will be dropped from the - queue, but the internal state will still be updated. The event - instance must not be modified. - - ''' - global _eventfilter_ref - if filter: - def f(e): - return filter(e.contents.specialize()) - _eventfilter_ref = _SDL_EventFilter(f) - else: - _eventfilter_ref = _SDL_EventFilter() - _SDL_SetEventFilter(_eventfilter_ref) - -SDL_GetEventFilter = function('SDL_GetEventFilter', - '''Return the current event filter. - - This can be used to "chain" filters. If there is no event filter set, - this function returns None. - - :rtype: function - ''', - args=[], - arg_types=[], - return_type=_SDL_EventFilter) - -SDL_EventState = function('SDL_EventState', - '''Ignore or enable the processing of certain events. - - The behaviour of this function depends on `state` - - `SDL_IGNORE` - the event will be automatically dropped from the event queue - and will not be event filtered. - `SDL_ENABLE` - the event will be processed normally. - `SDL_QUERY` - return the current processing state of the event. - - :Parameters: - `type` : int - Type of event, e.g. `SDL_KEYDOWN`, `SDL_MOUSEMOTION`, etc. - (see `SDL_Event`) - `state` : int - One of `SDL_IGNORE`, `SDL_ENABLE` or `SDL_QUERY` - - :rtype: int - :return: the event processing state: either `SDL_IGNORE or - `SDL_ENABLE`. - ''', - args=['type', 'state'], - arg_types=[c_ubyte, c_int], - return_type=c_int) diff --git a/src/m64py/SDL/image.py b/src/m64py/SDL/image.py deleted file mode 100644 index a53b6d3..0000000 --- a/src/m64py/SDL/image.py +++ /dev/null @@ -1,461 +0,0 @@ -#!/usr/bin/env python - -'''Load images of various formats as SDL surfaces. - -This module supports BMP, PNM (PPM/PGM/PBM), XPM, LBM, PCX, GIF, JPEG, PNG, -TGA and TIFF formats. - -Typical usage:: - - from SDL.image import * - surface = IMG_Load('image.png') - -:note: Early versions of this library (pre-1.2.5) do not have versioning - information; do not count on `IMG_Linked_Version` being available. -''' - -__docformat__ = 'restructuredtext' -__version__ = '$Id: $' - -from ctypes import * - -from .dll import SDL_DLL -from .error import SDL_NotImplementedError -from .rwops import SDL_RWops -from .version import SDL_version -from .video import SDL_Surface - -_dll = SDL_DLL('SDL_image', 'IMG_Linked_Version') - -IMG_Linked_Version = _dll.function('IMG_Linked_Version', - '''Get the version of the dynamically linked SDL_image library. - - :since: SDL_image 1.2.5 - ''', - args=[], - arg_types=[], - return_type=POINTER(SDL_version), - dereference_return=True, - require_return=True, - since=(1,2,5)) - -IMG_LoadTyped_RW = _dll.function('IMG_LoadTyped_RW', - '''Load an image from an SDL data source, specifying a type. - - If the image format supports a transparent pixel, SDL will set the - colorkey for the surface. You can enable RLE acceleration on the - surface afterwards by calling:: - - SDL_SetColorKey(image, SDL_RLEACCEL, image.format.colorkey) - - :Parameters: - `src` : `SDL_RWops` - Source RWops to load from. - `freesrc` : int - If non-zero, the source will be freed after loading. - `type` : string - One of "BMP", "GIF", "PNG", etc. - - :rtype: `SDL_Surface` - ''', - args=['src', 'freesrc', 'type'], - arg_types=[POINTER(SDL_RWops), c_int, c_char_p], - return_type=POINTER(SDL_Surface), - dereference_return=True, - require_return=True) - -IMG_Load = _dll.function('IMG_Load', - '''Load an image from a file. - - If the image format supports a transparent pixel, SDL will set the - colorkey for the surface. You can enable RLE acceleration on the - surface afterwards by calling:: - - SDL_SetColorKey(image, SDL_RLEACCEL, image.format.colorkey) - - :Parameters: - `file` : string - Filename to load. - - :rtype: `SDL_Surface` - ''', - args=['file'], - arg_types=[c_char_p], - return_type=POINTER(SDL_Surface), - dereference_return=True, - require_return=True) - -IMG_Load_RW = _dll.function('IMG_Load_RW', - '''Load an image from an SDL data source. - - If the image format supports a transparent pixel, SDL will set the - colorkey for the surface. You can enable RLE acceleration on the - surface afterwards by calling:: - - SDL_SetColorKey(image, SDL_RLEACCEL, image.format.colorkey) - - :Parameters: - `src` : `SDL_RWops` - Source RWops to load from. - `freesrc` : int - If non-zero, the source will be freed after loading. - - :rtype: `SDL_Surface` - ''', - args=['src', 'freesrc'], - arg_types=[POINTER(SDL_RWops), c_int], - return_type=POINTER(SDL_Surface), - dereference_return=True, - require_return=True) - -# IMG_InvertAlpha is a no-op. - -IMG_isBMP = _dll.function('IMG_isBMP', - '''Detect if a seekable source is a BMP image. - - :Parameters: - `src` : `SDL_RWops` - Source RWops to inspect. - - :rtype: int - ''', - args=['src'], - arg_types=[POINTER(SDL_RWops)], - return_type=c_int) - -IMG_isGIF = _dll.function('IMG_isGIF', - '''Detect if a seekable source is a GIF image. - - :Parameters: - `src` : `SDL_RWops` - Source RWops to inspect. - - :rtype: int - ''', - args=['src'], - arg_types=[POINTER(SDL_RWops)], - return_type=c_int) - - -IMG_isJPG = _dll.function('IMG_isJPG', - '''Detect if a seekable source is a JPG image. - - :Parameters: - `src` : `SDL_RWops` - Source RWops to inspect. - - :rtype: int - ''', - args=['src'], - arg_types=[POINTER(SDL_RWops)], - return_type=c_int) - - -IMG_isLBM = _dll.function('IMG_isLBM', - '''Detect if a seekable source is a LBM image. - - :Parameters: - `src` : `SDL_RWops` - Source RWops to inspect. - - :rtype: int - ''', - args=['src'], - arg_types=[POINTER(SDL_RWops)], - return_type=c_int) - - -IMG_isPCX = _dll.function('IMG_isPCX', - '''Detect if a seekable source is a PCX image. - - :Parameters: - `src` : `SDL_RWops` - Source RWops to inspect. - - :rtype: int - ''', - args=['src'], - arg_types=[POINTER(SDL_RWops)], - return_type=c_int) - - -IMG_isPNG = _dll.function('IMG_isPNG', - '''Detect if a seekable source is a PNG image. - - :Parameters: - `src` : `SDL_RWops` - Source RWops to inspect. - - :rtype: int - ''', - args=['src'], - arg_types=[POINTER(SDL_RWops)], - return_type=c_int) - - -IMG_isPNM = _dll.function('IMG_isPNM', - '''Detect if a seekable source is a PNM image. - - :Parameters: - `src` : `SDL_RWops` - Source RWops to inspect. - - :rtype: int - ''', - args=['src'], - arg_types=[POINTER(SDL_RWops)], - return_type=c_int) - - -IMG_isTIF = _dll.function('IMG_isTIF', - '''Detect if a seekable source is a TIF image. - - :Parameters: - `src` : `SDL_RWops` - Source RWops to inspect. - - :rtype: int - ''', - args=['src'], - arg_types=[POINTER(SDL_RWops)], - return_type=c_int) - - -IMG_isXCF = _dll.function('IMG_isXCF', - '''Detect if a seekable source is a XCF image. - - :Parameters: - `src` : `SDL_RWops` - Source RWops to inspect. - - :rtype: int - ''', - args=['src'], - arg_types=[POINTER(SDL_RWops)], - return_type=c_int) - - -IMG_isXPM = _dll.function('IMG_isXPM', - '''Detect if a seekable source is a XPM image. - - :Parameters: - `src` : `SDL_RWops` - Source RWops to inspect. - - :rtype: int - ''', - args=['src'], - arg_types=[POINTER(SDL_RWops)], - return_type=c_int) - - -if hasattr(_dll._dll, 'IMG_isXV'): - IMG_isXV = _dll.function('IMG_isXV', - '''Detect if a seekable source is a XV image. - - :Parameters: - `src` : `SDL_RWops` - Source RWops to inspect. - - :rtype: int - :since: SDL_image 1.2.5 - ''', - args=['src'], - arg_types=[POINTER(SDL_RWops)], - return_type=c_int, - since=(1,2,5)) -else: - # Broken build of SDL_image 1.2.5 on OS X does define xv.c symbols - def IMG_isXV(src): - raise SDL_NotImplementedError('Linked version of ' + \ - 'SDL_image does not define IMG_isXV') - -IMG_LoadBMP_RW = _dll.function('IMG_LoadBMP_RW', - '''Load a BMP image from an SDL data source. - - :Parameters: - `src` : `SDL_RWops` - Source RWops to load from. - - :rtype: `SDL_Surface` - ''', - args=['src'], - arg_types=[POINTER(SDL_RWops)], - return_type=POINTER(SDL_Surface), - dereference_return=True, - require_return=True) - -IMG_LoadGIF_RW = _dll.function('IMG_LoadGIF_RW', - '''Load a GIF image from an SDL data source. - - :Parameters: - `src` : `SDL_RWops` - Source RWops to load from. - - :rtype: `SDL_Surface` - ''', - args=['src'], - arg_types=[POINTER(SDL_RWops)], - return_type=POINTER(SDL_Surface), - dereference_return=True, - require_return=True) - -IMG_LoadJPG_RW = _dll.function('IMG_LoadJPG_RW', - '''Load a JPG image from an SDL data source. - - :Parameters: - `src` : `SDL_RWops` - Source RWops to load from. - - :rtype: `SDL_Surface` - ''', - args=['src'], - arg_types=[POINTER(SDL_RWops)], - return_type=POINTER(SDL_Surface), - dereference_return=True, - require_return=True) - -IMG_LoadLBM_RW = _dll.function('IMG_LoadLBM_RW', - '''Load a LBM image from an SDL data source. - - :Parameters: - `src` : `SDL_RWops` - Source RWops to load from. - - :rtype: `SDL_Surface` - ''', - args=['src'], - arg_types=[POINTER(SDL_RWops)], - return_type=POINTER(SDL_Surface), - dereference_return=True, - require_return=True) - -IMG_LoadPCX_RW = _dll.function('IMG_LoadPCX_RW', - '''Load a PCX image from an SDL data source. - - :Parameters: - `src` : `SDL_RWops` - Source RWops to load from. - - :rtype: `SDL_Surface` - ''', - args=['src'], - arg_types=[POINTER(SDL_RWops)], - return_type=POINTER(SDL_Surface), - dereference_return=True, - require_return=True) - -IMG_LoadPNG_RW = _dll.function('IMG_LoadPNG_RW', - '''Load a PNG image from an SDL data source. - - :Parameters: - `src` : `SDL_RWops` - Source RWops to load from. - - :rtype: `SDL_Surface` - ''', - args=['src'], - arg_types=[POINTER(SDL_RWops)], - return_type=POINTER(SDL_Surface), - dereference_return=True, - require_return=True) - -IMG_LoadPNM_RW = _dll.function('IMG_LoadPNM_RW', - '''Load a PNM image from an SDL data source. - - :Parameters: - `src` : `SDL_RWops` - Source RWops to load from. - - :rtype: `SDL_Surface` - ''', - args=['src'], - arg_types=[POINTER(SDL_RWops)], - return_type=POINTER(SDL_Surface), - dereference_return=True, - require_return=True) - -IMG_LoadTGA_RW = _dll.function('IMG_LoadTGA_RW', - '''Load a TGA image from an SDL data source. - - :Parameters: - `src` : `SDL_RWops` - Source RWops to load from. - - :rtype: `SDL_Surface` - ''', - args=['src'], - arg_types=[POINTER(SDL_RWops)], - return_type=POINTER(SDL_Surface), - dereference_return=True, - require_return=True) - -IMG_LoadTIF_RW = _dll.function('IMG_LoadTIF_RW', - '''Load a TIF image from an SDL data source. - - :Parameters: - `src` : `SDL_RWops` - Source RWops to load from. - - :rtype: `SDL_Surface` - ''', - args=['src'], - arg_types=[POINTER(SDL_RWops)], - return_type=POINTER(SDL_Surface), - dereference_return=True, - require_return=True) - -IMG_LoadXCF_RW = _dll.function('IMG_LoadXCF_RW', - '''Load a XCF image from an SDL data source. - - :Parameters: - `src` : `SDL_RWops` - Source RWops to load from. - - :rtype: `SDL_Surface` - ''', - args=['src'], - arg_types=[POINTER(SDL_RWops)], - return_type=POINTER(SDL_Surface), - dereference_return=True, - require_return=True) - -IMG_LoadXPM_RW = _dll.function('IMG_LoadXPM_RW', - '''Load a XPM image from an SDL data source. - - :Parameters: - `src` : `SDL_RWops` - Source RWops to load from. - - :rtype: `SDL_Surface` - ''', - args=['src'], - arg_types=[POINTER(SDL_RWops)], - return_type=POINTER(SDL_Surface), - dereference_return=True, - require_return=True) - -if hasattr(_dll._dll, 'IMG_LoadXV_RW'): - IMG_LoadXV_RW = _dll.function('IMG_LoadXV_RW', - '''Load a XV image from an SDL data source. - - :Parameters: - `src` : `SDL_RWops` - Source RWops to load from. - - :rtype: `SDL_Surface` - :since: SDL_image 1.2.5 - ''', - args=['src'], - arg_types=[POINTER(SDL_RWops)], - return_type=POINTER(SDL_Surface), - dereference_return=True, - require_return=True, - since=(1,2,5)) -else: - # Broken build of SDL_image 1.2.5 on OS X does define xv.c symbols - def IMG_LoadXV_RW(src): - raise SDL_NotImplementedError('Linked version of ' + \ - 'SDL_image does not define IMG_LoadXV_RW') - -# IMG_ReadXPMFromArray cannot be implemented. diff --git a/src/m64py/SDL/joystick.py b/src/m64py/SDL/joystick.py deleted file mode 100644 index 3b70b99..0000000 --- a/src/m64py/SDL/joystick.py +++ /dev/null @@ -1,249 +0,0 @@ -#!/usr/bin/env python - -'''Joystick event handling. - -TODO: This module is completely untested. -''' - -__docformat__ = 'restructuredtext' -__version__ = '$Id: $' - -from ctypes import * - -from .dll import function, private_function - -class _SDL_Joystick(Structure): - _fields_ = [('_dummy', c_void_p)] - -SDL_Joystick_p = POINTER(_SDL_Joystick) - -SDL_NumJoysticks = function('SDL_NumJoysticks', - '''Count the number of joysticks attached to the system. - - :rtype: int - ''', - args=[], - arg_types=[], - return_type=c_int) - -SDL_JoystickName = function('SDL_JoystickName', - '''Get the implementation dependent name of a joystick. - - This can be called before any joysticks are opened. If no name can be - found, this function returns None. - - :Parameters: - - `device_index`: int - - :rtype: str - ''', - args=['device_index'], - arg_types=[c_int], - return_type=c_char_p) - -SDL_JoystickOpen = function('SDL_JoystickOpen', - '''Open a joystick for use. - - The index passed as an argument refers to the N'th joystick on the - system. This index is the value which will identify this joystick in - future joystick events. - - This function returns an opaque joystick identifier. - - :Parameters: - - `device_index`: int - - :rtype: `SDL_Joystick_p` - ''', - args=['device_index'], - arg_types=[c_int], - return_type=SDL_Joystick_p, - require_return=True) - -SDL_JoystickOpened = function('SDL_JoystickOpened', - '''Determine if a joystick has been opened. - - :Parameters: - - `device_index`: int - - :rtype: `int` - :return: 1 if the joystick has been opened, or 0 if it has not. - ''', - args=['device_index'], - arg_types=[c_int], - return_type=c_int) - -SDL_JoystickIndex = function('SDL_JoystickIndex', - '''Get the device index of an opened joystick. - - :Parameters: - - `joystick`: `SDL_Joystick_p` - - :rtype: int - ''', - args=['joystick'], - arg_types=[SDL_Joystick_p], - return_type=c_int) - -SDL_JoystickNumAxes = function('SDL_JoystickNumAxes', - '''Get the number of general axis controls on a joystick. - - :Parameters: - - `joystick`: `SDL_Joystick_p` - - :rtype: int - ''', - args=['joystick'], - arg_types=[SDL_Joystick_p], - return_type=c_int) - -SDL_JoystickNumBalls = function('SDL_JoystickNumBalls', - '''Get the number of trackballs on a joystick. - - Joystick trackballs have only relative motion events associated with - them and their state cannot be polled. - - :Parameters: - - `joystick`: `SDL_Joystick_p` - - :rtype: int - ''', - args=['joystick'], - arg_types=[SDL_Joystick_p], - return_type=c_int) - -SDL_JoystickNumHats = function('SDL_JoystickNumHats', - '''Get the number of POV hats on a joystick. - - :Parameters: - - `joystick`: `SDL_Joystick_p` - - :rtype: int - ''', - args=['joystick'], - arg_types=[SDL_Joystick_p], - return_type=c_int) - -SDL_JoystickNumButtons = function('SDL_JoystickNumButtons', - '''Get the number of buttons on a joystick. - - :Parameters: - - `joystick`: `SDL_Joystick_p` - - :rtype: int - ''', - args=['joystick'], - arg_types=[SDL_Joystick_p], - return_type=c_int) - -SDL_JoystickUpdate = function('SDL_JoystickUpdate', - '''Update the current state of the open joysticks. - - This is called automatically by the event loop if any joystick events - are enabled. - ''', - args=[], - arg_types=[], - return_type=None) - -SDL_JoystickEventState = function('SDL_JoystickEventState', - '''Enable/disable joystick event polling. - - If joystick events are disabled, you must call `SDL_JoystickUpdate` - yourself and check the state of the joystick when you want joystick - information. - - :Parameters: - `state` : int - one of SDL_QUERY, SDL_ENABLE or SDL_IGNORE. - - :rtype: int - :return: undocumented - ''', - args=['state'], - arg_types=[c_int], - return_type=c_int) - - -SDL_JoystickGetAxis = function('SDL_JoystickGetAxis', - '''Get the current state of an axis control on a joystick. - - The axis indices start at index 0. - - :Parameters: - - `joystick`: `SDL_Joystick_p` - - `axis`: int - - :rtype: int - :return: a value ranging from -32,768 to 32767. - ''', - args=['joystick', 'axis'], - arg_types=[SDL_Joystick_p, c_int], - return_type=c_short) - -SDL_JoystickGetHat = function('SDL_JoystickGetHat', - '''Get the current state of POV hat on a joystick. - - The hat indices start at index 0. - - :Parameters: - - `joystick`: `SDL_Joystick_p` - - `hat`: int - - :rtype: int - :return: one of `SDL_HAT_CENTERED`, `SDL_HAT_UP`, `SDL_HAT_LEFT`, - `SDL_HAT_DOWN`, `SDL_HAT_RIGHT`, `SDL_HAT_RIGHTUP`, - `SDL_HAT_RIGHTDOWN`, `SDL_HAT_RIGHTUP`, `SDL_HAT_LEFTUP`, - `SDL_HAT_LEFTDOWN`. - ''', - args=['joystick', 'hat'], - arg_types=[SDL_Joystick_p, c_int], - return_type=c_ubyte) - -_SDL_JoystickGetBall = private_function('SDL_JoystickGetBall', - arg_types=[SDL_Joystick_p, c_int, POINTER(c_int), POINTER(c_int)], - return_type=c_int, - error_return=-1) - -def SDL_JoystickGetBall(joystick, ball): - '''Get the ball axis change since the last poll. - - The ball indicies start at index 0. - - :Parameters: - - `joystick`: `SDL_Joystick_p` - - `ball`: int - - :rtype: (int, int) - :return: a tuple (dx, dy) of the relative motion of the ball. - ''' - dx, dy = c_int(), c_int() - _SDL_JoystickGetBall(joystick, ball, byref(x), byref(y)) - return dx.value, dy.value - -SDL_JoystickGetButton = function('SDL_JoystickGetButton', - '''Get the current state of a button on a joystick. - - The button indices start at index 0. - - :Parameters: - - `joystick`: `SDL_Joystick_p` - - `button`: int - - :rtype: int - :return: undocumented - ''', - args=['joystick', 'button'], - arg_types=[SDL_Joystick_p, c_int], - return_type=c_ubyte) - -SDL_JoystickClose = function('SDL_JoystickClose', - '''Close a joystick previously opened with `SDL_JoystickOpen`. - - :Parameters: - - `joystick`: `SDL_Joystick_p` - - ''', - args=['joystick'], - arg_types=[SDL_Joystick_p], - return_type=None) diff --git a/src/m64py/SDL/keyboard.py b/src/m64py/SDL/keyboard.py deleted file mode 100644 index a2a8914..0000000 --- a/src/m64py/SDL/keyboard.py +++ /dev/null @@ -1,158 +0,0 @@ -#!/usr/bin/env python - -'''Keyboard event handling. - -You should call `SDL_Init` with `SDL_INIT_VIDEO` before using these functions. -''' - -__docformat__ = 'restructuredtext' -__version__ = '$Id: $' - -from ctypes import * - -from .dll import function, private_function - -class SDL_keysym(Structure): - '''Keysym structure - - * The scancode is hardware dependent, and should not be used by - general applications. If no hardware scancode is available, it will - be 0 - * The `unicode` translated character is only available when character - translation is enabled by `SDL_EnableUNICODE`. If non-empty, this is - unicode string of unit length. - - :Ivariables: - `scancode` : int - Hardware specific scancode - `sym` : int - SDL virtual keysym (SDLK_*) - `mod` : int - Bitwise OR of current key modifiers - `unicode` : string - Unicode character represented by keypress, or the empty string - if translation is not possible. - - ''' - _fields_ = [('scancode', c_ubyte), - ('sym', c_int), - ('mod', c_int), - ('_unicode', c_ushort)] - - def __getattr__(self, name): - if name == 'unicode': - return unichr(self._unicode) - raise AttributeError - -SDL_EnableUNICODE = function('SDL_EnableUNICODE', - '''Enable or disable Unicode translation of keyboard input. - - This translation has some overhead, so translation defaults off. - - :Parameters: - `enable` : int - * if 1, translation is enabled - * if 0, translation is disabled. - * if -1, the translation is not changed. - - :rtype: int - :return: the previous state of keyboard translation - ''', - args=['enable'], - arg_types=[c_int], - return_type=c_int) - -SDL_EnableKeyRepeat = function('SDL_EnableKeyRepeat', - '''Enable keyboard repeat. - - Keyboard repeat defaults to off. - - :Parameters: - `delay` : int - the initial delay in milliseconds between the time when a key is - pressed, and keyboard repeat begins. If 0, keyboard repeat is - disabled. - `interval` : int - the time in milliseconds between keyboard repeat events. - - :rtype: int - :return: undocumented (FIXME) - ''', - args=['delay', 'interval'], - arg_types=[c_int, c_int], - return_type=c_int) - -_SDL_GetKeyRepeat = private_function('SDL_GetKeyRepeat', - arg_types=[POINTER(c_int), POINTER(c_int)], - return_type=None, - since=(1,2,10)) - -def SDL_GetKeyRepeat(): - '''Get the keyboard repeat parameters. - - :see: `SDL_EnableKeyRepeat` - :rtype: (int, int) - :return: tuple (delay, interval), as defined in `SDL_EnableKeyRepeat` - :since: 1.2.10 - ''' - delay, interval = c_int(), c_int() - _SDL_GetKeyRepeat(byref(delay), byref(interval)) - return delay.value, interval.value - -_SDL_GetKeyState = private_function('SDL_GetKeyState', - arg_types=[POINTER(c_int)], - return_type=POINTER(c_ubyte)) - -def SDL_GetKeyState(): - '''Get a snapshot of the current state of the keyboard. - - Example:: - - keystate = SDL_GetKeyState() - if keystate[SDLK_RETURN]: - print ' is pressed' - - :rtype: list - :return: a list of integers indexed by the SDLK_* symbols - ''' - numkeys = c_int() - keystate = _SDL_GetKeyState(byref(numkeys)) - keystate_ar = cast(keystate, POINTER(c_ubyte * numkeys.value)).contents - return list(keystate_ar) - -SDL_GetModState = function('SDL_GetModState', - '''Get the current key modifier state. - - :rtype: int - ''', - args=[], - arg_types=[], - return_type=c_int) - -SDL_SetModState = function('SDL_SetModState', - '''Set the current key modifier state. - - This does not change the keyboard state, only the key modifier flags. - - :Parameters: - - `modstate`: int - - ''', - args=['modstate'], - arg_types=[c_int], - return_type=None) - -_SDL_GetKeyName = private_function('SDL_GetKeyName', - arg_types=[c_int], - return_type=c_char_p) - -def SDL_GetKeyName(key): - '''Get the name of an SDL virtual keysym. - - :Parameters: - - `key`: int - - :rtype: string - ''' - return _SDL_GetKeyName(key) - diff --git a/src/m64py/SDL/mixer.py b/src/m64py/SDL/mixer.py deleted file mode 100644 index f633bd6..0000000 --- a/src/m64py/SDL/mixer.py +++ /dev/null @@ -1,1191 +0,0 @@ -#!/usr/bin/env python - -'''A simple multi-channel audio mixer. - -It supports 8 channels of 16 bit stereo audio, plus a single channel -of music, mixed by MidMod MOD, Timidity MIDI or SMPEG MP3 libraries. - -The mixer can currently load Microsoft WAVE files and Creative Labs VOC -files as audio samples, and can load MIDI files via Timidity and the -following music formats via MikMod: MOD, S3M, IT, XM. It can load Ogg -Vorbis streams as music if built with the Ogg Vorbis libraries, and finally -it can load MP3 music using the SMPEG library. - -The process of mixing MIDI files to wave output is very CPU intensive, so -if playing regular WAVE files sounds great, but playing MIDI files sounds -choppy, try using 8-bit audio, mono audio, or lower frequencies. - -:note: The music stream does not resample to the required audio rate. You - must call `Mix_OpenAudio` with the sampling rate of your music track. -''' - -__docformat__ = 'restructuredtext' -__version__ = '$Id: $' - -from ctypes import * - -from .array import SDL_array, to_ctypes -from .dll import SDL_DLL -from .rwops import SDL_RWops, SDL_RWFromFile -from .version import SDL_version - -_dll = SDL_DLL('SDL_mixer', 'Mix_Linked_Version') - -Mix_Linked_Version = _dll.function('Mix_Linked_Version', - '''Get the version of the dynamically linked SDL_mixer library. - ''', - args=[], - arg_types=[], - return_type=POINTER(SDL_version), - dereference_return=True, - require_return=True) - -class Mix_Chunk(Structure): - '''Internal format for an audio chunk. - - :Ivariables: - `allocated` : int - Undocumented. - `abuf` : `SDL_array` - Buffer of audio data - `alen` : int - Length of audio buffer - `volume` : int - Per-sample volume, in range [0, 128] - - ''' - _fields_ = [('allocated', c_int), - ('_abuf', POINTER(c_ubyte)), - ('alen', c_uint), - ('volume', c_ubyte)] - - def __getattr__(self, attr): - if attr == 'abuf': - return SDL_array(self._abuf, self.alen, c_ubyte) - raise AttributeException(attr) - -# opaque type -_Mix_Music = c_void_p - -Mix_OpenAudio = _dll.function('Mix_OpenAudio', - '''Open the mixer with a certain audio format. - - :Parameters: - `frequency` : int - Samples per second. Typical values are 22050, 44100, 44800. - `format` : int - Audio format; one of AUDIO_U8, AUDIO_S8, AUDIO_U16LSB, - AUDIO_S16LSB, AUDIO_U16MSB or AUDIO_S16MSB - `channels` : int - Either 1 for monophonic or 2 for stereo. - `chunksize` : int - Size of the audio buffer. Typical values are 4096, 8192. - - ''', - args=['frequency', 'format', 'channels', 'chunksize'], - arg_types=[c_int, c_ushort, c_int, c_int], - return_type=c_int, - error_return=-1) - -Mix_AllocateChannels = _dll.function('Mix_AllocateChannels', - '''Dynamically change the number of channels managed by the mixer. - - If decreasing the number of channels, the upper channels - are stopped. - - :Parameters: - - `numchans`: int - - :rtype: int - :return: the new number of allocated channels. - ''', - args=['numchans'], - arg_types=[c_int], - return_type=c_int) - -_Mix_QuerySpec = _dll.private_function('Mix_QuerySpec', - arg_types=[POINTER(c_int), POINTER(c_ushort), POINTER(c_int)], - return_type=c_int) - -def Mix_QuerySpec(): - '''Find out what the actual audio device parameters are. - - The function returns a tuple giving each parameter value. The first - value is 1 if the audio has been opened, 0 otherwise. - - :rtype: (int, int, int, int) - :return: (opened, frequency, format, channels) - ''' - frequency, format, channels = c_int(), c_ushort(), c_int() - opened = _Mix_QuerySpec(byref(frequency), byref(format), byref(channels)) - return opened, frequency.value, format.value, channels.value - -Mix_LoadWAV_RW = _dll.function('Mix_LoadWAV_RW', - '''Load a WAV, RIFF, AIFF, OGG or VOC file from a RWops source. - - - - :rtype: `Mix_Chunk` - ''', - args=['src', 'freesrc'], - arg_types=[POINTER(SDL_RWops), c_int], - return_type=POINTER(Mix_Chunk), - dereference_return=True, - require_return=True) - -def Mix_LoadWAV(file): - '''Load a WAV, RIFF, AIFF, OGG or VOC file. - - :Parameters: - `file` : string - Filename to load. - - :rtype: `Mix_Chunk` - ''' - return Mix_LoadWAV_RW(SDL_RWFromFile(file, 'rb'), 1) - -Mix_LoadMUS = _dll.function('Mix_LoadMUS', - '''Load a WAV, MID, OGG, MP3 or MOD file. - - :Parameters: - `file` : string - Filename to load. - - :rtype: ``Mix_Music`` - ''', - args=['file'], - arg_types=[c_char_p], - return_type=_Mix_Music, - require_return=True) - -Mix_LoadMUS_RW = _dll.function('Mix_LoadMUS_RW', - '''Load a MID, OGG, MP3 or MOD file from a RWops source. - - :Parameters: - `src` : `SDL_RWops` - Readable RWops to load from. - `freesrc` : `int` - If non-zero, the source will be closed after loading. - - :rtype: ``Mix_Music`` - ''', - args=['file'], - arg_types=[c_char_p], - return_type=_Mix_Music, - require_return=True) - -_Mix_QuickLoad_WAV = _dll.private_function('Mix_QuickLoad_WAV', - arg_types=[POINTER(c_ubyte)], - return_type=POINTER(Mix_Chunk), - dereference_return=True, - require_return=True) - -def Mix_QuickLoad_WAV(mem): - '''Load a wave file of the mixer format from a sequence or SDL_array. - - :Parameters: - - `mem`: sequence or `SDL_array` - - :rtype: `Mix_Chunk` - ''' - ref, mem = to_ctypes(mem, len(mem), c_ubyte) - return _Mix_QuickLoad_WAV(mem) - -_Mix_QuickLoad_RAW = _dll.private_function('Mix_QuickLoad_RAW', - arg_types=[POINTER(c_ubyte), c_uint], - return_type=POINTER(Mix_Chunk), - dereference_return=True, - require_return=True) - -def Mix_QuickLoad_RAW(mem): - '''Load raw audio data of the mixer format from a sequence or SDL_array. - - :Parameters: - - `mem`: sequence or `SDL_array` - - :rtype: `Mix_Chunk` - ''' - l = len(mem) - ref, mem = to_ctypes(mem, len(mem), c_ubyte) - return _Mix_QuickLoad_RAW(mem, l) - -Mix_FreeChunk = _dll.function('Mix_FreeChunk', - '''Free an audio chunk previously loaded. - - :Parameters: - - `chunk`: `Mix_Chunk` - - ''', - args=['chunk'], - arg_types=[POINTER(Mix_Chunk)], - return_type=None) - -Mix_FreeMusic = _dll.function('Mix_FreeMusic', - '''Free a music chunk previously loaded. - - :Parameters: - - `music`: ``Mix_Music`` - - ''', - args=['music'], - arg_types=[_Mix_Music], - return_type=None) - -Mix_GetMusicType = _dll.function('Mix_GetMusicType', - '''Get the music format of a mixer music. - - Returns the format of the currently playing music if `music` is None. - - :Parameters: - - `music`: ``Mix_Music`` - - :rtype: int - :return: one of `MUS_NONE`, `MUS_CMD`, `MUS_WAV`, `MUS_MOD`, `MUS_MID`, - `MUS_OGG` or `MUS_MP3` - ''', - args=['music'], - arg_types=[_Mix_Music], - return_type=c_int) - -_Mix_FilterFunc = CFUNCTYPE(None, c_void_p, POINTER(c_ubyte), c_int) -def _make_filter(func, udata): - if func: - def f(ignored, stream, len): - stream = SDL_array(stream, len, c_ubyte) - func(udata, stream) - return _Mix_FilterFunc(f) - else: - return _Mix_FilterFunc() - -_Mix_SetPostMix = _dll.private_function('Mix_SetPostMix', - arg_types=[_Mix_FilterFunc, c_void_p], - return_type=None) - -_mix_postmix_ref = None - -def Mix_SetPostMix(mix_func, udata): - '''Set a function that is called after all mixing is performed. - - This can be used to provide real-time visual display of the audio - stream or add a custom mixer filter for the stream data. - - :Parameters - `mix_func` : function - The function must have the signature - (stream: `SDL_array`, udata: any) -> None. The first argument - is the array of audio data that may be modified in place. - `udata` is the value passed in this function. - `udata` : any - A variable that is passed to the `mix_func` function each - call. - - ''' - global _mix_postmix_ref - _mix_postmix_ref = _make_filter(mix_func, udata) - _Mix_SetPostMix(_mix_postmix_ref, None) - -_Mix_HookMusic = _dll.private_function('Mix_HookMusic', - arg_types=[_Mix_FilterFunc, c_void_p], - return_type=None) - -_hookmusic_ref = None - -def Mix_HookMusic(mix_func, udata): - '''Add your own music player or additional mixer function. - - If `mix_func` is None, the default music player is re-enabled. - - :Parameters - `mix_func` : function - The function must have the signature - (stream: `SDL_array`, udata: any) -> None. The first argument - is the array of audio data that may be modified in place. - `udata` is the value passed in this function. - `udata` : any - A variable that is passed to the `mix_func` function each - call. - - ''' - global _hookmusic_ref - _hookmusic_ref = _make_filter(mix_func, udata) - _Mix_HookMusic(_hookmusic_ref, None) - -_Mix_HookMusicFinishedFunc = CFUNCTYPE(None) - -_Mix_HookMusicFinished = _dll.private_function('Mix_HookMusicFinished', - arg_types=[_Mix_HookMusicFinishedFunc], - return_type=None) - -def Mix_HookMusicFinished(music_finished): - '''Add your own callback when the music has finished playing. - - This callback is only called if the music finishes naturally. - - :Parameters: - `music_finished` : function - The callback takes no arguments and returns no value. - - ''' - if music_finished: - _Mix_HookMusicFinished(_Mix_HookMusicFinishedFunc(music_finished)) - else: - _Mix_HookMusicFinished(_Mix_HookMusicFinishedFunc()) - -# Mix_GetMusicHookData not implemented (unnecessary) - -_Mix_ChannelFinishedFunc = CFUNCTYPE(None, c_int) - -_Mix_ChannelFinished = _dll.private_function('Mix_ChannelFinished', - arg_types=[_Mix_ChannelFinishedFunc], - return_type=None) - -# Keep the ctypes func around -_channelfinished_ref = None - -def Mix_ChannelFinished(channel_finished): - '''Add your own callback when a channel has finished playing. - - The callback may be called from the mixer's audio callback or it - could be called as a result of `Mix_HaltChannel`, etc. - - Do not call `SDL_LockAudio` from this callback; you will either be - inside the audio callback, or SDL_mixer will explicitly lock the - audio before calling your callback. - - :Parameters: - `channel_finished` : function - The function takes the channel number as its only argument, - and returns None. Pass None here to disable the callback. - - ''' - global _channelfinished_ref - if channel_finished: - _channelfinished_ref = _Mix_ChannelFinishedFunc(channel_finished) - else: - _channelfinished_ref = _Mix_ChannelFinishedFunc() - _Mix_ChannelFinished(_channelfinished_ref) - -_Mix_EffectFunc = CFUNCTYPE(None, c_int, POINTER(c_ubyte), c_int, c_void_p) -def _make_Mix_EffectFunc(func, udata): - if func: - def f(chan, stream, len, ignored): - stream = SDL_array(stream, len, c_ubyte) - func(chan, stream, udata) - return _Mix_EffectFunc(f) - else: - return _Mix_EffectFunc() - -_Mix_EffectDoneFunc = CFUNCTYPE(None, c_int, c_void_p) -def _make_Mix_EffectDoneFunc(func, udata): - if func: - def f(chan, ignored): - func(chan, udata) - return _MixEffectDoneFunc(f) - else: - return _MixEffectDoneFunc() - -_Mix_RegisterEffect = _dll.private_function('Mix_RegisterEffect', - arg_types=\ - [c_int, _Mix_EffectFunc, _Mix_EffectDoneFunc, c_void_p], - return_type=c_int, - error_return=0) - -_effect_func_refs = [] - -def Mix_RegisterEffect(chan, f, d, arg): - '''Register a special effect function. - - At mixing time, the channel data is copied into a buffer and passed - through each registered effect function. After it passes through all - the functions, it is mixed into the final output stream. The copy to - buffer is performed once, then each effect function performs on the - output of the previous effect. Understand that this extra copy to a - buffer is not performed if there are no effects registered for a given - chunk, which saves CPU cycles, and any given effect will be extra - cycles, too, so it is crucial that your code run fast. Also note that - the data that your function is given is in the format of the sound - device, and not the format you gave to `Mix_OpenAudio`, although they - may in reality be the same. This is an unfortunate but necessary speed - concern. Use `Mix_QuerySpec` to determine if you can handle the data - before you register your effect, and take appropriate actions. - - You may also specify a callback (`d`) that is called when the channel - finishes playing. This gives you a more fine-grained control than - `Mix_ChannelFinished`, in case you need to free effect-specific - resources, etc. If you don't need this, you can specify None. - - You may set the callbacks before or after calling `Mix_PlayChannel`. - - Things like `Mix_SetPanning` are just internal special effect - functions, so if you are using that, you've already incurred the - overhead of a copy to a separate buffer, and that these effects will be - in the queue with any functions you've registered. The list of - registered effects for a channel is reset when a chunk finishes - playing, so you need to explicitly set them with each call to - ``Mix_PlayChannel*``. - - You may also register a special effect function that is to be run after - final mixing occurs. The rules for these callbacks are identical to - those in `Mix_RegisterEffect`, but they are run after all the channels - and the music have been mixed into a single stream, whereas - channel-specific effects run on a given channel before any other mixing - occurs. These global effect callbacks are call "posteffects". - Posteffects only have their `d` function called when they are - unregistered (since the main output stream is never "done" in the same - sense as a channel). You must unregister them manually when you've had - enough. Your callback will be told that the channel being mixed is - (`MIX_CHANNEL_POST`) if the processing is considered a posteffect. - - After all these effects have finished processing, the callback - registered through `Mix_SetPostMix` runs, and then the stream goes to - the audio device. - - Do not call `SDL_LockAudio` from your callback function. - - :Parameters: - `chan` : int - Channel to set effect on, or `MIX_CHANNEL_POST` for postmix. - `f` : function - Callback function for effect. Must have the signature - (channel: int, stream: `SDL_array`, udata: any) -> None; - where channel is the channel being affected, stream contains - the audio data and udata is the user variable passed in to - this function. - `d` : function - Callback function for when the effect is done. The function - must have the signature (channel: int, udata: any) -> None. - `arg` : any - User data passed to both callbacks. - - ''' - f = _make_MixEffectFunc(f, arg) - d = _make_MixEffectDoneFunc(d, arg) - _effect_func_refs.append(f) - _effect_func_refs.append(d) - # TODO: override EffectDone callback to remove refs and prevent - # memory leak. Be careful with MIX_CHANNEL_POST - _Mix_RegisterEffect(chan, f, d, arg) - -# Mix_UnregisterEffect cannot be implemented - -Mix_UnregisterAllEffects = _dll.function('Mix_UnregisterAllEffects', - '''Unregister all effects for a channel. - - You may not need to call this explicitly, unless you need to stop all - effects from processing in the middle of a chunk's playback. Note that - this will also shut off some internal effect processing, since - `Mix_SetPanning` and others may use this API under the hood. This is - called internally when a channel completes playback. - - Posteffects are never implicitly unregistered as they are for channels, - but they may be explicitly unregistered through this function by - specifying `MIX_CHANNEL_POST` for a channel. - - :Parameters: - - `channel`: int - - ''', - args=['channel'], - arg_types=[c_int], - return_type=c_int, - error_return=0) - -Mix_SetPanning = _dll.function('Mix_SetPanning', - '''Set the panning of a channel. - - The left and right channels are specified as integers between 0 and - 255, quietest to loudest, respectively. - - Technically, this is just individual volume control for a sample with - two (stereo) channels, so it can be used for more than just panning. - If you want real panning, call it like this:: - - Mix_SetPanning(channel, left, 255 - left) - - Setting (channel) to `MIX_CHANNEL_POST` registers this as a posteffect, and - the panning will be done to the final mixed stream before passing it on - to the audio device. - - This uses the `Mix_RegisterEffect` API internally, and returns without - registering the effect function if the audio device is not configured - for stereo output. Setting both (left) and (right) to 255 causes this - effect to be unregistered, since that is the data's normal state. - - :Parameters: - - `channel`: int - - `left`: int - - `right`: int - - ''', - args=['channel', 'left', 'right'], - arg_types=[c_int, c_ubyte, c_ubyte], - return_type=c_int, - error_return=0) - -Mix_SetPosition = _dll.function('Mix_SetPosition', - '''Set the position of a channel. - - `angle` is an integer from 0 to 360, that specifies the location of the - sound in relation to the listener. `angle` will be reduced as neccesary - (540 becomes 180 degrees, -100 becomes 260). Angle 0 is due north, and - rotates clockwise as the value increases. For efficiency, the - precision of this effect may be limited (angles 1 through 7 might all - produce the same effect, 8 through 15 are equal, etc). `distance` is - an integer between 0 and 255 that specifies the space between the sound - and the listener. The larger the number, the further away the sound is. - Using 255 does not guarantee that the channel will be culled from the - mixing process or be completely silent. For efficiency, the precision - of this effect may be limited (distance 0 through 5 might all produce - the same effect, 6 through 10 are equal, etc). Setting `angle` and - `distance` to 0 unregisters this effect, since the data would be - unchanged. - - If you need more precise positional audio, consider using OpenAL for - spatialized effects instead of SDL_mixer. This is only meant to be a - basic effect for simple "3D" games. - - If the audio device is configured for mono output, then you won't get - any effectiveness from the angle; however, distance attenuation on the - channel will still occur. While this effect will function with stereo - voices, it makes more sense to use voices with only one channel of - sound, so when they are mixed through this effect, the positioning will - sound correct. You can convert them to mono through SDL before giving - them to the mixer in the first place if you like. - - Setting `channel` to `MIX_CHANNEL_POST` registers this as a posteffect, - and the positioning will be done to the final mixed stream before - passing it on to the audio device. - - This is a convenience wrapper over `Mix_SetDistance` and - `Mix_SetPanning`. - - :Parameters: - - `channel`: int - - `angle`: int - - `distance`: int - - ''', - args=['channel', 'angle', 'distance'], - arg_types=[c_int, c_short, c_ubyte], - return_type=c_int, - error_return=0) - -Mix_SetDistance = _dll.function('Mix_SetDistance', - '''Set the "distance" of a channel. - - `distance` is an integer from 0 to 255 that specifies the location of - the sound in relation to the listener. Distance 0 is overlapping the - listener, and 255 is as far away as possible A distance of 255 does not - guarantee silence; in such a case, you might want to try changing the - chunk's volume, or just cull the sample from the mixing process with - `Mix_HaltChannel`. - - For efficiency, the precision of this effect may be limited (distances - 1 through 7 might all produce the same effect, 8 through 15 are equal, - etc). `distance` is an integer between 0 and 255 that specifies the - space between the sound and the listener. The larger the number, the - further away the sound is. - - Setting `distance` to 0 unregisters this effect, since the data would - be unchanged. - - If you need more precise positional audio, consider using OpenAL for - spatialized effects instead of SDL_mixer. This is only meant to be a - basic effect for simple "3D" games. - - Setting `channel` to `MIX_CHANNEL_POST` registers this as a posteffect, - and the distance attenuation will be done to the final mixed stream - before passing it on to the audio device. - - This uses the `Mix_RegisterEffect` API internally. - - :Parameters: - - `channel`: int - - `distance`: distance - - ''', - args=['channel', 'distance'], - arg_types=[c_int, c_ubyte], - return_type=c_int, - error_return=0) - -Mix_SetReverseStereo = _dll.function('Mix_SetReverseStereo', - '''Causes a channel to reverse its stereo. - - This is handy if the user has his or her speakers hooked up backwards, - or you would like to have a minor bit of psychedelia in your sound - code. Calling this function with `flip` set to non-zero reverses the - chunks's usual channels. If `flip` is zero, the effect is unregistered. - - This uses the `Mix_RegisterEffect` API internally, and thus is probably - more CPU intensive than having the user just plug in his speakers - correctly. `Mix_SetReverseStereo` returns without registering the - effect function if the audio device is not configured for stereo - output. - - If you specify `MIX_CHANNEL_POST` for `channel`, then this the effect - is used on the final mixed stream before sending it on to the audio - device (a posteffect). - - :Parameters: - - `channel`: int - - `flip`: int - - ''', - args=['channel', 'flip'], - arg_types=[c_int, c_int], - return_type=c_int, - error_return=0) - -Mix_ReserveChannels = _dll.function('Mix_ReserveChannels', - '''Reserve the first channels (0 to n-1) for the application. - - If reserved, a channel will not be allocated dynamically to a sample - if requested with one of the ``Mix_Play*`` functions. - - :Parameters: - - `num`: int - - :rtype: int - :return: the number of reserved channels - ''', - args=['num'], - arg_types=[c_int], - return_type=c_int) - -Mix_GroupChannel = _dll.function('Mix_GroupChannel', - '''Assing a channel to a group. - - A tag can be assigned to several mixer channels, to form groups - of channels. If `tag` is -1, the tag is removed (actually -1 is the - tag used to represent the group of all the channels). - - :Parameters: - - `channel`: int - - `tag`: int - - ''', - args=['channel', 'tag'], - arg_types=[c_int, c_int], - return_type=c_int, - error_return=0) - -Mix_GroupChannels = _dll.function('Mix_GroupChannels', - '''Assign several consecutive channels to a group. - - A tag can be assigned to several mixer channels, to form groups - of channels. If `tag` is -1, the tag is removed (actually -1 is the - tag used to represent the group of all the channels). - - :Parameters: - - `channel_from`: int - - `channel_to`: int - - `tag`: int - - ''', - args=['channel_from', 'channel_to', 'tag'], - arg_types=[c_int, c_int, c_int], - return_type=c_int, - error_return=0) - -Mix_GroupAvailable = _dll.function('Mix_GroupAvailable', - '''Find the first available channel in a group of channels. - - :Parameters: - - `tag`: int - - :rtype: int - :return: a channel, or -1 if none are available. - ''', - args=['tag'], - arg_types=[c_int], - return_type=c_int) - -Mix_GroupCount = _dll.function('Mix_GroupCount', - '''Get the number of channels in a group. - - If `tag` is -1, returns the total number of channels. - - :Parameters: - - `tag`: int - - :rtype: int - ''', - args=['tag'], - arg_types=[c_int], - return_type=c_int) - -Mix_GroupOldest = _dll.function('Mix_GroupOldest', - '''Find the "oldest" sample playing in a group of channels. - - :Parameters: - - `tag`: int - - :rtype: int - ''', - args=['tag'], - arg_types=[c_int], - return_type=c_int) - -Mix_GroupNewer = _dll.function('Mix_GroupNewer', - '''Find the "most recent" (i.e., last) sample playing in a group of - channels. - - :Parameters: - - `tag`: int - - :rtype: int - ''', - args=['tag'], - arg_types=[c_int], - return_type=c_int) - -def Mix_PlayChannel(channel, chunk, loops): - '''Play an audio chunk on a specific channel. - - :Parameters: - `channel` : int - If -1, play on the first free channel. - `chunk` : `Mix_Chunk` - Chunk to play - `loops` : int - If greater than zero, the number of times to play the sound; - if -1, loop infinitely. - - :rtype: int - :return: the channel that was used to play the sound. - ''' - return Mix_PlayChannelTimed(channel, chunk, loops, -1) - -Mix_PlayChannelTimed = _dll.function('Mix_PlayChannelTimed', - '''Play an audio chunk on a specific channel for a specified amount of - time. - - :Parameters: - `channel` : int - If -1, play on the first free channel. - `chunk` : `Mix_Chunk` - Chunk to play - `loops` : int - If greater than zero, the number of times to play the sound; - if -1, loop infinitely. - `ticks` : int - Maximum number of milliseconds to play sound for. - - :rtype: int - :return: the channel that was used to play the sound. - ''', - args=['channel', 'chunk', 'loops', 'ticks'], - arg_types=[c_int, POINTER(Mix_Chunk), c_int, c_int], - return_type=c_int) - -Mix_PlayMusic = _dll.function('Mix_PlayMusic', - '''Play a music chunk. - - :Parameters: - `music` : ``Mix_Music`` - Chunk to play - `loops` : int - If greater than zero, the number of times to play the sound; - if -1, loop infinitely. - ''', - args=['music', 'loops'], - arg_types=[_Mix_Music, c_int], - return_type=c_int, - error_return=-1) - -Mix_FadeInMusic = _dll.function('Mix_FadeInMusic', - '''Fade in music over a period of time. - - :Parameters: - `music` : ``Mix_Music`` - Chunk to play - `loops` : int - If greater than zero, the number of times to play the sound; - if -1, loop infinitely. - `ms` : int - Number of milliseconds to fade up over. - ''', - args=['music', 'loops', 'ms'], - arg_types=[_Mix_Music, c_int, c_int], - return_type=c_int, - error_return=-1) - -Mix_FadeInMusicPos = _dll.function('Mix_FadeInMusicPos', - '''Fade in music at an offset over a period of time. - - :Parameters: - `music` : ``Mix_Music`` - Chunk to play - `loops` : int - If greater than zero, the number of times to play the sound; - if -1, loop infinitely. - `ms` : int - Number of milliseconds to fade up over. - `position` : float - Position within music to start at. Currently implemented - only for MOD, OGG and MP3. - - :see: Mix_SetMusicPosition - ''', - args=['music', 'loops', 'ms', 'position'], - arg_types=[_Mix_Music, c_int, c_int, c_double], - return_type=c_int, - error_return=-1) - -def Mix_FadeInChannel(channel, chunk, loops, ms): - '''Fade in a channel. - - :Parameters: - `channel` : int - If -1, play on the first free channel. - `chunk` : `Mix_Chunk` - Chunk to play - `loops` : int - If greater than zero, the number of times to play the sound; - if -1, loop infinitely. - `ms` : int - Number of milliseconds to fade up over. - ''' - Mix_FadeInChannelTimed(channel, chunk, loops, -1) - -Mix_FadeInChannelTimed = _dll.function('Mix_FadeInChannelTimed', - '''Fade in a channel and play for a specified amount of time. - - :Parameters: - `channel` : int - If -1, play on the first free channel. - `chunk` : `Mix_Chunk` - Chunk to play - `loops` : int - If greater than zero, the number of times to play the sound; - if -1, loop infinitely. - `ms` : int - Number of milliseconds to fade up over. - `ticks` : int - Maximum number of milliseconds to play sound for. - ''', - args=['channel', 'music', 'loops', 'ms', 'ticks'], - arg_types=[c_int, _Mix_Music, c_int, c_int, c_int], - return_type=c_int, - error_return=-1) - -Mix_Volume = _dll.function('Mix_Volume', - '''Set the volume in the range of 0-128 of a specific channel. - - :Parameters: - `channel` : int - If -1, set the volume for all channels - `volume` : int - Volume to set, in the range 0-128, or -1 to just return the - current volume. - - :rtype: int - :return: the original volume. - ''', - args=['channel', 'volume'], - arg_types=[c_int, c_int], - return_type=c_int) - -Mix_VolumeChunk = _dll.function('Mix_VolumeChunk', - '''Set the volume in the range of 0-128 of a chunk. - - :Parameters: - `chunk` : `Mix_Chunk` - Chunk to set volume. - `volume` : int - Volume to set, in the range 0-128, or -1 to just return the - current volume. - - :rtype: int - :return: the original volume. - ''', - args=['chunk', 'volume'], - arg_types=[POINTER(Mix_Chunk), c_int], - return_type=c_int) - -Mix_VolumeMusic = _dll.function('Mix_VolumeMusic', - '''Set the volume in the range of 0-128 of the music. - - :Parameters: - `volume` : int - Volume to set, in the range 0-128, or -1 to just return the - current volume. - - :rtype: int - :return: the original volume. - ''', - args=['volume'], - arg_types=[c_int], - return_type=c_int) - -Mix_HaltChannel = _dll.function('Mix_HaltChannel', - '''Halt playing of a particular channel. - - :Parameters: - - `channel`: int - ''', - args=['channel'], - arg_types=[c_int], - return_type=None) - -Mix_HaltGroup = _dll.function('Mix_HaltGroup', - '''Halt playing of a particular group. - - :Parameters: - - `tag`: int - ''', - args=['tag'], - arg_types=[c_int], - return_type=None) - -Mix_HaltMusic = _dll.function('Mix_HaltMusic', - '''Halt playing music. - ''', - args=[], - arg_types=[], - return_type=None) - -Mix_ExpireChannel = _dll.function('Mix_ExpireChannel', - '''Change the expiration delay for a particular channel. - - The sample will stop playing afte the `ticks` milliseconds have - elapsed, or remove the expiration if `ticks` is -1. - - :Parameters: - - `channel`: int - - `ticks`: int - - :rtype: int - :return: the number of channels affected. - ''', - args=['channel', 'ticks'], - arg_types=[c_int, c_int], - return_type=c_int) - -Mix_FadeOutChannel = _dll.function('Mix_FadeOutChannel', - '''Halt a channel, fading it out progressively until it's silent. - - The `ms` parameter indicates the number of milliseconds the fading - will take. - - :Parameters: - - `channel`: int - - `ms`: int - ''', - args=['channel', 'ms'], - arg_types=[c_int, c_int], - return_type=None) - -Mix_FadeOutGroup = _dll.function('Mix_FadeOutGroup', - '''Halt a group, fading it out progressively until it's silent. - - The `ms` parameter indicates the number of milliseconds the fading - will take. - - :Parameters: - - `tag`: int - - `ms`: int - ''', - args=['tag', 'ms'], - arg_types=[c_int, c_int], - return_type=None) - -Mix_FadeOutMusic = _dll.function('Mix_FadeOutMusic', - '''Halt playing music, fading it out progressively until it's silent. - - The `ms` parameter indicates the number of milliseconds the fading - will take. - - :Parameters: - - `ms`: int - ''', - args=['ms'], - arg_types=[c_int], - return_type=None) - -Mix_FadingMusic = _dll.function('Mix_FadingMusic', - '''Query the fading status of the music. - - :rtype: int - :return: one of MIX_NO_FADING, MIX_FADING_OUT, MIX_FADING_IN. - ''', - args=[], - arg_types=[], - return_type=c_int) - -Mix_FadingChannel = _dll.function('Mix_FadingChannel', - '''Query the fading status of a channel. - - :Parameters: - - `channel`: int - - :rtype: int - :return: one of MIX_NO_FADING, MIX_FADING_OUT, MIX_FADING_IN. - ''', - args=['channel'], - arg_types=[c_int], - return_type=c_int) - -Mix_Pause = _dll.function('Mix_Pause', - '''Pause a particular channel. - - :Parameters: - - `channel`: int - - ''', - args=['channel'], - arg_types=[c_int], - return_type=None) - -Mix_Resume = _dll.function('Mix_Resume', - '''Resume a particular channel. - - :Parameters: - - `channel`: int - - ''', - args=['channel'], - arg_types=[c_int], - return_type=None) - -Mix_Paused = _dll.function('Mix_Paused', - '''Query if a channel is paused. - - :Parameters: - - `channel`: int - - :rtype: int - ''', - args=['channel'], - arg_types=[c_int], - return_type=c_int) - -Mix_PauseMusic = _dll.function('Mix_PauseMusic', - '''Pause the music stream. - ''', - args=[], - arg_types=[], - return_type=None) - -Mix_ResumeMusic = _dll.function('Mix_ResumeMusic', - '''Resume the music stream. - ''', - args=[], - arg_types=[], - return_type=None) - -Mix_RewindMusic = _dll.function('Mix_RewindMusic', - '''Rewind the music stream. - ''', - args=[], - arg_types=[], - return_type=None) - -Mix_PausedMusic = _dll.function('Mix_PausedMusic', - '''Query if the music stream is paused. - - :rtype: int - ''', - args=[], - arg_types=[], - return_type=c_int) - -Mix_SetMusicPosition = _dll.function('Mix_SetMusicPosition', - '''Set the current position in the music stream. - - For MOD files the position represents the pattern order number; - for OGG and MP3 files the position is in seconds. Currently no other - music file formats support positioning. - - :Parameters: - - `position`: float - - ''', - args=['position'], - arg_types=[c_double], - return_type=c_int, - error_return=-1) - -Mix_Playing = _dll.function('Mix_Playing', - '''Query the status of a specific channel. - - :Parameters: - - `channel`: int - - :rtype: int - :return: the number of queried channels that are playing. - ''', - args=['channel'], - arg_types=[c_int], - return_type=c_int) - -Mix_PlayingMusic = _dll.function('Mix_PlayingMusic', - '''Query the status of the music stream. - - :rtype: int - :return: 1 if music is playing, 0 otherwise. - ''', - args=[], - arg_types=[], - return_type=c_int) - -Mix_SetMusicCMD = _dll.function('Mix_SetMusicCMD', - '''Set the external music playback command. - - Any currently playing music will stop. - - :Parameters: - - `command`: string - - ''', - args=['command'], - arg_types=[c_char_p], - return_type=c_int, - error_return=-1) - -Mix_SetSynchroValue = _dll.function('Mix_SetSynchroValue', - '''Set the synchro value for a MOD music stream. - - :Parameters: - - `value`: int - - ''', - args=['value'], - arg_types=[c_int], - return_type=c_int, - error_return=-1) - -Mix_GetSynchroValue = _dll.function('Mix_GetSynchroValue', - '''Get the synchro value for a MOD music stream. - - :rtype: int - ''', - args=[], - arg_types=[], - return_type=c_int) - -Mix_GetChunk = _dll.function('Mix_GetChunk', - '''Get the chunk currently associated with a mixer channel. - - Returns None if the channel is invalid or if there's no chunk associated. - - :Parameters: - - `channel`: int - - :rtype: `Mix_Chunk` - ''', - args=['channel'], - arg_types=[c_int], - return_type=POINTER(Mix_Chunk), - dereference_return=True) - -Mix_CloseAudio = _dll.function('Mix_CloseAudio', - '''Close the mixer, halting all playing audio. - - ''', - args=[], - arg_types=[], - return_type=None) - - diff --git a/src/m64py/SDL/mouse.py b/src/m64py/SDL/mouse.py deleted file mode 100644 index 03fcbfd..0000000 --- a/src/m64py/SDL/mouse.py +++ /dev/null @@ -1,199 +0,0 @@ -#!/usr/bin/env python - -'''Mouse event handling. -''' - -__docformat__ = 'restructuredtext' -__version__ = '$Id: $' - -from ctypes import * - -from .array import SDL_array, to_ctypes -from .dll import function, private_function -from .video import SDL_Rect -from .constants import SDL_BUTTON_LEFT, SDL_BUTTON_MIDDLE, SDL_BUTTON_RIGHT - -class SDL_Cursor(Structure): - '''Cursor structure. - - :Ivariables: - `area` : `SDL_Rect` - Area of the mouse cursor - `hot_x` : int - X coordinate of the tip of the cursor - `hot_y` : int - Y coordinate of the tip of the cursor - - ''' - _fields_ = [('area', SDL_Rect), - ('hot_x', c_short), - ('hot_y', c_short), - ('_data', POINTER(c_ubyte)), - ('_mask', POINTER(c_ubyte)), - ('save', POINTER(c_ubyte) * 2), - ('wm_cursor', c_void_p)] - - def __getattr__(self, name): - w, h = self.area.w, self.area.h - if name == 'data': - return SDL_array(self._data, w * h / 8, c_ubyte) - elif name == 'mask': - return SDL_array(self._mask, w * h / 8, c_ubyte) - raise AttributeError(name) - -_SDL_GetMouseState = private_function('SDL_GetMouseState', - arg_types=[POINTER(c_int), POINTER(c_int)], - return_type=c_ubyte) - -def SDL_GetMouseState(): - '''Retrieve the current state of the mouse. - - Example:: - - state, x, y = SDL_GetMouseState() - if state & SDL_BUTTON_LMASK: - print 'Left button pressed.' - - :rtype: (int, int, int) - :return: (state, x, y), where - * state is a button bitmask, which can be tested using `SDL_BUTTON` - * x and y are the current mouse cursor position. - - ''' - x, y = c_int(), c_int() - state = _SDL_GetMouseState(byref(x), byref(y)) - return state, x.value, y.value - -_SDL_GetRelativeMouseState = \ - private_function('SDL_GetRelativeMouseState', - arg_types=[POINTER(c_int), POINTER(c_int)], - return_type=c_ubyte) - -def SDL_GetRelativeMouseState(): - '''Retrieve the current state of the mouse. - - :rtype: (int, int, int) - :return: (state, dx, dy), - where state is a button bitmask, which can be tested using - `SDL_BUTTON`; dx and dy are the mouse deltas since the last call to - `SDL_GetRelativeMouseState` - - ''' - dx, dy = c_int(), c_int() - state = _SDL_GetRelativeMouseState(byref(dx), byref(dy)) - return state, dx.value, dy.value - -SDL_WarpMouse = function('SDL_WarpMouse', - '''Set the position of the mouse cursor. - - Generates a mouse motion event. - - :Parameters: - - `x`: int - - `y`: int - - ''', - args=['x', 'y'], - arg_types=[c_ushort, c_ushort], - return_type=None) - -_SDL_CreateCursor = private_function('SDL_CreateCursor', - arg_types=[POINTER(c_ubyte), POINTER(c_ubyte), c_int, c_int, c_int, c_int], - return_type=POINTER(SDL_Cursor), - dereference_return=True, - require_return=True) - -def SDL_CreateCursor(data, mask, w, h, hot_x, hot_y): - '''Create a cursor using the specified data and mask. - - The cursor width must be a multiple of 8 bits. Mask and cursor - data may be given as either SDL_array byte buffers or as a sequence - of bytes; in either case the data is in MSB order. - - The cursor is created in black and white according to the following: - - ==== ==== ========================================= - data mask resulting pixel on screen - ==== ==== ========================================= - 0 1 White - 1 1 Black - 0 0 Transparent - 1 0 Inverted color if possible, black if not. - ==== ==== ========================================= - - Cursors created with this function must be freed with `SDL_FreeCursor`. - - :Parameters: - - `data`: `SDL_array` - - `mask`: `SDL_array` - - `w`: int - - `h`: int - - `hot_x`: int - - `hot_y`: int - - :rtype: `SDL_Cursor` - ''' - dataref, data = to_ctypes(data, len(data), c_ubyte) - maskref, mask = to_ctypes(mask, len(mask), c_ubyte) - return _SDL_CreateCursor(data, mask, w, h, hot_x, hot_y) - -SDL_SetCursor = function('SDL_SetCursor', - '''Set the currently active cursor to the specified one. - - If the cursor is currently visible, the change will be immediately - represented on the display. - - :Parameters: - - `cursor`: `SDL_Cursor` - - ''', - args=['cursor'], - arg_types=[POINTER(SDL_Cursor)], - return_type=None) - -SDL_GetCursor = function('SDL_GetCursor', - '''Return the currently active cursor. - - :rtype: `SDL_Cursor` - ''', - args=[], - arg_types=[], - return_type=POINTER(SDL_Cursor), - dereference_return=True) - -SDL_FreeCursor = function('SDL_FreeCursor', - '''Deallocate a cursor created with `SDL_CreateCursor` - - :Parameters: - - `cursor`: `SDL_Cursor` - ''', - args=['cursor'], - arg_types=[POINTER(SDL_Cursor)], - return_type=None) - -SDL_ShowCursor = function('SDL_ShowCursor', - '''Toggle whether or not the curosr is shown on the screen. - - The cursor starts off displayed, but can be turned off. - - :Parameters: - `toggle` : int - if 1, shows the cursor; if 0, hides the cursor, if -1, returns - the current state of the cursor. - - :rtype: int - :return: 1 if the cursor was being displayed before the call, otherwise - 0. - ''', - args=['toggle'], - arg_types=[c_int], - return_type=c_int) - -def SDL_BUTTON(X): - '''Used to create a mask for a mouse button. - ''' - return 1 << (X-1) - -SDL_BUTTON_LMASK = SDL_BUTTON(SDL_BUTTON_LEFT) -SDL_BUTTON_MMASK = SDL_BUTTON(SDL_BUTTON_MIDDLE) -SDL_BUTTON_RMASK = SDL_BUTTON(SDL_BUTTON_RIGHT) diff --git a/src/m64py/SDL/quit.py b/src/m64py/SDL/quit.py deleted file mode 100644 index f250f71..0000000 --- a/src/m64py/SDL/quit.py +++ /dev/null @@ -1,30 +0,0 @@ -#!/usr/bin/env python - -'''Quit event handling. - -An `SDL_QUITEVENT` is generated when the user tries to close the application -window. If it is ignored or filtered out, the window will remain open. -If it is not ignored or filtered, it is queued normally and the window -is allowed to close. When the window is closed, screen updates will -complete, but have no effect. - -`SDL_Init` installs signal handlers for SIGINT (keyboard interrupt) -and SIGTERM (system termination request), if handlers do not already -exist, that generate `SDL_QUITEVENT` events as well. There is no way -to determine the cause of an `SDL_QUITEVENT`, but setting a signal -handler in your application will override the default generation of -quit events for that signal. -''' - -__docformat__ = 'restructuredtext' -__version__ = '$Id: $' - -from .events import SDL_PumpEvents, SDL_HaveEvents, SDL_QUITMASK - -def SDL_QuitRequested(): - '''Return True if there is a quit event in the event queue. - - :rtype: bool - ''' - SDL_PumpEvents() - return SDL_HaveEvents(SDL_QUITMASK) diff --git a/src/m64py/SDL/rwops.py b/src/m64py/SDL/rwops.py deleted file mode 100644 index ce4a263..0000000 --- a/src/m64py/SDL/rwops.py +++ /dev/null @@ -1,193 +0,0 @@ -#!/usr/bin/env python - -'''General interface for SDL to read and write data sources. - -For files, use `SDL_RWFromFile`. Other Python file-type objects can be -used with `SDL_RWFromObject`. If another library provides a constant void -pointer to a contiguous region of memory, `SDL_RWFromMem` and -`SDL_RWFromConstMem` can be used. -''' - -__docformat__ = 'restructuredtext' -__version__ = '$Id: $' - -from ctypes import * - -from .dll import function -from .constants import RW_SEEK_CUR - -_rwops_p = POINTER('SDL_RWops') -_seek_fn = CFUNCTYPE(c_int, _rwops_p, c_int, c_int) -_read_fn = CFUNCTYPE(c_int, _rwops_p, c_void_p, c_int, c_int) -_write_fn = CFUNCTYPE(c_int, _rwops_p, c_void_p, c_int, c_int) -_close_fn = CFUNCTYPE(c_int, _rwops_p) - -class _hidden_mem_t(Structure): - _fields_ = [('base', c_void_p), - ('here', c_void_p), - ('stop', c_void_p)] - -class SDL_RWops(Structure): - '''Read/write operations structure. - - :Ivariables: - `seek` : function - seek(context: `SDL_RWops`, offset: int, whence: int) -> int - `read` : function - read(context: `SDL_RWops`, ptr: c_void_p, size: int, maxnum: int) - -> int - `write` : function - write(context: `SDL_RWops`, ptr: c_void_p, size: int, num: int) -> - int - `close` : function - close(context: `SDL_RWops`) -> int - `type` : int - Undocumented - - ''' - _fields_ = [('seek', _seek_fn), - ('read', _read_fn), - ('write', _write_fn), - ('close', _close_fn), - ('type', c_uint), - ('_hidden_mem', _hidden_mem_t)] -SetPointerType(_rwops_p, SDL_RWops) - -SDL_RWFromFile = function('SDL_RWFromFile', - '''Create an SDL_RWops structure from a file on disk. - - :Parameters: - `file` : string - Filename - `mode` : string - Mode to open the file with; as with the built-in function ``open``. - - :rtype: `SDL_RWops` - ''', - args=['file', 'mode'], - arg_types=[c_char_p, c_char_p], - return_type=POINTER(SDL_RWops), - dereference_return=True, - require_return=True) - -SDL_RWFromMem = function('SDL_RWFromMem', - '''Create an SDL_RWops structure from a contiguous region of memory. - - :Parameters: - - `mem`: ``c_void_p`` - - `size`: int - - :rtype: `SDL_RWops` - ''', - args=['mem', 'size'], - arg_types=[c_void_p, c_int], - return_type=POINTER(SDL_RWops), - dereference_return=True, - require_return=True) - -SDL_RWFromConstMem = function('SDL_RWFromConstMem', - '''Create an SDL_RWops structure from a contiguous region of memory. - - :Parameters: - - `mem`: ``c_void_p`` - - `size`: int - - :rtype: `SDL_RWops` - :since: 1.2.7 - ''', - args=['mem', 'size'], - arg_types=[c_void_p, c_int], - return_type=POINTER(SDL_RWops), - dereference_return=True, - require_return=True, - since=(1,2,7)) - -""" These functions shouldn't be useful to Pythoners. -SDL_AllocRW = function('SDL_AllocRW', - '''Allocate a blank SDL_Rwops structure. - - :rtype: `SDL_RWops` - ''' - args=[], - arg_types=[], - return_type=POINTER(SDL_RWops), - dereference_return=True, - require_return=True) - -SDL_FreeRW = function('SDL_FreeRW', - '''Free a SDL_RWops structure. - - :param area: `SDL_RWops` - ''' - args=['area'], - arg_types=[POINTER(SDL_RWops)], - return_type=None) -""" - -# XXX Tested read from open() only so far -def SDL_RWFromObject(obj): - '''Construct an SDL_RWops structure from a Python file-like object. - - The object must support the following methods in the same fashion as - the builtin file object: - - - ``read(len) -> data`` - - ``write(data)`` - - ``seek(offset, whence)`` - - ``close()`` - - :Parameters: - - `obj`: Python file-like object to wrap - - :rtype: `SDL_RWops` - ''' - - ctx = SDL_RWops() - - def _seek(context, offset, whence): - obj.seek(offset, whence) - return obj.tell() - ctx.seek = _seek_fn(_seek) - - def _read(context, ptr, size, maximum): - try: - r = obj.read(maximum * size) - memmove(ptr, r, len(r)) - return len(r) / size - except: - return -1 - ctx.read = _read_fn(_read) - - def _write(context, ptr, size, num): - try: - obj.write(string_at(ptr, size*num)) - return num - except: - return -1 - ctx.write = _write_fn(_write) - - def _close(context): - obj.close() - ctx.close = _close_fn(_close) - return ctx - -""" -# XXX Usefulness of the following using raw pointers? - -def SDL_RWseek(ctx, offset, whence): - return ctx.seek(ctx, offset, whence) - -def SDL_RWtell(ctx): - return ctx.seek(ctx, 0, RW_SEEK_CUR) - -def SDL_RWread(ctx, ptr, size, n): - return ctx.read(ctx, ptr, size, n) - -def SDL_RWwrite(ctx, ptr, size, n): - return ctx.write(ctx, ptr, size, n) - -def SDL_RWclose(ctx): - return ctx.close(ctx) -""" - -# XXX not implemented: SDL_Read{BL}E* and SDL_Write{BL}E* diff --git a/src/m64py/SDL/sound.py b/src/m64py/SDL/sound.py deleted file mode 100644 index 3c858b0..0000000 --- a/src/m64py/SDL/sound.py +++ /dev/null @@ -1,577 +0,0 @@ -#!/usr/bin/env python - -'''An abstract sound format decoding API. - -The latest version of SDL_sound can be found at: http://icculus.org/SDL_sound/ - -The basic gist of SDL_sound is that you use an SDL_RWops to get sound data -into this library, and SDL_sound will take that data, in one of several -popular formats, and decode it into raw waveform data in the format of -your choice. This gives you a nice abstraction for getting sound into your -game or application; just feed it to SDL_sound, and it will handle -decoding and converting, so you can just pass it to your SDL audio -callback (or whatever). Since it gets data from an SDL_RWops, you can get -the initial sound data from any number of sources: file, memory buffer, -network connection, etc. - -As the name implies, this library depends on SDL: Simple Directmedia Layer, -which is a powerful, free, and cross-platform multimedia library. It can -be found at http://www.libsdl.org/ - -Support is in place or planned for the following sound formats: -- .WAV (Microsoft WAVfile RIFF data, internal.) -- .VOC (Creative Labs' Voice format, internal.) -- .MP3 (MPEG-1 Layer 3 support, via the SMPEG and mpglib libraries.) -- .MID (MIDI music converted to Waveform data, internal.) -- .MOD (MOD files, via MikMod and ModPlug.) -- .OGG (Ogg files, via Ogg Vorbis libraries.) -- .SPX (Speex files, via libspeex.) -- .SHN (Shorten files, internal.) -- .RAW (Raw sound data in any format, internal.) -- .AU (Sun's Audio format, internal.) -- .AIFF (Audio Interchange format, internal.) -- .FLAC (Lossless audio compression, via libFLAC.) -''' - -__docformat__ = 'restructuredtext' -__version__ = '$Id: $' - -from ctypes import * - -from .array import SDL_array, to_ctypes -from .dll import SDL_DLL, _version_parts -from .rwops import SDL_RWops - -_dll = SDL_DLL('SDL_sound', None) - -class Sound_Version(Structure): - '''Version structure. - - :Ivariables: - `major` : int - Major version number - `minor` : int - Minor version number - `patch` : int - Patch revision number - - ''' - _fields_ = [('major', c_int), - ('minor', c_int), - ('patch', c_int)] - - def __repr__(self): - return '%d.%d.%d' % (self.major, self.minor, self.patch) - -_Sound_GetLinkedVersion = _dll.private_function('Sound_GetLinkedVersion', - arg_types=[POINTER(Sound_Version)], - return_type=None) - -def Sound_GetLinkedVersion(): - '''Get the version of the dynamically linked SDL_sound library - - :rtype: `Sound_Version` - ''' - version = Sound_Version() - _Sound_GetLinkedVersion(byref(version)) - return version - -# Fill in non-standard linked version now, so "since" declarations can work -_dll._version = _version_parts(Sound_GetLinkedVersion()) - -class Sound_AudioInfo(Structure): - '''Information about an existing sample's format. - - :Ivariables: - `format` : int - Equivalent to `SDL_AudioSpec.format` - `channels` : int - Number of sound channels. 1 == mono, 2 == stereo. - `rate` : int - Sample rate, in samples per second. - - :see: `Sound_SampleNew` - :see: `Sound_SampleNewFromFile` - ''' - _fields_ = [('format', c_ushort), - ('channels', c_ubyte), - ('rate', c_uint)] - -class Sound_DecoderInfo(Structure): - '''Information about a sound decoder. - - Each decoder sets up one of these structures, which can be retrieved - via the `Sound_AvailableDecoders` function. Fields in this - structure are read-only. - - :Ivariables: - `extensions` : list of str - List of file extensions - `description` : str - Human-readable description of the decoder - `author` : str - Author and email address - `url` : str - URL specific to this decoder - ''' - _fields_ = [('_extensions', POINTER(c_char_p)), - ('description', c_char_p), - ('author', c_char_p), - ('url', c_char_p)] - - def __getattr__(self, name): - if name == 'extensions': - extensions = [] - ext_p = self._extensions - i = 0 - while ext_p[i]: - extensions.append(ext_p[i]) - i += 1 - return extensions - raise AttributeError(name) - -class Sound_Sample(Structure): - '''Represents sound data in the process of being decoded. - - The `Sound_Sample` structure is the heart of SDL_sound. This holds - information about a source of sound data as it is beind decoded. All - fields in this structure are read-only. - - :Ivariables: - `decoder` : `Sound_DecoderInfo` - Decoder used for this sample - `desired` : `Sound_AudioInfo` - Desired audio format for conversion - `actual` : `Sound_AudioInfo` - Actual audio format of the sample - `buffer` : `SDL_array` - Buffer of decoded data, as bytes - `buffer_size` : int - Current size of the buffer, in bytes - `flags` : int - Bitwise combination of SOUND_SAMPLEFLAG_CANSEEK, - SOUND_SAMPLEFLAG_EOF, SOUND_SAMPLEFLAG_ERROR, - SOUND_SAMPLEFLAG_EGAIN - - ''' - _fields_ = [('opaque', c_void_p), - ('_decoder', POINTER(Sound_DecoderInfo)), - ('desired', Sound_AudioInfo), - ('actual', Sound_AudioInfo), - ('_buffer', POINTER(c_ubyte)), - ('buffer_size', c_uint), - ('flags', c_int)] - - def __getattr__(self, name): - if name == 'decoder': - return self._decoder.contents - elif name == 'buffer': - return SDL_array(self._buffer, self.buffer_size, c_ubyte) - raise AttributeError(name) - -Sound_Init = _dll.function('Sound_Init', - '''Initialize SDL_sound. - - This must be called before any other SDL_sound function (except perhaps - `Sound_GetLinkedVersion`). You should call `SDL_Init` before calling - this. `Sound_Init` will attempt to call ``SDL_Init(SDL_INIT_AUDIO)``, - just in case. This is a safe behaviour, but it may not configure SDL - to your liking by itself. - ''', - args=[], - arg_types=[], - return_type=c_int, - error_return=0) - -Sound_Quit = _dll.function('Sound_Quit', - '''Shutdown SDL_sound. - - This closes any SDL_RWops that were being used as sound sources, and - frees any resources in use by SDL_sound. - - All Sound_Sample structures existing will become invalid. - - Once successfully deinitialized, `Sound_Init` can be called again to - restart the subsystem. All default API states are restored at this - point. - - You should call this before `SDL_Quit`. This will not call `SDL_Quit` - for you. - ''', - args=[], - arg_types=[], - return_type=c_int, - error_return=0) - -_Sound_AvailableDecoders = _dll.private_function('Sound_AvailableDecoders', - arg_types=[], - return_type=POINTER(POINTER(Sound_DecoderInfo))) - -def Sound_AvailableDecoders(): - '''Get a list of sound formats supported by this version of SDL_sound. - - This is for informational purposes only. Note that the extension listed - is merely convention: if we list "MP3", you can open an MPEG-1 Layer 3 - audio file with an extension of "XYZ", if you like. The file extensions - are informational, and only required as a hint to choosing the correct - decoder, since the sound data may not be coming from a file at all, - thanks to the abstraction that an SDL_RWops provides. - - :rtype: list of `Sound_DecoderInfo` - ''' - decoders = [] - decoder_p = _Sound_AvailableDecoders() - i = 0 - while decoder_p[i]: - decoders.append(decoder_p[i].contents) - i += 1 - return decoders - -Sound_GetError = _dll.function('Sound_GetError', - '''Get the last SDL_sound error message. - - This will be None if there's been no error since the last call to this - function. Each thread has a unique error state associated with it, but - each time a new error message is set, it will overwrite the previous - one associated with that thread. It is safe to call this function at - any time, even before `Sound_Init`. - - :rtype: str - ''', - args=[], - arg_types=[], - return_type=c_char_p) - -Sound_ClearError = _dll.function('Sound_ClearError', - '''Clear the current error message. - - The next call to `Sound_GetError` after `Sound_ClearError` will return - None. - ''', - args=[], - arg_types=[], - return_type=None) - -Sound_NewSample = _dll.function('Sound_NewSample', - '''Start decoding a new sound sample. - - The data is read via an SDL_RWops structure, so it may be coming from - memory, disk, network stream, etc. The `ext` parameter is merely a hint - to determining the correct decoder; if you specify, for example, "mp3" - for an extension, and one of the decoders lists that as a handled - extension, then that decoder is given first shot at trying to claim the - data for decoding. If none of the extensions match (or the extension is - None), then every decoder examines the data to determine if it can - handle it, until one accepts it. In such a case your SDL_RWops will - need to be capable of rewinding to the start of the stream. - - If no decoders can handle the data, an exception is raised. - - Optionally, a desired audio format can be specified. If the incoming data - is in a different format, SDL_sound will convert it to the desired format - on the fly. Note that this can be an expensive operation, so it may be - wise to convert data before you need to play it back, if possible, or - make sure your data is initially in the format that you need it in. - If you don't want to convert the data, you can specify None for a desired - format. The incoming format of the data, preconversion, can be found - in the `Sound_Sample` structure. - - Note that the raw sound data "decoder" needs you to specify both the - extension "RAW" and a "desired" format, or it will refuse to handle - the data. This is to prevent it from catching all formats unsupported - by the other decoders. - - Finally, specify an initial buffer size; this is the number of bytes that - will be allocated to store each read from the sound buffer. The more you - can safely allocate, the more decoding can be done in one block, but the - more resources you have to use up, and the longer each decoding call will - take. Note that different data formats require more or less space to - store. This buffer can be resized via `Sound_SetBufferSize`. - - The buffer size specified must be a multiple of the size of a single - sample point. So, if you want 16-bit, stereo samples, then your sample - point size is (2 channels 16 bits), or 32 bits per sample, which is four - bytes. In such a case, you could specify 128 or 132 bytes for a buffer, - but not 129, 130, or 131 (although in reality, you'll want to specify a - MUCH larger buffer). - - When you are done with this `Sound_Sample` instance, you can dispose of - it via `Sound_FreeSample`. - - You do not have to keep a reference to `rw` around. If this function - suceeds, it stores `rw` internally (and disposes of it during the call - to `Sound_FreeSample`). If this function fails, it will dispose of the - SDL_RWops for you. - - :Parameters: - `rw` : `SDL_RWops` - SDL_RWops with sound data - `ext` : str - File extension normally associated with a data format. Can - usually be None. - `desired` : `Sound_AudioInfo` - Format to convert sound data into. Can usually be None if you - don't need conversion. - `bufferSize` : int - Size, in bytes, to allocate for the decoding buffer - - :rtype: `Sound_Sample` - ''', - args=['rw', 'ext', 'desired', 'bufferSize'], - arg_types=[POINTER(SDL_RWops), c_char_p, - POINTER(Sound_AudioInfo), c_uint], - return_type=POINTER(Sound_Sample), - dereference_return=True, - require_return=True) - -_Sound_NewSampleFromMem = _dll.private_function('Sound_NewSampleFromMem', - arg_types=[POINTER(c_ubyte), c_uint, c_char_p, - POINTER(Sound_AudioInfo), c_uint], - return_type=POINTER(Sound_Sample), - dereference_return=True, - require_return=True, - since=(9,9,9)) # Appears in header only - -def Sound_NewSampleFromMem(data, ext, desired, bufferSize): - '''Start decoding a new sound sample from a buffer. - - This is identical to `Sound_NewSample`, but it creates an `SDL_RWops` - for you from the buffer. - - :Parameters: - `data` : `SDL_array` or sequence - Buffer holding encoded byte sound data - `ext` : str - File extension normally associated with a data format. Can - usually be None. - `desired` : `Sound_AudioInfo` - Format to convert sound data into. Can usually be None if you - don't need conversion. - `bufferSize` : int - Size, in bytes, to allocate for the decoding buffer - - :rtype: `Sound_Sample` - - :since: Not yet released in SDL_sound - ''' - ref, data = to_ctypes(data, len(data), c_ubyte) - return _Sound_NewSampleFromMem(data, len(data), ext, desired, bufferSize) - -Sound_NewSampleFromFile = _dll.function('Sound_NewSampleFromFile', - '''Start decoding a new sound sample from a file on disk. - - This is identical to `Sound_NewSample`, but it creates an `SDL_RWops - for you from the file located at `filename`. - ''', - args=['filename', 'desired', 'bufferSize'], - arg_types=[c_char_p, POINTER(Sound_AudioInfo), c_uint], - return_type=POINTER(Sound_Sample), - dereference_return=True, - require_return=True) - -Sound_FreeSample = _dll.function('Sound_FreeSample', - '''Dispose of a `Sound_Sample`. - - This will also close/dispose of the `SDL_RWops` that was used at - creation time. The `Sound_Sample` structure is invalid after this - call. - - :Parameters: - `sample` : `Sound_Sample` - The sound sample to delete. - - ''', - args=['sample'], - arg_types=[POINTER(Sound_Sample)], - return_type=None) - -Sound_GetDuration = _dll.function('Sound_GetDuration', - '''Retrieve the total play time of a sample, in milliseconds. - - Report total time length of sample, in milliseconds. This is a fast - call. Duration is calculated during `Sound_NewSample`, so this is just - an accessor into otherwise opaque data. - - Note that not all formats can determine a total time, some can't - be exact without fully decoding the data, and thus will estimate the - duration. Many decoders will require the ability to seek in the data - stream to calculate this, so even if we can tell you how long an .ogg - file will be, the same data set may fail if it's, say, streamed over an - HTTP connection. - - :Parameters: - `sample` : `Sound_Sample` - Sample from which to retrieve duration information. - - :rtype: int - :return: Sample length in milliseconds, or -1 if duration can't be - determined. - - :since: Not yet released in SDL_sound - ''', - args=['sample'], - arg_types=[POINTER(Sound_Sample)], - return_type=c_int, - since=(9,9,9)) - -Sound_SetBufferSize = _dll.function('Sound_SetBufferSize', - '''Change the current buffer size for a sample. - - If the buffer size could be changed, then the ``sample.buffer`` and - ``sample.buffer_size`` fields will reflect that. If they could not be - changed, then your original sample state is preserved. If the buffer is - shrinking, the data at the end of buffer is truncated. If the buffer is - growing, the contents of the new space at the end is undefined until you - decode more into it or initialize it yourself. - - The buffer size specified must be a multiple of the size of a single - sample point. So, if you want 16-bit, stereo samples, then your sample - point size is (2 channels 16 bits), or 32 bits per sample, which is four - bytes. In such a case, you could specify 128 or 132 bytes for a buffer, - but not 129, 130, or 131 (although in reality, you'll want to specify a - MUCH larger buffer). - - :Parameters: - `sample` : `Sound_Sample` - Sample to modify - `new_size` : int - The desired size, in bytes of the new buffer - - ''', - args=['sample', 'new_size'], - arg_types=[POINTER(Sound_Sample), c_uint], - return_type=c_int, - error_return=0) - -Sound_Decode = _dll.function('Sound_Decode', - '''Decode more of the sound data in a `Sound_Sample`. - - It will decode at most sample->buffer_size bytes into ``sample.buffer`` - in the desired format, and return the number of decoded bytes. - - If ``sample.buffer_size`` bytes could not be decoded, then refer to - ``sample.flags`` to determine if this was an end-of-stream or error - condition. - - :Parameters: - `sample` : `Sound_Sample` - Do more decoding to this sample - - :rtype: int - :return: number of bytes decoded into ``sample.buffer`` - ''', - args=['sample'], - arg_types=[POINTER(Sound_Sample)], - return_type=c_uint) - -Sound_DecodeAll = _dll.function('Sound_DecodeAll', - '''Decode the remainder of the sound data in a `Sound_Sample`. - - This will dynamically allocate memory for the entire remaining sample. - ``sample.buffer_size`` and ``sample.buffer`` will be updated to reflect - the new buffer. Refer to ``sample.flags`` to determine if the - decoding finished due to an End-of-stream or error condition. - - Be aware that sound data can take a large amount of memory, and that - this function may block for quite awhile while processing. Also note - that a streaming source (for example, from a SDL_RWops that is getting - fed from an Internet radio feed that doesn't end) may fill all available - memory before giving up...be sure to use this on finite sound sources - only. - - When decoding the sample in its entirety, the work is done one buffer - at a time. That is, sound is decoded in ``sample.buffer_size`` blocks, and - appended to a continually-growing buffer until the decoding completes. - That means that this function will need enough RAM to hold - approximately ``sample.buffer_size`` bytes plus the complete decoded - sample at most. The larger your buffer size, the less overhead this - function needs, but beware the possibility of paging to disk. Best to - make this user-configurable if the sample isn't specific and small. - - :Parameters: - `sample` : `Sound_Sample` - Do all decoding for this sample. - - :rtype: int - :return: number of bytes decoded into ``sample.buffer`` - ''', - args=['sample'], - arg_types=[POINTER(Sound_Sample)], - return_type=c_uint) - -Sound_Rewind = _dll.function('Sound_Rewind', - '''Rewind a sample to the start. - - Restart a sample at the start of its waveform data, as if newly - created with `Sound_NewSample`. If successful, the next call to - `Sound_Decode` will give audio data from the earliest point in the - stream. - - Beware that this function will fail if the SDL_RWops that feeds the - decoder can not be rewound via it's seek method, but this can - theoretically be avoided by wrapping it in some sort of buffering - SDL_RWops. - - This function will raise an exception if the RWops is not seekable, or - SDL_sound is not initialized. - - If this function fails, the state of the sample is undefined, but it - is still safe to call `Sound_FreeSample` to dispose of it. - - :Parameters: - `sample` : `Sound_Sample` - The sample to rewind - - ''', - args=['sample'], - arg_types=[POINTER(Sound_Sample)], - return_type=c_int, - error_return=0) - -Sound_Seek = _dll.function('Sound_Seek', - '''Seek to a different point in a sample. - - Reposition a sample's stream. If successful, the next call to - `Sound_Decode` or `Sound_DecodeAll` will give audio data from the - offset you specified. - - The offset is specified in milliseconds from the start of the - sample. - - Beware that this function can fail for several reasons. If the - SDL_RWops that feeds the decoder can not seek, this call will almost - certainly fail, but this can theoretically be avoided by wrapping it - in some sort of buffering SDL_RWops. Some decoders can never seek, - others can only seek with certain files. The decoders will set a flag - in the sample at creation time to help you determine this. - - You should check ``sample.flags & SOUND_SAMPLEFLAG_CANSEEK`` - before attempting. `Sound_Seek` reports failure immediately if this - flag isn't set. This function can still fail for other reasons if the - flag is set. - - This function can be emulated in the application with `Sound_Rewind` - and predecoding a specific amount of the sample, but this can be - extremely inefficient. `Sound_Seek()` accelerates the seek on a - with decoder-specific code. - - If this function fails, the sample should continue to function as if - this call was never made. If there was an unrecoverable error, - ``sample.flags & SOUND_SAMPLEFLAG_ERROR`` will be set, which your - regular decoding loop can pick up. - - On success, ERROR, EOF, and EAGAIN are cleared from sample->flags. - - :Parameters: - `sample` : `Sound_Sample` - The sample to seek - `ms` : int - The new position, in milliseconds, from the start of sample - - ''', - args=['sample', 'ms'], - arg_types=[POINTER(Sound_Sample), c_uint], - return_type=c_int, - error_return=0) - - diff --git a/src/m64py/SDL/timer.py b/src/m64py/SDL/timer.py deleted file mode 100644 index 8a87132..0000000 --- a/src/m64py/SDL/timer.py +++ /dev/null @@ -1,161 +0,0 @@ -#!/usr/bin/env python - -'''Time management routines. -''' - -__docformat__ = 'restructuredtext' -__version__ = '$Id: $' - -from ctypes import * - -from .dll import function, private_function -from .error import SDL_Exception, SDL_GetError - -SDL_GetTicks = function('SDL_GetTicks', - '''Get the number of milliseconds since the SDL library initialization. - - Note that this value wraps if the program runs for more than ~49 days. - - :rtype: int - ''', - args=[], - arg_types=[], - return_type=c_uint) - -SDL_Delay = function('SDL_Delay', - '''Wait a specified number of milliseconds before returning. - - :Parameters: - `ms` : int - delay in milliseconds - - ''', - args=['ms'], - arg_types=[c_uint], - return_type=None) - -_SDL_TimerCallback = CFUNCTYPE(c_int, c_uint) -_SDL_SetTimer = private_function('SDL_SetTimer', - arg_types=[c_uint, _SDL_TimerCallback], - return_type=c_int) - -_timercallback_ref = None # Keep global to avoid possible GC - -def SDL_SetTimer(interval, callback): - '''Set a callback to run after the specified number of milliseconds has - elapsed. - - The callback function is passed the current timer interval - and returns the next timer interval. If the returned value is the - same as the one passed in, the periodic alarm continues, otherwise a - new alarm is scheduled. If the callback returns 0, the periodic alarm - is cancelled. - - To cancel a currently running timer, call ``SDL_SetTimer(0, None)``. - - The timer callback function may run in a different thread than your - main code, and so shouldn't call any functions from within itself. - - The maximum resolution of this timer is 10 ms, which means that if - you request a 16 ms timer, your callback will run approximately 20 ms - later on an unloaded system. If you wanted to set a flag signaling - a frame update at 30 frames per second (every 33 ms), you might set a - timer for 30 ms:: - - SDL_SetTimer((33/10)*10, flag_update) - - If you use this function, you need to pass `SDL_INIT_TIMER` to - `SDL_Init`. - - Under UNIX, you should not use raise or use SIGALRM and this function - in the same program, as it is implemented using ``setitimer``. You - also should not use this function in multi-threaded applications as - signals to multi-threaded apps have undefined behavior in some - implementations. - - :Parameters: - `interval` : int - Interval before callback, in milliseconds. - `callback` : function - Callback function should accept one argument, the number of - milliseconds elapsed, and return the next timer interval, - in milliseconds. - ''' - - # Note SDL_SetTimer actually returns 1 on success, not 0 as documented - # in SDL_timer.h. - global _timercallback_ref - if callback: - _timercallback_ref = _SDL_TimerCallback(callback) - else: - _timercallback_ref = _SDL_TimerCallback() - - # XXX if this fails the global ref is incorrect and old one will - # possibly be collected early. - if _SDL_SetTimer(interval, _timercallback_ref) == -1: - raise SDL_Exception(SDL_GetError()) - - -# For the new timer functions, the void *param passed to the callback -# is ignored; using an local function instead. The SDL_TimerID type -# is not defined, we use c_void_p instead. - -_SDL_NewTimerCallback = CFUNCTYPE(c_uint, c_int, c_void_p) -_SDL_AddTimer = private_function('SDL_AddTimer', - arg_types=[c_uint, _SDL_NewTimerCallback, c_void_p], - return_type=c_void_p) - -_timer_refs = {} # Keep global to manage GC - -def SDL_AddTimer(interval, callback, param): - '''Add a new timer to the pool of timers already running. - - :Parameters: - `interval` : int - The interval before calling the callback, in milliseconds. - `callback` : function - The callback function. It is passed the current timer - interval, in millseconds, and returns the next timer interval, - in milliseconds. If the returned value is the same as the one - passed in, the periodic alarm continues, otherwise a new alarm - is scheduled. If the callback returns 0, the periodic alarm is - cancelled. An example callback function is:: - - def timer_callback(interval, param): - print 'timer called after %d ms.' % interval - return 1000 # call again in 1 second - - `param` : any - A value passed to the callback function. - - :rtype: int - :return: the timer ID - ''' - def _callback(interval, _ignored_param): - return callback(interval, param) - - func = _SDL_NewTimerCallback(_callback) - result = _SDL_AddTimer(interval, func, None) - if not result: - raise SDL_Exception(SDL_GetError()) - _timer_refs[result] = func - return result - -_SDL_RemoveTimer = private_function('SDL_RemoveTimer', - args=['t'], - arg_types=[c_void_p], - return_type=c_int, - error_return=0) - -def SDL_RemoveTimer(t): - '''Remove one of the multiple timers knowing its ID. - - :Parameters: - `t` : int - The timer ID, as returned by `SDL_AddTimer`. - - ''' - global _timer_refs - _SDL_RemoveTimer(t) - del _timer_refs[t] - diff --git a/src/m64py/SDL/ttf.py b/src/m64py/SDL/ttf.py deleted file mode 100644 index dc21147..0000000 --- a/src/m64py/SDL/ttf.py +++ /dev/null @@ -1,481 +0,0 @@ -#!/usr/bin/env python - -'''A companion module to SDL for working with TrueType fonts. - -This library is a wrapper around FreeType_ 2.0. - -.. _FreeType: http://www.freetype.org -''' - -__docformat__ = 'restructuredtext' -__version__ = '$Id: $' - -from ctypes import * - -from .dll import SDL_DLL -from .rwops import SDL_RWops -from .version import SDL_version -from .video import SDL_Color, SDL_Surface - -_dll = SDL_DLL('SDL_ttf', 'TTF_Linked_Version') - -TTF_Linked_Version = _dll.function('TTF_Linked_Version', - '''Get the version of the dynamically linked SDL_ttf library. - - :rtype: `SDL_version` - ''', - args=[], - arg_types=[], - return_type=POINTER(SDL_version), - dereference_return=True, - require_return=True) - -# Opaque type pointer -_TTF_Font = c_void_p - -TTF_Init = _dll.function('TTF_Init', - '''Initialize the TTF engine - ''', - args=[], - arg_types=[], - return_type=c_int, - error_return=-1) - -TTF_OpenFont = _dll.function('TTF_OpenFont', - '''Open a font file and create a font of the specified point size. - - :Parameters: - `file` : string - Filename of a Truetype font file to open. - `ptsize` : int - Size of the font face, in points. Type is rendered at 64 DPI. - - :rtype: ``TTF_Font`` - ''', - args=['file', 'ptsize'], - arg_types=[c_char_p, c_int], - return_type=_TTF_Font, - require_return=True) - -TTF_OpenFontIndex = _dll.function('TTF_OpenFontIndex', - '''Open a font collection file and create a font of the specified point - size. - - :Parameters: - `file` : string - Filename of a Truetype font file to open. - `ptsize` : int - Size of the font face, in points. Type is rendered at 64 DPI. - `index` : int - Zero-based index of the desired font within the file. - - :rtype: ``TTF_Font`` - ''', - args=['file', 'ptsize', 'index'], - arg_types=[c_char_p, c_int, c_int], - return_type=_TTF_Font, - require_return=True) - -TTF_OpenFontRW = _dll.function('TTF_OpenFontRW', - '''Create a font of the specified point size from a RWops object. - - You can create an SDL_RWops object from any Python file-like object - with `SDL_RWFromObject`. - - :Parameters: - `src` : `SDL_RWops` - Readable RWops object. - `freesrc` : int - If non-zero, the source will be closed when the face is closed. - `ptsize` : int - Size of the font face, in points. Type is rendered at 64 DPI. - - :rtype: ``TTF_Font`` - ''', - args=['src', 'freesrc', 'ptsize'], - arg_types=[POINTER(SDL_RWops), c_int, c_int], - return_type=_TTF_Font, - require_return=True) - -TTF_OpenFontIndexRW = _dll.function('TTF_OpenFontIndexRW', - '''Create a font of the specified point size from a RWops object. - - :Parameters: - `src` : `SDL_RWops` - Readable RWops object. - `freesrc` : int - If non-zero, the source will be closed when the face is closed. - `ptsize` : int - Size of the font face, in points. Type is rendered at 64 DPI. - `index` : int - Zero-based index of the desired font within the file. - - :rtype: ``TTF_Font`` - ''', - args=['src', 'freesrc', 'ptsize', 'index'], - arg_types=[POINTER(SDL_RWops), c_int, c_int, c_int], - return_type=_TTF_Font, - require_return=True) - - -TTF_GetFontStyle = _dll.function('TTF_GetFontStyle', - '''Get the modified font style. - - Note that the modified style has nothing to do with the underlying - style properties of the font, and merely reflects what has been - set in `TTF_SetFontStyle`. - - :Parameters: - - `font`: ``TTF_Font`` - - :rtype: int - :return: A bitwise combination of ``TTF_STYLE_BOLD``, ``TTF_STYLE_ITALIC`` - and ``TTF_STYLE_UNDERLINE``. - ''', - args=['font'], - arg_types=[_TTF_Font], - return_type=c_int) - -TTF_SetFontStyle = _dll.function('TTF_SetFontStyle', - '''Set the modified font style. - - This font style is implemented by modifying the font glyphs, and doesn't - reflect any inherent properties of the TrueType font file. - - :Parameters: - `font` : ``TTF_Font`` - Font object to modify. - `style` : int - Bitwise combination of any of ``TTF_STYLE_BOLD``, - ``TTF_STYLE_ITALIC`` and ``TTF_STYLE_UNDERLINE``. - - ''', - args=['font', 'style'], - arg_types=[_TTF_Font, c_int], - return_type=None) - -TTF_FontHeight = _dll.function('TTF_FontHeight', - '''Get the total height of the font, in pixels. - - :Parameters: - - `font`: ``TTF_Font`` - - :rtype: int - ''', - args=['font'], - arg_types=[_TTF_Font], - return_type=c_int) - -TTF_FontAscent = _dll.function('TTF_FontAscent', - '''Get the ascent of the font, in pixels. - - This is the offset from the baseline to the top of the font. - - :Parameters: - - `font`: ``TTF_Font`` - - :rtype: int - ''', - args=['font'], - arg_types=[_TTF_Font], - return_type=c_int) - -TTF_FontDescent = _dll.function('TTF_FontDescent', - '''Get the descent of the font, in pixels. - - This is the offset from the baseline to the lowest point of the font, - and is usually negative. - - :Parameters: - - `font`: ``TTF_Font`` - - :rtype: int - ''', - args=['font'], - arg_types=[_TTF_Font], - return_type=c_int) - -TTF_FontLineSkip = _dll.function('TTF_FontLineSkip', - '''Get the recommended spacing between lines of text, in pixels. - - :Parameters: - - `font`: ``TTF_Font`` - - :rtype: int - ''', - args=['font'], - arg_types=[_TTF_Font], - return_type=c_int) - -TTF_FontFaces = _dll.function('TTF_FontFaces', - '''Get the number of fonts in the font collection file. - - :Parameters: - - `font`: ``TTF_Font`` - - :rtype: int - ''', - args=['font'], - arg_types=[_TTF_Font], - return_type=c_long) - -TTF_FontFaceIsFixedWidth = _dll.function('TTF_FontFaceIsFixedWidth', - '''Determine if a font is monospaced or not. - - :Parameters: - - `font`: ``TTF_Font`` - - :rtype: int - :return: non-zero if monospaced, otherwise zero. - ''', - args=['font'], - arg_types=[_TTF_Font], - return_type=c_int) - -TTF_FontFaceFamilyName = _dll.function('TTF_FontFaceFamilyName', - '''Get the family name of the font. - - For example, "Times New Roman". - - :Parameters: - - `font`: ``TTF_Font`` - - :rtype: string - ''', - args=['font'], - arg_types=[_TTF_Font], - return_type=c_char_p) - -TTF_FontFaceStyleName = _dll.function('TTF_FontFaceStyleName', - '''Get the style name of the font. - - For example, "Regular", "Bold", "Italic", etc. - - :Parameters: - - `font`: ``TTF_Font`` - - :rtype: string - ''', - args=['font'], - arg_types=[_TTF_Font], - return_type=c_char_p) - -_TTF_GlyphMetrics = _dll.private_function('TTF_GlyphMetrics', - arg_types=[_TTF_Font, c_ushort, POINTER(c_int), POINTER(c_int), - POINTER(c_int), POINTER(c_int), POINTER(c_int)], - return_type=int, - error_return=-1) - -def TTF_GlyphMetrics(font, ch): - '''Get the metrics of a glyph. - - The character `ch` is used to look up the glyph metrics - for the given font. The metrics returned are: - - minx, maxx, miny, maxy - Bounding box for the glyph. - advance - Horizontal advance for the glyph. - - All metrics are returned in pixels. - - :Parameters: - `font` : ``TTF_Font`` - Font object to inspect. - `ch` : string of length 1 - Character to look up - - :rtype: (int, int, int, int, int) - :return: (minx, maxx, miny, maxy, advance) - ''' - minx, maxx, miny, maxy, advance = \ - c_int(), c_int(), c_int(), c_int(), c_int() - _TTF_GlyphMetrics(font, ord(ch), byref(minx), byref(maxx), byref(miny), - byref(maxy), byref(advance)) - return minx.value, maxx.value, miny.value, maxy.value, advance.value - -_TTF_SizeUTF8 = _dll.private_function('TTF_SizeUTF8', - arg_types=[_TTF_Font, c_char_p, POINTER(c_int), POINTER(c_int)], - return_type=c_int, - error_return=-1) - -def TTF_SizeText(font, text): - '''Get the dimensions of a rendered string of text, in pixels. - - :Parameters: - - `font`: ``TTF_Font`` - - `text`: string - - :rtype: (int, int) - :return: (width, height) - ''' - w, h = c_int(), c_int() - _TTF_SizeUTF8(font, text.encode('utf8'), byref(w), byref(h)) - return w.value, h.value - -_TTF_RenderUTF8_Solid = _dll.private_function('TTF_RenderUTF8_Solid', - arg_types=[_TTF_Font, c_char_p, SDL_Color], - return_type=POINTER(SDL_Surface), - require_return=True, - dereference_return=True) - -def TTF_RenderText_Solid(font, text, fg): - '''Create an 8-bit palettized surface and render the given text at - the fast quality with the given font and color. - - The palette has 0 as the colorkey, giving it a transparent background, - with 1 as the text color. - - :Parameters: - - `font`: ``TTF_Font`` - - `text`: string - - `fg`: `SDL_Color` - - :rtype: `SDL_Surface` - ''' - return _TTF_RenderUTF8_Solid(font, text.encode('utf8'), fg) - -_TTF_RenderGlyph_Solid = _dll.private_function('TTF_RenderGlyph_Solid', - arg_types=[_TTF_Font, c_ushort, SDL_Color], - return_type=POINTER(SDL_Surface), - require_return=True, - dereference_return=True) - -def TTF_RenderGlyph_Solid(font, ch, fg): - '''Create an 8-bit palettized surface and render the given character at - the fast quality with the given font and color. - - The palette has 0 as the colorkey, giving it a transparent background, - with 1 as the text color. - - The glyph is rendered without any padding or centering in the X direction, - and aligned normally in the Y direction. - - :Parameters: - - `font`: ``TTF_Font`` - - `ch`: string of length 1 - - `fg`: `SDL_Color` - - :rtype: `SDL_Surface` - ''' - return _TTF_RenderGlyph_Solid(font, ord(text), fg) - -_TTF_RenderUTF8_Shaded = _dll.private_function('TTF_RenderUTF8_Shaded', - arg_types=[_TTF_Font, c_char_p, SDL_Color, SDL_Color], - return_type=POINTER(SDL_Surface), - require_return=True, - dereference_return=True) - -def TTF_RenderText_Shaded(font, text, fg, bg): - '''Create an 8-bit palettized surface and render the given text at - high quality with the given font and colors. - - The 0 pixel is background, while other pixels have varying degrees of - the foreground color. - - :Parameters: - - `font`: ``TTF_Font`` - - `text`: string - - `fg`: `SDL_Color` - - `bg`: `SDL_Color` - - :rtype: `SDL_Surface` - ''' - return _TTF_RenderUTF8_Shaded(font, text.encode('utf8'), fg, bg) - -_TTF_RenderGlyph_Shaded = _dll.private_function('TTF_RenderGlyph_Shaded', - arg_types=[_TTF_Font, c_ushort, SDL_Color, SDL_Color], - return_type=POINTER(SDL_Surface), - require_return=True, - dereference_return=True) - -def TTF_RenderGlyph_Shaded(font, ch, fg, bg): - '''Create an 8-bit palettized surface and render the given character at - high quality with the given font and color. - - The 0 pixel is background, while other pixels have varying degrees of - the foreground color. - - The glyph is rendered without any padding or centering in the X direction, - and aligned normally in the Y direction. - - :Parameters: - - `font`: ``TTF_Font`` - - `ch`: string of length 1 - - `fg`: `SDL_Color` - - `bg`: `SDL_Color` - - :rtype: `SDL_Surface` - ''' - return _TTF_RenderGlyph_Shaded(font, ord(ch), fg, bg) - -_TTF_RenderUTF8_Blended = _dll.private_function('TTF_RenderUTF8_Blended', - arg_types=[_TTF_Font, c_char_p, SDL_Color], - return_type=POINTER(SDL_Surface), - require_return=True, - dereference_return=True) - -def TTF_RenderText_Blended(font, text, fg): - '''Create a 32-bit ARGB surface and render the given text at - high quality, using alpha blending to dither the font with the - given color. - - :Parameters: - - `font`: ``TTF_Font`` - - `text`: string - - `fg`: `SDL_Color` - - :rtype: `SDL_Surface` - ''' - return _TTF_RenderUTF8_Blended(font, text.encode('utf8'), fg) - -_TTF_RenderGlyph_Blended = _dll.private_function('TTF_RenderGlyph_Blended', - arg_types=[_TTF_Font, c_ushort, SDL_Color], - return_type=POINTER(SDL_Surface), - require_return=True, - dereference_return=True) - -def TTF_RenderGlyph_Blended(font, ch, fg): - '''Create a 32-bit ARGB surface and render the given character at - high quality, using alpha blending to dither the font with the - given color. - - The glyph is rendered without any padding or centering in the X direction, - and aligned normally in the Y direction. - - :Parameters: - - `font`: ``TTF_Font`` - - `ch`: string of length 1 - - `fg`: `SDL_Color` - - :rtype: `SDL_Surface` - ''' - return _TTF_RenderGlyph_Blended(font, ord(text), fg) - -TTF_CloseFont = _dll.function('TTF_CloseFont', - '''Close an opened font file. - - :Parameters: - - `font`: ``TTF_Font`` - - ''', - args=['font'], - arg_types=[_TTF_Font], - return_type=None) - -TTF_Quit = _dll.function('TTF_Quit', - '''De-initialize the TTF engine. - ''', - args=[], - arg_types=[], - return_type=None) - -TTF_WasInit = _dll.function('TTF_WasInit', - '''Check if the TTF engine is initialized. - - :rtype: int - :return: non-zero if initialized, otherwise zero. - ''', - args=[], - arg_types=[], - return_type=c_int) diff --git a/src/m64py/SDL/version.py b/src/m64py/SDL/version.py deleted file mode 100644 index 16ca301..0000000 --- a/src/m64py/SDL/version.py +++ /dev/null @@ -1,86 +0,0 @@ -#!/usr/bin/env python - -'''Functions related to the SDL shared library version. -''' - -__docformat__ = 'restructuredtext' -__version__ = '$Id: $' - -from ctypes import * - -from .dll import function - -class SDL_version(Structure): - '''Version structure. - - :Ivariables: - `major` : int - Major version number - `minor` : int - Minor version number - `patch` : int - Patch revision number - - ''' - _fields_ = [('major', c_ubyte), - ('minor', c_ubyte), - ('patch', c_ubyte)] - - def __repr__(self): - return '%d.%d.%d' % \ - (self.major, self.minor, self.patch) - - def is_since(self, required): - if hasattr(required, 'major'): - return self.major >= required.major and \ - self.minor >= required.minor and \ - self.patch >= required.patch - else: - return self.major >= required[0] and \ - self.minor >= required[1] and \ - self.patch >= required[2] - -def SDL_VERSIONNUM(major, minor, patch): - '''Turn the version numbers into a numeric value. - - For example:: - - >>> SDL_VERSIONNUM(1, 2, 3) - 1203 - - :Parameters: - - `major`: int - - `minor`: int - - `patch`: int - - :rtype: int - ''' - return x * 1000 + y * 100 + z - -SDL_Linked_Version = function('SDL_Linked_Version', - '''Get the version of the dynamically linked SDL library. - - :rtype: `SDL_version` - ''', - args=[], - arg_types=[], - return_type=POINTER(SDL_version), - dereference_return=True, - require_return=True) - -def SDL_VERSION_ATLEAST(major, minor, patch): - '''Determine if the SDL library is at least the given version. - - :Parameters: - - `major`: int - - `minor`: int - - `patch`: int - - :rtype: bool - ''' - v = SDL_Linked_Version() - return SDL_VERSIONNUM(v.major, v.minor, v.patch) >= \ - SDL_VERSIONNUM(major, minor, patch) - -# SDL_VERSION and SDL_COMPILEDVERSION not implemented as there is no -# sensible mapping to compiled version numbers. diff --git a/src/m64py/SDL/video.py b/src/m64py/SDL/video.py deleted file mode 100644 index e946083..0000000 --- a/src/m64py/SDL/video.py +++ /dev/null @@ -1,1649 +0,0 @@ -#!/usr/bin/env python - -'''Access to the SDL raw framebuffer window. - -:group YUV overlay functions: SDL_CreateYUVOverlay, SDL_LockYUVOverlay, - SDL_UnlockYUVOverlay, SDL_DisplayYUVOverlay, SDL_FreeYUVOverlay - -:group OpenGL support functions: SDL_GL_SetAttribute, - SDL_GL_GetAttribute, SDL_GL_SwapBuffers - -:group Window manager functions: SDL_WM_SetCaption, SDL_WM_GetCaption, - SDL_WM_SetIcon, SDL_WM_IconifyWindow, SDL_WM_ToggleFullScreen, - SDL_WM_GrabInput -''' - -__docformat__ = 'restructuredtext' -__version__ = '$Id: $' - -from ctypes import * - -from .array import SDL_array, to_ctypes -from .dll import function, private_function, assert_version_compatible -from .error import SDL_Exception, SDL_GetError -from .constants import SDL_HWSURFACE, SDL_ASYNCBLIT, SDL_RLEACCEL -from .rwops import SDL_RWops, SDL_RWFromFile - -class SDL_Rect(Structure): - '''Rectangle structure. - - Rectangles must be normalised, i.e., with their width and height - greater than zero. - - :Ivariables: - `x` : int - Top-left x coordinate. - `y` : int - Top-left y coordinate. - `w` : int - Width - `h` : int - Height - - ''' - - _fields_ = [('x', c_short), - ('y', c_short), - ('w', c_ushort), - ('h', c_ushort)] - - def __init__(self, x=0, y=0, w=0, h=0): - self.x = x - self.y = y - self.w = w - self.h = h - - def __repr__(self): - return 'SDL_Rect(x=%d, y=%d, w=%d, h=%d)' % \ - (self.x, self.y, self.w, self.h) - - def __copy__(self): - return SDL_Rect(self.x, self.y, self.w, self.h) - - def __deepcopy__(self, memo): - return SDL_Rect(self.x, self.y, self.w, self.h) - -class SDL_Color(Structure): - '''Structure defining a single color. - - ``SDL_Colour`` is a synonym for ``SDL_Color``. - - :Ivariables: - `r` : int - Red component, in range [0,255] - `g` : int - Green component, in range [0,255] - `b` : int - Blue component, in range [0,255] - - ''' - _fields_ = [('r', c_ubyte), - ('g', c_ubyte), - ('b', c_ubyte), - ('unused', c_ubyte)] - - def __init__(self, r=0, g=0, b=0, unused=0): - self.r = r - self.g = g - self.b = b - - def __repr__(self): - return 'SDL_Color(r=%d, g=%d, b=%d)' % \ - (self.r, self.g, self.b) - - def __copy__(self): - return SDL_Color(self.r, self.g, self.b) - - def __deepcopy__(self, memo): - return SDL_Color(self.r, self.g, self.b) - -SDL_Colour = SDL_Color - -class SDL_Palette(Structure): - '''Color palette array. - - :Ivariables: - `ncolors` : int - Number of colors in the palette - `colors` : `SDL_array` - Array of indexed colors of type `SDL_Color`. - - ''' - _fields_ = [('ncolors', c_int), - ('_colors', POINTER(SDL_Color))] - - def __getattr__(self, name): - if name == 'colors': - return SDL_array(self._colors, self.ncolors, SDL_Color) - raise AttributeError(name) - - -class SDL_PixelFormat(Structure): - '''Read-only surface format structure. - - :Ivariables: - `BitsPerPixel` : int - Number of bits per pixel - `BytesPerPixel` : int - Number of bytes per pixel. This is not necessarily 8 * - BitsPerPixel. - `Rloss` : int - Number of bits lost from an 8-bit red component - `Gloss` : int - Number of bits lost from an 8-bit green component - `Bloss` : int - Number of bits lost from an 8-bit blue component - `Aloss` : int - Number of bits lost from an 8-bit alpha component - `Rshift` : int - Number of bits to shift right red component when packing - `Gshift` : int - Number of bits to shift right green component when packing - `Bshift` : int - Number of bits to shift right blue component when packing - `Ashift` : int - Number of bits to shift right alpha component when packing - `Rmask` : int - 32-bit mask of red component - `Gmask` : int - 32-bit mask of green component - `Bmask` : int - 32-bit mask of blue component - `Amask` : int - 32-bit mask of alpha component - `colorkey` : int - Packed transparent color key, if set. - `alpha` : int - Surface alpha, in range [0, 255] - - ''' - _fields_ = [('_palette', POINTER(SDL_Palette)), - ('BitsPerPixel', c_ubyte), - ('BytesPerPixel', c_ubyte), - ('Rloss', c_ubyte), - ('Gloss', c_ubyte), - ('Bloss', c_ubyte), - ('Aloss', c_ubyte), - ('Rshift', c_ubyte), - ('Gshift', c_ubyte), - ('Bshift', c_ubyte), - ('Ashift', c_ubyte), - ('Rmask', c_uint), - ('Gmask', c_uint), - ('Bmask', c_uint), - ('Amask', c_uint), - ('colorkey', c_uint), - ('alpha', c_ubyte)] - - def __getattr__(self, name): - if name == 'palette': - if self._palette: - return self._palette.contents - return None - raise AttributeError - - def __copy__(self): - f = SDL_PixelFormat() - f._palette = self._palette - f.BitsPerPixel = self.BitsPerPixel - f.BytesPerPixel = self.BytesPerPixel - f.Rloss = self.Rloss - f.Gloss = self.Gloss - f.Bloss = self.Bloss - f.Aloss = self.Aloss - f.Rshift = self.Rshift - f.Gshift = self.Gshift - f.Bshift = self.Bshift - f.Ashift = self.Ashift - f.Rmask = self.Rmask - f.Gmask = self.Gmask - f.Bmask = self.Bmask - f.Amask = self.Amask - f.colorkey = self.colorkey - f.alpha = self.alpha - return f - -class SDL_Surface(Structure): - '''Read-only surface structure. - - :Ivariables: - `format` : `SDL_PixelFormat` - Pixel format used by this surface - `w` : int - Width - `h` : int - Height - `pitch` : int - Number of bytes between consecutive rows of pixel data. Note - that this may be larger than the width. - `pixels` : SDL_array - Buffer of integers of the type given in the pixel format. - Each element of the array corresponds to exactly one pixel - when ``format.BitsPerPixel`` is 8, 16 or 32; otherwise each - element is exactly one byte. Modifying this array has an - immediate effect on the pixel data of the surface. See - `SDL_LockSurface`. - - ''' - _fields_ = [('flags', c_uint), - ('_format', POINTER(SDL_PixelFormat)), - ('w', c_int), - ('h', c_int), - ('pitch', c_short), - ('_pixels', POINTER(c_ubyte)), - ('_offset', c_int), - ('_hwdata', c_void_p), - ('clip_rect', SDL_Rect), - ('_unused1', c_int), - ('_locked', c_int), - ('_map', c_void_p), - ('_format_version', c_int), - ('_refcount', c_int)] - - def __getattr__(self, name): - if name == 'format': - # Dereference format ptr - return self._format.contents - elif name == 'pixels': - # Return SDL_array type for pixels - if not self._pixels: - raise SDL_Exception('Surface needs locking') - bpp = self.format.BitsPerPixel - count = self.pitch / self.format.BytesPerPixel * self.h - if bpp == 1: - sz = c_ubyte - # Can't rely on BytesPerPixel when calculating 1 bit pitch - byte_pitch = self.pitch * 8 / bpp - count = (byte_pitch * self.h + 7) / 8 - elif bpp == 8: - sz = c_ubyte - elif bpp == 16: - sz = c_ushort - elif bpp == 24: - sz = c_ubyte - count = self.pitch * self.h - elif bpp == 32: - sz = c_uint - else: - raise SDL_Exception('Unsupported bytes-per-pixel') - return SDL_array(self._pixels, count, sz) - raise AttributeError(name) - -def SDL_MUSTLOCK(surface): - '''Evaluates to true if the surface needs to be locked before access. - - :Parameters: - - `surface`: SDL_Surface - - :return: True if the surface needs to be locked before access, - otherwise False. - ''' - return surface._offset or \ - ((surface.flags & \ - (SDL_HWSURFACE | \ - SDL_ASYNCBLIT | \ - SDL_RLEACCEL)) != 0) - -SDL_blit = CFUNCTYPE(c_int, POINTER(SDL_Surface), POINTER(SDL_Rect), - POINTER(SDL_Surface), POINTER(SDL_Rect)) - -class SDL_VideoInfo(Structure): - '''Useful for determining the video hardware capabilities. - - :Ivariables: - `hw_available` : bool - True if hardware surfaces can be created - `wm_available` : bool - True if a window manager is available - `blit_hw` : bool - True if hardware to hardware blits are accelerated - `blit_hw_CC` : bool - True if hardware to hardware color-keyed blits are accelerated - `blit_hw_A` : bool - True if hardware to hardware alpha-blended blits are accelerated - `blit_sw` : bool - True if software to hardware blits are accelerated - `blit_sw_CC` : bool - True if software to hardware color-keyed blits are accelerated - `blit_sw_A` : bool - True if software to hardware alpha-blended blits are accelerated - `blit_fill` : bool - True if color fills are accelerated - `video_mem` : int - Total amount of video memory, in kilobytes (unreliable) - `vfmt` : `SDL_PixelFormat` - Pixel format of the video surface - `current_w` : int - Current video width. Available in SDL 1.2.10 and later. - `current_h` : int - Current video height. Available in SDL 1.2.10 and later. - - ''' - _fields_ = [('bitfield', c_uint), - ('video_mem', c_uint), - ('_vfmt', POINTER(SDL_PixelFormat)), - ('_current_w', c_int), - ('_current_h', c_int)] - - def __getattr__(self, name): - '''Retrieve bitfields as bool. All bets are off about whether - this will actually work (ordering of bitfields is compiler - dependent.''' - if name == 'hw_available': - return self.bitfield & 0x1 != 0 - elif name == 'wm_available': - return self.bitfield & 0x2 != 0 - elif name == 'blit_hw': - return self.bitfield & 0x200 != 0 - elif name == 'blit_hw_CC': - return self.bitfield & 0x400 != 0 - elif name == 'blit_hw_A': - return self.bitfield & 0x800 != 0 - elif name == 'blit_sw': - return self.bitfield & 0x1000 != 0 - elif name == 'blit_sw_CC': - return self.bitfield & 0x2000 != 0 - elif name == 'blit_sw_A': - return self.bitfield & 0x4000 != 0 - elif name == 'blit_fill': - return self.bitfield & 0x8000 != 0 - elif name == 'vfmt': # Dereference vfmt pointer. - if self._vfmt: - return self._vfmt.contents - return None - - # current_w and current_h added in SDL 1.2.10 - if name in ('current_w', 'current_h'): - assert_version_compatible(name, (1,2,10)) - return getattr(self, '_%s' % name) - raise AttributeError(name) - - -class SDL_Overlay(Structure): - '''The YUV hardware video overlay. - - :Ivariables: - `format` : int - Overlay pixel layout. One of SDL_YV12_OVERLAY, SDL_IYUV_OVERLAY, - SDL_YUY2_OVERLAY, SDL_UYVY_OVERLAY, SDL_YVYU_OVERLAY. - `w` : int - Width of the overlay. - `h` : int - Height of the overlay. - `planes` : int - Number of planes of pixel data. - `pitches` : list of int - List of pitches for each plane. - `pixels` : list of `SDL_array` - List of pixel buffers, one for each plane. All pixel buffers - provided as byte buffers. - - ''' - _fields_ = [('format', c_uint), - ('w', c_int), - ('h', c_int), - ('planes', c_int), - ('pitches', POINTER(c_short)), - ('_pixels', POINTER(POINTER(c_byte))), - ('hwfuncs', c_void_p), - ('hwdata', c_void_p), - ('flags', c_uint)] - - def __getattr__(self, name): - '''Retrieve bitfields as bool. All bets are off about whether - this will actually work (ordering of bitfields is compiler - dependent.''' - if name == 'hw_overlay': - return self.flags & 0x1 != 0 - - elif name == 'pixels': - if not self._pixels: - raise SDL_Exception('Overlay needs locking') - p = [] - for i in range(self.planes): - sz = self.pitches[i] * self.h - p.append(SDL_array(self._pixels[i], sz, c_byte)) - return p - - -# SDL_VideoInit and SDL_VideoQuit not implemented (internal only, according -# to SDL_video.h). - -_SDL_VideoDriverName = private_function('SDL_VideoDriverName', - arg_types=[c_char_p, c_int], - return_type=c_int) - -def SDL_VideoDriverName(maxlen=1024): - ''' - Returns the name of the video driver. - - :Parameters: - `maxlen` - Maximum length of the returned driver name; defaults to 1024. - - :rtype: string - ''' - buf = create_string_buffer(maxlen) - if _SDL_VideoDriverName(buf, maxlen): - return buf.value - return None - -SDL_GetVideoSurface = function('SDL_GetVideoSurface', - '''Return the current display surface. - - If SDL is doing format conversion on the display surface, this - function returns the publicly visible surface, not the real - video surface. - - :rtype: SDL_Surface - ''', - return_type=POINTER(SDL_Surface), - dereference_return=True) - -SDL_GetVideoInfo = function('SDL_GetVideoInfo', - '''Return information about the video hardware. - - If this is called before `SDL_SetVideoMode`, the ``vfmt`` member - of the returned structure will contain the pixel format of the - "best" video mode. - - :rtype: SDL_VideoInfo - ''', - return_type=POINTER(SDL_VideoInfo), - dereference_return=True) - -SDL_VideoModeOK = function('SDL_VideoModeOK', - '''Check to see if a particular video mode is supported. - - Returns 0 if the requested mode is not supported under any bit - depth, or returns the bits-per-pixel of the closest available - mode with the given width and height. If this bits-per-pixel - is different from the one used when setting the video mode, - `SDL_SetVideoMode` will succeed, but will emulate the requested - bits-per-pixel with a shadow surface. - - The arguments to `SDL_VideoModeOK` are the same ones you would - pass to `SDL_SetVideoMode`. - - :Parameters: - - `width`: int - - `height`: int - - `bpp`: int - - `flags`: int - - :rtype: int - - :return: bits-per-pixel of the closest available mode, or 0 if - the mode is not supported. - ''', - args=['width', 'height', 'bpp', 'flags'], - arg_types=[c_int, c_int, c_int, c_uint], - return_type=c_int) - -_SDL_ListModes = private_function('SDL_ListModes', - arg_types=[POINTER(SDL_PixelFormat), c_uint], - return_type=POINTER(POINTER(SDL_Rect))) - -def SDL_ListModes(format, flags): - '''Return a list of available screen dimensions for the given - format and video flags, sorted largest to smallest. - - Returns -1 if any size can be used, otherwise a list of `SDL_Rect` - (which may be empty). - - If `format` is ``None``, the mode list will be for the format - given by ``SDL_GetVideoInfo().vfmt``. - - :Parameters: - - `format`: `SDL_PixelFormat` - - `flags`: int - - :rtype: list - :return: -1 or list of `SDL_Rect` - ''' - ar = _SDL_ListModes(format, flags) - if not ar: - return [] - if addressof(ar.contents) == -1: - return SDL_ANY_DIMENSION - i = 0 - lst = [] - while ar[i]: - lst.append(ar[i].contents) - i += 1 - return lst - -SDL_SetVideoMode = function('SDL_SetVideoMode', - '''Set up a video mode with the specified width, height and - bits-per-pixel. - - If `bpp` is 0, it is treated as the current display bits-per-pixel. - - The `flags` can be a bitwise-OR of: - - `SDL_ANYFORMAT` - the SDL library will try to set the requested - bits-per-pixel, but will return whatever video pixel format - is available. The default is to emulate the requested pixel - format if it is not natively available. - `SDL_HWSURFACE` - the video surface will be placed in video memory, if - possible, and you may have to call `SDL_LockSurface` in - order to access the raw framebuffer. Otherwise, the video - surface will be created in system memory. - `SDL_ASYNCBLIT` - SDL will try to perform rectangle updates asynchronously, - but you must always lock before accessing pixels. SDL will - wait for updates to complete before returning from the lock. - `SDL_HWPALETTE` - the SDL library will guarantee that the colors set by - `SDL_SetColors` will be the colors you get. Otherwise, in - 8-bit mode, `SDL_SetColors` may not be able to set all of - the colors exactly the way they are requested, and you - should look at the video surface structure to determine the - actual palette. If SDL cannot guarantee that the colors you - request can be set, i.e. if the colormap is shared, then - the video surface may be created under emulation in system - memory, overriding the `SDL_HWSURFACE` flag. - `SDL_FULLSCREEN` - the SDL library will try to set a fullscreen video mode. - The default is to create a windowed mode if the current - graphics system has a window manager. If the SDL library is - able to set a fullscreen video mode, this flag will be set - in the surface that is returned. - `SDL_DOUBLEBUF` - the SDL library will try to set up two surfaces in video - memory and swap between them when you call `SDL_Flip`. This - is usually slower than the normal single-buffering scheme, - but prevents "tearing" artifacts caused by modifying video - memory while the monitor is refreshing. It should only be - used by applications that redraw the entire screen on every - update. - `SDL_RESIZABLE` - the SDL library will allow the window manager, if any, to - resize the window at runtime. When this occurs, SDL will - send a `SDL_VIDEORESIZE` event to you application, and you - must respond to the event by re-calling `SDL_SetVideoMode` - with the requested size (or another size that suits the - application). - `SDL_NOFRAME` - the SDL library will create a window without any title bar - or frame decoration. Fullscreen video modes have this flag - set automatically. - - This function returns the video framebuffer surface, or ``None`` if - it fails. - - If you rely on functionality provided by certain video flags, check - the flags of the returned surface to make sure that functionality is - available. SDL will fall back to reduced functionality if the exact - flags you wanted are not available. - - :Parameters: - - `width`: int - - `height`: int - - `bpp`: int - - `flags`: int - - :rtype: `SDL_Surface` - ''', - args=['width', 'height', 'bpp', 'flags'], - arg_types=[c_int, c_int, c_int, c_uint], - return_type=POINTER(SDL_Surface), - dereference_return=True, - require_return=True) - -_SDL_UpdateRects = private_function('SDL_UpdateRects', - arg_types=[POINTER(SDL_Surface), c_int, POINTER(SDL_Rect)], - return_type=None) - -def SDL_UpdateRects(screen, rects): - '''Make sure that the given list of rectangles is updated on the - given screen. - - This function should not be called while `screen` is locked. - - :Parameters: - - `screen`: `SDL_Surface` - - `rects`: list of `SDL_Rect` - ''' - ref, ar = to_ctypes(rects, len(rects), SDL_Rect) - _SDL_UpdateRects(screen, len(rects), ar) - -SDL_UpdateRect = function('SDL_UpdateRect', - '''Make sure that the given rectangle is updated on the given - screen. - - If `x`, `y`, `w` and `h` are all 0, `SDL_UpdateRect` will update the - entire screen. - - This function should not be called while `screen` is locked. - - :Parameters: - - `screen`: `SDL_Surface` - - `x`: int - - `y`: int - - `w`: int - - `h`: int - ''', - args=['screen', 'x', 'y', 'w', 'h'], - arg_types=[POINTER(SDL_Surface), c_int, c_int, c_uint, c_uint], - return_type=None) - -SDL_Flip = function('SDL_Flip', - '''Flip the front and back buffers. - - On hardware that supports double-buffering, this function sets up a - flip and returns. The hardware will wait for vertical retrace, and - then swap video buffers before the next video surface blit or lock - will return. - - On hardware that doesn not support double-buffering, this is - equivalent to calling ``SDL_UpdateRect(screen, 0, 0, 0, 0)``. - - The `SDL_DOUBLEBUF` flag must have been passed to `SDL_SetVideoMode` - when setting the video mode for this function to perform hardware - flipping. - - :param `screen`: `SDL_Surface` - ''', - args=['screen'], - arg_types=[POINTER(SDL_Surface)], - return_type=c_int, - success_return=0) - -SDL_SetGamma = function('SDL_SetGamma', - '''Set the gamma correction for each of the color channels. - - The gamma values range (approximately) between 0.1 and 10.0 - - If this function isn't supported directly by the hardware, it will - be emulated using gamma ramps, if available. - - :Parameters: - - `red`: float - - `green`: float - - `blue`: float - - ''', - args=['red', 'green', 'blue'], - arg_types=[c_float, c_float, c_float], - return_type=c_int, - success_return=0) - -_SDL_SetGammaRamp = private_function('SDL_SetGammaRamp', - arg_types=[POINTER(c_ushort), POINTER(c_ushort), POINTER(c_ushort)], - return_type=c_int) - -def SDL_SetGammaRamp(red, green, blue): - '''Set the gamma translation table for the red, green and blue - channels of the video hardware. - - Each table is a list of 256 ints in the range [0, 2**16), - representing a mapping between the input and output for that - channel. The input is the index into the array, and the output is - the 16-bit gamma value at that index, scaled to the output color - precision. - - You may pass ``None`` for any of the channels to leave it unchanged. - - :Parameters: - `red` : SDL_array - For each channel you may pass either None (to leave the channel - unchanged), an SDL_array or ctypes array of length 256, or - any other sequence of length 256. - `green` : SDL_array - As above - `blue` : SDL_array - As above - - ''' - rar = gar = bar = None - if red: - rref, rar = to_ctypes(red, 256, c_ushort) - if green: - gref, gar = to_ctypes(green, 256, c_ushort) - if blue: - bref, bar = to_ctypes(blue, 256, c_ushort) - result = _SDL_SetGammaRamp(rar, gar, bar) - if result != 0: - raise SDL_Exception(SDL_GetError()) - -_SDL_GetGammaRamp = private_function('SDL_GetGammaRamp', - arg_types=[POINTER(c_ushort), POINTER(c_ushort), POINTER(c_ushort)], - return_type=c_int) - -def SDL_GetGammaRamp(): - '''Retrieve the current values of the gamma translation tables. - - :rtype: (SDL_array, SDL_array, SDL_array) - :return: a tuple (``red``, ``green``, ``blue``) where each element - is either None (if the display driver doesn't support gamma - translation) or an SDL_array of 256 ints in the range [0, 2**16). - ''' - rar = SDL_array(None, 256, c_ushort) - gar = SDL_array(None, 256, c_ushort) - bar = SDL_array(None, 256, c_ushort) - if _SDL_GetGammaRamp(rar.as_ctypes(), gar.as_ctypes(), bar.as_ctypes()) == 0: - return rar, gar, bar - return None, None, None - -_SDL_SetColors = private_function('SDL_SetColors', - arg_types=[POINTER(SDL_Surface), POINTER(SDL_Color), c_int, c_int], - return_type=c_int) - -def SDL_SetColors(surface, colors, firstcolor): - '''Sets a portion of the colormap for the given 8-bit surface. - - If `surface` is not a palettized surface, this function does - nothing, returning 0. If all of the colors were set as passed to - `SDL_SetColors`, it will return 1. If not all the color entries - were set exactly as given, it will return 0, and you should look at - the surface palette to determine the actual color palette. - - When `surface` is the surface associated with the current display, the - display colormap will be updated with the requested colors. If - `SDL_HWPALETTE` was set in `SDL_SetVideoMode` flags, `SDL_SetColors` - will always return 1, and the palette is guaranteed to be set the way - you desire, even if the window colormap has to be warped or run under - emulation. - - :Parameters: - - `surface`: `SDL_Surface` - - `colors`: sequence or SDL_array of `SDL_Color` - - `firstcolor`: int; the first color index to set. - - :rtype: int - :return: 1 if all colors were set as passed, otherwise 0. - ''' - ref, ar = to_ctypes(colors, len(colors), SDL_Color) - return _SDL_SetColors(surface, ar, firstcolor, len(colors)) - -_SDL_SetPalette = private_function('SDL_SetPalette', - arg_types=[POINTER(SDL_Surface), c_int, POINTER(SDL_Color), c_int, c_int], - return_type=c_int) - -def SDL_SetPalette(surface, flags, colors, firstcolor): - '''Sets a portion of the colormap for a given 8-bit surface. - - `flags` is one or both of: - `SDL_LOGPAL` - set logical palette, which controls how blits are mapped - to/from the surface - `SDL_PHYSPAL` - set physical palette, which controls how pixels look on the - screen. - - Only screens have physical palettes. Separate change of - physical/logical palettes is only possible if the screen has - `SDL_HWPALETTE` set. - - `SDL_SetColors` is equivalent to calling this function with - ``flags = (SDL_LOGPAL | SDL_PHYSPAL)``. - - :Parameters: - - `surface`: `SDL_Surface` - - `flags`: int - - `colors`: sequence or SDL_array of `SDL_Color` - - `firstcolor`: int; the first color index to set. - ''' - ref, ar = to_ctypes(colors, len(colors), SDL_Color) - result = _SDL_SetPalette(surface, flags, ar, firstcolor, len(colors)) - if result != 1: - raise SDL_Exception(SDL_GetError()) - -SDL_MapRGB = function('SDL_MapRGB', - '''Map an RGB triple to an opaque pixel value for a given pixel - format. - - :Parameters: - - `format`: `SDL_PixelFormat` - - `r`: int in the range [0, 255] - - `g`: int in the range [0, 255] - - `b`: int in the range [0, 255] - - :rtype: int - :return: the opaque pixel value - ''', - args=['format', 'r', 'g', 'b'], - arg_types=[POINTER(SDL_PixelFormat), c_ubyte, c_ubyte, c_ubyte], - return_type=c_uint) - -SDL_MapRGBA = function('SDL_MapRGBA', - '''Map an RGBA quadruple to an opaque pixel value for a given pixel - format. - - :Parameters: - - `format`: `SDL_PixelFormat` - - `r`: int in the range [0, 255] - - `g`: int in the range [0, 255] - - `b`: int in the range [0, 255] - - `a`: int in the range [0, 255] - - :rtype: int - :return: the opaque pixel value - ''', - args=['format', 'r', 'g', 'b', 'a'], - arg_types=[POINTER(SDL_PixelFormat), c_ubyte, c_ubyte, c_ubyte, c_ubyte], - return_type=c_uint) - -_SDL_GetRGB = private_function('SDL_GetRGB', - arg_types=[c_uint, POINTER(SDL_PixelFormat), - POINTER(c_ubyte), POINTER(c_ubyte), POINTER(c_ubyte)], - return_type=None) - -def SDL_GetRGB(pixel, fmt): - '''Map a pixel value into the RGB components for a given pixel - format. - - :Parameters: - - `pixel`: int - - `fmt`: `SDL_PixelFormat` - - :rtype: (int, int, int) - :return: tuple (``r``, ``g``, ``b``) where each element is an int - in the range [0, 255] - ''' - r, g, b = c_ubyte(), c_ubyte(), c_ubyte() - _SDL_GetRGB(pixel, fmt, byref(r), byref(g), byref(b)) - return r.value, g.value, b.value - -_SDL_GetRGBA = private_function('SDL_GetRGBA', - arg_types=[c_uint, POINTER(SDL_PixelFormat), - POINTER(c_ubyte), POINTER(c_ubyte), - POINTER(c_ubyte), POINTER(c_ubyte)], - return_type=None) - -def SDL_GetRGBA(pixel, fmt): - '''Map a pixel value into the RGBA components for a given pixel - format. - - :Parameters: - - `pixel`: int - - `fmt`: `SDL_PixelFormat` - - :rtype: (int, int, int, int) - :return: tuple (``r``, ``g``, ``b``, ``a``) where each element is an - int in the range [0, 255] - ''' - r, g, b, a = c_ubyte(), c_ubyte(), c_ubyte(), c_ubyte() - _SDL_GetRGBA(pixel, fmt, byref(r), byref(g), byref(b), byref(a)) - return r.value, g.value, b.value, a.value - -SDL_CreateRGBSurface = function('SDL_CreateRGBSurface', - '''Allocate an RGB surface. - - Must be called after `SDL_SetVideoMode`. If the depth is 4 or 8 - bits, an empty palette is allocated for the surface. If the depth - is greater than 8 bits, the pixel format is set using the flags - ``[RGB]mask``. - - The `flags` tell what kind of surface to create - - `SDL_SWSURFACE` - the surface should be created in system memory. - `SDL_HWSURFACE` - the surface should be created in video memory, with the same - format as the display surface. This is useful for surfaces - that will not change much, to take advantage of hardware - acceleration when being blitted to the display surface. - `SDL_ASYNCBLIT` - SDL will try to perform asynchronous blits with this - surface, but you must always lock it before accessing the - pixels. SDL will wait for current blits to finish before - returning from the lock. - `SDL_SRCCOLORKEY` - the surface will be used for colorkey blits. If the - hardware supports acceleration of colorkey blits between two - surfaces in video memory, SDL will try to place the surface - in video memory. If this isn't possible or if there is no - hardware acceleration available, the surface will be placed - in system memory. - `SDL_SRCALPHA` - the surface will be used for alpha blits and if the hardware - supports hardware acceleration of alpha blits between two - surfaces in video memory, to place the surface in video - memory if possible, otherwise it will be placed in system - memory. - - If the surface is created in video memory, blits will be _much_ - faster, but the surface format must be identical to the video - surface format, and the only way to access the pixels member of the - surface is to use the `SDL_LockSurface` and `SDL_UnlockSurface` - calls. - - If the requested surface actually resides in video memory, - `SDL_HWSURFACE` will be set in the flags member of the returned - surface. If for some reason the surface could not be placed in - video memory, it will not have the `SDL_HWSURFACE` flag set, and - will be created in system memory instead. - - :Parameters: - - `flags`: int - - `width`: int - - `height`: int - - `depth`: int - - `Rmask`: int - - `Gmask`: int - - `Bmask`: int - - `Amask`: int - - :rtype: `SDL_Surface` - ''', - args=['flags', 'width', 'height', 'depth', 'Rmask', 'Gmask', - 'Bmask', 'Amask'], - arg_types=[c_uint, c_int, c_int, c_int, c_uint, c_uint, c_uint, c_uint], - return_type=POINTER(SDL_Surface), - dereference_return=True, - require_return=True) - -_SDL_CreateRGBSurfaceFrom = \ - private_function('SDL_CreateRGBSurfaceFrom', - arg_types=[POINTER(c_ubyte), c_int, c_int, c_int, - c_uint, c_uint, c_uint, c_uint], - return_type=POINTER(SDL_Surface), - dereference_return=True, - require_return=True) - -def SDL_CreateRGBSurfaceFrom(pixels, width, height, depth, pitch, - Rmask, Gmask, Bmask, Amask): - '''Allocate and initialise an RGB surface. - - Must be called after `SDL_SetVideoMode`. If the depth is 4 or 8 - bits, an empty palette is allocated for the surface. If the depth - is greater than 8 bits, the pixel format is set using the flags - ``[RGB]mask``. - - `pixels` may be any sequence of integers of size `depth`, or a - sequence of bytes, an SDL_array or a numpy array. The type - of data passed will be detected based on the values of `width`, - `height` and `depth`. If `depth` is less than 8 bits, you must - pass the data as bytes. - - :Parameters: - - `pixels`: sequence or SDL_array - - `width`: int - - `height`: int - - `depth`: int - - `pitch`: int - - `Rmask`: int - - `Gmask`: int - - `Bmask`: int - - `Amask`: int - - :rtype: `SDL_Surface` - ''' - if hasattr(pixels, 'contents'): - # accept ctypes pointer without modification - ref, ar = None, pixels - else: - len_pixels = len(pixels) - if len(pixels) == pitch * 8 / depth * height: - # pixel array? - if depth == 8: - ref, ar = to_ctypes(pixels, len(pixels), c_ubyte) - elif depth == 16: - ref, ar = to_ctypes(pixels, len(pixels), c_ushort) - elif depth == 32: - ref, ar = to_ctypes(pixels, len(pixels), c_uint) - elif len(pixels) == pitch * height: - # byte array - ref, ar = to_ctypes(pixels, len(pixels), c_ubyte) - else: - raise TypeError('Length of pixels does not match given dimensions.') - - surface = _SDL_CreateRGBSurfaceFrom(cast(ar, POINTER(c_ubyte)), - width, height, depth, pitch, Rmask, Gmask, Bmask, Amask) - surface._buffer_ref = ref - return surface - -SDL_FreeSurface = function('SDL_FreeSurface', - '''Free an RGB Surface. - - :Parameters: - - `surface`: `SDL_Surface` - ''', - args=['surface'], - arg_types=[POINTER(SDL_Surface)], - return_type=None) - -SDL_LockSurface = function('SDL_LockSurface', - '''Set up a surface for directly accessing the pixels. - - Between calls to `SDL_LockSurface`/`SDL_UnlockSurface`, you can write - to and read from ``surface.pixels``, using the pixel format stored in - ``surface.format``. Once you are done accessing the surface, you should - use `SDL_UnlockSurface` to release it. - - Not all surfaces require locking. If `SDL_MUSTLOCK` evaluates - to 0, then you can read and write to the surface at any time, and the - pixel format of the surface will not change. In particular, if the - `SDL_HWSURFACE` flag is not given when calling `SDL_SetVideoMode`, you - will not need to lock the display surface before accessing it. - - No operating system or library calls should be made between lock/unlock - pairs, as critical system locks may be held during this time. - - :Parameters: - - `surface`: `SDL_Surface` - ''', - args=['surface'], - arg_types=[POINTER(SDL_Surface)], - return_type=c_int, - success_return=0) - -SDL_UnlockSurface = function('SDL_UnlockSurface', - '''Unlock a surface locked with `SDL_LockSurface`. - - :Parameters: - - `surface`: `SDL_Surface` - ''', - args=['surface'], - arg_types=[POINTER(SDL_Surface)], - return_type=None) - -SDL_LoadBMP_RW = function('SDL_LoadBMP_RW', - '''Load a surface from a seekable SDL data source (memory or file). - - If `freesrc` is non-zero, the source will be closed after being read. - The new surface which is returned should be freed with - `SDL_FreeSurface`. - - :Parameters: - - `src`: `SDL_RWops` - - `freesrc`: int - - :rtype: `SDL_Surface` - ''', - args=['src', 'freesrc'], - arg_types=[POINTER(SDL_RWops), c_int], - return_type=POINTER(SDL_Surface), - dereference_return=True, - require_return=True) - -def SDL_LoadBMP(file): - '''Load a surface from a file. - - Convenience function equivalent to - ``SDL_LoadBMP_RW(SDL_RWFromFile(file, 'rb'), 1)``. - - :Parameters: - - `file`: string, the location of the bitmap file. - - :rtype: `SDL_Surface` - ''' - return SDL_LoadBMP_RW(SDL_RWFromFile(file, 'rb'), 1) - -SDL_SaveBMP_RW = function('SDL_SaveBMP_RW', - '''Save a surface to a seekable SDL data source (memory or file). - - If `freedst` is non-zero, the destination will be closed after being - written. - - :Parameters: - - `surface`: `SDL_Surface` - - `dst`: `SDL_RWops` - - `freesrc`: int - ''', - args=['surface', 'dst', 'freedst'], - arg_types=[POINTER(SDL_Surface), POINTER(SDL_RWops), c_int], - return_type=c_int, - success_return=0) - -def SDL_SaveBMP(surface, file): - '''Save a surface to a file. - - Convenience function equivalent to - ``SDL_SaveBMP_RW(surface, SDL_RWFromFile(file, 'wb'), 1)`` - - :Parameters: - - `surface`: `SDL_Surface` - - `dst`: `SDL_RWops` - ''' - return SDL_SaveBMP_RW(surface, SDL_RWFromFile(file, 'wb'), 1) - -SDL_SetColorKey = function('SDL_SetColorKey', - '''Set the color key (transparent pixel) in a blittable surface. - - If `flag` is `SDL_SRCCOLORKEY` (optionally OR'd with `SDL_RLEACCEL`), - `key` will be the transparent pixel in the source image of a blit. - `SDL_RLEACCEL` requests RLE acceleration for the surface if present, - and removes RLE acceleration if absent. If `flag` is 0, this - function clears any current color key. - - :Parameters: - - `surface`: `SDL_Surface` - - `flag`: int - - `key`: int, see `SDL_MapRGB` - ''', - args=['surface', 'flag', 'key'], - arg_types=[POINTER(SDL_Surface), c_uint, c_uint], - return_type=c_int, - success_return=0) - -SDL_SetAlpha = function('SDL_SetAlpha', - '''Set the alpha value for the entire surface, as opposed to using - the alpha component of each pixel. - - This value measures the range of transparency of the surface, 0 - being completely transparent to 255 being completely opaque. An - `alpha` value of 255 causes blits to be opaque, the source pixels - copied to the destination (the default). Note that per-surface alpha - can be combined with colorkey transparency. - - If `flag` is 0, alpha blending is disabled for the surface. If - `flag` is `SDL_SRCALPHA`, alpha blending is enabled for the surface. - OR'ing the flag with `SDL_RLEACCEL` requests RLE acceleration for - the surface; if `SDL_RLEACCEL` is not specified, the RLE accel will - be removed. - - The `alpha` parameter is ignored for surfaces that have an alpha - channel. - - :Parameters: - - `surface`: `SDL_Surface` - - `flag`: int - - `alpha`: int - - :return: int; undocumented. (FIXME) - ''', - args=['surface', 'flag', 'alpha'], - arg_types=[POINTER(SDL_Surface), c_uint, c_uint], - return_type=c_int) - -SDL_SetClipRect = function('SDL_SetClipRect', - '''Set the clipping rectangle for the destination surface in a blit. - - If the clip rectangle is None, clipping will be disabled. - If the clip rectangle doesn't intersect the surface, the function will - return False and blits will be completely clipped. Otherwise the - function returns True and blits to the surface will be clipped to - the intersection of the surface area and the clipping rectangle. - - Note that blits are automatically clipped to the edges of the source - and destination surfaces. - - :Parameters: - - `surface`: `SDL_Surface` - - `rect`: `SDL_Rect` or None - - :rtype: int - :return: non-zero if blitting will not be entirely clipped, otherwise - zero. - ''', - args=['surface', 'rect'], - arg_types=[POINTER(SDL_Surface), POINTER(SDL_Rect)], - return_type=c_int) - -_SDL_GetClipRect = private_function('SDL_GetClipRect', - arg_types=[POINTER(SDL_Surface), POINTER(SDL_Rect)], - return_type=None) - -def SDL_GetClipRect(surface): - '''Get the clipping rectangle for the destination surface in a blit. - - :see: `SDL_SetClipRect` - - :Parameters: - - `surface`: `SDL_Surface` - - :rtype: `SDL_Rect` - ''' - rect = SDL_Rect() - _SDL_GetClipRect(surface, byref(rect)) - return rect - -SDL_ConvertSurface = function('SDL_ConvertSurface', - '''Create a new surface of the specified format, then copy and - map the given surface to it so the blit of the converted surface - will be as fast as possible. - - The `flags` parameter is passed to `SDL_CreateRGBSurface` and has those - semantics. You can also pass `SDL_RLEACCEL` in the flags parameter and - SDL will try to RLE accelerate colorkey and alpha blits in the resulting - surface. - - This function is used internally by `SDL_DisplayFormat`. - - :Parameters: - - `src`: `SDL_Surface` - - `fmt`: `SDL_PixelFormat` - - `flags`: int - - :rtype: `SDL_Surface` - ''', - args=['src', 'fmt', 'flags'], - arg_types=[POINTER(SDL_Surface), POINTER(SDL_PixelFormat), c_uint], - return_type=POINTER(SDL_Surface), - dereference_return=True, - require_return=True) - -SDL_UpperBlit = function('SDL_UpperBlit', - '''Perform a fast blit from the source surface to the destination - surface. - - ``SDL_BlitSurface`` is a synonym for ``SDL_UpperBlit``. - - This function assumes that the source and destination rectangles are - the same size. If either `srcrect` or `dstrect` are None, the entire - surface (`src` or `dst`) is copied. The final blit rectangles are saved - in `srcrect` and `dstrect` after all clipping is performed. - - The blit function should not be called on a locked surface. - - The blit semantics for surfaces with and without alpha and colorkey - are defined as follows: - - RGBA to RGB - `SDL_SRCALPHA` set: - - alpha-blend (using alpha-channel) - - `SDL_SRCCOLORKEY` ignored - `SDL_SRCALPHA` not set: - - copy RGB - - if `SDL_SRCCOLORKEY` set, only copy the pixels - matching the RGB value of the source color key, - ignoring alpha in the comparison. - RGB to RGBA: - `SDL_SRCALPHA` set: - - alpha-blend (using the source per-surface alpha value) - - set destination alpha to opaque - `SDL_SRCALPHA` not set: - - copy RGB, set destination alpha to source per-surface - alpha value. - `SDL_SRCCOLORKEY` set: - - only copy pixels matching the source color key - RGBA to RGBA: - `SDL_SRCALPHA` set: - - alpha-blend (using the source alpha channel) the RGB - values; leave destination alpha untouched. - - `SDL_SRCCOLORKEY` ignored. - `SDL_SRCALPHA` not set: - - copy all of RGBA to the destination - - if `SDL_SRCCOLORKEY` set, only copy the pixels - matching the RGB value of the source color key, - ignoring alpha in the comparison. - RGB to RGB: - `SDL_SRCHALPHA` set: - - alpha-blend (using the source per-surface alpha value) - `SDL_SRCALPHA` not set: - - copy RGB - `SDL_SRCCOLORKEY` set: - - only copy the pixels matching the source color key. - - If either of the surfaces were in video memory, and the blit returns - -2, the video memory was lost, so it should be reloaded with artwork - and reblitted:: - - while SDL_BlitSurface(image, imgrect, screen, dstrect) == -2: - while SDL_LockSurface(image) < 0: - sleep(10) - # Write image pixels to image.pixels - SDL_UnlockSurface(image) - - This happens under DirectX 5.0 when the system switches away from - your fullscreen application. The lock will also fail until you have - access to the video memory again. - - :Parameters: - - `src`: `SDL_Surface` - - `srcrect`: `SDL_Rect` - - `dst`: `SDL_Surface` - - `dstrect`: `SDL_Rect` - - :rtype: int - :return: 0 if successful, or -2 if there was an error and video - memory was lost. (any other error will raise an exception) - ''', - args=['src', 'srcrect', 'dst', 'dstrect'], - arg_types=[POINTER(SDL_Surface), POINTER(SDL_Rect), - POINTER(SDL_Surface), POINTER(SDL_Rect)], - return_type=c_int, - error_return=-1) - -SDL_BlitSurface = function('SDL_UpperBlit', - '''Perform a fast blit from the source surface to the destination - surface. - - This function is a synonym for `SDL_UpperBlit`. - - :rtype: int - ''', - args=['src', 'srcrect', 'dst', 'dstrect'], - arg_types=[POINTER(SDL_Surface), POINTER(SDL_Rect), - POINTER(SDL_Surface), POINTER(SDL_Rect)], - return_type=c_int, - error_return=-1) - -SDL_LowerBlit = function('SDL_LowerBlit', - '''Low-level fast blit. - - This is a semi-private blit function that does not perform - rectangle validation or clipping. See `SDL_UpperBlit` for the - public function. - - :rtype: int - ''', - args=['src', 'srcrect', 'dst', 'dstrect'], - arg_types=[POINTER(SDL_Surface), POINTER(SDL_Rect), - POINTER(SDL_Surface), POINTER(SDL_Rect)], - return_type=c_int, - error_return=-1) - -SDL_FillRect = function('SDL_FillRect', - '''Perform a fast fill of the given rectangle with `color`. - - The given rectangle is clipped to the destination surface clip area - and the final fill rectangle is saved in the passed in rectangle. - If `dstrect` is None, the whole surface will be filled with `color` - The color should be a pixel of the format used by the surface, and - can be generated by the `SDL_MapRGB` function. - - :Parameters: - - `dst`: `SDL_Surface` - - `dstrect`: `SDL_Rect` - - `color`: int - ''', - args=['dst', 'dstrect', 'color'], - arg_types=[POINTER(SDL_Surface), POINTER(SDL_Rect), c_uint], - return_type=c_int, - success_return=0) - -SDL_DisplayFormat = function('SDL_DisplayFormat', - '''Copy a surface to the pixel format and colors of the display - buffer. - - This function makes a copy of a surface suitable for fast blitting - onto the display surface. It calls `SDL_ConvertSurface`. - - If you want to take advantage of hardware colorkey or alpha blit - acceleration, you should set the colorkey and alpha value before - calling this function. - - :Parameters: - - `surface`: `SDL_Surface` - - :rtype: `SDL_Surface` - ''', - args=['surface'], - arg_types=[POINTER(SDL_Surface)], - return_type=POINTER(SDL_Surface), - dereference_return=True, - require_return=True) - -SDL_DisplayFormatAlpha = function('SDL_DisplayFormatAlpha', - '''Copy a surface to the pixel format and colors of the display - buffer. - - This function makes a copy of a surface suitable for fast alpha - blitting onto the display surface. The new surface will always have - an alpha channel. - - If you want to take advantage of hardware colorkey or alpha blit - acceleration, you should set the colorkey and alpha value before - calling this function. - - :Parameters: - - `surface`: `SDL_Surface` - - :rtype: `SDL_Surface` - ''', - args=['surface'], - arg_types=[POINTER(SDL_Surface)], - return_type=POINTER(SDL_Surface), - dereference_return=True, - require_return=True) - -SDL_CreateYUVOverlay = function('SDL_CreateYUVOverlay', - '''Create a video output overlay. - - Calling the returned surface an overlay is something of a misnomer - because the contents of the display surface underneath the area - where the ovelay is shown is undefined - it may be overwritten with - the converted YUV data. - - The most common video overlay formats are: - - `SDL_YV12_OVERLAY` - Planar mode: Y + V + U (3 planes) - `SDL_IYUV_OVERLAY` - Planar mode: Y + U + V (3 planes) - `SDL_YUY2_OVERLAY` - Packed moed: Y0 + U0 + Y1 + V0 (1 plane) - `SDL_UYVY_OVERLAY` - Packed moed: U0 + Y0 + V0 + Y1 (1 plane) - `SDL_YVYU_OVERLAY` - Packed moed: Y0 + V0 + Y1 + U0 (1 plane) - - For an explanation of these pixel formats, see - http://www.webartz.com/fourcc/indexyuv.htm - - For more information on the relationship between color spaces, see: - http://www.neuro.sfc.keio.ac.jp/~aly/polygon/info/color-space-faq.html - - :Parameters: - - `width`: int - - `height`: int - - `format`: int - - `display`: `SDL_Surface` - - :rtype: `SDL_Overlay` - ''', - args=['width', 'height', 'format', 'display'], - arg_types=[c_int, c_int, c_uint, POINTER(SDL_Surface)], - return_type=POINTER(SDL_Overlay), - dereference_return=True, - require_return=True) - -SDL_LockYUVOverlay = function('SDL_LockYUVOverlay', - '''Lock an overlay for direct access. - - Unlock the overlay when done with `SDL_UnlockYUVOverlay`. - - :Parameters: - - `overlay`: `SDL_Overlay` - - :rtype: int - :return: undocumented (FIXME) - ''', - args=['overlay'], - arg_types=[POINTER(SDL_Overlay)], - return_type=c_int) - -SDL_UnlockYUVOverlay = function('SDL_UnlockYUVOverlay', - '''Unlock an overlay after locking it with `SDL_LockYUVOverlay`. - - :Parameters: - - `overlay`: `SDL_Overlay` - ''', - args=['overlay'], - arg_types=[POINTER(SDL_Overlay)], - return_type=None) - -SDL_DisplayYUVOverlay = function('SDL_DisplayYUVOverlay', - '''Blit a video overlay to the display surface. - - The contents of the video surface underneath the blit destination - are not defined. The width and height of the destination rectangle - may be different from that of the overlay, but currently only 2x - scaling is supported. - - :Parameters: - - `overlay`: `SDL_Overlay` - - `dstrect`: `SDL_Rect` - - :rtype: int - :return: undocumented (FIXME) - ''', - args=['overlay', 'dstrect'], - arg_types=[POINTER(SDL_Overlay), POINTER(SDL_Rect)], - return_type=c_int) - -SDL_FreeYUVOverlay = function('SDL_FreeYUVOverlay', - '''Free a video overlay. - - :Parameters: - - `overlay`: `SDL_Overlay` - - ''', - args=['overlay'], - arg_types=[POINTER(SDL_Overlay)], - return_type=None) - -# SDL_GL_LoadLibrary, SDL_GL_GetProcAddress not implemented. - -SDL_GL_SetAttribute = function('SDL_GL_SetAttribute', - '''Set an attribute of the OpenGL subsystem before initialization. - - :Parameters: - - `attr`: int - - `value`: int - - :rtype: int - :return: undocumented (FIXME) - ''', - args=['attr', 'value'], - arg_types=[c_uint, c_int], - return_type=c_int) - -_SDL_GL_GetAttribute = private_function('SDL_GL_GetAttribute', - arg_types=[c_int, POINTER(c_int)], - return_type=c_int) - -def SDL_GL_GetAttribute(attr): - '''Get an attribute of the OpenGL subsystem from the windowing - interface, such as glX. - ''' - val = c_int() - _SDL_GL_GetAttribute(attr, byref(val)) - return val.value - -SDL_GL_SwapBuffers = function('SDL_GL_SwapBuffers', - '''Swap the OpenGL buffers, if double-buffering is supported. - ''', - args=[], - arg_types=[], - return_type=None) - -# SDL_GL_UpdateRects, SDL_GL_Lock and SDL_GL_Unlock not implemented (marked -# private in SDL_video.h) - -_SDL_WM_SetCaption = private_function('SDL_WM_SetCaption', - arg_types=[c_char_p, c_char_p], - return_type=None) - -def SDL_WM_SetCaption(title, icon): - '''Set the title and icon text of the display window. - - Unicode strings are also accepted since 1.2.10. - - :Parameters: - - `title`: string - - `icon`: string - ''' - _SDL_WM_SetCaption(title.encode(), icon.encode()) - - -_SDL_WM_GetCaption = private_function('SDL_WM_GetCaption', - arg_types=[POINTER(c_char_p), POINTER(c_char_p)], - return_type=None) - -def SDL_WM_GetCaption(): - '''Get the title and icon text of the display window. - - :rtype: (string, string) - :return: a tuple (title, icon) where each element is a Unicode string - ''' - title, icon = c_char_p(), c_char_p() - _SDL_WM_GetCaption(byref(title), byref(icon)) - - if title.value: - title = title.value.decode() - else: - title = None - - if icon.value: - icon = icon.value.decode() - else: - icon = None - return title, icon - -_SDL_WM_SetIcon = private_function('SDL_WM_SetIcon', - arg_types=[POINTER(SDL_Surface), POINTER(c_ubyte)], - return_type=None) - -def SDL_WM_SetIcon(icon, mask): - '''Set the icon for the display window. - - This function must be called before the first call to `SDL_SetVideoMode`. - It takes an icon surface, and a mask in MSB format. If `mask` is None, - the entire icon surface will be used as the icon. - - :Parameters: - - `icon`: `SDL_Surface` - - `mask`: `SDL_array` or sequence - - ''' - if mask: - ref, mask = \ - to_ctypes(mask, (icon.w * icon.h + 7) / 8, c_ubyte) - _SDL_WM_SetIcon(icon, mask) - -SDL_WM_IconifyWindow = function('SDL_WM_IconifyWindow', - '''Iconify the window. - - If the function succeeds, it generates an `SDL_APPACTIVATE` loss - event. - ''', - args=[], - arg_types=[], - return_type=c_int, - error_return=0) - -SDL_WM_ToggleFullScreen = function('SDL_WM_ToggleFullScreen', - '''Toggle fullscreen mode without changing the contents of the - screen. - - If the display surface does not require locking before accessing - the pixel information, then the memory pointers will not change. - - The next call to `SDL_SetVideoMode` will set the mode fullscreen - attribute based on the flags parameter - if `SDL_FULLSCREEN` is not - set, then the display will be windowed by default where supported. - - This is currently only implemented in the X11 video driver. - - :Parameters: - - `surface`: `SDL_Surface` - ''', - args=['surface'], - arg_types=[POINTER(SDL_Surface)], - return_type=c_int, - error_return=0) - -SDL_WM_GrabInput = function('SDL_WM_GrabInput', - '''Set the grab mode for the mouse and keyboard. - - Grabbing means that the mouse is confined to the application window, - and nearly all keyboard input is passed directly to the application, - and not interpreted by a window manager, if any. - - The behaviour of this function depends on the value of `mode`: - - `SDL_GRAB_QUERY` - Return the current input grab mode. - `SDL_GRAB_OFF` - Turn off grab mode and return the new input grab mode. - `SDL_GRAB_ON` - Turn on grab mode and return the new input grab mode. - - :Parameters: - - `mode`: int - - :rtype: int - :return: the new input grab mode. - ''', - args=['mode'], - arg_types=[c_int], - return_type=c_int) - -# SDL_SoftStretch not implemented (marked private in SDL_video.h) diff --git a/src/m64py/core/core.py b/src/m64py/core/core.py index 4ebc9bd..9afe79c 100644 --- a/src/m64py/core/core.py +++ b/src/m64py/core/core.py @@ -28,7 +28,6 @@ from m64py.frontend.log import log from m64py.utils import version_split from m64py.opts import VERBOSE from m64py.archive import ROM_TYPE -from m64py.platform import LDD_CMD from m64py.core.vidext import vidext def debug_callback(context, level, message): @@ -77,7 +76,6 @@ class Core: self.core_path = "" self.core_name = "Mupen64Plus Core" self.core_version = "Unknown" - self.core_sdl2 = False def get_handle(self): """Retrieves core library handle.""" @@ -133,14 +131,6 @@ class Core: self.core_name = plugin_name self.core_version = plugin_version - if LDD_CMD: - proc = subprocess.Popen( - LDD_CMD % self.core_path, shell=True, - preexec_fn=lambda: signal.signal(signal.SIGPIPE, signal.SIG_DFL)) - proc.communicate() - if proc.returncode == 0: - self.core_sdl2 = True - log.info("attached to library '%s' version %s" % (self.core_name, version_split(self.core_version))) if plugin_cap & M64CAPS_DYNAREC: diff --git a/src/m64py/core/vidext.py b/src/m64py/core/vidext.py index 295f184..3f7b8ce 100644 --- a/src/m64py/core/vidext.py +++ b/src/m64py/core/vidext.py @@ -26,30 +26,20 @@ except ImportError: glimport = False from m64py.core.defs import * -from m64py.opts import SDL2 from m64py.frontend.log import log -if SDL2: - from m64py.SDL2 import SDL_WasInit, SDL_InitSubSystem, SDL_QuitSubSystem, SDL_INIT_VIDEO - from m64py.SDL2 import SDL_GetNumDisplayModes, SDL_DisplayMode, SDL_GetDisplayMode -else: - from m64py.SDL import SDL_WasInit, SDL_InitSubSystem, SDL_QuitSubSystem, SDL_INIT_VIDEO - from m64py.SDL import SDL_ListModes, SDL_FULLSCREEN, SDL_HWSURFACE +from m64py.SDL2 import SDL_WasInit, SDL_InitSubSystem, SDL_QuitSubSystem, SDL_INIT_VIDEO +from m64py.SDL2 import SDL_GetNumDisplayModes, SDL_DisplayMode, SDL_GetDisplayMode try: if not SDL_WasInit(SDL_INIT_VIDEO): SDL_InitSubSystem(SDL_INIT_VIDEO) MODES = [] - if SDL2: - display = SDL_DisplayMode() - for mode in range(SDL_GetNumDisplayModes(0)): - ret = SDL_GetDisplayMode(0, mode, ctypes.byref(display)) - if (display.w, display.h) not in MODES: - MODES.append((display.w, display.h)) - else: - for mode in SDL_ListModes(None, SDL_FULLSCREEN|SDL_HWSURFACE): - if (mode.w, mode.h) not in MODES: - MODES.append((mode.w, mode.h)) + display = SDL_DisplayMode() + for mode in range(SDL_GetNumDisplayModes(0)): + ret = SDL_GetDisplayMode(0, mode, ctypes.byref(display)) + if (display.w, display.h) not in MODES: + MODES.append((display.w, display.h)) if SDL_WasInit(SDL_INIT_VIDEO): SDL_QuitSubSystem(SDL_INIT_VIDEO) except Exception as err: diff --git a/src/m64py/frontend/glwidget.py b/src/m64py/frontend/glwidget.py index 6454c69..eb5e508 100644 --- a/src/m64py/frontend/glwidget.py +++ b/src/m64py/frontend/glwidget.py @@ -18,8 +18,7 @@ from PyQt5.QtCore import Qt, pyqtSignal, QMargins from PyQt5.QtOpenGL import QGLWidget from m64py.core.defs import * -from m64py.opts import SDL2 -from m64py.frontend.keymap import QT2SDL, QT2SDL2 +from m64py.frontend.keymap import QT2SDL2 class GLWidget(QGLWidget): @@ -62,10 +61,7 @@ class GLWidget(QGLWidget): self.worker.save_snapshot() else: try: - if SDL2 or self.worker.core.core_sdl2: - sdl_key = QT2SDL2[key] - else: - sdl_key = QT2SDL[key] + sdl_key = QT2SDL2[key] self.worker.send_sdl_keydown(sdl_key) except KeyError: pass @@ -74,10 +70,7 @@ class GLWidget(QGLWidget): if self.worker.state == M64EMU_RUNNING: key = event.key() try: - if SDL2 or self.worker.core.core_sdl2: - sdl_key = QT2SDL2[key] - else: - sdl_key = QT2SDL[key] + sdl_key = QT2SDL2[key] self.worker.send_sdl_keyup(sdl_key) except KeyError: pass diff --git a/src/m64py/frontend/input.py b/src/m64py/frontend/input.py index 60b55c2..8025b33 100644 --- a/src/m64py/frontend/input.py +++ b/src/m64py/frontend/input.py @@ -19,18 +19,15 @@ import re from PyQt5.QtWidgets import QDialog from PyQt5.QtGui import QKeySequence -from m64py.opts import SDL2 +from m64py.SDL2 import SDL_WasInit, SDL_InitSubSystem, SDL_QuitSubSystem, SDL_INIT_VIDEO +from m64py.SDL2.keyboard import SDL_GetScancodeFromName + from m64py.core.defs import * from m64py.utils import format_tooltip from m64py.frontend.joystick import Joystick -from m64py.frontend.keymap import QT2SDL, SCANCODE2KEYCODE, KEYCODE2SCANCODE +from m64py.frontend.keymap import SCANCODE2KEYCODE, KEYCODE2SCANCODE from m64py.ui.input_ui import Ui_InputDialog -if SDL2: - from m64py.SDL2 import SDL_WasInit, SDL_InitSubSystem, SDL_QuitSubSystem, SDL_INIT_VIDEO -else: - from m64py.SDL import SDL_WasInit, SDL_InitSubSystem, SDL_QuitSubSystem, SDL_INIT_VIDEO - KEY_RE = re.compile("([a-z]+)\((.*)\)") AXIS_RE = re.compile("([a-z]+)\((.*?),(.*?)\)") @@ -414,34 +411,24 @@ class Input(QDialog, Ui_InputDialog): return [0, 0] def get_sdl_key(self, text): - if SDL2 or self.parent.worker.core.core_sdl2: - from m64py.SDL2.keyboard import SDL_GetScancodeFromName - if "Shift" in text or "Ctrl" in text or "Alt" in text: - text = "Left %s" % text - text = text.encode() - return SCANCODE2KEYCODE[SDL_GetScancodeFromName(text)] - else: - try: - key = QKeySequence(text)[0] - return QT2SDL[key] - except KeyError: - return None + if "Shift" in text or "Ctrl" in text or "Alt" in text: + text = "Left %s" % text + text = text.encode() + return SCANCODE2KEYCODE[SDL_GetScancodeFromName(text)] def get_key_name(self, sdl_key): if not sdl_key: return self.tr("Select...") - if SDL2 or self.parent.worker.core.core_sdl2: - from m64py.SDL2.keyboard import SDL_GetScancodeName - try: - text = SDL_GetScancodeName(KEYCODE2SCANCODE[int(sdl_key)]) - except Exception: - return self.tr("Select...") - else: - from m64py.SDL.keyboard import SDL_GetKeyName - text = SDL_GetKeyName(int(sdl_key)).title() + + try: + text = SDL_GetScancodeName(KEYCODE2SCANCODE[int(sdl_key)]) + except Exception: + return self.tr("Select...") + text = text.decode() if not text: return self.tr("Select...") if "Shift" in text or "Ctrl" in text or "Alt" in text: text = text.replace("Left ", "") + return text.title() diff --git a/src/m64py/frontend/joystick.py b/src/m64py/frontend/joystick.py index 36880e2..7165aac 100644 --- a/src/m64py/frontend/joystick.py +++ b/src/m64py/frontend/joystick.py @@ -19,22 +19,15 @@ from PyQt5.QtCore import QObject, pyqtSignal, QTime, QTimer -from m64py.opts import SDL2 from m64py.frontend.log import log import ctypes -if SDL2: - from m64py.SDL2 import SDL_WasInit, SDL_InitSubSystem, SDL_INIT_JOYSTICK - from m64py.SDL2 import SDL_JoystickOpen, SDL_JoystickClose, SDL_NumJoysticks, SDL_JoystickNameForIndex - from m64py.SDL2 import SDL_JoystickNumAxes, SDL_JoystickNumButtons, SDL_JoystickNumHats, SDL_JoystickNumBalls - from m64py.SDL2 import SDL_JoystickGetAxis, SDL_JoystickGetButton, SDL_JoystickGetHat, SDL_JoystickUpdate, SDL_JoystickInstanceID - from m64py.SDL2 import SDL_Event, SDL_PollEvent - from m64py.SDL2 import SDL_JOYAXISMOTION, SDL_JOYHATMOTION, SDL_JOYBALLMOTION, SDL_JOYBUTTONDOWN, SDL_JOYBUTTONUP -else: - from m64py.SDL import SDL_WasInit, SDL_InitSubSystem, SDL_INIT_JOYSTICK - from m64py.SDL import SDL_JoystickOpen, SDL_JoystickClose, SDL_NumJoysticks, SDL_JoystickName - from m64py.SDL import SDL_JoystickNumAxes, SDL_JoystickNumButtons, SDL_JoystickNumHats, SDL_JoystickNumBalls - from m64py.SDL import SDL_JoystickGetAxis, SDL_JoystickGetButton, SDL_JoystickGetHat, SDL_JoystickUpdate +from m64py.SDL2 import SDL_WasInit, SDL_InitSubSystem, SDL_INIT_JOYSTICK +from m64py.SDL2 import SDL_JoystickOpen, SDL_JoystickClose, SDL_NumJoysticks, SDL_JoystickNameForIndex +from m64py.SDL2 import SDL_JoystickNumAxes, SDL_JoystickNumButtons, SDL_JoystickNumHats, SDL_JoystickNumBalls +from m64py.SDL2 import SDL_JoystickGetAxis, SDL_JoystickGetButton, SDL_JoystickGetHat, SDL_JoystickUpdate, SDL_JoystickInstanceID +from m64py.SDL2 import SDL_Event, SDL_PollEvent +from m64py.SDL2 import SDL_JOYAXISMOTION, SDL_JOYHATMOTION, SDL_JOYBALLMOTION, SDL_JOYBUTTONDOWN, SDL_JOYBUTTONUP JOYSTICK_DEADZONE = 0 JOYSTICK_SENSITIVITY = 0 @@ -80,23 +73,16 @@ class Joystick(QObject): if not SDL_WasInit(SDL_INIT_JOYSTICK): if SDL_InitSubSystem(SDL_INIT_JOYSTICK) == 0: for i in range(SDL_NumJoysticks()): - if SDL2: - self.joystick_names.append(SDL_JoystickNameForIndex(i)) - else: - self.joystick_names.append(SDL_JoystickName(i)) + self.joystick_names.append(SDL_JoystickNameForIndex(i)) - if SDL2: - self.joystick_timer.timeout.connect(self.process_events_sdl2) - else: - self.joystick_timer.timeout.connect(self.process_events) + self.joystick_timer.timeout.connect(self.process_events) else: log.info("couldn't initialize SDL joystick support") def clear_events(self): - if SDL2: - event = SDL_Event() - while SDL_PollEvent(ctypes.byref(event)) != 0: - pass + event = SDL_Event() + while SDL_PollEvent(ctypes.byref(event)) != 0: + pass def open(self, stick=0): if self.joystick: @@ -145,61 +131,6 @@ class Joystick(QObject): if not self.joystick: return - SDL_JoystickUpdate() - - for i in range(self.num_axes): - moved = SDL_JoystickGetAxis(self.joystick, i) - if abs(moved) >= self.deadzones[i]: - if moved != self.axes[i]: - delta_moved = abs(self.axes[i] - moved) - if delta_moved >= self.sensitivities[i]: - self.axis_value_changed.emit(i, moved) - self.axes[i] = moved - self.axis_repeat_timers[i].restart() - elif self.auto_repeat and moved != 0: - if self.axis_repeat_timers[i].elapsed() >= self.auto_repeat_delay: - self.axis_value_changed.emit(i, moved) - self.axes[i] = moved - else: - self.axis_repeat_timers[i].restart() - else: - self.axis_value_changed.emit(i, 0) - - for i in range(self.num_buttons): - changed = SDL_JoystickGetButton(self.joystick, i) - if changed != self.buttons[i]: - self.button_value_changed.emit(i, changed) - self.buttons[i] = changed - self.button_repeat_timers[i].restart() - elif self.auto_repeat and changed != 0: - if self.button_repeat_timers[i].elapsed() >= self.auto_repeat_delay: - self.button_value_changed.emit(i, changed) - self.buttons[i] = changed - else: - self.button_repeat_timers[i].restart() - - for i in range(self.num_hats): - changed = SDL_JoystickGetHat(self.joystick, i) - if changed != self.hats[i]: - self.hat_value_changed.emit(i, changed) - self.hats[i] = changed - self.hat_repeat_timers[i].restart() - elif self.auto_repeat and changed != 0: - if self.hat_repeat_timers[i].elapsed() >= self.auto_repeat_delay: - self.hat_value_changed.emit(i, changed) - self.hats[i] = changed - else: - self.hat_repeat_timers[i].restart() - - for i in range(self.num_trackballs): - dx, dy = self.joystick.get_ball(i) - if dx != 0 or dy != 0: - self.trackball_value_changed.emit(i, dx, dy) - - def process_events_sdl2(self): - if not self.joystick: - return - stickid = SDL_JoystickInstanceID(self.joystick) event = SDL_Event() while SDL_PollEvent(ctypes.byref(event)) != 0: diff --git a/src/m64py/opts.py b/src/m64py/opts.py index 612c4d1..fad21b9 100644 --- a/src/m64py/opts.py +++ b/src/m64py/opts.py @@ -21,8 +21,6 @@ from m64py.core.defs import FRONTEND_VERSION usage = 'usage: %prog ' parser = OptionParser(usage=usage, version="M64Py Version %s" % FRONTEND_VERSION) parser.add_option("-v", "--verbose", action="store_true", dest="verbose", help="show verbose output") -parser.add_option("--sdl2", action="store_true", dest="sdl2", help="use libSDL2 library", default=False) opts, args = parser.parse_args() -SDL2 = opts.sdl2 VERBOSE = opts.verbose diff --git a/src/m64py/platform.py b/src/m64py/platform.py index 1bcf7ae..8c31936 100644 --- a/src/m64py/platform.py +++ b/src/m64py/platform.py @@ -18,7 +18,6 @@ import os import sys if sys.platform.startswith("linux"): - LDD_CMD = "ldd %s | grep -q SDL2" DLL_EXT = ".so" DLL_FILTER = ".so.2" DEFAULT_DYNLIB = "libmupen64plus.so.2" @@ -33,7 +32,6 @@ if sys.platform.startswith("linux"): "." ] elif sys.platform.startswith("openbsd"): - LDD_CMD = "ldd %s | grep -q SDL2" DLL_EXT = ".so" DLL_FILTER = "" DEFAULT_DYNLIB = "libmupen64plus.so" @@ -42,7 +40,6 @@ elif sys.platform.startswith("openbsd"): "." ] elif sys.platform == "darwin": - LDD_CMD = "otool -L %s | grep -q SDL2" DLL_EXT = ".dylib" DLL_FILTER = ".dylib" DEFAULT_DYNLIB = "libmupen64plus.dylib" @@ -52,7 +49,6 @@ elif sys.platform == "darwin": "." ] elif sys.platform == "win32": - LDD_CMD = "" DLL_EXT = ".dll" DLL_FILTER = ".dll" DEFAULT_DYNLIB = "mupen64plus.dll" diff --git a/src/m64py/ui/inputbutton.py b/src/m64py/ui/inputbutton.py index e4478df..3949a49 100644 --- a/src/m64py/ui/inputbutton.py +++ b/src/m64py/ui/inputbutton.py @@ -17,8 +17,9 @@ from PyQt5.QtWidgets import QPushButton from PyQt5.QtCore import Qt -from m64py.opts import SDL2 -from m64py.frontend.keymap import QT2SDL, QT2SDL2 +from m64py.SDL2.keyboard import SDL_GetScancodeName + +from m64py.frontend.keymap import QT2SDL2 SDL_HAT_UP = 0x01 SDL_HAT_RIGHT = 0x02 @@ -65,12 +66,7 @@ class InputButton(QPushButton): text = self.tr("Select...") self.setCheckable(False) else: - if SDL2 or self.input.parent.worker.core.core_sdl2: - from m64py.SDL2.keyboard import SDL_GetScancodeName - text = SDL_GetScancodeName(QT2SDL2[key]) - else: - from m64py.SDL.keyboard import SDL_GetKeyName - text = SDL_GetKeyName(QT2SDL[key]).title() + text = SDL_GetScancodeName(QT2SDL2[key]) text = text.decode() text = text.replace("Left ", "")