all repos — mgba @ 34964495171d71264e34874e001046c471b2df74

mGBA Game Boy Advance Emulator

src/platform/python/mgba/gb.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
 7from .lr35902 import LR35902Core
 8from .core import Core
 9from .memory import Memory
10from .tile import Sprite
11
12class GB(Core):
13    KEY_A = lib.GBA_KEY_A
14    KEY_B = lib.GBA_KEY_B
15    KEY_SELECT = lib.GBA_KEY_SELECT
16    KEY_START = lib.GBA_KEY_START
17    KEY_DOWN = lib.GBA_KEY_DOWN
18    KEY_UP = lib.GBA_KEY_UP
19    KEY_LEFT = lib.GBA_KEY_LEFT
20    KEY_RIGHT = lib.GBA_KEY_RIGHT
21
22    def __init__(self, native):
23        super(GB, self).__init__(native)
24        self._native = ffi.cast("struct GB*", native.board)
25        self.sprites = GBObjs(self)
26        self.cpu = LR35902Core(self._core.cpu)
27
28    def _initTileCache(self, cache):
29        lib.GBVideoTileCacheInit(cache)
30        lib.GBVideoTileCacheAssociate(cache, ffi.addressof(self._native.video))
31
32    def _deinitTileCache(self, cache):
33        self._native.video.renderer.cache = ffi.NULL
34        lib.mTileCacheDeinit(cache)
35
36class GBMemory(Memory):
37    def __init__(self, core):
38        super(GBMemory, self).__init__(core, 0x10000)
39
40        self.cart = Memory(core, lib.GB_SIZE_CART_BANK0 * 2, lib.GB_BASE_CART_BANK0)
41        self.vram = Memory(core, lib.GB_SIZE_VRAM, lib.GB_BASE_VRAM)
42        self.sram = Memory(core, lib.GB_SIZE_EXTERNAL_RAM, lib.GB_REGION_EXTERNAL_RAM)
43        self.iwram = Memory(core, lib.GB_SIZE_WORKING_RAM_BANK0, lib.GB_BASE_WORKING_RAM_BANK0)
44        self.oam = Memory(core, lib.GB_SIZE_OAM, lib.GB_BASE_OAM)
45        self.io = Memory(core, lib.GB_SIZE_IO, lib.GB_BASE_IO)
46        self.hram = Memory(core, lib.GB_SIZE_HRAM, lib.GB_BASE_HRAM)
47
48class GBSprite(Sprite):
49    PALETTE_BASE = 8,
50
51    def __init__(self, obj, core):
52        self.x = obj.x
53        self.y = obj.y
54        self.tile = obj.tile
55        self._attr = obj.attr
56        self.width = 8
57        lcdc = core._native.memory.io[0x40]
58        self.height = 16 if lcdc & 4 else 8
59        if core._native.model >= lib.GB_MODEL_CGB:
60            if self._attr & 8:
61                self.tile += 512
62            self.paletteId = self._attr & 7
63        else:
64            self.paletteId = (self._attr >> 4) & 1
65
66
67class GBObjs:
68    def __init__(self, core):
69        self._core = core
70        self._obj = core._native.video.oam.obj
71
72    def __len__(self):
73        return 40
74
75    def __getitem__(self, index):
76        if index >= len(self):
77            raise IndexError()
78        sprite = GBSprite(self._obj[index], self._core)
79        sprite.constitute(self._core.tiles, 0, 0)
80        return sprite