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 @staticmethod
240 def _keys_to_int(*args, **kwargs):
241 keys = 0
242 if 'raw' in kwargs:
243 keys = kwargs['raw']
244 for key in args:
245 keys |= 1 << key
246 return keys
247
248 @protected
249 def set_keys(self, *args, **kwargs):
250 self._core.setKeys(self._core, self._keys_to_int(*args, **kwargs))
251
252 @protected
253 def add_keys(self, *args, **kwargs):
254 self._core.addKeys(self._core, self._keys_to_int(*args, **kwargs))
255
256 @protected
257 def clear_keys(self, *args, **kwargs):
258 self._core.clearKeys(self._core, self._keys_to_int(*args, **kwargs))
259
260 @property
261 @needs_reset
262 def frame_counter(self):
263 return self._core.frameCounter(self._core)
264
265 @property
266 def frame_cycles(self):
267 return self._core.frameCycles(self._core)
268
269 @property
270 def frequency(self):
271 return self._core.frequency(self._core)
272
273 @property
274 def game_title(self):
275 title = ffi.new("char[16]")
276 self._core.getGameTitle(self._core, title)
277 return ffi.string(title, 16).decode("ascii")
278
279 @property
280 def game_code(self):
281 code = ffi.new("char[12]")
282 self._core.getGameCode(self._core, code)
283 return ffi.string(code, 12).decode("ascii")
284
285 def add_frame_callback(self, callback):
286 self._callbacks.video_frame_ended.append(callback)
287
288 @property
289 def crc32(self):
290 return self._native.romCrc32
291
292
293class ICoreOwner(object):
294 def claim(self):
295 raise NotImplementedError
296
297 def release(self):
298 raise NotImplementedError
299
300 def __enter__(self):
301 self.core = self.claim()
302 self.core._protected = True
303 return self.core
304
305 def __exit__(self, type, value, traceback):
306 self.core._protected = False
307 self.release()
308
309
310class IRunner(object):
311 def pause(self):
312 raise NotImplementedError
313
314 def unpause(self):
315 raise NotImplementedError
316
317 def use_core(self):
318 raise NotImplementedError
319
320 @property
321 def running(self):
322 raise NotImplementedError
323
324 @property
325 def paused(self):
326 raise NotImplementedError
327
328
329class Config(object):
330 def __init__(self, native=None, port=None, defaults={}):
331 if not native:
332 self._port = ffi.NULL
333 if port:
334 self._port = ffi.new("char[]", port.encode("UTF-8"))
335 native = ffi.gc(ffi.new("struct mCoreConfig*"), lib.mCoreConfigDeinit)
336 lib.mCoreConfigInit(native, self._port)
337 self._native = native
338 for key, value in defaults.items():
339 if isinstance(value, bool):
340 value = int(value)
341 lib.mCoreConfigSetDefaultValue(self._native, ffi.new("char[]", key.encode("UTF-8")), ffi.new("char[]", str(value).encode("UTF-8")))
342
343 def __getitem__(self, key):
344 string = lib.mCoreConfigGetValue(self._native, ffi.new("char[]", key.encode("UTF-8")))
345 if not string:
346 return None
347 return ffi.string(string)
348
349 def __setitem__(self, key, value):
350 if isinstance(value, bool):
351 value = int(value)
352 lib.mCoreConfigSetValue(self._native, ffi.new("char[]", key.encode("UTF-8")), ffi.new("char[]", str(value).encode("UTF-8")))