all repos — mgba @ e6aa23f19cdfe97161f3696fbb3dbc4e3794edd5

mGBA Game Boy Advance Emulator

src/platform/python/mgba/core.py (view raw)

  1# Copyright (c) 2013-2016 Jeffrey Pfau
  2#
  3# This Source Code Form is subject to the terms of the Mozilla Public
  4# License, v. 2.0. If a copy of the MPL was not distributed with this
  5# file, You can obtain one at http://mozilla.org/MPL/2.0/.
  6from ._pylib import ffi, lib  # pylint: disable=no-name-in-module
  7from . import tile
  8from cached_property import cached_property
  9from functools import wraps
 10
 11
 12def find(path):
 13    core = lib.mCoreFind(path.encode('UTF-8'))
 14    if core == ffi.NULL:
 15        return None
 16    return Core._init(core)
 17
 18
 19def find_vf(vfile):
 20    core = lib.mCoreFindVF(vfile.handle)
 21    if core == ffi.NULL:
 22        return None
 23    return Core._init(core)
 24
 25
 26def load_path(path):
 27    core = find(path)
 28    if not core or not core.load_file(path):
 29        return None
 30    return core
 31
 32
 33def load_vf(vfile):
 34    core = find_vf(vfile)
 35    if not core or not core.load_rom(vfile):
 36        return None
 37    return core
 38
 39
 40def needs_reset(func):
 41    @wraps(func)
 42    def wrapper(self, *args, **kwargs):
 43        if not self._was_reset:
 44            raise RuntimeError("Core must be reset first")
 45        return func(self, *args, **kwargs)
 46    return wrapper
 47
 48
 49def protected(func):
 50    @wraps(func)
 51    def wrapper(self, *args, **kwargs):
 52        if self._protected:
 53            raise RuntimeError("Core is protected")
 54        return func(self, *args, **kwargs)
 55    return wrapper
 56
 57
 58@ffi.def_extern()
 59def _mCorePythonCallbacksVideoFrameStarted(user):  # pylint: disable=invalid-name
 60    context = ffi.from_handle(user)
 61    context._video_frame_started()
 62
 63
 64@ffi.def_extern()
 65def _mCorePythonCallbacksVideoFrameEnded(user):  # pylint: disable=invalid-name
 66    context = ffi.from_handle(user)
 67    context._video_frame_ended()
 68
 69
 70@ffi.def_extern()
 71def _mCorePythonCallbacksCoreCrashed(user):  # pylint: disable=invalid-name
 72    context = ffi.from_handle(user)
 73    context._core_crashed()
 74
 75
 76@ffi.def_extern()
 77def _mCorePythonCallbacksSleep(user):  # pylint: disable=invalid-name
 78    context = ffi.from_handle(user)
 79    context._sleep()
 80
 81
 82class CoreCallbacks(object):
 83    def __init__(self):
 84        self._handle = ffi.new_handle(self)
 85        self.video_frame_started = []
 86        self.video_frame_ended = []
 87        self.core_crashed = []
 88        self.sleep = []
 89        self.context = lib.mCorePythonCallbackCreate(self._handle)
 90
 91    def _video_frame_started(self):
 92        for callback in self.video_frame_started:
 93            callback()
 94
 95    def _video_frame_ended(self):
 96        for callback in self.video_frame_ended:
 97            callback()
 98
 99    def _core_crashed(self):
100        for callback in self.core_crashed:
101            callback()
102
103    def _sleep(self):
104        for callback in self.sleep:
105            callback()
106
107
108class Core(object):
109    if hasattr(lib, 'PLATFORM_GBA'):
110        PLATFORM_GBA = lib.PLATFORM_GBA
111
112    if hasattr(lib, 'PLATFORM_GB'):
113        PLATFORM_GB = lib.PLATFORM_GB
114
115    if hasattr(lib, 'PLATFORM_DS'):
116        PLATFORM_GB = lib.PLATFORM_DS
117
118    def __init__(self, native):
119        self._core = native
120        self._was_reset = False
121        self._protected = False
122        self._callbacks = CoreCallbacks()
123        self._core.addCoreCallbacks(self._core, self._callbacks.context)
124        self.config = Config(ffi.addressof(native.config))
125
126    def __del__(self):
127        self._was_reset = False
128
129    @cached_property
130    def graphics_cache(self):
131        if not self._was_reset:
132            raise RuntimeError("Core must be reset first")
133        return tile.CacheSet(self)
134
135    @cached_property
136    def tiles(self):
137        tiles = []
138        native_tiles = ffi.addressof(self.graphics_cache.cache.tiles)
139        for i in range(lib.mTileCacheSetSize(native_tiles)):
140            tiles.append(tile.TileView(lib.mTileCacheSetGetPointer(native_tiles, i)))
141        return tiles
142
143    @cached_property
144    def maps(self):
145        maps = []
146        native_maps = ffi.addressof(self.graphics_cache.cache.maps)
147        for i in range(lib.mMapCacheSetSize(native_maps)):
148            maps.append(tile.MapView(lib.mMapCacheSetGetPointer(native_maps, i)))
149        return maps
150
151    @classmethod
152    def _init(cls, native):
153        core = ffi.gc(native, native.deinit)
154        success = bool(core.init(core))
155        lib.mCoreInitConfig(core, ffi.NULL)
156        if not success:
157            raise RuntimeError("Failed to initialize core")
158        return cls._detect(core)
159
160    @classmethod
161    def _detect(cls, core):
162        if hasattr(cls, 'PLATFORM_GBA') and core.platform(core) == cls.PLATFORM_GBA:
163            from .gba import GBA
164            return GBA(core)
165        if hasattr(cls, 'PLATFORM_GB') and core.platform(core) == cls.PLATFORM_GB:
166            from .gb import GB
167            return GB(core)
168        if hasattr(cls, 'PLATFORM_DS') and core.platform(core) == cls.PLATFORM_DS:
169            from .ds import DS
170            return DS(core)
171        return Core(core)
172
173    def _load(self):
174        self._was_reset = True
175
176    def load_file(self, path):
177        return bool(lib.mCoreLoadFile(self._core, path.encode('UTF-8')))
178
179    def is_rom(self, vfile):
180        return bool(self._core.isROM(vfile.handle))
181
182    def load_rom(self, vfile):
183        return bool(self._core.loadROM(self._core, vfile.handle))
184
185    def load_bios(self, vfile, id=0):
186        return bool(self._core.loadBIOS(self._core, vfile.handle, id))
187
188    def load_save(self, vfile):
189        return bool(self._core.loadSave(self._core, vfile.handle))
190
191    def load_temporary_save(self, vfile):
192        return bool(self._core.loadTemporarySave(self._core, vfile.handle))
193
194    def load_patch(self, vfile):
195        return bool(self._core.loadPatch(self._core, vfile.handle))
196
197    def load_config(self, config):
198        lib.mCoreLoadForeignConfig(self._core, config._native)
199
200    def autoload_save(self):
201        return bool(lib.mCoreAutoloadSave(self._core))
202
203    def autoload_patch(self):
204        return bool(lib.mCoreAutoloadPatch(self._core))
205
206    def autoload_cheats(self):
207        return bool(lib.mCoreAutoloadCheats(self._core))
208
209    def platform(self):
210        return self._core.platform(self._core)
211
212    def desired_video_dimensions(self):
213        width = ffi.new("unsigned*")
214        height = ffi.new("unsigned*")
215        self._core.desiredVideoDimensions(self._core, width, height)
216        return width[0], height[0]
217
218    def set_video_buffer(self, image):
219        self._core.setVideoBuffer(self._core, image.buffer, image.stride)
220
221    def reset(self):
222        self._core.reset(self._core)
223        self._load()
224
225    @needs_reset
226    @protected
227    def run_frame(self):
228        self._core.runFrame(self._core)
229
230    @needs_reset
231    @protected
232    def run_loop(self):
233        self._core.runLoop(self._core)
234
235    @needs_reset
236    def step(self):
237        self._core.step(self._core)
238
239    @needs_reset
240    @protected
241    def load_raw_state(self, state):
242        if len(state) < self._core.stateSize(self._core):
243            return False
244        return self._core.loadState(self._core, state)
245
246    @needs_reset
247    @protected
248    def save_raw_state(self):
249        state = ffi.new('unsigned char[%i]' % self._core.stateSize(self._core))
250        if self._core.saveState(self._core, state):
251            return state
252        return None
253
254    @staticmethod
255    def _keys_to_int(*args, **kwargs):
256        keys = 0
257        if 'raw' in kwargs:
258            keys = kwargs['raw']
259        for key in args:
260            keys |= 1 << key
261        return keys
262
263    @protected
264    def set_keys(self, *args, **kwargs):
265        self._core.setKeys(self._core, self._keys_to_int(*args, **kwargs))
266
267    @protected
268    def add_keys(self, *args, **kwargs):
269        self._core.addKeys(self._core, self._keys_to_int(*args, **kwargs))
270
271    @protected
272    def clear_keys(self, *args, **kwargs):
273        self._core.clearKeys(self._core, self._keys_to_int(*args, **kwargs))
274
275    @property
276    @needs_reset
277    def frame_counter(self):
278        return self._core.frameCounter(self._core)
279
280    @property
281    def frame_cycles(self):
282        return self._core.frameCycles(self._core)
283
284    @property
285    def frequency(self):
286        return self._core.frequency(self._core)
287
288    @property
289    def game_title(self):
290        title = ffi.new("char[16]")
291        self._core.getGameTitle(self._core, title)
292        return ffi.string(title, 16).decode("ascii")
293
294    @property
295    def game_code(self):
296        code = ffi.new("char[12]")
297        self._core.getGameCode(self._core, code)
298        return ffi.string(code, 12).decode("ascii")
299
300    def add_frame_callback(self, callback):
301        self._callbacks.video_frame_ended.append(callback)
302
303    @property
304    def crc32(self):
305        return self._native.romCrc32
306
307
308class ICoreOwner(object):
309    def claim(self):
310        raise NotImplementedError
311
312    def release(self):
313        raise NotImplementedError
314
315    def __enter__(self):
316        self.core = self.claim()
317        self.core._protected = True
318        return self.core
319
320    def __exit__(self, type, value, traceback):
321        self.core._protected = False
322        self.release()
323
324
325class IRunner(object):
326    def pause(self):
327        raise NotImplementedError
328
329    def unpause(self):
330        raise NotImplementedError
331
332    def use_core(self):
333        raise NotImplementedError
334
335    @property
336    def running(self):
337        raise NotImplementedError
338
339    @property
340    def paused(self):
341        raise NotImplementedError
342
343
344class Config(object):
345    def __init__(self, native=None, port=None, defaults={}):
346        if not native:
347            self._port = ffi.NULL
348            if port:
349                self._port = ffi.new("char[]", port.encode("UTF-8"))
350            native = ffi.gc(ffi.new("struct mCoreConfig*"), lib.mCoreConfigDeinit)
351            lib.mCoreConfigInit(native, self._port)
352        self._native = native
353        for key, value in defaults.items():
354            if isinstance(value, bool):
355                value = int(value)
356            lib.mCoreConfigSetDefaultValue(self._native, ffi.new("char[]", key.encode("UTF-8")), ffi.new("char[]", str(value).encode("UTF-8")))
357
358    def __getitem__(self, key):
359        string = lib.mCoreConfigGetValue(self._native, ffi.new("char[]", key.encode("UTF-8")))
360        if not string:
361            return None
362        return ffi.string(string)
363
364    def __setitem__(self, key, value):
365        if isinstance(value, bool):
366            value = int(value)
367        lib.mCoreConfigSetValue(self._native, ffi.new("char[]", key.encode("UTF-8")), ffi.new("char[]", str(value).encode("UTF-8")))