├── MANIFEST.in ├── docs ├── nacho_demo1.png ├── original_man.pdf ├── platter_demo1.png ├── Viper-Volume1Issue02.pdf ├── sphinx │ ├── Makefile │ ├── conf.py │ └── index.rst └── README.md ├── minimized └── chip8 │ ├── play.wav │ ├── __main__.py │ ├── display.py │ └── emulator.py ├── tortilla8 ├── sound │ ├── play.wav │ └── README.md ├── constants │ ├── __init__.py │ ├── symbols.py │ ├── preprocessor.py │ ├── reg_rom_stack.py │ ├── graphics.py │ ├── curses.py │ └── opcodes.py ├── __init__.py ├── salsa.py ├── cilantro.py ├── jalapeno.py ├── instructions.py ├── nacho.py ├── __main__.py ├── blackbean.py ├── guacamole.py └── platter.py ├── roms ├── empty.asm ├── dot_dude.asm ├── fake_mandelbrot.asm ├── vertical_stripes_pp.asm └── vertical_stripes.asm ├── setup.py ├── .gitignore ├── README.md └── LICENSE /MANIFEST.in: -------------------------------------------------------------------------------- 1 | include tortilla8/sound/* 2 | include tortilla8/constants/* 3 | -------------------------------------------------------------------------------- /docs/nacho_demo1.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/aanunez/tortilla8/HEAD/docs/nacho_demo1.png -------------------------------------------------------------------------------- /docs/original_man.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/aanunez/tortilla8/HEAD/docs/original_man.pdf -------------------------------------------------------------------------------- /docs/platter_demo1.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/aanunez/tortilla8/HEAD/docs/platter_demo1.png -------------------------------------------------------------------------------- /minimized/chip8/play.wav: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/aanunez/tortilla8/HEAD/minimized/chip8/play.wav -------------------------------------------------------------------------------- /tortilla8/sound/play.wav: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/aanunez/tortilla8/HEAD/tortilla8/sound/play.wav -------------------------------------------------------------------------------- /docs/Viper-Volume1Issue02.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/aanunez/tortilla8/HEAD/docs/Viper-Volume1Issue02.pdf -------------------------------------------------------------------------------- /tortilla8/constants/__init__.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | 3 | # This is only used to easily organize and import constants 4 | -------------------------------------------------------------------------------- /tortilla8/constants/symbols.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | 3 | # General 4 | BEGIN_COMMENT = ';' 5 | HEX_ESC = '#' 6 | BIN_ESC = '$' 7 | 8 | -------------------------------------------------------------------------------- /roms/empty.asm: -------------------------------------------------------------------------------- 1 | ; Empty Rom for CHIP 8 2 | ; 3 | ; 4 | ; Licensed under GPLv3, Adam Nunez 5 | ; Apart of the tortilla 8 project 6 | ; 7 | 8 | spin: 9 | jp spin 10 | -------------------------------------------------------------------------------- /tortilla8/sound/README.md: -------------------------------------------------------------------------------- 1 | The file in this directory named 'play.wav' is used by platter as the default tone for the sound timmer when the '-a' flag is not provided. The default tone is a 440Hz square wave. This file may be replaced with any wav file. You can use the [Online Tone Generator](http://onlinetonegenerator.com/) for other simple, single tone, wav files. 2 | -------------------------------------------------------------------------------- /tortilla8/constants/preprocessor.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | 3 | END_MEM_TAG = ':' 4 | 5 | # Data Declaration (Sizes in bytes) 6 | DATA_DECLARE = {'db':1,'dw':2,'dd':4} 7 | 8 | # Pre Processor 9 | ELSE_IF = ('elif','elseif','elifdef','elseifdef') 10 | END_MARKS = ('endif','else') + ELSE_IF 11 | EQU_MARKS = ('equ','=') 12 | MODE_MARKS = ('option','align','list','nolist') 13 | PRE_PROC = ('ifdef','ifndef') + END_MARKS + EQU_MARKS + MODE_MARKS 14 | -------------------------------------------------------------------------------- /tortilla8/constants/reg_rom_stack.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | 3 | # Register stuff 4 | NUMB_OF_REGS = 16 5 | ARG_SUB = {0:'x',1:'y',2:'z'} 6 | REGISTERS = ('v0','v1','v2','v3', 7 | 'v4','v5','v6','v7', 8 | 'v8','v9','va','vb', 9 | 'vc','vd','ve','vf') 10 | 11 | # ROM Memory Addresses and Related 12 | BYTES_OF_RAM = 4096 13 | MAX_ROM_SIZE = 3232 14 | PROGRAM_BEGIN_ADDRESS = 0x200 15 | #PROGRAM_BEGIN_ADDRESS = 0x600 #I dunno who uses this 16 | OVERFLOW_ADDRESS = PROGRAM_BEGIN_ADDRESS+MAX_ROM_SIZE 17 | 18 | # Stack 19 | STACK_SIZE = 12 20 | STACK_ADDRESS = None 21 | #STACK_ADDRESS = 0xEA0 #Uncomment to emulate stack in ram 22 | 23 | -------------------------------------------------------------------------------- /docs/sphinx/Makefile: -------------------------------------------------------------------------------- 1 | # Minimal makefile for Sphinx documentation 2 | # 3 | 4 | # You can set these variables from the command line. 5 | SPHINXOPTS = 6 | SPHINXBUILD = python3 -msphinx 7 | SPHINXPROJ = ipsy 8 | SOURCEDIR = . 9 | BUILDDIR = _build 10 | 11 | # Put it first so that "make" without argument is like "make help". 12 | help: 13 | @$(SPHINXBUILD) -M help "$(SOURCEDIR)" "$(BUILDDIR)" $(SPHINXOPTS) $(O) 14 | 15 | .PHONY: help Makefile 16 | 17 | # Catch-all target: route all unknown targets to Sphinx using the new 18 | # "make mode" option. $(O) is meant as a shortcut for $(SPHINXOPTS). 19 | %: Makefile 20 | @$(SPHINXBUILD) -M $@ "$(SOURCEDIR)" "$(BUILDDIR)" $(SPHINXOPTS) $(O) 21 | -------------------------------------------------------------------------------- /docs/sphinx/conf.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | 3 | import sys 4 | import os 5 | sys.path.insert(0, os.path.abspath(os.path.join('..','..'))) 6 | 7 | extensions = [ 'sphinx.ext.autodoc', 8 | 'sphinx.ext.todo', 9 | 'sphinx.ext.viewcode'] 10 | source_suffix = '.rst' 11 | master_doc = 'index' 12 | project = u'tortilla8' 13 | copyright = u'2017, adam nunez' 14 | author = u'adam nunez' 15 | version = u'0.2' 16 | release = u'0.2' 17 | language = None 18 | exclude_patterns = ['_build'] 19 | pygments_style = 'sphinx' 20 | todo_include_todos = True 21 | html_theme = 'classic' 22 | #html_theme_options = {} 23 | htmlhelp_basename = 'tortilla8doc' 24 | man_pages = [ (master_doc, 'tortilla8', u'tortilla8 Documentation',[author], 1) ] 25 | texinfo_documents = [ (master_doc, 'tortilla8', u'tortilla8 Documentation', 26 | author, 'tortilla8', 'One line description of project.', 'Miscellaneous') ] 27 | -------------------------------------------------------------------------------- /tortilla8/constants/graphics.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | 3 | GFX_ADDRESS = 0xF00 4 | GFX_HEIGHT_PX = 32 5 | GFX_WIDTH_PX = 64 6 | GFX_WIDTH = int(GFX_WIDTH_PX/8) 7 | GFX_RESOLUTION = int(GFX_WIDTH*GFX_HEIGHT_PX) #In bytes 8 | 9 | SET_VF_ON_GFX_OVERFLOW = False # Undocumented 'feature'. When 'Add I, VX' overflows 'I' 10 | # VF is set to one when this is True. The insturction does 11 | # not set VF low. Used by Spacefight 2019. 12 | # Fonts (80 bytes) 13 | GFX_FONT_ADDRESS = 0x050 14 | GFX_FONT = ( 15 | 0xF0, 0x90, 0x90, 0x90, 0xF0, # 0 16 | 0x20, 0x60, 0x20, 0x20, 0x70, # 1 17 | 0xF0, 0x10, 0xF0, 0x80, 0xF0, # 2 18 | 0xF0, 0x10, 0xF0, 0x10, 0xF0, # 3 19 | 0x90, 0x90, 0xF0, 0x10, 0x10, # 4 20 | 0xF0, 0x80, 0xF0, 0x10, 0xF0, # 5 21 | 0xF0, 0x80, 0xF0, 0x90, 0xF0, # 6 22 | 0xF0, 0x10, 0x20, 0x40, 0x40, # 7 23 | 0xF0, 0x90, 0xF0, 0x90, 0xF0, # 8 24 | 0xF0, 0x90, 0xF0, 0x10, 0xF0, # 9 25 | 0xF0, 0x90, 0xF0, 0x90, 0x90, # A 26 | 0xE0, 0x90, 0xE0, 0x90, 0xE0, # B 27 | 0xF0, 0x80, 0x80, 0x80, 0xF0, # C 28 | 0xE0, 0x90, 0x90, 0x90, 0xE0, # D 29 | 0xF0, 0x80, 0xF0, 0x80, 0xF0, # E 30 | 0xF0, 0x80, 0xF0, 0x80, 0x80 # F 31 | ) 32 | 33 | -------------------------------------------------------------------------------- /tortilla8/__init__.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | 3 | # This snipit adds EVERYTHING to __all__ 4 | #from os.path import dirname, basename, isfile 5 | #from glob import glob 6 | #modules = glob(dirname(__file__)+"/*.py") 7 | #__all__ = [ basename(f)[:-3] for f in modules if isfile(f) and not f.endswith('__init__.py') ] 8 | 9 | __all__ = [] 10 | 11 | from sys import modules 12 | def export(defn): 13 | mod = modules[defn.__module__] 14 | if hasattr(mod, '__all__'): 15 | name, all_ = defn.__name__, mod.__all__ 16 | if name not in __all__: 17 | all_.append(name) 18 | else: 19 | mod.__all__ = [defn.__name__] 20 | return defn 21 | 22 | from enum import Enum 23 | @export 24 | class EmulationError(Enum): 25 | _Information = 1 26 | _Warning = 2 27 | _Fatal = 3 28 | 29 | def __str__(self): 30 | return self.name[1:] 31 | 32 | @classmethod 33 | def from_string(self, value): 34 | value = value.lower() 35 | if (value == "info") or (value == "information"): 36 | return self._Information 37 | if (value == "warning"): 38 | return self._Warning 39 | if (value == "fatal"): 40 | return self._Fatal 41 | return None 42 | 43 | # Skipping platter and instructions, they are not useful to programmers 44 | from .blackbean import * 45 | from .cilantro import * 46 | from .guacamole import * 47 | from .jalapeno import * 48 | from .salsa import * 49 | 50 | 51 | -------------------------------------------------------------------------------- /setup.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | 3 | # doc page: 4 | # https://docs.python.org/3.5/distutils/setupscript.html 5 | from setuptools import setup 6 | 7 | setup( 8 | name = 'tortilla8', 9 | version = '0.2', 10 | description = 'A collection of Chip8 tools for pre-processing, assembling, emulating, disassembling, and visualizing Chip8 ROMs.', 11 | author = 'Adam Nunez', 12 | author_email = 'adam.a.nunez@gmail.com', 13 | license = 'GPLv3', 14 | url = 'https://github.com/aanunez/tortilla8', 15 | packages = ['tortilla8'], 16 | #install_requires = [], #Curses and SimpleAudio are optional 17 | extras_require = { 18 | 'Sound': ['simpleaudio'], 19 | }, 20 | #scripts = [ 21 | # 'scripts/t8-assemble', 22 | # 'scripts/t8-disassemble', 23 | # 'scripts/t8-execute', 24 | # 'scripts/t8-preproc', 25 | # 'scripts/t8-emulate' 26 | # ], 27 | include_package_data = True, 28 | entry_points={ 29 | 'console_scripts': [ 30 | 'tortilla8 = tortilla8.__main__:main' 31 | ] 32 | }, 33 | classifiers=[ 34 | # List here: https://pypi.python.org/pypi?%3Aaction=browse 35 | 'Development Status :: 4 - Beta', 36 | 'Intended Audience :: Developers', 37 | 'Topic :: Software Development', 38 | 'License :: OSI Approved :: GNU General Public License v3 (GPLv3)', 39 | 'Programming Language :: Python :: 3.5', 40 | ], 41 | keywords='emulation chip-8 chip8 rom emulator assembler disassembler' 42 | ) 43 | -------------------------------------------------------------------------------- /docs/README.md: -------------------------------------------------------------------------------- 1 | # CHIP-8 Documentation 2 | The included docs, plus maybe bugging people on /r/emudev should be more than enough to make a working CHIP8 emulator. 3 | 4 | Things I got stuck on: 5 | * Setting VF high means setting it to exectly one. 6 | * The 'add i, reg' instruction has undocumented behavior where an overflow of I causes the VF flag to be set, but the instruction never sets VF low. This is accounted for via a constant 'SET_VF_ON_GFX_OVERFLOW' in tortilla8 and is off by default. 7 | 8 | Included 9 | -------- 10 | * Original manual - Original RCA manual with chip 8. Excludes some instructions (XOR, shifts, subn) 11 | * Viper Vol 1, Issue 2 - Goes over the above missing instructions on page 3. 12 | * Cowgod's Chip-8 Technical Reference - Probably the most complete spec for the Chip-8 13 | 14 | Additional Online Sources 15 | ------------------------- 16 | [Mastering Chip-8 by Matthew Mikolay](http://mattmik.com/files/chip8/mastering/chip8.html) 17 | 18 | [How to write an emulator by Laurence Muller](http://www.multigesture.net/articles/how-to-write-an-emulator-chip-8-interpreter/) 19 | 20 | [Reddit user Dannyg86 asking about bugs in their emulator](https://www.reddit.com/r/EmuDev/comments/5so1bo/chip8_emu_questions/) 21 | 22 | [Chip8.com Archive](https://web.archive.org/web/20161002171937/http://chip8.com/) 23 | 24 | [Chip8.com's rom collection](https://web.archive.org/web/20161020052454/http://chip8.com/downloads/Chip-8%20Pack.zip) 25 | 26 | [Wiki Article](https://en.wikipedia.org/wiki/CHIP-8) 27 | -------------------------------------------------------------------------------- /docs/sphinx/index.rst: -------------------------------------------------------------------------------- 1 | tortilla8's docs 2 | ================ 3 | 4 | Summary goes here 5 | 6 | Using tortilla8 7 | =============== 8 | 9 | Stuff goes here 10 | 11 | Code 12 | ==== 13 | 14 | .. automodule:: tortilla8.salsa 15 | :members: 16 | 17 | .. automodule:: tortilla8.guacamole 18 | :members: 19 | 20 | .. automodule:: tortilla8.blackbean 21 | :members: 22 | 23 | .. automodule:: tortilla8.cilantro 24 | :members: 25 | 26 | .. automodule:: tortilla8.jalapeno 27 | :members: 28 | 29 | .. toctree:: 30 | :hidden: 31 | :maxdepth: 2 32 | 33 | 34 | Desgin - Curses 35 | =============== 36 | 37 | [UniCurses](https://pdcurses.sourceforge.io/) was not used for Platter as the syntax differs on Posix and Windows implimentations. Unicruses on Windows uses [PDCurses](https://pdcurses.sourceforge.io/). Instructions on installing follow, but, to be clear,**support is not included**. 38 | ``` 39 | :: Use pip to install UniCurses 40 | pip install https://sourceforge.net/projects/pyunicurses/files/latest/download?source=typ_redirect 41 | ``` 42 | You will also need the dlls for both PDCurses and SDL; [PDCurses](https://pdcurses.sourceforge.io/) distributes both source, pre-built dlls, and cofig files for this. Similarly, [SDL](https://www.libsdl.org/download-1.2.php) pre-built dlls, source, and configs can be easily found online. SDL 1.2 is the recomended version for UniCurses 1.2, the latests avaialbe version as of writing, and was used for testing while UniCurses was being used. 43 | 44 | Design - Why Tkinter 45 | ==================== 46 | 47 | Indices and tables 48 | ================== 49 | 50 | * :ref:`genindex` 51 | * :ref:`modindex` 52 | * :ref:`search` 53 | 54 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | # Exclude dir 2 | docs/sphinx/_build/* 3 | docs/sphinx/_static/* 4 | docs/sphinx/_templates/* 5 | exclude/ 6 | foo 7 | *.lst 8 | *.src 9 | *.ch8 10 | *.bin 11 | *.strip 12 | *.stp 13 | *.jala 14 | *.SRC 15 | 16 | 17 | # Byte-compiled / optimized / DLL files 18 | __pycache__/ 19 | *.py[cod] 20 | *$py.class 21 | 22 | # C extensions 23 | *.so 24 | 25 | # Distribution / packaging 26 | .Python 27 | env/ 28 | build/ 29 | develop-eggs/ 30 | dist/ 31 | downloads/ 32 | eggs/ 33 | .eggs/ 34 | lib/ 35 | lib64/ 36 | parts/ 37 | sdist/ 38 | var/ 39 | *.egg-info/ 40 | .installed.cfg 41 | *.egg 42 | 43 | # PyInstaller 44 | # Usually these files are written by a python script from a template 45 | # before PyInstaller builds the exe, so as to inject date/other infos into it. 46 | *.manifest 47 | *.spec 48 | 49 | # Installer logs 50 | pip-log.txt 51 | pip-delete-this-directory.txt 52 | 53 | # Unit test / coverage reports 54 | htmlcov/ 55 | .tox/ 56 | .coverage 57 | .coverage.* 58 | .cache 59 | nosetests.xml 60 | coverage.xml 61 | *,cover 62 | .hypothesis/ 63 | 64 | # Translations 65 | *.mo 66 | *.pot 67 | 68 | # Django stuff: 69 | *.log 70 | local_settings.py 71 | 72 | # Flask stuff: 73 | instance/ 74 | .webassets-cache 75 | 76 | # Scrapy stuff: 77 | .scrapy 78 | 79 | # Sphinx documentation 80 | docs/_build/ 81 | 82 | # PyBuilder 83 | target/ 84 | 85 | # IPython Notebook 86 | .ipynb_checkpoints 87 | 88 | # pyenv 89 | .python-version 90 | 91 | # celery beat schedule file 92 | celerybeat-schedule 93 | 94 | # dotenv 95 | .env 96 | 97 | # virtualenv 98 | venv/ 99 | ENV/ 100 | 101 | # Spyder project settings 102 | .spyderproject 103 | 104 | # Rope project settings 105 | .ropeproject 106 | -------------------------------------------------------------------------------- /roms/dot_dude.asm: -------------------------------------------------------------------------------- 1 | ; Dot Dude Rom for CHIP 8 2 | ; 3 | ; This rom is for testing the Load key instruction in a 4 | ; chip-8 emulator. It moves a dot in the direction of 5 | ; the key press (2 4 6 8) then waits for another input. 6 | ; 7 | ; Licensed under GPLv3, Adam Nunez 8 | ; Apart of the tortilla 8 project 9 | ; 10 | 11 | 12 | ld va, 32 ; init x cord 64/2 13 | ld vb, 16 ; init y cord 32/2 14 | ld i, dot ; dot for drawing 15 | ld vd, 1 ; Sub can only to reg to reg 16 | loop: 17 | drw va, vb, 1 ; Draw current dot 18 | ld vc, k ; Wait for input 19 | drw va, vb, 1 ; Remove current dot 20 | sne vc, 2 ; ---------------------------- 21 | jp down ; Check val of key press on a 22 | sne vc, 4 ; modern PC numb pad and jump 23 | jp left ; to current address. If any 24 | sne vc, 6 ; other key is pressed just 25 | jp right ; jump back to the top of the 26 | sne vc, 8 ; loop. 27 | jp up ; 28 | jp loop ; ---------------------------- 29 | down: ; ---------------------------- 30 | add vb, vd ; Add or subtract to the x/y 31 | jp loop ; cord depending on what was 32 | left: ; pressed then jump back to 33 | sub va, vd ; top of loop. 34 | jp loop ; 35 | right: ; 36 | add va, vd ; 37 | jp loop ; 38 | up: ; 39 | sub vb, vd ; 40 | jp loop ; ---------------------------- 41 | dot: ; 42 | db #80 ; Dot for drawing 43 | -------------------------------------------------------------------------------- /minimized/chip8/__main__.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | 3 | from os.path import isfile 4 | from sys import platform, argv 5 | from argparse import ArgumentParser, ArgumentTypeError 6 | from .emulator import Emulator 7 | from .display import Display 8 | 9 | def pos_int(value): 10 | ivalue = int(value) 11 | if ivalue < 1: 12 | raise ArgumentTypeError("%s is an invalid positive int value." % value) 13 | return ivalue 14 | 15 | def parse_args(): 16 | parser = ArgumentParser(description= 17 | ''' 18 | Start a text (unicode) based Chip8 emulator which disaplys a game screen, all 19 | registers, the stack, recently processed instructions, and a console to log 20 | any issues that occur. 21 | ''') 22 | 23 | parser.add_argument('rom', help= 24 | 'ROM to load and play.') 25 | parser.add_argument('-f','--frequency', type=pos_int, default=10,help= 26 | 'CPU frequency to target, minimum 1Hz. 10Hz by default.') 27 | parser.add_argument('-d','--drawfix', action='store_true', help= 28 | 'Enable anti-flicker, stops the display from drawing to the screen when sprites are only removed.', ) 29 | parser.add_argument('-a','--audio', help= 30 | 'Path to audio to play for Sound Timer, or "off" to prevent sound from playing.' + \ 31 | 'By default a 440Hz square wave is used.') 32 | parser.add_argument("-u","--unicode", action='store_true', help= 33 | 'Forces unicode to be used for the game screen.') 34 | 35 | return parser.parse_args() 36 | 37 | def main(): 38 | if len(argv) == 1: 39 | argv.append('-h') 40 | 41 | opts = parse_args() 42 | if not isfile(opts.rom): 43 | raise OSError("File '" + opts.rom + "' does not exist") 44 | 45 | screen_unicode = True if platform != 'win32' or opts.unicode else False 46 | disp = Display( opts.rom, opts.frequency, 60, 60, opts.drawfix, screen_unicode, opts.audio ) 47 | disp.start() 48 | 49 | if __name__ == "__main__": 50 | main() 51 | -------------------------------------------------------------------------------- /tortilla8/constants/curses.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | 3 | # Window Sizes 4 | BORDERS = 2 5 | WIN_REG_H = 8 6 | WIN_REG_W = 9*4 + BORDERS 7 | WIN_STACK_W = 11 + BORDERS 8 | WIN_INSTR_W = 16 + BORDERS 9 | WIN_LOGO_W = 7 10 | WIN_MENU_H = 1 + BORDERS 11 | 12 | # TITLE OFFSETS 13 | REG_OFFSET = 15 14 | STAK_OFFSET = 4 15 | 16 | # Min size to function 17 | W_MIN = 80 18 | H_MIN = 24 19 | 20 | # Messages to display when window is too small 21 | DY_MSG_1 = "Window too small" 22 | DY_MSG_2 = "Resize to " + str(W_MIN) + "x" + str(H_MIN) 23 | 24 | # Display size, and mins 25 | DISPLAY_MIN_W = 104 26 | DISPLAY_MIN_H = 34 27 | DISPLAY_H = 16 + BORDERS # Terminal blocks are twice as tall as wide 28 | DISPLAY_W = 64 + BORDERS 29 | 30 | LEN_STR_REG = len("Regiters") 31 | LEN_STR_STA = len("Stack") 32 | 33 | # Action Keys 34 | KEY_ESC = 27 # Invisable esc 35 | KEY_ARROW = 91 # '[' 36 | KEY_STEP = 115 # S 37 | KEY_EXIT = 120 # X 38 | KEY_RESET = 114 # R 39 | KEY_REWIN = 119 # W 40 | KEY_RESUM = 117 # U 41 | 42 | KEY_CONTROLS={ 43 | 48:0x0, 49:0x1, 50:0x2, 51:0x3, # 0 1 2 3 44 | 52:0x4, 53:0x5, 54:0x6, 55:0x7, # 4 5 6 7 45 | 56:0x8, 57:0x9, 47:0xA, 42:0xB, # 8 9 / * 46 | 45:0xC, 43:0xD, 10:0xE, 46:0xF} # - + E . 47 | 48 | KEY_ARROW_MAP={65:'up',66:'down',67:'right',68:'left'} 49 | 50 | # Graphics Draw 51 | from collections import namedtuple 52 | CHAR_SET = namedtuple('CHAR_SET', 'upper lower both empty') 53 | UNICODE_DRAW = CHAR_SET('▀','▄','█',' ') 54 | WIN_DRAW = CHAR_SET('*','o','8',' ') 55 | 56 | KEYPAD_DRAW=[ 57 | '┌────────────────┐', 58 | '│ Keypad │', 59 | '│┌──┐┌──┐┌──┐┌──┐│', 60 | '││00││01││02││03││', 61 | '│└──┘└──┘└──┘└──┘│', 62 | '│┌──┐┌──┐┌──┐┌──┐│', 63 | '││04││05││06││07││', 64 | '│└──┘└──┘└──┘└──┘│', 65 | '│┌──┐┌──┐┌──┐┌──┐│', 66 | '││08││09││10││11││', 67 | '│└──┘└──┘└──┘└──┘│', 68 | '│┌──┐┌──┐┌──┐┌──┐│', 69 | '││12││13││14││15││', 70 | '│└──┘└──┘└──┘└──┘│', 71 | '└────────────────┘' 72 | ] 73 | 74 | # Prefixes to use for hz 75 | PREFIX = [ 76 | ['Y', 1e24], # yotta 77 | ['Z', 1e21], # zetta 78 | ['E', 1e18], # exa 79 | ['P', 1e15], # peta 80 | ['T', 1e12], # tera 81 | ['G', 1e9 ], # giga 82 | ['M', 1e6 ], # mega 83 | ['k', 1e3 ] # kilo 84 | ] 85 | 86 | # Logo 87 | LOGO_MIN = 34 88 | LOGO=[ 89 | ' ██ ', 90 | '███████', 91 | '█ ██ ', 92 | ' ', 93 | '██████ ', 94 | '█ ██ ', 95 | '██████ ', 96 | ' ', 97 | '██████ ', 98 | ' ██ ', 99 | ' ', 100 | ' ██ ', 101 | '███████', 102 | '█ ██ ', 103 | ' ', 104 | '████ ██', 105 | ' ', 106 | '███████', 107 | ' ', 108 | '███████', 109 | ' ', 110 | '████ █ ', 111 | '█ █ █ ', 112 | '██████ ', 113 | '███ '] 114 | 115 | 116 | 117 | -------------------------------------------------------------------------------- /tortilla8/constants/opcodes.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | 3 | from collections import namedtuple 4 | 5 | # OP CODES 6 | OP_CODE_SIZE = 2 7 | OpData = namedtuple('OpData', 'regular, args, hex') 8 | OP_CODES = { # X and Y in the right most indicates if it is for the 1st or 2nd arg 9 | 'cls' : OpData('00e0',[],'00E0'), 10 | 'ret' : OpData('00ee',[],'00EE'), 11 | 'sys' : OpData('0(^0)..',['addr'],'0xxx'), # prevent match to cls or ret 12 | 'call': OpData('2...',['addr'],'2xxx'), 13 | 'skp' : OpData('e.9e',['reg'],'Ex9E'), 14 | 'sknp': OpData('e.a1',['reg'],'ExA1'), 15 | 'se' :(OpData('5..0',['reg','reg'],'5xy0'), 16 | OpData('3...',['reg','byte'],'3xyy')), 17 | 'sne' :(OpData('9..0',['reg','reg'],'9xy0'), 18 | OpData('4...',['reg','byte'],'4xyy')), 19 | 'add' :(OpData('7...',['reg','byte'],'7xyy'), 20 | OpData('8..4',['reg','reg'],'8xy4'), 21 | OpData('f.1e',['i','reg'],'Fy1E')), 22 | 'or' : OpData('8..1',['reg','reg'],'8xy1'), 23 | 'and' : OpData('8..2',['reg','reg'],'8xy2'), 24 | 'xor' : OpData('8..3',['reg','reg'],'8xy3'), 25 | 'sub' : OpData('8..5',['reg','reg'],'8xy5'), 26 | 'subn': OpData('8..7',['reg','reg'],'8xy7'), 27 | 'shr' :(OpData('8..6',['reg'],'8x06'), 28 | OpData(' ',['reg','reg'],'8xy6')), # Blank regex, we never match, use shfit_mod instead 29 | 'shl' :(OpData('8..e',['reg'],'8x0E'), 30 | OpData(' ',['reg','reg'],'8xyE')), # as above 31 | 'rnd' : OpData('c...',['reg','byte'],'Cxyy'), 32 | 'jp' :(OpData('b...',['v0','addr'],'Byyy'), 33 | OpData('1...',['addr'],'1xxx')), 34 | 'ld' :(OpData('6...',['reg','byte'],'6xyy'), 35 | OpData('8..0',['reg','reg'],'8xy0'), 36 | OpData('f.07',['reg','dt'],'Fx07'), 37 | OpData('f.0a',['reg','k'],'Fx0A'), 38 | OpData('f.65',['reg','[i]'],'Fx65'), 39 | OpData('a...',['i','addr'],'Ayyy'), 40 | OpData('f.15',['dt','reg'],'Fy15'), 41 | OpData('f.18',['st','reg'],'Fy18'), 42 | OpData('f.29',['f','reg'],'Fy29'), 43 | OpData('f.33',['b','reg'],'Fy33'), 44 | OpData('f.55',['[i]','reg'],'Fy55')), 45 | 'drw' : OpData('d...',['reg','reg','nibble'],'Dxyz') 46 | } 47 | 48 | UNOFFICIAL_OP_CODES = ('xor','shr','shl','subn') # But still supported 49 | BANNED_OP_CODES = ('7f..','8f.4','8f.6','8f.e','cf..','6f..','8f.0','ff07','ff0a','ff65') # Ins that modify VF: add, shr, shl, rnd, ld 50 | SUPER_CHIP_OP_CODES = ('00c.','00fb','00fc','00fd','00fe','00ff','d..0','f.30','f.75','f.85') # Super chip-8, not supported 51 | 52 | # Used to explode opcodes that are not used (below) 53 | def explode_op_codes( op_code_list ): 54 | exploded_list = [] 55 | for item in op_code_list: 56 | if item.find('.') == -1: 57 | exploded_list.append(item) 58 | else: 59 | upper,repl,fill = 16,'.',1 60 | if item[2:] == '..': 61 | upper,repl,fill = 256,'..',2 62 | for i in range(0, upper): 63 | exploded_list.append(item.replace(repl, hex(i)[2:].zfill(fill))) 64 | return exploded_list 65 | 66 | BANNED_OP_CODES_EXPLODED = explode_op_codes(BANNED_OP_CODES) 67 | SUPER_CHIP_OP_CODES_EXPLODED = explode_op_codes(SUPER_CHIP_OP_CODES) 68 | 69 | 70 | 71 | -------------------------------------------------------------------------------- /tortilla8/salsa.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | 3 | from . import export 4 | from re import match 5 | from collections import namedtuple 6 | from .constants.opcodes import OP_CODES, UNOFFICIAL_OP_CODES, \ 7 | BANNED_OP_CODES_EXPLODED, SUPER_CHIP_OP_CODES_EXPLODED 8 | __all__ = [] 9 | 10 | @export 11 | class ASMdata( namedtuple('ASMdata', 'hex_instruction is_valid mnemonic\ 12 | mnemonic_arg_types disassembled_line unoffical_op is_banned is_super8') ): 13 | pass 14 | 15 | class EarlyExit(Exception): 16 | pass 17 | 18 | @export 19 | def Salsa(byte_list): 20 | ''' 21 | Salsa is a one line (2 byte) dissassembler function for CHIP-8 Rom It 22 | returns a named tuple with various information on the line. 23 | ''' 24 | hex_instruction = hex( byte_list[0] )[2:].zfill(2) 25 | hex_instruction += hex( byte_list[1] )[2:].zfill(2) 26 | is_valid = False 27 | mnemonic = None 28 | mnemonic_arg_types = None 29 | disassembled_line = "" 30 | unoffical_op = False 31 | is_banned = False 32 | is_super8 = False 33 | 34 | try: 35 | # Check if the Op-Code a Super-8 instruction 36 | if hex_instruction in SUPER_CHIP_OP_CODES_EXPLODED: 37 | mnemonic = 'SPR' 38 | is_super8 = True 39 | raise EarlyExit 40 | 41 | # Match the instruction via a regex index 42 | for mnemonic, reg_patterns in OP_CODES.items(): 43 | 44 | if type(reg_patterns) is not tuple: 45 | reg_patterns = (reg_patterns,) 46 | for pattern_version in reg_patterns: 47 | if not match(pattern_version.regular, hex_instruction): 48 | continue 49 | mnemonic = mnemonic 50 | mnemonic_arg_types = pattern_version.args 51 | is_valid = True 52 | break 53 | if is_valid: 54 | break 55 | 56 | # If not a valid instruction, assume data 57 | if not is_valid: 58 | disassembled_line = hex_instruction 59 | raise EarlyExit 60 | 61 | # If banned, flag and exit. 62 | if hex_instruction in BANNED_OP_CODES_EXPLODED: 63 | is_banned = True 64 | raise EarlyExit 65 | 66 | # If unoffical, flag it. 67 | if mnemonic in UNOFFICIAL_OP_CODES: 68 | unoffical_op = True 69 | 70 | # No args to parse 71 | if mnemonic_arg_types is None: 72 | disassembled_line = mnemonic 73 | raise EarlyExit 74 | 75 | # Parse Args 76 | tmp = '' 77 | reg_numb = 1 78 | for arg_type in mnemonic_arg_types: 79 | if arg_type is 'reg': 80 | tmp = 'v'+hex_instruction[reg_numb] 81 | elif arg_type is 'byte': 82 | tmp = '#'+hex_instruction[2:] 83 | elif arg_type is 'addr': 84 | tmp = '#'+hex_instruction[1:] 85 | elif arg_type is 'nibble': 86 | tmp = '#'+hex_instruction[3] 87 | else: 88 | tmp = arg_type 89 | disassembled_line += tmp.ljust(5) + ',' 90 | reg_numb = 2 91 | 92 | disassembled_line = (mnemonic.ljust(5) + disassembled_line[:-1]).rstrip() 93 | except EarlyExit: 94 | pass 95 | finally: 96 | return ASMdata(hex_instruction, is_valid, mnemonic, 97 | mnemonic_arg_types, disassembled_line, unoffical_op, 98 | is_banned, is_super8) 99 | 100 | -------------------------------------------------------------------------------- /roms/fake_mandelbrot.asm: -------------------------------------------------------------------------------- 1 | ; Fake Mandelbrot Set Rom for CHIP 8 2 | ; 3 | ; 4 | ; Licensed under GPLv3, Adam Nunez 5 | ; Apart of the tortilla 8 project 6 | ; 7 | 8 | ld va, 0 ; init x cord 9 | ld vb, 0 ; init y cord 10 | ld vc, 1 ; inc for i reg 11 | ld i, mandelbrot ; dot for drawing 12 | loop: 13 | drw va, vb, 1 ; Draw 14 | add i, vc ; Inc the Index 15 | add va, 8 ; Inc x by 1 byte 16 | se va, 64 ; If x == 64, skip jp 17 | jp loop ; Jump back to draw rest of line 18 | ld va, 0 ; reset va 19 | add vb, 1 ; Inc y by 1 to draw the next line 20 | se vb, 32 ; If y == 32, skip jp 21 | jp loop ; Jump back to draw another line 22 | spin: 23 | jp spin ; Finished 24 | 25 | mandelbrot: 26 | db $........,$........,$........,$........,$........,$........,$........,$........ 27 | db $........,$........,$........,$........,$........,$........,$........,$........ 28 | db $........,$........,$........,$........,$.......1,$1.......,$........,$........ 29 | db $........,$........,$........,$........,$......11,$11......,$........,$........ 30 | db $........,$........,$........,$........,$......11,$11......,$........,$........ 31 | db $........,$........,$........,$.......1,$......11,$11......,$........,$........ 32 | db $........,$........,$........,$.......1,$1.111111,$1111.1..,$........,$........ 33 | db $........,$........,$........,$......11,$11111111,$11111111,$1.......,$........ 34 | db $........,$........,$........,$......11,$11111111,$11111111,$1.......,$........ 35 | db $........,$........,$........,$.....111,$11111111,$11111111,$11......,$........ 36 | db $........,$........,$........,$...11111,$11111111,$11111111,$111.....,$........ 37 | db $........,$........,$.....1..,$...11111,$11111111,$11111111,$11......,$........ 38 | db $........,$........,$..111111,$1..11111,$11111111,$11111111,$1111....,$........ 39 | db $........,$........,$11111111,$11.11111,$11111111,$11111111,$11......,$........ 40 | db $........,$.....1..,$11111111,$11111111,$11111111,$11111111,$11......,$........ 41 | db $........,$......11,$11111111,$11111111,$11111111,$11111111,$1.......,$........ 42 | db $........,$......11,$11111111,$11111111,$11111111,$11111111,$1.......,$........ 43 | db $........,$.....1..,$11111111,$11111111,$11111111,$11111111,$11......,$........ 44 | db $........,$........,$11111111,$11.11111,$11111111,$11111111,$11......,$........ 45 | db $........,$........,$..111111,$1..11111,$11111111,$11111111,$1111....,$........ 46 | db $........,$........,$.....1..,$...11111,$11111111,$11111111,$11......,$........ 47 | db $........,$........,$........,$...11111,$11111111,$11111111,$111.....,$........ 48 | db $........,$........,$........,$.....111,$11111111,$11111111,$11......,$........ 49 | db $........,$........,$........,$......11,$11111111,$11111111,$1.......,$........ 50 | db $........,$........,$........,$......11,$11111111,$11111111,$1.......,$........ 51 | db $........,$........,$........,$.......1,$1.111111,$1111.1..,$........,$........ 52 | db $........,$........,$........,$.......1,$......11,$11......,$........,$........ 53 | db $........,$........,$........,$........,$......11,$11......,$........,$........ 54 | db $........,$........,$........,$........,$......11,$11......,$........,$........ 55 | db $........,$........,$........,$........,$.......1,$1.......,$........,$........ 56 | db $........,$........,$........,$........,$........,$........,$........,$........ 57 | db $........,$........,$........,$........,$........,$........,$........,$........ 58 | -------------------------------------------------------------------------------- /tortilla8/cilantro.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | 3 | from . import export 4 | from .constants.preprocessor import END_MEM_TAG, PRE_PROC, DATA_DECLARE 5 | from .constants.symbols import BEGIN_COMMENT 6 | from .constants.opcodes import OP_CODES 7 | __all__ = [] 8 | 9 | @export 10 | class Cilantro: 11 | ''' 12 | Lexer/tokenizer for Chip 8 instructions. Used by Blackbean (assembler) 13 | and Jalapeno (pre-processor). 14 | ''' 15 | 16 | def __init__(self, line, line_number): 17 | """ 18 | Intializes by parsing the line and storing the line_number. 19 | The object is then used as a data container for Blackbean. 20 | """ 21 | self.is_empty = True #Default, is blank or comment only 22 | self.original = line #whole, unedited, line 23 | self.comment = "" #comment on the line 24 | self.mem_tag = "" #tag/label for the line, no ":" 25 | self.mem_address = 0 #address 26 | self.line_numb = line_number #1 index line number 27 | 28 | self.pp_directive = "" #pre-procs directive on the line 29 | self.pp_args = [] #arguments after or surounding a pp directive 30 | self.pp_line = "" #line with pp applied 31 | 32 | self.data_declarations = [] #list of strings in original form 33 | self.data_size = 0 #size (in bytes) of data defined on line 34 | self.dd_ints = [] #ints for machine code of size dataType 35 | 36 | self.instruction = "" #"cls", "ret" etc 37 | self.arguments = [] #list of args in original form 38 | self.instruction_int = None #single int for machine code 39 | 40 | line = line.lstrip() 41 | 42 | # Remove Blanks 43 | if line.isspace() or not line: 44 | return 45 | 46 | # Remove Comment only lines 47 | if line.lstrip().startswith(BEGIN_COMMENT): 48 | self.comment = line.rstrip() 49 | return 50 | 51 | self.is_empty = False 52 | 53 | # Check for any comments 54 | self.comment = ''.join(line.split(BEGIN_COMMENT)[1:]) 55 | line = line.split(BEGIN_COMMENT)[0].rstrip() 56 | 57 | # Breakout into array 58 | line_array = line.lower().split() 59 | 60 | # Check if tag exists, must be left most 61 | if line_array[0].endswith(END_MEM_TAG): 62 | self.mem_tag = line_array[0][:-1] 63 | line_array.pop(0) 64 | if not line_array: 65 | return 66 | 67 | # If there are additional tags raise error 68 | if END_MEM_TAG in ''.join(line_array): 69 | raise RuntimeError("Multiple Memory Tags found on line " + str(self.line_numb)) 70 | 71 | # Check for any pre-processor commands 72 | for i,word in enumerate(line_array): 73 | if word in PRE_PROC: 74 | self.pp_directive = word 75 | line_array.pop(i) 76 | self.pp_args = line_array 77 | return 78 | 79 | # Check for data declarations 80 | if line_array[0] in DATA_DECLARE: 81 | self.data_size = DATA_DECLARE[line_array[0]] 82 | line_array.pop(0) 83 | if not line_array: 84 | raise RuntimeError("Expected data declaration on line " + str(self.line_numb)) 85 | self.data_declarations = ''.join(line_array).split(',') 86 | return 87 | 88 | # Check for assembly instruction 89 | if line_array[0] in OP_CODES: 90 | self.instruction = line_array[0] 91 | line_array.pop(0) 92 | self.arguments = [] 93 | if line_array: 94 | self.arguments = ''.join(line_array).split(',') 95 | return 96 | 97 | # Trash 98 | raise RuntimeError("Cannot parse line " + str(self.line_numb)) 99 | -------------------------------------------------------------------------------- /roms/vertical_stripes_pp.asm: -------------------------------------------------------------------------------- 1 | ; Vertical Strip Test Rom for CHIP 8 2 | ; 3 | ; Displays alternating stripes on the screen in a variety 4 | ; of ways then spins, rom must be terminated manually. 5 | ; Pre-Processor directives are only here for testing and 6 | ; can be removed. 7 | ; 8 | ; Licensed under GPLv3, Adam Nunez 9 | ; Apart of the tortilla 8 project 10 | ; 11 | 12 | 13 | 14 | ; Vertical stripes, one at a time 15 | call reset 16 | ld i, stripe ; Load stripe for drawing 17 | test1: 18 | drw va, vb, 1 ; Draw a 1px tall, 8px wide block 19 | add va, 8 ; Inc x by 1 byte 20 | se va, 64 ; If x == 64, skip jp 21 | jp test1 ; Jump back to draw rest of line 22 | ld va, 0 ; reset va 23 | add vb, 2 ; Inc y by 2 24 | se vb, 32 ; If y == 32, skip jp 25 | jp test1 ; Jump back to draw another line 26 | 27 | 28 | ; Vertical stripes, several at a time (8x8) 29 | call reset 30 | ld i, block ; Load block for drawing 31 | test2: 32 | drw va, vb, 8 ; Draw a 8px tall, 8px wide block 33 | add va, 8 ; Inc x by 1 byte 34 | se va, 64 ; If x == 64, skip jp 35 | jp test2 ; Jump back to draw rest of line 36 | ld va, 0 ; reset va 37 | add vb, 8 ; Inc y by 8, the height of the block 38 | se vb, 32 ; If y == 32, skip jp 39 | jp test2 ; Jump back to draw another line 40 | 41 | 42 | ; Checker board, 4x4 at a time 43 | call reset 44 | ld i, checker ; Load block for drawing 45 | test3: 46 | drw va, vb, 4 ; Draw a 4px tall, 8px wide block 47 | add va, 8 ; Inc x by a byte 48 | se va, 64 ; If x == 64, skip jp 49 | jp test3 ; Jump back to draw rest of line 50 | ld va, 0 ; reset va 51 | add vb, 4 ; Inc y by 4, the height of the block 52 | se vb, 32 ; If y == 32, skip jp 53 | jp test3 ; Jump back to draw another line 54 | 55 | 56 | ; Paint solid white, 8x8 at a time 57 | call reset 58 | ld i, largestripe ; Load thick stripe 59 | test4: 60 | drw va, vb, 8 ; Draw a 8px tall, 8px wide block 61 | add va, 8 ; Inc x by a byte 62 | se va, 64 ; If x == 64, skip jp 63 | jp test4 ; Jump back to draw rest of line 64 | ld va, 0 ; reset va 65 | add vb, 8 ; Inc y by 8, the height of the block 66 | se vb, 32 ; If y == 32, skip jp 67 | jp test4 ; Jump back to draw another line 68 | 69 | 70 | ; Re paint Checker board, 4x4 at a time, skipping reset to test XOR 71 | ld va, 0 ; Initial X cord 72 | ld vb, 0 ; Initial Y cord 73 | ld i, checker ; Load block for drawing 74 | test5: 75 | drw va, vb, 4 ; Draw a 4px tall, 8px wide block 76 | add va, 8 ; Inc x by a byte 77 | se va, 64 ; If x == 64, skip jp 78 | jp test5 ; Jump back to draw rest of line 79 | ld va, 0 ; reset va 80 | add vb, 4 ; Inc y by 4, the height of the block 81 | se vb, 32 ; If y == 32, skip jp 82 | jp test5 ; Jump back to draw another line 83 | 84 | spin: 85 | jp spin ; Spin forever 86 | 87 | reset: 88 | cls 89 | ld va, 0 ; Initial X cord 90 | ld vb, 0 ; Initial Y cord 91 | ret 92 | 93 | stripe: 94 | db #ff 95 | 96 | largestripe: 97 | db #ff,#ff,#ff,#ff,#ff,#ff,#ff,#ff 98 | 99 | block: 100 | db #00,#ff,#00,#ff,#00,#ff,#00,#ff 101 | 102 | checker: 103 | db #AA,#55,#AA,#55 104 | 105 | dd #00000000 ; Useless padding 106 | -------------------------------------------------------------------------------- /roms/vertical_stripes.asm: -------------------------------------------------------------------------------- 1 | ; Vertical Strip Test Rom for CHIP 8 2 | ; 3 | ; Displays alternating stripes on the screen in a variety 4 | ; of ways then spins, rom must be terminated manually. 5 | ; Pre-Processor directives are only here for testing and 6 | ; can be removed. 7 | ; 8 | ; Licensed under GPLv3, Adam Nunez 9 | ; Apart of the tortilla 8 project 10 | ; 11 | 12 | solid EQU #ff ; Testing replacment 13 | blank EQU #00 ; Testing replacment 14 | 15 | 16 | ; Vertical stripes, one at a time 17 | call reset 18 | ld i, stripe ; Load stripe for drawing 19 | test1: 20 | drw va, vb, 1 ; Draw a 1px tall, 8px wide block 21 | add va, 8 ; Inc x by 1 byte 22 | se va, 64 ; If x == 64, skip jp 23 | jp test1 ; Jump back to draw rest of line 24 | ld va, 0 ; reset va 25 | add vb, 2 ; Inc y by 2 26 | se vb, 32 ; If y == 32, skip jp 27 | jp test1 ; Jump back to draw another line 28 | 29 | 30 | ; Vertical stripes, several at a time (8x8) 31 | call reset 32 | ld i, block ; Load block for drawing 33 | test2: 34 | drw va, vb, 8 ; Draw a 8px tall, 8px wide block 35 | add va, 8 ; Inc x by 1 byte 36 | se va, 64 ; If x == 64, skip jp 37 | jp test2 ; Jump back to draw rest of line 38 | ld va, 0 ; reset va 39 | add vb, 8 ; Inc y by 8, the height of the block 40 | se vb, 32 ; If y == 32, skip jp 41 | jp test2 ; Jump back to draw another line 42 | 43 | 44 | ; Checker board, 4x4 at a time 45 | call reset 46 | ld i, checker ; Load block for drawing 47 | test3: 48 | drw va, vb, 4 ; Draw a 4px tall, 8px wide block 49 | add va, 8 ; Inc x by a byte 50 | se va, 64 ; If x == 64, skip jp 51 | jp test3 ; Jump back to draw rest of line 52 | ld va, 0 ; reset va 53 | add vb, 4 ; Inc y by 4, the height of the block 54 | se vb, 32 ; If y == 32, skip jp 55 | jp test3 ; Jump back to draw another line 56 | 57 | 58 | ; Paint solid white, 8x8 at a time 59 | call reset 60 | ld i, largestripe ; Load thick stripe 61 | test4: 62 | drw va, vb, 8 ; Draw a 8px tall, 8px wide block 63 | add va, 8 ; Inc x by a byte 64 | se va, 64 ; If x == 64, skip jp 65 | jp test4 ; Jump back to draw rest of line 66 | ld va, 0 ; reset va 67 | add vb, 8 ; Inc y by 8, the height of the block 68 | se vb, 32 ; If y == 32, skip jp 69 | jp test4 ; Jump back to draw another line 70 | 71 | 72 | ; Re paint Checker board, 4x4 at a time, skipping reset to test XOR 73 | ld va, 0 ; Initial X cord 74 | ld vb, 0 ; Initial Y cord 75 | ld i, checker ; Load block for drawing 76 | test5: 77 | drw va, vb, 4 ; Draw a 4px tall, 8px wide block 78 | add va, 8 ; Inc x by a byte 79 | se va, 64 ; If x == 64, skip jp 80 | jp test5 ; Jump back to draw rest of line 81 | ld va, 0 ; reset va 82 | add vb, 4 ; Inc y by 4, the height of the block 83 | se vb, 32 ; If y == 32, skip jp 84 | jp test5 ; Jump back to draw another line 85 | 86 | spin: 87 | jp spin ; Spin forever 88 | 89 | reset: 90 | cls 91 | ld va, 0 ; Initial X cord 92 | ld vb, 0 ; Initial Y cord 93 | ret 94 | 95 | stripe: 96 | db solid 97 | 98 | largestripe: 99 | db solid,solid,solid,solid,solid,solid,solid,solid 100 | 101 | block: 102 | db blank,solid,blank,solid,blank,solid,blank,solid 103 | 104 | checker: 105 | db #AA,#55,#AA,#55 106 | 107 | ifdef something 108 | ; Stuff to be thrown away 109 | else 110 | dd #00000000 ; Useless padding 111 | endif 112 | -------------------------------------------------------------------------------- /tortilla8/jalapeno.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | 3 | from . import export 4 | from .cilantro import Cilantro 5 | from .constants.symbols import BEGIN_COMMENT 6 | from .constants.preprocessor import MODE_MARKS, EQU_MARKS, ELSE_IF, END_MARKS 7 | __all__ = [] 8 | 9 | #TODO Respect MODE_MARKS and add common directives to it. 10 | #TODO Remove excess whitespace when its around pre-proc directives 11 | 12 | @export 13 | class Jalapeno: 14 | """ 15 | Jalapeno is a pre-processor class that can take file handlers, 16 | process all common chip8 pre processor directives and return 17 | a flattend source file. 18 | """ 19 | 20 | def __init__(self, file_handler=None, definitions=None): 21 | """ 22 | Init the token collection and symbols list. 23 | """ 24 | self.collection = [] 25 | self.symbols = {} 26 | 27 | if file_handler: 28 | self.process(file_handler, definitions) 29 | 30 | def reset(self): 31 | """ 32 | Reset the pre-processor to process another file. 33 | """ 34 | self.__init__(self) 35 | 36 | def process(self, file_handler, definitions=None): 37 | """ 38 | Flattens all if/else/elif etc and replaces EQU directives for a file. 39 | Stores to the lexer class under cilantro.pp_line 40 | Does not currently support any option or mode directives. 41 | """ 42 | skipping_lines = False 43 | awaiting_end = False 44 | if definitions is None: 45 | definitions = [] 46 | 47 | # Flatten all IF/ELSE/ETC directives - Pass One 48 | for i,line in enumerate(file_handler): 49 | t = Cilantro(line, i) 50 | 51 | if skipping_lines: 52 | if (t.pp_directive in ('endif','else')) or\ 53 | (t.pp_directive in ELSE_IF and t.pp_args[0] in definitions): 54 | skipping_lines = False 55 | awaiting_end = True 56 | continue 57 | 58 | if not t.pp_directive: 59 | self.collection.append(t) 60 | continue 61 | 62 | if awaiting_end and t.pp_directive in END_MARKS: 63 | awaiting_end = False 64 | continue 65 | 66 | if t.pp_directive == 'ifdef': 67 | if t.pp_args[0] in definitions: 68 | awaiting_end = True 69 | else: 70 | skipping_lines = True 71 | continue 72 | 73 | if t.pp_directive == 'ifndef': 74 | if t.pp_args[0] not in definitions: 75 | awaiting_end = True 76 | else: 77 | skipping_lines = True 78 | continue 79 | 80 | if t.pp_directive in MODE_MARKS: 81 | continue #TODO Throw away for now 82 | 83 | if t.pp_directive in EQU_MARKS: 84 | self.symbols[t.pp_args[0]] = t.pp_args[1] 85 | continue 86 | 87 | self.collection.append(t) 88 | 89 | # Replace Symbols ( EQU and '=' ) and set pp_line - Pass Two 90 | for sym in self.symbols: 91 | for tl in self.collection: 92 | 93 | if not tl.pp_line: 94 | tl.pp_line = tl.original 95 | 96 | iterator = tl.arguments if tl.arguments != [] else tl.data_declarations 97 | for i,arg in enumerate(iterator): 98 | if arg == sym: 99 | if tl.arguments != []: 100 | tl.arguments[i] = self.symbols[sym] 101 | else: 102 | tl.data_declarations[i] = self.symbols[sym] 103 | tl.pp_line = tl.pp_line.replace(sym, self.symbols[sym]) 104 | if tl.pp_line.find(BEGIN_COMMENT) != -1: 105 | tl.pp_line = tl.pp_line.split(BEGIN_COMMENT)[0] + BEGIN_COMMENT + tl.comment 106 | 107 | def print_processed_source(self, file_handler=None): 108 | """ 109 | Print flattened source code to stdout or file handler. 110 | """ 111 | for tl in self.collection: 112 | if file_handler is None: 113 | print(tl.pp_line, end='') 114 | else: 115 | file_handler.write(tl.pp_line) 116 | 117 | 118 | 119 | 120 | -------------------------------------------------------------------------------- /minimized/chip8/display.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | 3 | # Import curses 4 | try: import curses 5 | except ImportError: 6 | raise ImportError("Curses is missing from your system! ") 7 | 8 | # Import Sound (optional) 9 | try: import simpleaudio as sa 10 | except ImportError: sa = None 11 | 12 | # Everything else 13 | from os import path 14 | from sys import platform 15 | from time import time, sleep 16 | from .emulator import Emulator 17 | from collections import namedtuple 18 | 19 | CHAR_SET = namedtuple('CHAR_SET', 'upper lower both empty') 20 | 21 | class Display: 22 | 23 | UNICODE_DRAW = CHAR_SET('▀','▄','█',' ') 24 | WIN_DRAW = CHAR_SET('*','o','8',' ') 25 | 26 | KEY_EXIT = 107 # k 27 | KEY_CONTROLS={ 28 | 120:0x0, 49:0x1, 50:0x2, 51:0x3, # 1 2 3 4 29 | 113:0x4, 119:0x5, 101:0x6, 97:0x7, # q w e r 30 | 115:0x8, 100:0x9, 52:0xA, 114:0xB, # a s d f 31 | 102:0xC, 118:0xD, 122:0xE, 99:0xF} # z x c v 32 | 33 | def __init__(self, rom, cpuhz, audiohz, delayhz, drawfix, enable_unicode, wave_file=None): 34 | 35 | # Check if windows (no unicode in their Curses) 36 | self.screen_unicode = enable_unicode 37 | self.draw_char = Display.UNICODE_DRAW if enable_unicode else Display.WIN_DRAW 38 | 39 | # Init Curses 40 | self.screen = curses.initscr() 41 | self.screen.clear() 42 | 43 | # Used for graphics "smoothing" w/ -d flag 44 | self.draw_fix = drawfix 45 | self.prev_board=[0x00]*Emulator.GFX_RESOLUTION 46 | 47 | # General Prep 48 | self.window = curses.newwin( int(Emulator.GFX_HEIGHT_PX/2)+2, Emulator.GFX_WIDTH_PX+2, 0, 0) 49 | self.window.nodelay(1) 50 | self.window.clear() 51 | self.window.refresh() 52 | self.window.border() 53 | 54 | # Load default sound 55 | self.wave_obj = None 56 | if not wave_file: 57 | wave_file = path.join('play.wav') 58 | 59 | # Init sound if available 60 | elif wave_file.lower() != 'off': 61 | try: 62 | self.wave_obj = sa.WaveObject.from_wave_file(wave_file) 63 | self.play_obj = None 64 | self.audio_playing = False 65 | except FileNotFoundError: 66 | pass 67 | 68 | # Init the emulator 69 | self.emu = Emulator(rom, cpuhz, audiohz, delayhz) 70 | 71 | # Curses settings 72 | curses.noecho() 73 | curses.cbreak() 74 | curses.curs_set(0) 75 | 76 | def start(self): 77 | halt = False 78 | key_press_time = 0 79 | previous_pc = 0 80 | 81 | try: 82 | while True: 83 | 84 | # Grab key 85 | key = self.window.getch() 86 | 87 | # Update Keypad press 88 | if time() - key_press_time > 0.5: #TODO Better input? 89 | self.emu.prev_keypad = 0 90 | self.emu.keypad = [False] * 16 91 | key_press_time = time() 92 | if key in Display.KEY_CONTROLS: 93 | self.emu.keypad[Display.KEY_CONTROLS[key]] = True 94 | 95 | # Exit check 96 | if key == Display.KEY_EXIT: 97 | break 98 | 99 | # Try to tick the cpu 100 | if not halt: 101 | self.emu.run() 102 | 103 | # Update Display if we executed 104 | if self.emu.program_counter != previous_pc: 105 | previous_pc = self.emu.program_counter 106 | self.display_game() 107 | curses.doupdate() 108 | 109 | # Detect jp Spinning 110 | elif not halt and self.emu.spinning: 111 | halt = True 112 | 113 | # Start/stop Audio 114 | if sa is not None and self.wave_obj is not None: 115 | self.audio_playing = False if self.emu.sound_timer_register == 0 else True 116 | if not self.audio_playing and self.play_obj is None: 117 | pass 118 | elif self.audio_playing and self.play_obj is None: 119 | self.play_obj = self.wave_obj.play() 120 | elif not self.audio_playing and self.play_obj is not None: 121 | self.play_obj.stop() 122 | self.play_obj = None 123 | elif self.audio_playing and not self.play_obj.is_playing(): 124 | self.play_obj = self.wave_obj.play() 125 | 126 | # Don't waste too many cycles 127 | sleep(self.emu.cpu_wait * 0.25) 128 | 129 | except KeyboardInterrupt: 130 | return 131 | except: 132 | raise 133 | finally: 134 | curses.nocbreak() 135 | curses.echo() 136 | curses.endwin() 137 | 138 | def display_game(self): 139 | if not self.emu.draw_flag: return 140 | self.emu.draw_flag = False 141 | 142 | if self.draw_fix: 143 | prev_str = "" 144 | curr_str = "" 145 | for val in self.prev_board: 146 | prev_str += bin(val)[2:].zfill(8) 147 | for val in self.emu.ram[Emulator.GFX_ADDRESS:Emulator.GFX_ADDRESS+Emulator.GFX_RESOLUTION]: 148 | curr_str += bin(val)[2:].zfill(8) 149 | int_prev = int(prev_str,2) 150 | int_curr = int(curr_str,2) 151 | self.prev_board = self.emu.ram[Emulator.GFX_ADDRESS:Emulator.GFX_ADDRESS+Emulator.GFX_RESOLUTION] 152 | if ( ( int_prev ^ int_curr ) & int_prev ) == ( int_prev ^ int_curr ): 153 | #Only 1s were changed to 0s, skip the draw to prevent SOME flicker 154 | return 155 | 156 | for y in range( int(Emulator.GFX_HEIGHT_PX / 2) ): 157 | for x in range(Emulator.GFX_WIDTH): 158 | upper_chunk = int( bin( self.emu.ram[ Emulator.GFX_ADDRESS + ( (y * 2 + 0) * Emulator.GFX_WIDTH) + x ] )[2:] ) 159 | lower_chunk = int( bin( self.emu.ram[ Emulator.GFX_ADDRESS + ( (y * 2 + 1) * Emulator.GFX_WIDTH) + x ] )[2:].replace('1','2') ) 160 | total_chunk = str(upper_chunk + lower_chunk).zfill(8) \ 161 | .replace('3', self.draw_char.both ).replace('2', self.draw_char.lower ) \ 162 | .replace('1', self.draw_char.upper ).replace('0', self.draw_char.empty ) 163 | self.window.addstr( 1+y, 1+x*8, total_chunk ) 164 | self.window.noutrefresh() 165 | 166 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # tortilla8 2 | 3 | Tortilla8 is a collection of Chip8 tools for per-processing, assembling, emulating, disassembling, and visualizing Chip8 ROMs. 4 | 5 | ## What is Chip8 6 | 7 | [Chip8](https://en.wikipedia.org/wiki/CHIP-8) is a language published in 1978 via the RCA COSMAC VIP Instruction Manual that was bosted as making game programming easier for hobbiests on the system. Chip8 is popular to emulate due to its simplicity and the now extensive amount of documentation. Unfortunately there are some issues with Chip8 emulations, notably that there were differing implementations early on. These differences have been very well documented [here](https://github.com/Chromatophore/HP48-Superchip#behavior-and-quirk-investigations). Some of these isuses are addressed in tortilla8, but some are not as I have yet to encounter them for myself. 8 | 9 | ## Known Issues 10 | 11 | * No docs for modules 12 | * Platter: keypad input could be better 13 | * Platter: controls can't be edited 14 | * Platter: rewinding while waiting for key input (ld reg, k) causes odd behavior 15 | * Jalapeno: does not remove extra whitespace due to removing 'junk' lines 16 | * Nacho: still under development 17 | 18 | ## Setup 19 | 20 | Setup is strait forward, two dependencies are used for the text based gui (platter), Simple Audio and Curses, the later of which is discussed in detail below for specifc OSes. 21 | 22 | ``` 23 | # If you haven't installed pip, do that 24 | python -m pip install -U pip setuptools 25 | # Navigate to the root of the package 26 | # Install tortiall8 27 | pip install . 28 | # Install Simple Audio (optional) 29 | pip install simpleaudio 30 | ``` 31 | 32 | ## Demo 33 | 34 | After insallation you can pre-processes, assemble, and emulate the any of the provided ROMs (or your own) by... 35 | ``` 36 | tortilla8 pre-process roms/vertical_stripes.asm 37 | tortilla8 assemble roms/vertical_stripes_pp.asm -o roms/demo 38 | tortilla8 emulate roms/demo.ch8 -f 150 39 | ``` 40 | 41 | ![tortillas are made into chips, get it?](https://github.com/aanunez/tortilla8/raw/master/docs/platter_demo1.png "Platter running vertical_stripes.ch8") 42 | 43 | You can also start Nacho (the tkinter based GUI) by invoking `tortilla8` without arguments. 44 | 45 | ![Super cool GUI](https://github.com/aanunez/tortilla8/raw/master/docs/nacho_demo1.png "Nacho running a UFO game.") 46 | 47 | ## Usage 48 | 49 | The main entry point after install is `tortilla8`, which has five options: assemble, disassemble, pre-process, execute, and emulate. More information for each can be found via tortilla8's help menus. 50 | 51 | ``` 52 | usage: tortilla8 [-h] {pre-process,assemble,disassemble,execute,emulate} ... 53 | 54 | A collection of Chip8 tools for pre-processing, assembling, emulating, 55 | disassembling, and visualizing Chip8 ROMs. Call with no arguments to start the 56 | tortilla8 GUI, Nacho! 57 | 58 | positional arguments: 59 | {pre-process,assemble,disassemble,execute,emulate} 60 | Options for tortilla8... 61 | pre-process Scan your CHIP-8 source code for pre-processor 62 | directives, apply them as needed, and produce a 63 | flattend source file. Respected Directives are: 64 | 'ifdef', 'ifndef', 'elif', 'elseif', 65 | 'elifdef','elseifdef', 'endif', 'else', 'equ', '='. 66 | Currently, no mode modifers ('option', 'align' etc) 67 | are respected. 68 | assemble Assemble your CHIP-8 programs to executable machine 69 | code. Listing files and comment-striped files can also 70 | be generated. Arguments to mnemonics must be either be 71 | integers in decimal or hex using '#' as a prefix. Data 72 | declares may also be prefixed with '$' to denote 73 | binary (i.e. '$11001100' or '$11..11..'). 74 | disassemble Dissassemble a Chip8 ROM, any byte pair that is not an 75 | instruction is assumed to be a data declaration. No 76 | checks are performed to insure the program is valid. 77 | execute Execute a rom to quickly check for errors. The program 78 | counter, hex instruction (the two bytes that make up 79 | the opcode), and mnemonic are printed to the screen 80 | immediately after the execution of that operation 81 | code. All errors (info, warning, and fatal) are 82 | printed to screen. 83 | emulate Start a text (unicode) based Chip8 emulator which 84 | disaplys a game screen, all registers, the stack, 85 | recently processed instructions, and a console to log 86 | any issues that occur. 87 | 88 | optional arguments: 89 | -h, --help show this help message and exit 90 | ``` 91 | 92 | ## Modules 93 | 94 | ### Cilantro 95 | 96 | A lexer/tokenizer used by blackbean and jalapeno for individual lines of Chip8 assembly. The initialiser does the tokenizing, the class is then used as a data container that can be populated later for information only the assembler or pre-proccessor would know. 97 | 98 | ### Jalapeno 99 | 100 | Pre-Processor used to flatten files before running them through blackbean. Currently strips "mode" and "option" directives without respecting them. Repects options such as "if" and "else". 101 | 102 | ### Blackbean 103 | 104 | An assembler that can generate Chip8 roms, comment-stripped Chip8 assembly, or a listing file (asm with memory addresses). The assembler makes no attempt to insure that illegal calls are not made or that the VF register isn't set. 105 | 106 | ### Salsa 107 | 108 | Disassembler function for two bytes worth of data. If the input is not a valid instruction then it is assumed to be a data declaration. 109 | 110 | ### Guacamole 111 | 112 | Emulator for the Chip8 language/system. The emulator has no display, for that you should use platter or nacho. There are currently no known major bugs in guacamole, however there are oddoties in Chip-8 in general (see abve in the 'What is Chip8' section). Guacamole makes use of two other modules: 'emulation_error' which houses a simple enum to determine the severity of an error that occured within the emulation and not one raised by python, and 'instructions' which contains a function for every Chip-8 opcode. 113 | 114 | ### Platter 115 | 116 | Text based GUI for Guacamole that requires curses and simpleaudio, see below for any issues with your OS. Display information, warnings, and fatal errors reported by the emulator along with all registers, the stack, and recently executed instructions. Detects when the emulator enters a "spin" state and gives the option of reseting. Press the underlined (on GNU/Linux) or uppercase (Mac/Windows) to perform the menu actions (i.e. Stepping through the program, exiting) and use the arrow keys to control the rewind size (Left/Right) and emulation target frequency (Up/Down). 117 | 118 | ### Nacho 119 | 120 | Tkinter based GUI for easily playing Chip8 that is still being developed. If you have an issue using sound in Nacho on GNU/Linux, speciffically with installing SimpleAudio, please try to install both the python3 dev tools and the libasound dev libraray. 121 | 122 | ``` 123 | apt install python3-dev 124 | apt install libasound2-dev 125 | 126 | ``` 127 | 128 | ## Platter Compatability (Curses) 129 | 130 | ### Running on GNU/Linux, BSD variants 131 | 132 | The Curses module ships with your python install, I have had no issues thus far. Some terminals will not correctly display some unicode characters, you can use either use the '-u' flag to disable unicode if that is the case. 133 | 134 | ### Running on Windows 135 | 136 | Python for Windows does not ship with Curses, which is needed by platter, so you'll need install the wheel package yourself from [here](http://www.lfd.uci.edu/~gohlke/pythonlibs/). The 'cp34' (CPython 3.4) was tested on Windows 7. Once the package is downloaded, just cd to the directory and install via pip. 137 | ``` 138 | :: If you haven't installed Wheel, do that 139 | pip install wheel 140 | :: Install Curses for win32 141 | python -m pip install curses-2.2-cp34-none-win32.whl 142 | ``` 143 | Unfortunately the windows version of curses doesn't support unicode, so the game display in Platter is 'unique'. 144 | 145 | ### Running on Mac OS X 146 | 147 | The Curses module ships with your python install, however the mac default terminal does not correctly display unicode underline characters. Instead a version is shown where the uppercase letters are the hot-keys to perform the action. 148 | 149 | -------------------------------------------------------------------------------- /tortilla8/instructions.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | 3 | from random import randint 4 | from . import EmulationError 5 | from .constants.reg_rom_stack import STACK_ADDRESS, STACK_SIZE 6 | from .constants.graphics import GFX_FONT_ADDRESS, GFX_RESOLUTION, GFX_ADDRESS, \ 7 | GFX_WIDTH, GFX_HEIGHT_PX, GFX_WIDTH_PX, \ 8 | SET_VF_ON_GFX_OVERFLOW 9 | 10 | # Instructions - All 20 mnemonics, 35 total instructions 11 | # Add-3 SE-2 SNE-2 LD-11 JP-2 (mnemonics w/ extra instructions) 12 | 13 | def i_cls(emu): 14 | emu.ram[GFX_ADDRESS:GFX_ADDRESS + GFX_RESOLUTION] = [0x00] * GFX_RESOLUTION 15 | emu.draw_flag = True 16 | 17 | def i_ret(emu): 18 | emu.stack_pointer -= 1 19 | if emu.stack_pointer < 0: 20 | emu.log("Stack underflow", EmulationError._Fatal) 21 | emu.program_counter = emu.stack.pop() 22 | 23 | def i_sys(emu): 24 | emu.log("RCA 1802 call to " + hex( get_address(emu) ) + " was ignored.", EmulationError._Warning) 25 | 26 | def i_call(emu): 27 | if STACK_ADDRESS: 28 | emu.ram[stack_pointer] = emu.program_counter 29 | emu.stack_pointer += 1 30 | emu.stack.append(emu.program_counter) 31 | if emu.stack_pointer > STACK_SIZE: 32 | emu.log("Stack overflow. Stack is now size " + emu.stack_pointer, EmulationError._Warning) 33 | emu.program_counter = get_address(emu) - 2 34 | 35 | def i_skp(emu): 36 | if emu.keypad[ get_reg1_val(emu) & 0x0F ]: 37 | emu.program_counter += 2 38 | 39 | def i_sknp(emu): 40 | if not emu.keypad[ get_reg1_val(emu) & 0x0F ]: 41 | emu.program_counter += 2 42 | 43 | def i_se(emu): 44 | comp = get_lower_byte(emu) if 'byte' is emu.dis_ins.mnemonic_arg_types[1] else get_reg2_val(emu) 45 | if get_reg1_val(emu) == comp: 46 | emu.program_counter += 2 47 | 48 | def i_sne(emu): 49 | comp = get_lower_byte(emu) if 'byte' is emu.dis_ins.mnemonic_arg_types[1] else get_reg2_val(emu) 50 | if get_reg1_val(emu) != comp: 51 | emu.program_counter += 2 52 | 53 | def i_shl(emu): 54 | if emu.legacy_shift: 55 | emu.register[0xF] = 0x01 if get_reg2_val(emu) >= 0x80 else 0x0 56 | emu.register[ get_reg1(emu) ] = ( get_reg2_val(emu) << 1 ) & 0xFF 57 | else: 58 | emu.register[0xF] = 0x01 if get_reg1_val(emu) >= 0x80 else 0x0 59 | emu.register[ get_reg1(emu) ] = ( get_reg1_val(emu) << 1 ) & 0xFF 60 | 61 | def i_shr(emu): 62 | if emu.legacy_shift: 63 | emu.register[0xF] = 0x01 if ( get_reg2_val(emu) % 2) == 1 else 0x0 64 | emu.register[ get_reg1(emu) ] = get_reg2_val(emu) >> 1 65 | else: 66 | emu.register[0xF] = 0x01 if ( get_reg1_val(emu) % 2) == 1 else 0x0 67 | emu.register[ get_reg1(emu) ] = get_reg1_val(emu) >> 1 68 | 69 | def i_or(emu): 70 | emu.register[ get_reg1(emu) ] = get_reg1_val(emu) | get_reg2_val(emu) 71 | 72 | def i_and(emu): 73 | emu.register[ get_reg1(emu) ] = get_reg1_val(emu) & get_reg2_val(emu) 74 | 75 | def i_xor(emu): 76 | emu.register[ get_reg1(emu) ] = get_reg1_val(emu) ^ get_reg2_val(emu) 77 | 78 | def i_sub(emu): 79 | emu.register[0xF] = 0x01 if get_reg1_val(emu) >= get_reg2_val(emu) else 0x00 80 | emu.register[ get_reg1(emu) ] = get_reg1_val(emu) - get_reg2_val(emu) 81 | emu.register[ get_reg1(emu) ] &= 0xFF 82 | 83 | def i_subn(emu): 84 | emu.register[0xF] = 0x01 if get_reg2_val(emu) >= get_reg1_val(emu) else 0x00 85 | emu.register[ get_reg1(emu) ] = get_reg2_val(emu) - get_reg1_val(emu) 86 | emu.register[ get_reg1(emu) ] &= 0xFF 87 | 88 | def i_jp(emu): 89 | init_pc = emu.program_counter 90 | numb_args = len(emu.dis_ins.mnemonic_arg_types) 91 | 92 | if 'v0' is emu.dis_ins.mnemonic_arg_types[0] and numb_args == 2: 93 | emu.program_counter = get_address(emu) + emu.register[0] - 2 94 | elif numb_args == 1: 95 | emu.program_counter = get_address(emu) - 2 96 | else: 97 | emu.log("Unknown argument at address " + hex(emu.program_counter), EmulationError._Fatal) 98 | 99 | if init_pc == emu.program_counter + 2: 100 | emu.spinning = True 101 | 102 | def i_rnd(emu): 103 | emu.register[ get_reg1(emu) ] = randint(0, 255) & get_lower_byte(emu) 104 | 105 | def i_add(emu): 106 | arg1 = emu.dis_ins.mnemonic_arg_types[0] 107 | arg2 = emu.dis_ins.mnemonic_arg_types[1] 108 | 109 | if 'reg' is arg1: 110 | 111 | if 'byte' is arg2: 112 | emu.register[ get_reg1(emu) ] = get_reg1_val(emu) + get_lower_byte(emu) 113 | emu.register[ get_reg1(emu) ] &= 0xFF 114 | elif 'reg' is arg2: 115 | emu.register[ get_reg1(emu) ] = get_reg1_val(emu) + get_reg2_val(emu) 116 | emu.register[0xF] = 0x01 if emu.register[ get_reg1(emu) ] > 0xFF else 0x00 117 | emu.register[ get_reg1(emu) ] &= 0xFF 118 | else: 119 | emu.log("Unknown argument at address " + hex(emu.program_counter), EmulationError._Fatal) 120 | 121 | elif 'i' in arg1 and 'reg' is arg2: 122 | emu.index_register += get_reg1_val(emu) 123 | if (emu.index_register > 0xFF) and SET_VF_ON_GFX_OVERFLOW: 124 | emu.register[0xF] = 0x01 125 | emu.index_register &= 0xFFF 126 | 127 | else: 128 | emu.log("Unknown argument at address " + hex(emu.program_counter), EmulationError._Fatal) 129 | 130 | def i_ld(emu): 131 | arg1 = emu.dis_ins.mnemonic_arg_types[0] 132 | arg2 = emu.dis_ins.mnemonic_arg_types[1] 133 | 134 | if 'reg' is arg1: 135 | if 'byte' is arg2: 136 | emu.register[ get_reg1(emu) ] = get_lower_byte(emu) 137 | elif 'reg' is arg2: 138 | emu.register[ get_reg1(emu) ] = get_reg2_val(emu) 139 | elif 'dt' is arg2: 140 | emu.register[ get_reg1(emu) ] = emu.delay_timer_register 141 | elif 'k' is arg2: 142 | emu.waiting_for_key = True 143 | emu.program_counter -= 2 144 | elif '[i]' == arg2: 145 | emu.register[0: get_reg1(emu) + 1] = emu.ram[ emu.index_register : emu.index_register + get_reg1(emu) + 1] 146 | else: 147 | emu.log("Loads with second argument type '" + arg2 + \ 148 | "' are not supported.", EmulationError._Fatal) 149 | 150 | elif 'reg' is arg2: 151 | if 'dt' is arg1: 152 | emu.delay_timer_register = get_reg1_val(emu) 153 | elif 'st' is arg1: 154 | emu.sound_timer_register = get_reg1_val(emu) 155 | elif 'f' is arg1: 156 | emu.index_register = GFX_FONT_ADDRESS + ( 5 * get_reg1_val(emu) ) 157 | elif 'b' is arg1: 158 | bcd = [int(f) for f in list(str( get_reg1_val(emu) ).zfill(3))] 159 | emu.ram[ emu.index_register : emu.index_register + len(bcd)] = bcd 160 | elif '[i]' == arg1: 161 | emu.ram[ emu.index_register : emu.index_register + get_reg1(emu) + 1] = emu.register[0: get_reg1(emu) + 1] 162 | else: 163 | emu.log("Unknown argument at address " + hex(emu.program_counter), EmulationError._Fatal) 164 | 165 | elif 'i' is arg1 and 'addr' is arg2: 166 | emu.index_register = get_address(emu) 167 | 168 | else: 169 | emu.log("Unknown argument at address " + hex(emu.program_counter), EmulationError._Fatal) 170 | 171 | def i_drw(emu): 172 | emu.draw_flag = True 173 | height = int(emu.dis_ins.hex_instruction[3],16) 174 | x_origin_byte = int( get_reg1_val(emu) / 8 ) % GFX_WIDTH 175 | y_origin_byte = (get_reg2_val(emu) % GFX_HEIGHT_PX) * GFX_WIDTH 176 | shift_amount = get_reg1_val(emu) % GFX_WIDTH_PX % 8 177 | next_byte_offset = 1 if x_origin_byte + 1 != GFX_WIDTH else 1-GFX_WIDTH 178 | 179 | emu.register[0xF] = 0x00 180 | for y in range(height): 181 | sprite = emu.ram[ emu.index_register + y ] << (8-shift_amount) 182 | 183 | working_bytes = ( 184 | GFX_ADDRESS + (( x_origin_byte + y_origin_byte + (y * GFX_WIDTH) ) % GFX_RESOLUTION) , 185 | GFX_ADDRESS + (( x_origin_byte + y_origin_byte + (y * GFX_WIDTH) + next_byte_offset ) % GFX_RESOLUTION) 186 | ) 187 | 188 | original = ( emu.ram[ working_bytes[0] ], emu.ram[ working_bytes[1] ] ) 189 | xor = (original[0]*256 + original[1]) ^ sprite 190 | emu.ram[ working_bytes[0] ], emu.ram[ working_bytes[1] ] = xor >> 8, xor & 0x00FF 191 | 192 | if (bin( ( emu.ram[ working_bytes[0] ] ^ original[0] ) & original[0] ) + \ 193 | bin( ( emu.ram[ working_bytes[1] ] ^ original[1] ) & original[1] )).find('1') != -1: 194 | emu.register[0xF] = 0x01 195 | 196 | # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # 197 | # Hex Extraction 198 | 199 | def get_address(emu): 200 | return int(emu.dis_ins.hex_instruction[1:4], 16) 201 | 202 | def get_reg1(emu): 203 | return int(emu.dis_ins.hex_instruction[1],16) 204 | 205 | def get_reg2(emu): 206 | return int(emu.dis_ins.hex_instruction[2],16) 207 | 208 | def get_reg1_val(emu): 209 | return emu.register[int(emu.dis_ins.hex_instruction[1],16)] 210 | 211 | def get_reg2_val(emu): 212 | return emu.register[int(emu.dis_ins.hex_instruction[2],16)] 213 | 214 | def get_lower_byte(emu): 215 | return int(emu.dis_ins.hex_instruction[2:4], 16) 216 | 217 | 218 | -------------------------------------------------------------------------------- /tortilla8/nacho.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | 3 | from . import Guacamole, EmulationError 4 | from os.path import join as pathjoin 5 | from tkinter import * 6 | from tkinter import filedialog 7 | from webbrowser import open as openweb 8 | 9 | # Import Sound (optional) 10 | try: import simpleaudio as sa 11 | except ImportError: 12 | sa = None 13 | 14 | # TODO Settings windows below 15 | # TODO better error display. 16 | # Display error? 17 | # Doesn't remove itself after error 18 | 19 | class Nacho(Frame): 20 | 21 | TIMER_REFRESH = 17 # 17ms = 60hz 22 | INPUT_REFRESH = 200 # 200ms = 5 Hz 23 | DEFAULT_FREQ = 1000 # Limiting Freq 24 | Y_SIZE = 32 25 | X_SIZE = 64 26 | ABOUT =''' 27 | Tortilla8 is a collection of Chip8 tools tools for per-processing, 28 | assembling, emulating, disassembling, and visualizing Chip8 ROMs 29 | written by Adam Nunez. This software is free, like free speach, 30 | and is licensed under the GPLv3. Feel free to share this program, 31 | make modifications, or suggest fixes via github. 32 | ''' 33 | 34 | def __init__(self): 35 | 36 | # Defaults 37 | self.scale = 18 38 | self.tile_size = (self.scale, self.scale) 39 | self.emu = None 40 | self.prev_screen = 0 41 | self.fatal = False 42 | self.run_time = 1000 # 1000/this = Freq 43 | self.color_border = "white" 44 | self.color_fill = "white" 45 | self.color_back = "black" 46 | self.controls ={ 47 | 'KP_0':0x0, 'KP_1':0x1, 'KP_2':0x2, 'KP_3':0x3, 48 | 'KP_4':0x4, 'KP_5':0x5, 'KP_6':0x6, 'KP_7':0x7, 49 | 'KP_8':0x8, 'KP_9':0x9, 'KP_Divide':0xA, 'KP_Multiply':0xB, 50 | 'KP_Subtract':0xC, 'KP_Add':0xD, 'KP_Enter':0xE, 'KP_Decimal':0xF} 51 | 52 | # Setup audio 53 | self.wave_file = pathjoin('tortilla8','sound','play.wav') 54 | self.audio_on = False 55 | if sa is None: 56 | print("SimpleAudio is missing from your system. You can install it " + \ 57 | "via 'pip install simpleaudio'. Audio has been disabled.") 58 | else: 59 | try: 60 | self.wave_obj = sa.WaveObject.from_wave_file(self.wave_file) 61 | self.play_obj = None 62 | self.audio_playing = False 63 | self.audio_on = True 64 | except FileNotFoundError: 65 | print("An error occured while initalizing audo. Audio has been disabled.") 66 | 67 | # Init TK and canvas 68 | self.root = Tk() 69 | self.root.wm_title("Tortilla8 - A Chip8 Emulator") 70 | self.root.resizable(width=False, height=False) 71 | Frame.__init__(self, self.root) 72 | self.menubar = Menu(self.root) 73 | self.root.config(menu=self.menubar) 74 | self.root.update() 75 | self.screen = Canvas(self.root, width=Nacho.X_SIZE*self.scale, height=Nacho.Y_SIZE*self.scale) 76 | self.screen.create_rectangle( 0, 0, Nacho.X_SIZE*self.scale, Nacho.Y_SIZE*self.scale, fill=self.color_back ) 77 | self.screen.pack() 78 | 79 | # Init TK Vars 80 | self.antiflicker = BooleanVar() 81 | self.antiflicker.set(True) 82 | self.lock_aspect = BooleanVar() 83 | self.lock_aspect.set(True) 84 | 85 | # Bind some functions 86 | self.root.bind("", self.key_down) 87 | self.root.bind("", self.key_up) 88 | self.root.protocol("WM_DELETE_WINDOW", self.on_closing) 89 | 90 | # Populate the 'File' section 91 | filemenu = Menu(self.menubar, tearoff=0) 92 | filemenu.add_command(label="Load Rom", command=self.load) 93 | filemenu.add_command(label="Exit", command=self.on_closing) 94 | self.menubar.add_cascade(label="File", menu=filemenu) 95 | 96 | # Populate the 'Settings' section 97 | setmenu = Menu(self.menubar, tearoff=0) 98 | setmenu.add_command(label="Display", command=self.win_display_settings) 99 | setmenu.add_command(label="Emulation", command=self.win_emu_settings) 100 | if self.audio_on: 101 | setmenu.add_command(label="Audio", command=self.win_audio_settings) 102 | else: 103 | setmenu.add_command(label="Audio", command=self.win_audio_settings, state='disable') 104 | setmenu.add_checkbutton(label="Anti-Flicker", onvalue=True, offvalue=False, variable=self.antiflicker) 105 | self.menubar.add_cascade(label="Settings", menu=setmenu) 106 | 107 | # Populate the 'Help' section 108 | helpmenu = Menu(self.menubar, tearoff=0) 109 | helpmenu.add_command(label="PyPi Index", 110 | command=lambda:openweb("https://pypi.org/project/tortilla8")) 111 | helpmenu.add_command(label="Source Code", 112 | command=lambda:openweb("https://github.com/aanunez/tortilla8")) 113 | helpmenu.add_command(label="About", command=self.window_about) 114 | self.menubar.add_cascade(label="Help", menu=helpmenu) 115 | 116 | def load(self): 117 | file_path = filedialog.askopenfilename() 118 | if file_path: 119 | self.emu = Guacamole(rom=file_path, cpuhz=Nacho.DEFAULT_FREQ, audiohz=60, delayhz=60, 120 | init_ram=True, legacy_shift=False, err_unoffical="None", rewind_frames=0) 121 | self.run_time = 1 # 1khz 122 | self.emu_event() 123 | self.timers_event() 124 | 125 | def set_controls(self, *controls): 126 | tmp = {} 127 | for i, key in enumerate(controls): 128 | tmp[key] = i 129 | self.controls = tmp 130 | 131 | def win_display_settings(self): 132 | # Display Settings TODO 133 | # Scale edit 134 | # Unlock aspect ratio 135 | # Outline Color 136 | # Fill Color 137 | # Background Color 138 | window = Toplevel(self) 139 | window.wm_title("Display Settings") 140 | window.minsize(width=264, height=190) 141 | window.resizable(width=False, height=False) 142 | Checkbutton(window, text="Lock Aspect Ratio", variable=self.lock_aspect).place(x=10, y=15) 143 | Label(window, text="Scale: ").place(x=160, y=16) 144 | e = Entry(window) 145 | e.insert(0, str(self.scale)) 146 | e.place(x=210, y=16, width=40) 147 | Label(window, text="Background").place(x=14, y=65) 148 | Label(window, text="Foreground").place(x=14, y=105) 149 | Label(window, text="Border").place(x=14, y=145) 150 | 151 | def win_emu_settings(self): 152 | # Emulation Settings TODO 153 | # Controls Edit 154 | # CPU Freq edit 155 | # various handles for weird "features" 156 | window = Toplevel(self) 157 | window.resizable(width=False, height=False) 158 | label = Label(window, text="temp") 159 | label.pack(side="top", fill="both", padx=10, pady=10) 160 | 161 | def win_audio_settings(self): 162 | # Audio TODO 163 | # Choose freq 164 | # Custom file 165 | # mute? 166 | window = Toplevel(self) 167 | window.resizable(width=False, height=False) 168 | label = Label(window, text="temp") 169 | label.pack(side="top", fill="both", padx=10, pady=10) 170 | 171 | def window_about(self): 172 | window = Toplevel(self) 173 | window.resizable(width=False, height=False) 174 | label = Label(window, text=' '.join(Nacho.ABOUT.split(' '*11))) 175 | label.pack(side="top", fill="both", padx=10, pady=10) 176 | 177 | def on_closing(self): 178 | self.root.destroy() 179 | 180 | def key_down(self, key): 181 | if self.emu is not None: 182 | val = self.controls.get(key.keysym) 183 | if val: 184 | self.emu.keypad[val] = True 185 | 186 | def key_up(self, key): 187 | if self.emu is not None: 188 | val = self.controls.get(key.keysym) 189 | if val: 190 | self.emu.keypad[val] = False 191 | 192 | def draw(self): 193 | self.screen.delete("all") 194 | self.screen.create_rectangle( 0, 0, Nacho.X_SIZE*self.scale, 195 | Nacho.Y_SIZE*self.scale, fill=self.color_back ) 196 | for i,pix in enumerate(self.emu.graphics()): 197 | if pix: 198 | x = self.scale*(i%Nacho.X_SIZE) 199 | y = self.scale*(i//Nacho.X_SIZE) 200 | self.screen.create_rectangle( x, y, x+self.scale, y+self.scale, 201 | fill=self.color_fill, outline=self.color_border ) 202 | 203 | def timers_event(self): 204 | if (self.emu is not None) and (self.fatal is False): 205 | if self.audio_on: 206 | if self.emu.sound_timer_register != 0: 207 | self.wave_obj.play() 208 | else: 209 | sa.stop_all() 210 | 211 | self.emu.sound_timer_register -= 1 if self.emu.sound_timer_register != 0 else 0 212 | self.emu.delay_timer_register -= 1 if self.emu.delay_timer_register != 0 else 0 213 | 214 | self.root.after(Nacho.TIMER_REFRESH, self.timers_event) 215 | 216 | def emu_event(self): 217 | self.emu.cpu_tick() 218 | 219 | for err in self.emu.error_log: 220 | print( str(err[0]) + ": " + err[1] ) 221 | if err[0] is EmulationError._Fatal: 222 | self.fatal = True 223 | self.emu.error_log = [] 224 | 225 | if self.emu.draw_flag: 226 | self.emu.draw_flag = False 227 | 228 | if not self.antiflicker.get(): 229 | self.draw() 230 | else: 231 | cur_screen = '' 232 | for i,pix in enumerate(self.emu.graphics()): 233 | cur_screen += '1' if pix else '0' 234 | cur_screen = int(cur_screen,2) 235 | 236 | if ( ( self.prev_screen ^ cur_screen ) & self.prev_screen ) != ( self.prev_screen ^ cur_screen ): 237 | self.draw() 238 | self.prev_screen = cur_screen 239 | 240 | if not self.fatal: 241 | self.root.after(self.run_time, self.emu_event) 242 | else: 243 | self.menubar.add_cascade(label="Fatal Error has occured!", menu=Menu(self.menubar, tearoff=0)) 244 | sa.stop_all() 245 | 246 | -------------------------------------------------------------------------------- /tortilla8/__main__.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | 3 | import os 4 | import select 5 | import contextlib 6 | from time import sleep 7 | from sys import platform, argv 8 | from argparse import ArgumentParser, ArgumentTypeError 9 | from .jalapeno import Jalapeno 10 | from .blackbean import Blackbean 11 | from .salsa import Salsa 12 | from .guacamole import Guacamole 13 | from .platter import Platter 14 | from .nacho import Nacho 15 | 16 | def pos_int(value): 17 | ivalue = int(value) 18 | if ivalue < 1: 19 | raise ArgumentTypeError("%s is an invalid positive int value." % value) 20 | return ivalue 21 | 22 | def dissassemble_file(in_handler, out_handler): 23 | byte_list = [] 24 | file_size = os.path.getsize(input_path) 25 | for _ in range(int(file_size/2)): 26 | byte_list[0:2] = [int.from_bytes(in_handler.read(1), 'big') for _ in range(2)] 27 | dis_inis = Salsa(byte_list) 28 | out_handler.write(dis_inis.disassembled_line + '\n') 29 | if file_size % 2 == 1: 30 | out_handler.write(hex(int.from_bytes(in_handler.read(1), 'big'))[2:].zfill(2) + '\n') 31 | 32 | def parse_args(): 33 | parser = ArgumentParser(description= 34 | ''' 35 | A collection of Chip8 tools for pre-processing, assembling, 36 | emulating, disassembling, and visualizing Chip8 ROMs. Call with 37 | no arguments to start the tortilla8 GUI, Nacho! 38 | ''') 39 | subparsers = parser.add_subparsers(dest='option', help= 40 | 'Options for tortilla8...') 41 | 42 | pp_parser = subparsers.add_parser('pre-process',help= 43 | ''' 44 | Scan your CHIP-8 source code for pre-processor directives, apply them as 45 | needed, and produce a flattend source file. Respected Directives are: 46 | 'ifdef', 'ifndef', 'elif', 'elseif', 'elifdef','elseifdef', 'endif', 47 | 'else', 'equ', '='. Currently, no mode modifers ('option', 'align' etc) 48 | are respected. 49 | ''') 50 | pp_parser.add_argument('input', help= 51 | 'File to assemble.') 52 | pp_parser.add_argument('-d','--define',nargs='+',help= 53 | 'Strings to define as true for evaluation of pre-processor directives.') 54 | pp_parser.add_argument('-o','--output',help= 55 | 'File to store processed source to, by default INPUT_pp.asm is used.') 56 | 57 | asm_parser = subparsers.add_parser('assemble', help= 58 | ''' 59 | Assemble your CHIP-8 programs to executable machine code. Listing files and 60 | comment-striped files can also be generated. Arguments to mnemonics must be 61 | either be integers in decimal or hex using '#' as a prefix. Data declares may 62 | also be prefixed with '$' to denote binary (i.e. '$11001100' or '$11..11..'). 63 | ''') 64 | asm_parser.add_argument('input', nargs='?', help= 65 | 'File to assemble.') 66 | asm_parser.add_argument('-o','--output',help= 67 | 'Name of every generated file, will have either "strip", "lst", or "ch8" appended.') 68 | asm_parser.add_argument('-l','--list', help= 69 | 'Generate listing file and store to OUTPUT.lst file.',action='store_true') 70 | asm_parser.add_argument('-s','--strip', help= 71 | 'Strip comments and store to OUTPUT.strip file.',action='store_true') 72 | asm_parser.add_argument('-e','--enforce',action='store_true',help= 73 | 'Force original Chip-8 specification and do not allow SHR, SHL, XOR, or SUBN instructions.') 74 | 75 | dis_parser = subparsers.add_parser('disassemble', help= 76 | ''' 77 | Dissassemble a Chip8 ROM, any byte pair that is not an instruction is assumed 78 | to be a data declaration. No checks are performed to insure the program is 79 | valid. 80 | ''') 81 | dis_parser.add_argument('rom', nargs='?', help= 82 | 'File to disassemble.') 83 | dis_parser.add_argument('-o','--output',help= 84 | 'File to write to.') 85 | 86 | ex_parser = subparsers.add_parser('execute', help= 87 | ''' 88 | Execute a rom to quickly check for errors. The program counter, hex instruction (the two 89 | bytes that make up the opcode), and mnemonic are printed to the screen immediately after 90 | the execution of that operation code. All errors (info, warning, and fatal) are printed 91 | to screen. 92 | ''') 93 | ex_parser.add_argument('rom', help='ROM to load and play.') 94 | ex_parser.add_argument("-f","--frequency", type=pos_int, default=5, help= 95 | 'Frequency (in Hz) to target for CPU.') 96 | ex_parser.add_argument("-st","--soundtimer", type=pos_int, default=60, help= 97 | 'Frequency (in Hz) to target for the audio timmer.') 98 | ex_parser.add_argument("-dt","--delaytimer", type=pos_int, default=60, help= 99 | 'Frequency (in Hz) to target for the delay timmer.') 100 | ex_parser.add_argument('-i','--initram', help= 101 | 'Initialize RAM to all zero values.', action='store_true') 102 | ex_parser.add_argument('-ls','--legacy_shift', help= 103 | 'Use the legacy shift method of bit shift Y and storing to X.', action='store_true') 104 | ex_parser.add_argument("-e","--enforce_instructions", default='None', help= 105 | 'Warning to log if an unoffical instruction is executed. Options: None Info Warning Fatal') 106 | 107 | emu_parser = subparsers.add_parser('emulate', help= 108 | ''' 109 | Start a text (unicode) based Chip8 emulator which disaplys a game screen, all 110 | registers, the stack, recently processed instructions, and a console to log 111 | any issues that occur. 112 | ''') 113 | emu_parser.add_argument('rom', help= 114 | 'ROM to load and play.') 115 | group = emu_parser.add_mutually_exclusive_group() 116 | group.add_argument('-f','--frequency', type=pos_int, default=10,help= 117 | 'CPU frequency to target, minimum 1Hz. 10Hz by default.CPU frequency can be adjusted in platter.') 118 | group.add_argument('-s','--step', action='store_true', help= 119 | 'Start the emulator in "step" mode. Allows for execution of a single instruction at a time.') 120 | emu_parser.add_argument('-d','--drawfix', action='store_true', help= 121 | 'Enable anti-flicker, stops platter from drawing to the screen when sprites are only removed.', ) 122 | emu_parser.add_argument('-i','--initram', action='store_true', help= 123 | 'Initialize RAM to all zero values. Needed to run some ROMs that assume untouched addresses to be zero. By default RAM address without values are not initalized, accessing them will cause an Emulation Error.') 124 | emu_parser.add_argument('-a','--audio', help= 125 | 'Path to audio to play for Sound Timer, or "off" to prevent sound from playing.' + \ 126 | 'By default a 440Hz square wave is used.') 127 | emu_parser.add_argument("-st","--soundtimer", type=pos_int, default=60, help= 128 | 'Frequency to target for the audio timmer. 60Hz by default.') 129 | emu_parser.add_argument("-dt","--delaytimer", type=pos_int, default=60, help= 130 | 'Frequency to target for the delay timmer. 60Hz by default.') 131 | emu_parser.add_argument('-ls','--legacy_shift', action='store_true', help= 132 | 'Use the legacy shift method of bit shift Y and storing to X. ' +\ 133 | 'By default the newer method is used where Y is ignored and X is bitshifted then stored to itself.') 134 | emu_parser.add_argument("-e","--enforce_instructions", default='None', help= 135 | 'Warning to log if an unoffical instruction is executed. ' +\ 136 | 'By default, no errors are logged. Options: None Info Warning Fatal') 137 | emu_parser.add_argument("-r","--rewind_depth", type=pos_int, default=1000, help= 138 | 'Number of instructions back to be recorded to enable rewinding. ' +\ 139 | 'To disable set to zero or "off". By default 1000 instructions are recorded.') 140 | emu_parser.add_argument("-u","--unicode", nargs='*', help= 141 | 'Forces unicode on or off for the menu and game screen. ' +\ 142 | 'Valid values are: On, Off, Menu-On, Menu-Off, Game-On, Game-Off. ' +\ 143 | 'By default, unicode support is determined by the OS. ' +\ 144 | 'Mac displays a unicode game screen, Windows displays no unicode, ' +\ 145 | 'and GNU/Linux displays both the game and menu in unicode.') 146 | 147 | return parser.parse_args() 148 | 149 | def main(): 150 | if len(argv) == 1: 151 | chip8 = Nacho() 152 | chip8.mainloop() 153 | return 154 | 155 | opts = parse_args() 156 | 157 | if opts.option == 'pre-process': 158 | if not os.path.isfile(opts.input): 159 | raise OSError("File '" + opts.input + "' does not exist.") 160 | 161 | if not opts.output: 162 | opts.output = '.'.join(opts.input.split('.')[0:-1]) if opts.input.find('.') != -1 else opts.input 163 | opts.output += '_pp.asm' 164 | 165 | with open(opts.input) as fh: 166 | pp = Jalapeno(fh, opts.define) 167 | 168 | with open(opts.output, 'w+') as fh: 169 | pp.print_processed_source(fh) 170 | 171 | if opts.option == 'assemble': 172 | if not os.path.isfile(opts.input): 173 | raise OSError("File '" + opts.input + "' does not exist.") 174 | 175 | if not opts.output: 176 | opts.output = '.'.join(opts.input.split('.')[0:-1]) if opts.input.find('.') != -1 else opts.input 177 | 178 | bb = Blackbean() 179 | with open(opts.input) as fh: 180 | bb.assemble(fh) 181 | 182 | if opts.list: 183 | with open(opts.output + '.lst', 'w') as fh: 184 | bb.print_listing(fh) 185 | 186 | if opts.strip: 187 | with open(opts.output + '.strip', 'w') as fh: 188 | bb.print_strip(fh) 189 | 190 | with open(opts.output + '.ch8', 'wb') as fh: 191 | bb.export_binary(fh) 192 | 193 | if opts.option == 'disassemble': 194 | if opts.output is None: 195 | opts.output = '.'.join(opts.rom.split('.')[0:-1]) if opts.rom.find('.') != -1 else opts.rom 196 | opts.output += '.asm' 197 | 198 | with open(opts.rom, 'rb') as fi: 199 | with open(opts.output, 'w+') as fo: 200 | dissassemble_file(fi, fo) 201 | 202 | if opts.option == 'execute': 203 | if not os.path.isfile(opts.rom): 204 | raise OSError("File '" + opts.rom + "' does not exist.") 205 | 206 | guac = Guacamole(opts.rom, opts.frequency, opts.soundtimer, opts.delaytimer, 207 | opts.initram, opts.legacy_shift, opts.enforce_instructions) 208 | guac.log_to_screen = True 209 | sleep_time = (1/opts.frequency)*.98 210 | try: 211 | while True: 212 | guac.run() 213 | sleep(sleep_time) 214 | 215 | except KeyboardInterrupt: 216 | pass 217 | 218 | if opts.option == 'emulate': 219 | if not os.path.isfile(opts.rom): 220 | raise OSError("File '" + opts.rom + "' does not exist") 221 | 222 | if opts.step: 223 | opts.frequency = 1000000 # 1 Ghz 224 | 225 | screen_unicode = False if platform == 'win32' else True 226 | menu_unicode = True if platform == 'linux' else False 227 | if opts.unicode: 228 | if len(opts.unicode) > 2: 229 | raise IOError("Too many values following the '--unicode' flag.") 230 | for val in opts.unicode: 231 | val = val.lower().split('-') 232 | if val[0] == 'menu' and val[1]== 'on': 233 | menu_unicode = True 234 | elif val[0] == 'menu' and val[1]== 'off': 235 | menu_unicode = False 236 | elif val[0] == 'game' and val[1]== 'on': 237 | game_unicode = True 238 | elif val[0] == 'game' and val[1]== 'off': 239 | game_unicode = False 240 | else: 241 | raise IOError("Unknown value following the '--unicode' flag.") 242 | 243 | disp = Platter( opts.rom, opts.frequency, opts.soundtimer, opts.delaytimer, 244 | opts.initram, opts.legacy_shift, opts.enforce_instructions, 245 | opts.rewind_depth, opts.drawfix, screen_unicode, menu_unicode, 246 | opts.audio ) 247 | disp.start(opts.step) 248 | 249 | if __name__ == "__main__": 250 | main() 251 | -------------------------------------------------------------------------------- /tortilla8/blackbean.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | 3 | from . import export 4 | from warnings import warn 5 | from .cilantro import Cilantro 6 | from .constants.reg_rom_stack import PROGRAM_BEGIN_ADDRESS, ARG_SUB, OVERFLOW_ADDRESS, REGISTERS 7 | from .constants.opcodes import OP_CODES, OP_CODE_SIZE, BANNED_OP_CODES_EXPLODED 8 | from .constants.symbols import BEGIN_COMMENT, HEX_ESC, BIN_ESC 9 | __all__ = [] 10 | 11 | #Opcode reminders: SHR, SHL, XOR, and SUBN/SM are NOT offically supported by original spec 12 | # SHR and SHL may or may not move Y (Shifted) into X or just shift X. 13 | # Enforce flag can be used to prevent using them. 14 | 15 | @export 16 | class Blackbean: 17 | """ 18 | Blackbean is an assembler class that can take file handlers, 19 | assemble the contents, and return a stripped (comment free), 20 | listing, or binary file. 21 | """ 22 | def __init__(self, token_collection=None, enforce_offical_ins=False): 23 | """ 24 | Init the token collection and memory map. Pre-Processor may 25 | have already done the hard bit for us. Memory addresses 26 | start at 0x200 on the CHIP 8. 27 | """ 28 | self.collection = [] if token_collection is None else token_collection 29 | self.mmap = {} 30 | self.address = PROGRAM_BEGIN_ADDRESS 31 | self.enforce = enforce_offical_ins 32 | 33 | def reset(self, token_collection=None): 34 | """ 35 | Reset the blackbean to assemble another file. 36 | """ 37 | self.__init__(token_collection) 38 | 39 | def assemble(self, file_handler): 40 | """ 41 | Assemble a file. Tokenizes, calculates memory addreses, and 42 | translates mnemonic instructions into hex. 43 | """ 44 | # Pass One, Tokenize and Address 45 | for i,line in enumerate(file_handler): 46 | t = Cilantro(line, i) 47 | self.collection.append(t) 48 | if t.is_empty: continue 49 | self.calc_mem_address(t) 50 | 51 | # Pass Two, decode mnemonics 52 | for t in self.collection: 53 | if t.is_empty: continue 54 | self.calc_opcode(t) 55 | self.calc_data_declares(t) 56 | 57 | def print_listing(self, file_handler=None): 58 | """ 59 | Prints a the orignal file with two additonal columns, the first 60 | being the memory address of the first byte of the line and the 61 | second being the calculated hex value for the mnemonic on the 62 | line. Data declarations do not have their calculated hex 63 | values shown as they may take more than the normal two bytes 64 | for all other assembler instructions. 65 | """ 66 | if not self.collection: 67 | warn("No file has been assembled. Nothing to print.") 68 | return 69 | 70 | for line in self.collection: 71 | if line.instruction_int: 72 | form_line = format(line.mem_address, '#06x') + (4*' ') +\ 73 | format(line.instruction_int, '#06x') + (4*' ') +\ 74 | line.original 75 | elif line.dd_ints: 76 | form_line = format(line.mem_address, '#06x') + (14*' ') +\ 77 | line.original 78 | else: 79 | form_line = (20*' ') + line.original 80 | 81 | if file_handler is None: 82 | print(form_line, end='') 83 | else: 84 | file_handler.write(form_line) 85 | 86 | def print_strip(self, file_handler=None): 87 | """ 88 | Prints a copy of the input file with all comments and white 89 | space lines removed. Useful for CHIP 8 interpreters. 90 | """ 91 | if not self.collection: 92 | warn("No file has been assembled. Nothing to print.") 93 | return 94 | 95 | for line in self.collection: 96 | if line.is_empty: 97 | continue 98 | if file_handler is None: 99 | print(line.original.split(BEGIN_COMMENT)[0].rstrip(), end='') 100 | else: 101 | file_handler.write(line.original.split(BEGIN_COMMENT)[0].rstrip() + '\n') 102 | 103 | def export_binary(self, file_handler): 104 | """ 105 | Writes the assembled file to a binary blob. 106 | """ 107 | if not self.collection: 108 | warn("No file has been assembled. Nothing to print.") 109 | return 110 | 111 | for line in self.collection: 112 | if line.is_empty: 113 | continue 114 | if line.instruction_int: 115 | file_handler.write(line.instruction_int.to_bytes(OP_CODE_SIZE, byteorder='big')) 116 | elif line.dd_ints: 117 | for i in range(len(line.dd_ints)): 118 | file_handler.write(line.dd_ints[i].to_bytes(line.data_size , byteorder='big')) 119 | 120 | def calc_opcode(self, tl): 121 | """ 122 | Resolve mnemonics into hex string then to ints.These 123 | can be easily written out. All instructions are 2 bytes. 124 | Input should be a Cilantro 'tokenized line' data container. 125 | """ 126 | # Skip empty lines 127 | if not tl.instruction: 128 | return 129 | 130 | if self.enforce and tl.instruction in UNOFFICIAL_OP_CODES: 131 | raise RuntimeError("Restricted instruction on line " + \ 132 | str(tl.line_numb) + "\n" + tl.original ) 133 | 134 | # If not stored as tuple, just add to a length 1 tuple 135 | loop = OP_CODES[tl.instruction] if type(OP_CODES[tl.instruction]) is tuple else (OP_CODES[tl.instruction],) 136 | for ver in loop: 137 | issue = False 138 | 139 | # Skips versions of the OPCODE that can't work 140 | if len(ver.args) != len(tl.arguments): 141 | continue 142 | 143 | # Easy matches 144 | if len(ver.args) == 0: 145 | tl.instruction_int = int(ver.hex, 16) 146 | break 147 | 148 | # Validate every argument provided to the instruction 149 | working_hex = ver.hex 150 | for i, arg_type in enumerate(ver.args): 151 | working_hex = self.is_valid_instruction_arg(arg_type, tl.arguments[i], working_hex, ARG_SUB[i]) 152 | if not working_hex: 153 | break 154 | 155 | # If working hex is populated then save it off and break 156 | if working_hex: 157 | tl.instruction_int = int(working_hex, 16) 158 | if working_hex in BANNED_OP_CODES_EXPLODED: 159 | warn("Instruction that modifies F register on line " + str(tl.line_numb)) 160 | break 161 | 162 | if not tl.instruction_int: 163 | raise RuntimeError("Unkown mnemonic-argument combination on line " + \ 164 | str(tl.line_numb) + "\n" + tl.original ) 165 | 166 | def is_valid_instruction_arg(self, arg_type, arg_value, hex_template, sub_string): 167 | """ 168 | Validates an instruction's arg_value to insure it meets the parameters 169 | of arg_type. If so, hex_template is returned with sub_string correctly 170 | updated. 171 | """ 172 | if arg_type == arg_value: 173 | return hex_template 174 | 175 | if arg_type is 'reg': 176 | if arg_value in REGISTERS: 177 | return hex_template.replace(sub_string, arg_value[1]) 178 | 179 | elif arg_type is 'addr': 180 | if arg_value[0] is HEX_ESC: 181 | arg_value = arg_value[1:] 182 | if len(arg_value) == 3: 183 | try: 184 | int(arg_value, 16) 185 | return hex_template.replace(sub_string * 3, arg_value) 186 | except: pass 187 | elif arg_value in self.mmap: 188 | if self.mmap.get(arg_value): 189 | return hex_template.replace(sub_string * 3, hex(self.mmap[arg_value])[2:]) 190 | 191 | elif arg_type is 'byte': 192 | if arg_value[0] is HEX_ESC: 193 | arg_value = arg_value[1:] 194 | else: 195 | try: 196 | arg_value = hex(int(arg_value))[2:].zfill(2) 197 | except: 198 | pass 199 | if len(arg_value) == 2: 200 | try: 201 | int(arg_value, 16) 202 | return hex_template.replace(sub_string * 2, arg_value) 203 | except: 204 | pass 205 | 206 | elif arg_type is 'nibble': 207 | if arg_value[0] is HEX_ESC: 208 | arg_value = arg_value[1:] 209 | if len(arg_value) == 1: 210 | try: 211 | int(arg_value, 16) 212 | return hex_template.replace(sub_string, arg_value) 213 | except: 214 | pass 215 | 216 | return '' 217 | 218 | def calc_data_declares(self, tl): 219 | """ 220 | Resolve a data declarations into list of ints. These can 221 | be easily written out. Support exists for Hex escaped values 222 | just like on all other arguments, but also for binary 223 | escaped (via $) in for the form '$1111....' or '$11110000'. 224 | """ 225 | # Skip lines w/o dd 226 | if not tl.data_declarations: 227 | return 228 | 229 | for arg in tl.data_declarations: 230 | val = None 231 | 232 | # Try to parse the values 233 | if arg[0] is HEX_ESC: 234 | arg = arg[1:] 235 | if len(arg) == (2 * tl.data_size): 236 | try: val = int(arg, 16) 237 | except: pass 238 | elif arg[0] is BIN_ESC: 239 | arg = arg[1:].replace('.','0') 240 | if len(arg) == (8 * tl.data_size): 241 | try: val = int(arg, 2) 242 | except: pass 243 | elif arg.isdigit(): 244 | val = int(arg) 245 | 246 | # Raise errors if parse failed or val too large 247 | if val == None: 248 | raise RuntimeError("Incorrectly formated data declaration on line " + str(tl.line_numb)) 249 | if val >= pow(256, tl.data_size): 250 | raise RuntimeError("Data declaration overflow on line " + str(tl.line_numb)) 251 | 252 | tl.dd_ints.append(val) 253 | 254 | def calc_mem_address(self, tl): 255 | """ 256 | Assign memory addresses to mnemonics (now packed in tokenized 257 | lines). Store any memory tags found in the memory map to be 258 | used on the second pass. 259 | """ 260 | # Add any tags to the mem map 261 | if tl.mem_tag: 262 | self.mmap[tl.mem_tag] = self.address 263 | 264 | # One or the other per line, if both then errors are raised 265 | if tl.instruction: 266 | tl.mem_address = self.address 267 | self.address += OP_CODE_SIZE 268 | elif tl.data_size: 269 | tl.mem_address = self.address 270 | self.address += (len(tl.data_declarations) * tl.data_size) 271 | 272 | if self.address >= OVERFLOW_ADDRESS: 273 | warn("Memory overflow as of line " + str(tl.line_numb)) 274 | 275 | ############################################################ 276 | # Below are utility functions usefull if creating a class 277 | # is over shooting your needs. 278 | 279 | def util_strip_comments(file_path, outpout_handler = None): 280 | with open(file_path) as fhandler: 281 | for line in fhandler: 282 | if line.isspace(): continue 283 | if line.lstrip().startswith(BEGIN_COMMENT): continue 284 | line = line.split(BEGIN_COMMENT)[0].rstrip() 285 | if outpout_handler == None: 286 | print(line) 287 | else: 288 | outpout_handler.write(line) 289 | 290 | def util_add_listing(file_path, outpout_handler = None): 291 | mem_addr = 0x0200 292 | with open(file_path) as fhandler: 293 | for line in fhandler: 294 | mem_inc = 2 295 | nocomment = line.split(BEGIN_COMMENT)[0].rstrip().lower() 296 | if not nocomment or nocomment.endswith(':') or any(s in nocomment for s in PRE_PROC): 297 | line = (10*' ') + line 298 | else: 299 | for k in DATA_DEFINE: 300 | if k in nocomment: 301 | mem_inc = DATA_DEFINE[k] 302 | break 303 | line = format(mem_addr, '#06x') + (4*' ') + line 304 | mem_addr += mem_inc 305 | if outpout_handler == None: 306 | print(line, end='') 307 | else: 308 | outpout_handler.write(line, end='') 309 | 310 | 311 | 312 | 313 | -------------------------------------------------------------------------------- /tortilla8/guacamole.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | 3 | from . import export 4 | from . import EmulationError 5 | from os.path import getsize 6 | from time import time 7 | from .salsa import Salsa 8 | from collections import namedtuple, deque 9 | from .instructions import * 10 | from .constants.reg_rom_stack import BYTES_OF_RAM, PROGRAM_BEGIN_ADDRESS, \ 11 | NUMB_OF_REGS, MAX_ROM_SIZE 12 | from .constants.graphics import GFX_FONT, GFX_FONT_ADDRESS, GFX_RESOLUTION, GFX_ADDRESS 13 | __all__ = [] 14 | 15 | # TODO Rewind bug when waiting for keypress 16 | # TODO Rewind isn't storing all of RAM, so ld [i], reg will break rewind 17 | 18 | @export 19 | class RewindData( namedtuple('RewindData', 'gfx_buffer register index_register ' + \ 20 | 'delay_timer_register sound_timer_register program_counter calling_pc ' + \ 21 | 'dis_ins stack stack_pointer draw_flag waiting_for_key spinning') ): 22 | pass 23 | 24 | @export 25 | class Guacamole: 26 | ''' 27 | Guacamole is an emulator class that will happily emulate a Chip-8 ROM 28 | at a select frequency with various other options available. 29 | ''' 30 | def __init__(self, rom=None, cpuhz=200, audiohz=60, delayhz=60, 31 | init_ram=False, legacy_shift=False, err_unoffical="None", 32 | rewind_frames=1000): 33 | ''' 34 | Init the RAM, registers, instruction information, IO, load the ROM etc. ROM 35 | is a path to a chip-8 rom, *hz is the frequency to target for for the cpu, 36 | audio register, or delay register. Init_Ram signals that the RAM should be 37 | initialized to zero. Not initializing the RAM is a great way to find 38 | incorrect RAM accesses. Legacy Shift can be set to true to use the older 39 | 'Store shift Y to X' rather than 'Shift X' method of bitshifting. Lastly, 40 | err_unoffical can be used to log an error when an offical instruction is 41 | found in the program. 42 | ''' 43 | 44 | # # # # # # # # # # # # # # # # # # # # # # # # 45 | # Public 46 | 47 | # RAM 48 | self.ram = [0x00] * BYTES_OF_RAM if init_ram else [None] * BYTES_OF_RAM 49 | 50 | # Registers 51 | self.register = [0x00] * NUMB_OF_REGS 52 | self.index_register = 0x000 53 | self.delay_timer_register = 0x00 54 | self.sound_timer_register = 0x00 55 | 56 | # Current dissassembled instruction / OP Code 57 | self.dis_ins = None 58 | 59 | # Program Counter 60 | self.program_counter = PROGRAM_BEGIN_ADDRESS 61 | self.calling_pc = PROGRAM_BEGIN_ADDRESS 62 | 63 | # I/O 64 | self.keypad = [False] * 16 65 | self.prev_keypad = 0 66 | self.draw_flag = False 67 | self.waiting_for_key = False 68 | self.spinning = False 69 | 70 | # Stack 71 | self.stack = [] 72 | self.stack_pointer = 0 73 | 74 | # Instruction modification settings 75 | self.legacy_shift = legacy_shift 76 | self.warn_exotic_ins = EmulationError.from_string(err_unoffical) 77 | 78 | # Rewind Info 79 | self.rewind_frames = None if rewind_frames == 0 else deque(maxlen=rewind_frames) 80 | 81 | # # # # # # # # # # # # # # # # # # # # # # # # 82 | # Private (ish) 83 | 84 | # Warning control 85 | self.debug = False 86 | self.error_log = [] 87 | 88 | # Timming variables 89 | self.cpu_hz = cpuhz 90 | self.cpu_wait = 1/cpuhz 91 | self.cpu_time = 0 92 | self.audio_hz = audiohz 93 | self.audio_wait = 1/audiohz 94 | self.audio_time = 0 95 | self.delay_hz = delayhz 96 | self.delay_wait = 1/delayhz 97 | self.delay_time = 0 98 | 99 | # Load Font, clear screen 100 | self.ram[GFX_FONT_ADDRESS:GFX_FONT_ADDRESS + len(GFX_FONT)] = GFX_FONT 101 | self.ram[GFX_ADDRESS:GFX_ADDRESS + GFX_RESOLUTION] = [0x00] * GFX_RESOLUTION 102 | 103 | # Notification 104 | self.log("Initializing emulator at " + str(cpuhz) + " hz" ,EmulationError._Information) 105 | self.log("Max Rewind of " + str(rewind_frames) + " instructions" ,EmulationError._Information) 106 | 107 | # Load Rom 108 | if rom is not None: 109 | self.load_rom(rom) 110 | 111 | # Instruction lookup table 112 | self.ins_tbl={ 113 | 'cls' :i_cls, 'ret' :i_ret, 'sys' :i_sys, 'call':i_call, 114 | 'skp' :i_skp, 'sknp':i_sknp, 'se' :i_se, 'sne' :i_sne, 115 | 'add' :i_add, 'or' :i_or, 'and' :i_and, 'xor' :i_xor, 116 | 'sub' :i_sub, 'subn':i_subn, 'shr' :i_shr, 'shl' :i_shl, 117 | 'rnd' :i_rnd, 'jp' :i_jp, 'ld' :i_ld, 'drw' :i_drw} 118 | 119 | def load_rom(self, file_path): 120 | ''' 121 | Loads a Chip-8 ROM from a file into the RAM. 122 | ''' 123 | file_size = getsize(file_path) 124 | if file_size > MAX_ROM_SIZE: 125 | self.log("Rom file exceeds maximum rom size of " + str(MAX_ROM_SIZE) + \ 126 | " bytes" , EmulationError._Fatal) 127 | return 128 | 129 | with open(file_path, "rb") as fh: 130 | self.ram[PROGRAM_BEGIN_ADDRESS:PROGRAM_BEGIN_ADDRESS + file_size] = \ 131 | [int.from_bytes(fh.read(1), 'big') for i in range(file_size)] 132 | self.log("Rom file loaded" , EmulationError._Information) 133 | 134 | def reset(self, rom=None, cpuhz=None, audiohz=None, delayhz=None, 135 | init_ram=None, legacy_shift=None, err_unoffical="None", 136 | rewind_frames=1000): 137 | ''' 138 | Resets the emulator to run another game. By default all frequencies 139 | and the init_ram flag are preserved. 140 | ''' 141 | if cpuhz is None: cpuhz = self.cpu_hz 142 | if audiohz is None: audiohz = self.audio_hz 143 | if delayhz is None: delayhz = self.delay_hz 144 | if init_ram is None: init_ram = True if self.ram[0] == 0 else False 145 | if legacy_shift is None: legacy_shift = self.legacy_shift 146 | if err_unoffical is None: err_unoffical = str(self.warn_exotic_ins) 147 | if rewind_frames is None: 148 | rewind_frames = 0 if self.rewind_frames == None else self.rewind_frames.maxlen 149 | 150 | self.__init__(rom, cpuhz, audiohz, delayhz, 151 | init_ram, legacy_shift, err_unoffical, 152 | rewind_frames) 153 | 154 | def run(self): 155 | ''' 156 | Attempt to run the next instruction. This should be called as a part 157 | of the main loop, it insures that the CPU and timers execute at the 158 | target frequency. 159 | ''' 160 | if self.cpu_wait <= (time() - self.cpu_time): 161 | self.cpu_time = time() 162 | self.cpu_tick() 163 | 164 | if self.audio_wait <= (time() - self.audio_time): 165 | self.audio_time = time() 166 | self.sound_timer_register -= 1 if self.sound_timer_register != 0 else 0 167 | 168 | if self.delay_wait <= (time() - self.delay_time): 169 | self.delay_time = time() 170 | self.delay_timer_register -= 1 if self.delay_timer_register != 0 else 0 171 | 172 | def cpu_tick(self): 173 | ''' 174 | Ticks the CPU forward a cycle without regard for the target frequency. 175 | ''' 176 | # Handle the ld reg,k instruction 177 | if self.waiting_for_key: 178 | self.handle_load_key() 179 | return 180 | else: 181 | self.prev_keypad = self.decode_keypad() 182 | 183 | # Record current PC, Reset error log 184 | self.calling_pc = self.program_counter 185 | self.error = [] 186 | 187 | # Dissassemble next instruction 188 | self.dis_ins = None 189 | try: 190 | self.dis_ins = Salsa(self.ram[self.program_counter:self.program_counter+2]) 191 | except TypeError: 192 | self.log("No instruction found at " + hex(self.program_counter), EmulationError._Fatal) 193 | return 194 | 195 | # Execute instruction 196 | if self.dis_ins.is_valid: 197 | if self.warn_exotic_ins and self.dis_ins.unoffical_op: 198 | self.log("Unoffical instruction '" + self.dis_ins.mnemonic + \ 199 | "' executed at " + hex(self.program_counter), self.warn_exotic_ins) 200 | self.ins_tbl[self.dis_ins.mnemonic](self) 201 | 202 | # Error out. NOTE: to add new instruction update OP_CODES and self.ins_tbl 203 | elif self.dis_ins.is_super8: 204 | self.log("Super8 instruction " + self.dis_ins.hex_instruction + " at " + \ 205 | hex(self.program_counter), EmulationError._Fatal) 206 | elif self.dis_ins.is_banned: 207 | self.log("Banned instruction (makes a modification to VF)" + self.dis_ins.hex_instruction + \ 208 | " at " + hex(self.program_counter), EmulationError._Fatal) 209 | else: 210 | self.log("Unknown instruction " + self.dis_ins.hex_instruction + " at " + \ 211 | hex(self.program_counter), EmulationError._Fatal) 212 | 213 | # Print what was processed to screen 214 | if self.debug: 215 | self.enforce_rules() 216 | print( hex(self.calling_pc) + " " + self.dis_ins.hex_instruction + " " + self.dis_ins.mnemonic ) 217 | 218 | # Increment the PC, Store Rewind Data 219 | self.program_counter += 2 220 | self.store_RewindData() 221 | 222 | def store_RewindData(self): 223 | ''' 224 | Save the current state of the emulator. 225 | Without rewind guac/platter use 7.6 megs of RAM. Using rewind uses 226 | 2.64 kB of ram per frame. 227 | ''' 228 | if self.rewind_frames is None: 229 | return 230 | gfx_buffer = self.ram[GFX_ADDRESS:GFX_ADDRESS + GFX_RESOLUTION] 231 | self.rewind_frames.append( RewindData(gfx_buffer, self.register.copy(), self.index_register, 232 | self.delay_timer_register, self.sound_timer_register, self.program_counter, self.calling_pc, 233 | self.dis_ins + (), self.stack.copy(), self.stack_pointer, self.draw_flag, self.waiting_for_key, 234 | self.spinning ) ) 235 | 236 | def rewind(self, depth): 237 | ''' 238 | "Un-ticks" the CPU depth many times. 239 | ''' 240 | frame = None 241 | try: 242 | for _ in range(depth): 243 | frame = self.rewind_frames.pop() 244 | except IndexError: 245 | if frame is None: 246 | return 247 | self.ram[GFX_ADDRESS:GFX_ADDRESS + GFX_RESOLUTION] = \ 248 | frame.gfx_buffer 249 | self.register, self.index_register = \ 250 | frame.register, frame.index_register 251 | self.delay_timer_register, self.sound_timer_register = \ 252 | frame.delay_timer_register, frame.sound_timer_register 253 | self.program_counter, self.calling_pc = \ 254 | frame.program_counter, frame.calling_pc 255 | self.dis_ins, self.stack, self.stack_pointer = \ 256 | self.dis_ins, frame.stack, frame.stack_pointer 257 | self.draw_flag, self.waiting_for_key, self.spinning = \ 258 | frame.draw_flag, frame.waiting_for_key, frame.spinning 259 | 260 | def graphics(self): 261 | ''' 262 | Generator that returns true/false if the nth pixel is set. 263 | ''' 264 | for i in self.ram[GFX_ADDRESS:GFX_ADDRESS + GFX_RESOLUTION]: 265 | for j in bin(i)[2:].zfill(8): 266 | yield j=='1' 267 | 268 | def log(self, message, error_type): 269 | ''' 270 | Logs an EmulationError that can be latter addressed by the instantiator 271 | or prints it to screen if called from command line. 272 | ''' 273 | if self.debug: 274 | print(str(error_type) + ": " + message) 275 | if error_type is EmulationError._Fatal: 276 | print("Fatal error has occured, please reset.") 277 | else: 278 | self.error_log.append( (error_type, message) ) 279 | 280 | # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # 281 | # Helpers for Load Key ( Private ) 282 | 283 | def decode_keypad(self): 284 | ''' 285 | Helper method to decode the current keypad into a binary string 286 | ''' 287 | return int(''.join(['1' if x else '0' for x in self.keypad]),2) 288 | 289 | def handle_load_key(self): 290 | ''' 291 | Helper method to check if keys have changed and, if so, load the 292 | key per the ld reg,k instruction. 293 | ''' 294 | k = self.decode_keypad() 295 | nk = bin( (k ^ self.prev_keypad) & k )[2:].zfill(16).find('1') 296 | if nk != -1: 297 | self.register[ self.get_reg1() ] = nk 298 | self.program_counter += 2 299 | self.waiting_for_key = False 300 | 301 | # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # 302 | # Debug 303 | 304 | def dump_ram(self): 305 | for i,val in enumerate(self.ram): 306 | if val is None: 307 | print('0x' + hex(i)[2:].zfill(3)) 308 | else: 309 | print('0x' + hex(i)[2:].zfill(3) + ' ' + '0x' + hex(val)[2:].zfill(2)) 310 | 311 | def dump_gfx(self): 312 | for i,b in enumerate(self.ram[ GFX_ADDRESS : GFX_ADDRESS + GFX_RESOLUTION ]): 313 | if i%8 == 0: 314 | print() 315 | print( bin(b)[2:].zfill(8).replace('1','X').replace('0','.'), end='') 316 | print() 317 | 318 | def dump_reg(self): 319 | for i,val in enumerate(self.register): 320 | if (i % 4) == 0: 321 | print() 322 | print(hex(i) + " 0x" + hex(val)[2:].zfill(2) + " ", end='') 323 | print() 324 | 325 | def dump_keypad(self): 326 | r_val = '' 327 | for i,val in enumerate(self.keypad): 328 | if val: 329 | r_val += hex(i) + " " 330 | return r_val 331 | 332 | def enforce_rules(self): 333 | assert(self.index_register is not None) 334 | assert(self.index_register <= 0xFFF) 335 | assert(self.index_register >= 0x000) 336 | assert(self.delay_timer_register <= 0xFF) 337 | assert(self.delay_timer_register >= 0x00) 338 | assert(self.sound_timer_register <= 0xFF) 339 | assert(self.sound_timer_register >= 0x00) 340 | for i,val in enumerate(self.register): 341 | assert val is not None, "Register " + hex(i) + " has value 'None'" + self.dump_pc() 342 | assert val >= 0x00, "Register " + hex(i) + "is less than 0x00" + self.dump_pc() 343 | assert val <= 0xFF, "Register " + hex(i) + "is greater than 0xFF" + self.dump_pc() 344 | for i,val in enumerate(self.ram): 345 | if val is None: continue 346 | assert val >= 0x00, "Ram Address " + hex(i) + "is less than 0x00" + self.dump_pc() 347 | assert val <= 0xFF, "Ram Address " + hex(i) + "is greater than 0xFF" + self.dump_pc() 348 | 349 | def dump_pc(self): 350 | return "\nPC: " + hex(self.program_counter) + " INS: " + self.dis_ins.hex_instruction 351 | 352 | -------------------------------------------------------------------------------- /tortilla8/platter.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | 3 | # Import curses 4 | try: import curses 5 | except ImportError: 6 | raise ImportError("Curses is missing from your system. " + \ 7 | "Consult the README for information on installing for your platform.") 8 | 9 | # Import Sound (optional) 10 | try: import simpleaudio as sa 11 | except ImportError: 12 | sa = None 13 | 14 | # Import System to clear keybuffer 15 | try: 16 | termios = True 17 | from termios import tcflush, TCIOFLUSH 18 | from sys import stdin 19 | except ImportError: 20 | termios = None 21 | from msvcrt import getch, kbhit 22 | 23 | # Everything else 24 | from os import path 25 | from enum import Enum 26 | from sys import platform 27 | from textwrap import wrap 28 | from time import time, sleep 29 | from collections import deque 30 | from .constants.curses import * 31 | from .guacamole import Guacamole 32 | from .guacamole import EmulationError 33 | from .constants.reg_rom_stack import PROGRAM_BEGIN_ADDRESS, NUMB_OF_REGS 34 | from .constants.graphics import GFX_RESOLUTION, GFX_ADDRESS, GFX_HEIGHT_PX, GFX_WIDTH 35 | from resource import getrusage, RUSAGE_SELF 36 | 37 | # TODO Prevent menu from drawing when screen is small 38 | # TODO Allow editing controls 39 | # TODO Improve input. 40 | # TODO double the resolution if window is large enough 41 | # TODO add Keypad display? 42 | 43 | class Platter: 44 | 45 | def __init__(self, rom, cpuhz, audiohz, delayhz, 46 | init_ram, legacy_shift, enforce_ins, 47 | rewind_depth, drawfix, 48 | enable_screen_unicode, enable_menu_unicode, 49 | wave_file=None): 50 | 51 | # Check if windows (no unicode in their Curses) 52 | self.screen_unicode = enable_screen_unicode 53 | self.menu_unicode = enable_menu_unicode 54 | self.draw_char = UNICODE_DRAW if enable_screen_unicode else WIN_DRAW 55 | 56 | # Init Curses 57 | self.screen = curses.initscr() 58 | self.screen.clear() 59 | self.L, self.C = self.screen.getmaxyx() 60 | 61 | # Used for graphics "smoothing" w/ -d flag 62 | self.draw_fix = drawfix 63 | self.prev_board=[0x00]*GFX_RESOLUTION 64 | 65 | # General Prep 66 | self.rom = rom 67 | self.dynamic_window_gen() 68 | self.clear_all_windows() 69 | self.init_logs() 70 | 71 | # Print FYI for game window 72 | if self.w_game is None: 73 | self.console_print("Window must be atleast " + str(DISPLAY_MIN_W) + \ 74 | "x" + str(DISPLAY_MIN_H) +" to display the game screen") 75 | 76 | # Load default sound 77 | self.wave_obj = None 78 | if not wave_file: 79 | wave_file = path.join('tortilla8','sound','play.wav') 80 | 81 | # Print FYI for sound if no SA 82 | if sa is None: 83 | self.console_print("SimpleAudio is missing from your system." + \ 84 | "You can install it via 'pip install simpleaudio'. " + \ 85 | "The sound timmer will not be raised.") 86 | 87 | # Init sound if available 88 | elif wave_file.lower() != 'off': 89 | try: 90 | self.wave_obj = sa.WaveObject.from_wave_file(wave_file) 91 | self.play_obj = None 92 | self.audio_playing = False 93 | except FileNotFoundError: 94 | self.console_print("No sound file provided as parameter. " + \ 95 | "Unable to load default 'play.wav' from sound directory.") 96 | 97 | # Init the emulator 98 | self.emu = Guacamole(rom, cpuhz, audiohz, delayhz, init_ram, legacy_shift, enforce_ins, rewind_depth) 99 | self.check_log() 100 | self.init_emu_status() 101 | self.rewind_size = 5 102 | 103 | # Curses settings 104 | curses.noecho() 105 | curses.cbreak() 106 | curses.curs_set(0) 107 | 108 | def init_emu_status(self): 109 | self.previous_pc = PROGRAM_BEGIN_ADDRESS 110 | self.halt = False 111 | 112 | def init_logs(self): 113 | self.instr_history = deque(maxlen = self.w_instr.getmaxyx()[0] - BORDERS) 114 | self.console_history = deque(maxlen = self.w_console.getmaxyx()[0] - BORDERS) 115 | 116 | def resize_logs(self): 117 | if (self.w_instr.getmaxyx()[0] - BORDERS) != self.instr_history.maxlen: 118 | self.instr_history 119 | self.console_history 120 | 121 | def start(self, step_mode=False): 122 | key_press_time = 0 123 | key_msg_displayed = False 124 | 125 | if step_mode: 126 | self.console_print("Emulator started in step mode. Press '" + \ 127 | chr(KEY_STEP).upper() + "' to process one instruction.") 128 | 129 | try: 130 | 131 | while True: 132 | 133 | # Grab key, escape any arrow seq 134 | key = self.w_console.getch() 135 | if key == KEY_ESC: 136 | key = self.w_console.getch() 137 | if key == KEY_ARROW: 138 | key = KEY_ARROW_MAP[self.w_console.getch()] 139 | flush_key_buffer() 140 | 141 | if key == 122: 142 | self.console_print("Mem: " + str(getrusage(RUSAGE_SELF).ru_maxrss/1000) + " MB") 143 | 144 | # Freq modifications 145 | if key == 'up': 146 | self.emu.cpu_hz *= 1.05 147 | self.emu.cpu_wait = 1/self.emu.cpu_hz 148 | if key == 'down': 149 | self.emu.cpu_hz = 1 if self.emu.cpu_hz * .95 < 1 else self.emu.cpu_hz * .95 150 | self.emu.cpu_wait = 1/self.emu.cpu_hz 151 | 152 | # Rewind modifications 153 | if key == 'left': 154 | self.rewind_size -= 1 if self.rewind_size > 1 else 0 155 | if key == 'right': 156 | self.rewind_size += 1 157 | 158 | # Update Keypad press 159 | if time() - key_press_time > 0.5: #TODO Better input? 160 | self.emu.prev_keypad = 0 161 | self.emu.keypad = [False] * 16 162 | key_press_time = time() 163 | if key in KEY_CONTROLS: 164 | self.emu.keypad[KEY_CONTROLS[key]] = True 165 | 166 | # Exit check 167 | if key == KEY_EXIT: 168 | break 169 | 170 | # Rewind check: 171 | if key == KEY_REWIN: 172 | self.emu.rewind(self.rewind_size) 173 | self.instr_history.appendleft("rewind: " + hex3(self.emu.program_counter)) 174 | continue 175 | 176 | # Reset check 177 | if key == KEY_RESET: 178 | self.emu.reset( self.rom ) 179 | self.init_emu_status() 180 | self.init_logs() 181 | self.clear_all_windows() 182 | continue 183 | 184 | # Step check 185 | if key == KEY_STEP: 186 | step_mode = True 187 | self.halt = False 188 | 189 | # Resume check 190 | if key == KEY_RESUM: 191 | step_mode = False 192 | self.halt = False 193 | 194 | # Try to tick the cpu 195 | if not self.halt: 196 | self.emu.run() 197 | 198 | # Update Display if we executed 199 | if self.emu.program_counter != self.previous_pc: 200 | self.previous_pc = self.emu.program_counter 201 | self.update_instr_history() 202 | key_msg_displayed = False 203 | 204 | # Watch for spin for key 205 | elif self.emu.waiting_for_key and not key_msg_displayed: 206 | self.instr_history.appendleft(hex3(self.emu.program_counter) + " key ld") 207 | self.console_print("Program is trying to load a key press.") 208 | key_msg_displayed = True 209 | 210 | # Detect jp Spinning 211 | elif not self.halt and self.emu.spinning: 212 | self.instr_history.appendleft(hex3(self.emu.program_counter) + " spin jp") 213 | self.console_print("Spin detected. Press '" + chr(KEY_EXIT).upper() + "' to exit") 214 | self.halt = True 215 | 216 | # Toggle for Step Mode 217 | if step_mode: 218 | self.halt = True 219 | 220 | # Start/stop Audio 221 | if sa is not None and self.wave_obj is not None: 222 | self.audio_playing = False if self.emu.sound_timer_register == 0 else True 223 | if not self.audio_playing and self.play_obj is None: 224 | pass 225 | elif self.audio_playing and self.play_obj is None: 226 | self.play_obj = self.wave_obj.play() 227 | elif not self.audio_playing and self.play_obj is not None: 228 | self.play_obj.stop() 229 | self.play_obj = None 230 | elif self.audio_playing and not self.play_obj.is_playing(): 231 | self.play_obj = self.wave_obj.play() 232 | 233 | # Check if screen was re-sized 234 | if platform != 'win32': 235 | if curses.is_term_resized(self.L, self.C): 236 | self.L, self.C = self.screen.getmaxyx() 237 | curses.resizeterm(self.L, self.C) 238 | self.screen.clear() 239 | self.screen.refresh() 240 | self.dynamic_window_gen() 241 | self.clear_all_windows() 242 | self.init_logs() 243 | 244 | # Update the logs/screen 245 | self.check_log() 246 | self.update_screen() 247 | 248 | # Don't waste too many cycles 249 | sleep(self.emu.cpu_wait * 0.25) 250 | 251 | self.update_screen() 252 | except KeyboardInterrupt: 253 | return 254 | except: 255 | print("Unhandled Error!") 256 | raise 257 | finally: 258 | self.cleanup() 259 | 260 | def check_log(self): 261 | # Print all logged errors in the emu 262 | for err in reversed(self.emu.error_log): 263 | self.console_print( str(err[0]) + ": " + err[1] ) 264 | if err[0] is EmulationError._Fatal: 265 | self.halt = True 266 | self.console_print( "Fatal error has occured. Press '" + \ 267 | chr(KEY_RESET).upper() + "' to reset" ) 268 | 269 | # Manually reset 270 | self.emu.error_log = [] 271 | 272 | def cleanup(self): 273 | curses.nocbreak() 274 | curses.echo() 275 | curses.endwin() 276 | 277 | def update_screen(self): 278 | self.display_registers() 279 | self.display_stack() 280 | self.display_instructions() 281 | self.display_game() 282 | self.display_menu() 283 | curses.doupdate() 284 | 285 | def update_instr_history(self): 286 | self.instr_history.appendleft(hex3(self.emu.calling_pc) + " " + \ 287 | self.emu.dis_ins.hex_instruction + " " + \ 288 | self.emu.dis_ins.mnemonic) 289 | 290 | # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # 291 | # Display functions for windows 292 | 293 | def console_print(self, message): 294 | message_list = wrap("-" + message, self.w_console.getmaxyx()[1]- (BORDERS + 1) ) 295 | for msg in reversed(message_list): 296 | self.console_history.appendleft( msg.ljust(self.w_console.getmaxyx()[1] - (BORDERS + 1) ) ) 297 | for i,val in enumerate(self.console_history): 298 | self.w_console.addstr( 1 + i, 1, val ) 299 | self.w_console.noutrefresh() 300 | 301 | def clear_all_windows(self): 302 | self.screen.clear() 303 | self.w_stack.clear() 304 | self.w_console.clear() 305 | self.w_instr.clear() 306 | if self.w_menu is not None: 307 | self.w_menu.clear() 308 | self.w_menu.border() 309 | self.w_menu.refresh() 310 | if self.w_game is not None: 311 | self.w_game.clear() 312 | self.w_game.border() 313 | self.w_game.refresh() 314 | self.w_reg.border() 315 | self.w_reg.addstr( 1, REG_OFFSET, "Registers") 316 | self.w_stack.border() 317 | self.w_stack.addstr( 1, STAK_OFFSET, "Stack") 318 | self.w_console.border() 319 | self.w_instr.border() 320 | self.w_console.nodelay(1) 321 | self.display_logo() 322 | 323 | def display_logo(self): 324 | if self.screen.getmaxyx()[0] < LOGO_MIN: 325 | return 326 | if not self.screen_unicode: 327 | return 328 | try: # Moving the window quickly causes an error, but on on the logo... weird. 329 | logo_offset = ( self.w_logo.getmaxyx()[0] - len(LOGO) ) // 2 330 | for i in range(len(LOGO)): 331 | self.w_logo.addstr( i + logo_offset, 0, LOGO[i] ) 332 | self.w_logo.noutrefresh() 333 | except: 334 | self.w_logo.clear() 335 | pass 336 | 337 | def display_game(self): 338 | if not self.w_game or not self.emu.draw_flag: return 339 | self.emu.draw_flag = False 340 | 341 | if self.draw_fix: 342 | prev_str = "" 343 | curr_str = "" 344 | for val in self.prev_board: 345 | prev_str += bin(val)[2:].zfill(8) 346 | for val in self.emu.ram[GFX_ADDRESS:GFX_ADDRESS+GFX_RESOLUTION]: 347 | curr_str += bin(val)[2:].zfill(8) 348 | int_prev = int(prev_str,2) 349 | int_curr = int(curr_str,2) 350 | self.prev_board = self.emu.ram[GFX_ADDRESS:GFX_ADDRESS+GFX_RESOLUTION] 351 | if ( ( int_prev ^ int_curr ) & int_prev ) == ( int_prev ^ int_curr ): 352 | #Only 1s were changed to 0s, skip the draw to prevent SOME flicker 353 | return 354 | 355 | for y in range( int(GFX_HEIGHT_PX / 2) ): 356 | for x in range(GFX_WIDTH): 357 | upper_chunk = int( bin( self.emu.ram[ GFX_ADDRESS + ( (y * 2 + 0) * GFX_WIDTH) + x ] )[2:] ) 358 | lower_chunk = int( bin( self.emu.ram[ GFX_ADDRESS + ( (y * 2 + 1) * GFX_WIDTH) + x ] )[2:].replace('1','2') ) 359 | total_chunk = str(upper_chunk + lower_chunk).zfill(8) \ 360 | .replace('3', self.draw_char.both ).replace('2', self.draw_char.lower ) \ 361 | .replace('1', self.draw_char.upper ).replace('0', self.draw_char.empty ) 362 | self.w_game.addstr( 1 + y, 1 + x * 8, total_chunk ) 363 | self.w_game.noutrefresh() 364 | 365 | def display_instructions(self): 366 | for i,val in enumerate(self.instr_history): 367 | self.w_instr.addstr( 1 + i, 2, val.ljust(15)) 368 | self.w_instr.noutrefresh() 369 | 370 | def display_registers(self): 371 | for i, reg in enumerate(self.emu.register): 372 | self.w_reg.addstr( ( i // 4 ) + 2, i % 4 * 9 + 2, hex(i)[2] + ": " + hex2(reg) ) 373 | self.w_reg.addstr(6, 1, " dt: " + hex2(self.emu.delay_timer_register) + \ 374 | " st: " + hex2(self.emu.sound_timer_register) + \ 375 | " i: " + hex3(self.emu.index_register)) 376 | self.w_reg.noutrefresh() 377 | 378 | def display_stack(self): 379 | top = max(3, self.w_stack.getmaxyx()[0] - 1 - self.emu.stack_pointer) 380 | if top > 3: 381 | self.w_stack.addstr( top - 2, 1, " " * 10 ) 382 | self.w_stack.addstr( top - 1, 2, str(self.emu.stack_pointer).zfill(2) + ": sp ") 383 | for i,val in enumerate(reversed(self.emu.stack)): 384 | if i == self.w_stack.getmaxyx()[0] - 4: break 385 | self.w_stack.addstr(top + i, 2, str(self.emu.stack_pointer - i - 1).zfill(2) + ": " + hex2(val)) 386 | self.w_stack.noutrefresh() 387 | 388 | def display_menu(self): 389 | if self.w_menu is None: return 390 | prefix = "" 391 | cpu_hz = str(self.emu.cpu_hz) if self.emu.cpu_hz > 1e3 else str(self.emu.cpu_hz)[0:5] 392 | for pre,val in PREFIX: 393 | if self.emu.cpu_hz % val != self.emu.cpu_hz: 394 | prefix = pre 395 | cpu_hz = str(self.emu.cpu_hz / val)[0:5] 396 | break 397 | 398 | if self.menu_unicode: 399 | left = "E̲xit ̲Reset ̲Step Re̲wind Res̲ume" 400 | right = "⇄RwSize " + str(self.rewind_size) + " ⇅Freq " + cpu_hz + prefix + "hz" 401 | middle = " " * ( self.w_menu.getmaxyx()[1] - len(left) - len(right) + 1 ) 402 | else: 403 | left = "eXit Reset Step reWind resUme" 404 | right = "RwSize " + str(self.rewind_size) + " Freq " + cpu_hz + prefix + "hz" 405 | middle = " " * ( self.w_menu.getmaxyx()[1] - len(left) - len(right) - 4 ) 406 | 407 | self.w_menu.addstr( 1, 2, left + middle + right ) 408 | self.w_menu.noutrefresh() 409 | 410 | # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # 411 | # Dynamic Window Generator 412 | 413 | def dynamic_window_gen(self): 414 | while (self.L < H_MIN) or (self.C < W_MIN): 415 | try: 416 | self.screen.addstr(self.L//2 -1, (self.C - len(DY_MSG_1)) //2 , DY_MSG_1) 417 | self.screen.addstr(self.L//2, (self.C - len(DY_MSG_2)) //2 , DY_MSG_2) 418 | self.screen.refresh() 419 | if curses.is_term_resized(self.L, self.C): 420 | self.L, self.C = self.screen.getmaxyx() 421 | curses.resizeterm(self.L, self.C) 422 | self.screen.clear() 423 | except: 424 | self.cleanup() 425 | raise IOError("Terminal window too small to use.\nResize to atleast " + str(W_MIN) + "x" + str(H_MIN)) 426 | 427 | self.w_reg = curses.newwin( WIN_REG_H, WIN_REG_W , 0, self.C - WIN_REG_W ) 428 | self.w_instr = curses.newwin( self.L - WIN_REG_H, WIN_INSTR_W, WIN_REG_H, self.w_reg.getbegyx()[1] ) 429 | self.w_stack = curses.newwin( self.L - WIN_REG_H, WIN_STACK_W, WIN_REG_H, self.w_instr.getbegyx()[1] + WIN_INSTR_W ) 430 | self.w_logo = curses.newwin( self.L - WIN_REG_H, WIN_LOGO_W , WIN_REG_H, self.w_stack.getbegyx()[1] + WIN_STACK_W ) 431 | self.w_menu = curses.newwin( WIN_MENU_H, self.w_reg.getbegyx()[1], self.L - WIN_MENU_H, 0 ) 432 | self.w_game = None 433 | self.w_console = None 434 | 435 | if (self.L < DISPLAY_MIN_H) or (self.C < DISPLAY_MIN_W): 436 | self.w_console = curses.newwin( self.L - WIN_MENU_H, self.w_reg.getbegyx()[1], 0, 0 ) 437 | else: 438 | self.w_game = curses.newwin( DISPLAY_H, DISPLAY_W, 0, ( self.C - WIN_REG_W - DISPLAY_W ) // 2 ) 439 | self.w_console = curses.newwin( self.L - DISPLAY_H - WIN_MENU_H, self.w_reg.getbegyx()[1], DISPLAY_H, 0 ) 440 | 441 | # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # 442 | # Helper functions 443 | 444 | def hex2(integer): 445 | return "0x" + hex(integer)[2:].zfill(2) 446 | 447 | def hex3(integer): 448 | return "0x" + hex(integer)[2:].zfill(3) 449 | 450 | def flush_key_buffer(): 451 | if termios: 452 | tcflush(stdin, TCIOFLUSH) 453 | else: 454 | while kbhit(): 455 | getch() 456 | 457 | -------------------------------------------------------------------------------- /minimized/chip8/emulator.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | 3 | from re import match 4 | from random import randint 5 | from os.path import getsize 6 | from time import time 7 | from collections import namedtuple 8 | 9 | OP_CODES = ( 10 | ('cls' , ('00e0',())), 11 | ('ret' , ('00ee',())), 12 | ('sys' , ('0(^0)..',('addr',))), # prevent match to cls or ret 13 | ('call', ('2...',('addr',))), 14 | ('skp' , ('e.9e',('reg',))), 15 | ('sknp', ('e.a1',('reg',))), 16 | ('se' ,(('5..0',('reg','reg')), 17 | ('3...',('reg','byte')))), 18 | ('sne' ,(('9..0',('reg','reg')), 19 | ('4...',('reg','byte')))), 20 | ('add' ,(('7...',('reg','byte')), 21 | ('8..4',('reg','reg')), 22 | ('f.1e',('i','reg')))), 23 | ('or' , ('8..1',('reg','reg'))), 24 | ('and' , ('8..2',('reg','reg'))), 25 | ('xor' , ('8..3',('reg','reg'))), 26 | ('sub' , ('8..5',('reg','reg'))), 27 | ('subn', ('8..7',('reg','reg'))), 28 | ('shr' ,(('8..6',('reg',)), 29 | (' ',('reg','reg')))), # Blank regex, we never match, use Legacy_shift instead 30 | ('shl' ,(('8..e',('reg',)), 31 | (' ',('reg','reg')))), # as above 32 | ('rnd' , ('c...',('reg','byte'))), 33 | ('jp' ,(('b...',('v0','addr')), 34 | ('1...',('addr',)))), 35 | ('ld' ,(('6...',('reg','byte')), 36 | ('8..0',('reg','reg')), 37 | ('f.07',('reg','dt')), 38 | ('f.0a',('reg','k')), 39 | ('f.65',('reg','(i)')), 40 | ('a...',('i','addr')), 41 | ('f.15',('dt','reg')), 42 | ('f.18',('st','reg')), 43 | ('f.29',('f','reg')), 44 | ('f.33',('b','reg')), 45 | ('f.55',('(i)','reg')))), 46 | ('drw' , ('d...',('reg','reg','nibble'))) 47 | ) 48 | 49 | class ASMdata( namedtuple('ASMdata', 'hex_instruction valid mnemonic\ 50 | mnemonic_arg_types disassembled_line unoffical_op banned super8') ): 51 | pass 52 | 53 | def explode_op_codes( op_code_list ): 54 | exploded_list = [] 55 | for item in op_code_list: 56 | if item.find('.') == -1: 57 | exploded_list.append(item) 58 | else: 59 | upper,repl,fill = 16,'.',1 60 | if item[2:] == '..': 61 | upper,repl,fill = 256,'..',2 62 | for i in range(0, upper): 63 | exploded_list.append(item.replace(repl, hex(i)[2:].zfill(fill))) 64 | return exploded_list 65 | 66 | class RomLoadError(Exception): pass 67 | class StackUnderflowError(Exception): pass 68 | class StackOverflowError(Exception): pass 69 | class InvalidInstructionError(Exception): pass 70 | class DisassemblerError(Exception): pass 71 | 72 | class Emulator: 73 | 74 | SET_VF_ON_GFX_OVERFLOW = False # Undocumented 'feature'. When 'Add I, VX' overflows 'I' 75 | # VF is set to one when this is True. The insturction does 76 | # not set VF low. Used by Spacefight 2019. 77 | ENABLE_LEGACY_SHIFT = False # Legacy Shift is performed by copying y into x and shifting, 78 | # rather than shifting x. Not sure who uses this. 79 | NUMB_OF_REGS = 16 80 | BYTES_OF_RAM = 4096 81 | MAX_ROM_SIZE = 3232 82 | PROGRAM_BEGIN_ADDRESS = 0x200 # Some use 0x600 83 | 84 | STACK_SIZE = 12 85 | STACK_ADDRESS = None 86 | 87 | GFX_ADDRESS = 0xF00 88 | GFX_HEIGHT_PX = 32 89 | GFX_WIDTH_PX = 64 90 | GFX_WIDTH = 8 91 | GFX_RESOLUTION = 8*32 #In bytes 92 | 93 | GFX_FONT_ADDRESS = 0x050 94 | GFX_FONT = ( 95 | 0xF0, 0x90, 0x90, 0x90, 0xF0, 0x20, 0x60, 0x20, 0x20, 0x70, # 0 1 96 | 0xF0, 0x10, 0xF0, 0x80, 0xF0, 0xF0, 0x10, 0xF0, 0x10, 0xF0, # 2 3 97 | 0x90, 0x90, 0xF0, 0x10, 0x10, 0xF0, 0x80, 0xF0, 0x10, 0xF0, # 4 5 98 | 0xF0, 0x80, 0xF0, 0x90, 0xF0, 0xF0, 0x10, 0x20, 0x40, 0x40, # 6 7 99 | 0xF0, 0x90, 0xF0, 0x90, 0xF0, 0xF0, 0x90, 0xF0, 0x10, 0xF0, # 8 9 100 | 0xF0, 0x90, 0xF0, 0x90, 0x90, 0xE0, 0x90, 0xE0, 0x90, 0xE0, # A B 101 | 0xF0, 0x80, 0x80, 0x80, 0xF0, 0xE0, 0x90, 0x90, 0x90, 0xE0, # C D 102 | 0xF0, 0x80, 0xF0, 0x80, 0xF0, 0xF0, 0x80, 0xF0, 0x80, 0x80 # E F 103 | ) 104 | 105 | OP_CODE_SIZE = 2 106 | UNOFFICIAL_OP_CODES = ('xor','shr','shl','subn') # But still supported 107 | BANNED_OP_CODES = ('7f..','8f.4','8f.6','8f.e','cf..','6f..','8f.0','ff07','ff0a','ff65') # Ins that modify VF: add, shr, shl, rnd, ld 108 | SUPER_CHIP_OP_CODES = ('00c.','00fb','00fc','00fd','00fe','00ff','d..0','f.30','f.75','f.85') # Super chip-8, not supported 109 | BANNED_OP_CODES_EXPLODED = explode_op_codes(BANNED_OP_CODES) 110 | SUPER_CHIP_OP_CODES_EXPLODED = explode_op_codes(SUPER_CHIP_OP_CODES) 111 | 112 | def __init__(self, rom=None, cpuhz=200, audiohz=60, delayhz=60): 113 | 114 | # RAM 115 | self.ram = [0x00] * Emulator.BYTES_OF_RAM 116 | 117 | # Registers 118 | self.register = [0x00] * Emulator.NUMB_OF_REGS 119 | self.index_register = 0x000 120 | self.delay_timer_register = 0x00 121 | self.sound_timer_register = 0x00 122 | 123 | # Current dissassembled instruction / OP Code 124 | self.dis_ins = None 125 | 126 | # Program Counter 127 | self.program_counter = Emulator.PROGRAM_BEGIN_ADDRESS 128 | self.calling_pc = Emulator.PROGRAM_BEGIN_ADDRESS 129 | 130 | # I/O 131 | self.keypad = [False] * 16 132 | self.prev_keypad = 0 133 | self.draw_flag = False 134 | self.waiting_for_key = False 135 | self.spinning = False 136 | 137 | # Stack 138 | self.stack = [] 139 | self.stack_pointer = 0 140 | 141 | # Timming variables 142 | self.cpu_wait = 1/cpuhz 143 | self.audio_wait = 1/audiohz 144 | self.delay_wait = 1/delayhz 145 | self._cpu_time = 0 146 | self._audio_time = 0 147 | self._delay_time = 0 148 | 149 | # Load Font, clear screen 150 | self.ram[Emulator.GFX_FONT_ADDRESS:Emulator.GFX_FONT_ADDRESS + len(Emulator.GFX_FONT)] = Emulator.GFX_FONT 151 | self.ram[Emulator.GFX_ADDRESS:Emulator.GFX_ADDRESS + Emulator.GFX_RESOLUTION] = [0x00] * Emulator.GFX_RESOLUTION 152 | 153 | # Load Rom 154 | if rom is not None: 155 | self.load_rom(rom) 156 | 157 | # Instruction lookup table 158 | self.ins_tbl={ 159 | 'cls' :i_cls, 'ret' :i_ret, 'sys' :i_sys, 'call':i_call, 160 | 'skp' :i_skp, 'sknp':i_sknp, 'se' :i_se, 'sne' :i_sne, 161 | 'add' :i_add, 'or' :i_or, 'and' :i_and, 'xor' :i_xor, 162 | 'sub' :i_sub, 'subn':i_subn, 'shr' :i_shr, 'shl' :i_shl, 163 | 'rnd' :i_rnd, 'jp' :i_jp, 'ld' :i_ld, 'drw' :i_drw} 164 | 165 | def load_rom(self, file_path): 166 | ''' 167 | Loads a Chip-8 ROM from a file into the RAM. 168 | ''' 169 | file_size = getsize(file_path) 170 | if file_size > Emulator.MAX_ROM_SIZE: 171 | raise RomLoadError 172 | 173 | with open(file_path, "rb") as fh: 174 | self.ram[Emulator.PROGRAM_BEGIN_ADDRESS:Emulator.PROGRAM_BEGIN_ADDRESS + file_size] = \ 175 | [int.from_bytes(fh.read(1), 'big') for i in range(file_size)] 176 | 177 | def run(self): 178 | ''' 179 | Attempt to run the next instruction. This should be called as a part 180 | of the main loop, it insures that the CPU and timers execute at the 181 | target frequency. 182 | ''' 183 | t = time() 184 | if self.cpu_wait <= (t - self._cpu_time): 185 | self.cpu_time = t 186 | self.cpu_tick() 187 | 188 | if self.audio_wait <= (t - self._audio_time): 189 | self.audio_time = t 190 | self.sound_timer_register -= 1 if self.sound_timer_register != 0 else 0 191 | 192 | if self.delay_wait <= (t - self._delay_time): 193 | self.delay_time = t 194 | self.delay_timer_register -= 1 if self.delay_timer_register != 0 else 0 195 | 196 | def cpu_tick(self): 197 | ''' 198 | Ticks the CPU forward a cycle without regard for the target frequency. 199 | ''' 200 | # Handle the ld reg,k instruction 201 | if self.waiting_for_key: 202 | self.handle_load_key() 203 | return 204 | else: 205 | self.prev_keypad = self.decode_keypad() 206 | 207 | self.calling_pc = self.program_counter 208 | 209 | # Disassemble next instruction 210 | self.dis_ins = None 211 | try: 212 | self.dis_ins = self.disassemble(self.ram[self.program_counter:self.program_counter+Emulator.OP_CODE_SIZE]) 213 | except: 214 | raise 215 | 216 | # Execute instruction 217 | if self.dis_ins.valid: 218 | self.ins_tbl[self.dis_ins.mnemonic](self) 219 | else: 220 | raise InvalidInstructionError(self.dis_ins) 221 | 222 | # Increment the PC 223 | self.program_counter += 2 224 | 225 | # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # 226 | # Helpers for Load Key 227 | 228 | def decode_keypad(self): 229 | ''' 230 | Helper method to decode the current keypad into a binary string 231 | ''' 232 | return int(''.join(['1' if x else '0' for x in self.keypad]),2) 233 | 234 | def handle_load_key(self): 235 | ''' 236 | Helper method to check if keys have changed and, if so, load the 237 | key per the ld reg,k instruction. 238 | ''' 239 | k = self.decode_keypad() 240 | nk = bin( (k ^ self.prev_keypad) & k )[2:].zfill(16).find('1') 241 | if nk != -1: 242 | self.register[ get_reg1(self) ] = nk 243 | self.program_counter += 2 244 | self.waiting_for_key = False 245 | 246 | # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # 247 | # Dissassembler 248 | 249 | @staticmethod 250 | def disassemble(byte_list): 251 | ''' 252 | A one line (2 byte) dissassembler function for CHIP-8 Rom. It 253 | returns a named tuple with various information on the line. 254 | ''' 255 | class EarlyExit(Exception): 256 | pass 257 | 258 | hex_instruction = hex( byte_list[0] )[2:].zfill(2) + hex( byte_list[1] )[2:].zfill(2) 259 | valid = False 260 | mnemonic = None 261 | mnemonic_arg_types = None 262 | disassembled_line = "" 263 | unoffical_op = False 264 | banned = False 265 | super8 = False 266 | 267 | try: 268 | # Check if the Op-Code a Super-8 instruction 269 | if hex_instruction in Emulator.SUPER_CHIP_OP_CODES_EXPLODED: 270 | mnemonic = 'SPR' 271 | super8 = True 272 | raise EarlyExit 273 | 274 | # Match the instruction via a regex index 275 | for instruction in OP_CODES: 276 | _mnemonic = instruction[0] 277 | reg_patterns = instruction[1] 278 | if type(reg_patterns[0]) is not tuple: 279 | reg_patterns = (reg_patterns,) 280 | for pattern_version in reg_patterns: 281 | if not pattern_version or not match(pattern_version[0], hex_instruction): 282 | continue 283 | mnemonic = _mnemonic 284 | mnemonic_arg_types = pattern_version[1] 285 | valid = True 286 | break 287 | if valid: 288 | break 289 | 290 | # If not a valid instruction, assume data 291 | if not valid: 292 | disassembled_line = hex_instruction 293 | raise EarlyExit 294 | 295 | # If banned, flag and exit. 296 | if hex_instruction in Emulator.BANNED_OP_CODES_EXPLODED: 297 | banned = True 298 | raise EarlyExit 299 | 300 | # If unoffical, flag it. 301 | if mnemonic in Emulator.UNOFFICIAL_OP_CODES: 302 | unoffical_op = True 303 | 304 | # No args to parse 305 | if mnemonic_arg_types is None: 306 | disassembled_line = mnemonic 307 | raise EarlyExit 308 | 309 | # Parse Args 310 | tmp = '' 311 | reg_numb = 1 312 | for arg_type in mnemonic_arg_types: 313 | if arg_type is 'reg': 314 | tmp = 'v'+hex_instruction[reg_numb] 315 | elif arg_type is 'byte': 316 | tmp = '#'+hex_instruction[2:] 317 | elif arg_type is 'addr': 318 | tmp = '#'+hex_instruction[1:] 319 | elif arg_type is 'nibble': 320 | tmp = '#'+hex_instruction[3] 321 | else: 322 | tmp = arg_type 323 | disassembled_line += tmp.ljust(5) + ',' 324 | reg_numb = 2 325 | 326 | disassembled_line = (mnemonic.ljust(5) + disassembled_line[:-1]).rstrip() 327 | except EarlyExit: 328 | pass 329 | except: 330 | raise 331 | finally: 332 | return ASMdata(hex_instruction, valid, mnemonic, 333 | mnemonic_arg_types, disassembled_line, unoffical_op, 334 | banned, super8) 335 | 336 | 337 | # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # 338 | # Instructions - All 20 mnemonics, 35 total instructions 339 | # Add-3 SE-2 SNE-2 LD-11 JP-2 (mnemonics w/ extra instructions) 340 | 341 | def i_cls(emu): 342 | emu.ram[Emulator.GFX_ADDRESS:Emulator.GFX_ADDRESS + Emulator.GFX_RESOLUTION] = [0x00] * Emulator.GFX_RESOLUTION 343 | emu.draw_flag = True 344 | 345 | def i_ret(emu): 346 | emu.stack_pointer -= 1 347 | if emu.stack_pointer < 0: 348 | raise StackUnderflowError 349 | emu.program_counter = emu.stack.pop() 350 | 351 | def i_sys(emu): 352 | pass 353 | 354 | def i_call(emu): 355 | if Emulator.STACK_ADDRESS: 356 | emu.ram[stack_pointer] = emu.program_counter 357 | emu.stack_pointer += 1 358 | emu.stack.append(emu.program_counter) 359 | if emu.stack_pointer > Emulator.STACK_SIZE: 360 | raise StackOverflowError 361 | emu.program_counter = get_address(emu) - 2 362 | 363 | def i_skp(emu): 364 | if emu.keypad[ get_reg1_val(emu) & 0x0F ]: 365 | emu.program_counter += 2 366 | 367 | def i_sknp(emu): 368 | if not emu.keypad[ get_reg1_val(emu) & 0x0F ]: 369 | emu.program_counter += 2 370 | 371 | def i_se(emu): 372 | comp = get_lower_byte(emu) if 'byte' is emu.dis_ins.mnemonic_arg_types[1] else get_reg2_val(emu) 373 | if get_reg1_val(emu) == comp: 374 | emu.program_counter += 2 375 | 376 | def i_sne(emu): 377 | comp = get_lower_byte(emu) if 'byte' is emu.dis_ins.mnemonic_arg_types[1] else get_reg2_val(emu) 378 | if get_reg1_val(emu) != comp: 379 | emu.program_counter += 2 380 | 381 | def i_shl(emu): 382 | if Emulator.ENABLE_LEGACY_SHIFT: 383 | emu.register[0xF] = 0x01 if get_reg2_val(emu) >= 0x80 else 0x0 384 | emu.register[ get_reg1(emu) ] = ( get_reg2_val(emu) << 1 ) & 0xFF 385 | else: 386 | emu.register[0xF] = 0x01 if get_reg1_val(emu) >= 0x80 else 0x0 387 | emu.register[ get_reg1(emu) ] = ( get_reg1_val(emu) << 1 ) & 0xFF 388 | 389 | def i_shr(emu): 390 | if Emulator.ENABLE_LEGACY_SHIFT: 391 | emu.register[0xF] = 0x01 if ( get_reg2_val(emu) % 2) == 1 else 0x0 392 | emu.register[ get_reg1(emu) ] = get_reg2_val(emu) >> 1 393 | else: 394 | emu.register[0xF] = 0x01 if ( get_reg1_val(emu) % 2) == 1 else 0x0 395 | emu.register[ get_reg1(emu) ] = get_reg1_val(emu) >> 1 396 | 397 | def i_or(emu): 398 | emu.register[ get_reg1(emu) ] = get_reg1_val(emu) | get_reg2_val(emu) 399 | 400 | def i_and(emu): 401 | emu.register[ get_reg1(emu) ] = get_reg1_val(emu) & get_reg2_val(emu) 402 | 403 | def i_xor(emu): 404 | emu.register[ get_reg1(emu) ] = get_reg1_val(emu) ^ get_reg2_val(emu) 405 | 406 | def i_sub(emu): 407 | emu.register[0xF] = 0x01 if get_reg1_val(emu) >= get_reg2_val(emu) else 0x00 408 | emu.register[ get_reg1(emu) ] = get_reg1_val(emu) - get_reg2_val(emu) 409 | emu.register[ get_reg1(emu) ] &= 0xFF 410 | 411 | def i_subn(emu): 412 | emu.register[0xF] = 0x01 if get_reg2_val(emu) >= get_reg1_val(emu) else 0x00 413 | emu.register[ get_reg1(emu) ] = get_reg2_val(emu) - get_reg1_val(emu) 414 | emu.register[ get_reg1(emu) ] &= 0xFF 415 | 416 | def i_jp(emu): 417 | init_pc = emu.program_counter 418 | numb_args = len(emu.dis_ins.mnemonic_arg_types) 419 | 420 | if 'v0' is emu.dis_ins.mnemonic_arg_types[0] and numb_args == 2: 421 | emu.program_counter = get_address(emu) + emu.register[0] - 2 422 | elif numb_args == 1: 423 | emu.program_counter = get_address(emu) - 2 424 | 425 | if init_pc == emu.program_counter + 2: 426 | emu.spinning = True 427 | 428 | def i_rnd(emu): 429 | emu.register[ get_reg1(emu) ] = randint(0, 255) & get_lower_byte(emu) 430 | 431 | def i_add(emu): 432 | arg1 = emu.dis_ins.mnemonic_arg_types[0] 433 | arg2 = emu.dis_ins.mnemonic_arg_types[1] 434 | 435 | if 'reg' is arg1: 436 | 437 | if 'byte' is arg2: 438 | emu.register[ get_reg1(emu) ] = get_reg1_val(emu) + get_lower_byte(emu) 439 | emu.register[ get_reg1(emu) ] &= 0xFF 440 | elif 'reg' is arg2: 441 | emu.register[ get_reg1(emu) ] = get_reg1_val(emu) + get_reg2_val(emu) 442 | emu.register[0xF] = 0x01 if emu.register[ get_reg1(emu) ] > 0xFF else 0x00 443 | emu.register[ get_reg1(emu) ] &= 0xFF 444 | 445 | elif 'i' in arg1 and 'reg' is arg2: 446 | emu.index_register += get_reg1_val(emu) 447 | if (emu.index_register > 0xFF) and Emulator.SET_VF_ON_GFX_OVERFLOW: 448 | emu.register[0xF] = 0x01 449 | emu.index_register &= 0xFFF 450 | 451 | def i_ld(emu): 452 | arg1 = emu.dis_ins.mnemonic_arg_types[0] 453 | arg2 = emu.dis_ins.mnemonic_arg_types[1] 454 | 455 | if 'reg' is arg1: 456 | if 'byte' is arg2: 457 | emu.register[ get_reg1(emu) ] = get_lower_byte(emu) 458 | elif 'reg' is arg2: 459 | emu.register[ get_reg1(emu) ] = get_reg2_val(emu) 460 | elif 'dt' is arg2: 461 | emu.register[ get_reg1(emu) ] = emu.delay_timer_register 462 | elif 'k' is arg2: 463 | emu.waiting_for_key = True 464 | emu.program_counter -= 2 465 | elif '[i]' == arg2: 466 | emu.register[0: get_reg1(emu) + 1] = emu.ram[ emu.index_register : emu.index_register + get_reg1(emu) + 1] 467 | 468 | elif 'reg' is arg2: 469 | if 'dt' is arg1: 470 | emu.delay_timer_register = get_reg1_val(emu) 471 | elif 'st' is arg1: 472 | emu.sound_timer_register = get_reg1_val(emu) 473 | elif 'f' is arg1: 474 | emu.index_register = Emulator.GFX_FONT_ADDRESS + ( 5 * get_reg1_val(emu) ) 475 | elif 'b' is arg1: 476 | bcd = [int(f) for f in list(str( get_reg1_val(emu) ).zfill(3))] 477 | emu.ram[ emu.index_register : emu.index_register + len(bcd)] = bcd 478 | elif '[i]' == arg1: 479 | emu.ram[ emu.index_register : emu.index_register + get_reg1(emu) + 1] = emu.register[0: get_reg1(emu) + 1] 480 | 481 | elif 'i' is arg1 and 'addr' is arg2: 482 | emu.index_register = get_address(emu) 483 | 484 | def i_drw(emu): 485 | emu.draw_flag = True 486 | height = int(emu.dis_ins.hex_instruction[3],16) 487 | x_origin_byte = int( get_reg1_val(emu) / 8 ) % Emulator.GFX_WIDTH 488 | y_origin_byte = (get_reg2_val(emu) % Emulator.GFX_HEIGHT_PX) * Emulator.GFX_WIDTH 489 | shift_amount = get_reg1_val(emu) % Emulator.GFX_WIDTH_PX % 8 490 | next_byte_offset = 1 if x_origin_byte + 1 != Emulator.GFX_WIDTH else 1-Emulator.GFX_WIDTH 491 | 492 | emu.register[0xF] = 0x00 493 | for y in range(height): 494 | sprite = emu.ram[ emu.index_register + y ] << (8-shift_amount) 495 | 496 | working_bytes = ( 497 | Emulator.GFX_ADDRESS + (( x_origin_byte + y_origin_byte + (y * Emulator.GFX_WIDTH) ) % Emulator.GFX_RESOLUTION) , 498 | Emulator.GFX_ADDRESS + (( x_origin_byte + y_origin_byte + (y * Emulator.GFX_WIDTH) + next_byte_offset ) % Emulator.GFX_RESOLUTION) 499 | ) 500 | 501 | original = ( emu.ram[ working_bytes[0] ], emu.ram[ working_bytes[1] ] ) 502 | xor = (original[0]*256 + original[1]) ^ sprite 503 | emu.ram[ working_bytes[0] ], emu.ram[ working_bytes[1] ] = xor >> 8, xor & 0x00FF 504 | 505 | if (bin( ( emu.ram[ working_bytes[0] ] ^ original[0] ) & original[0] ) + \ 506 | bin( ( emu.ram[ working_bytes[1] ] ^ original[1] ) & original[1] )).find('1') != -1: 507 | emu.register[0xF] = 0x01 508 | 509 | # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # 510 | # Hex Extraction 511 | 512 | get_address = lambda emu : int(emu.dis_ins.hex_instruction[1:4], 16) 513 | get_reg1 = lambda emu : int(emu.dis_ins.hex_instruction[1],16) 514 | get_reg2 = lambda emu : int(emu.dis_ins.hex_instruction[2],16) 515 | get_reg1_val = lambda emu : emu.register[int(emu.dis_ins.hex_instruction[1],16)] 516 | get_reg2_val = lambda emu : emu.register[int(emu.dis_ins.hex_instruction[2],16)] 517 | get_lower_byte = lambda emu : int(emu.dis_ins.hex_instruction[2:4], 16) 518 | 519 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | GNU GENERAL PUBLIC LICENSE 2 | Version 3, 29 June 2007 3 | 4 | Copyright (C) 2007 Free Software Foundation, Inc. 5 | Everyone is permitted to copy and distribute verbatim copies 6 | of this license document, but changing it is not allowed. 7 | 8 | Preamble 9 | 10 | The GNU General Public License is a free, copyleft license for 11 | software and other kinds of works. 12 | 13 | The licenses for most software and other practical works are designed 14 | to take away your freedom to share and change the works. By contrast, 15 | the GNU General Public License is intended to guarantee your freedom to 16 | share and change all versions of a program--to make sure it remains free 17 | software for all its users. We, the Free Software Foundation, use the 18 | GNU General Public License for most of our software; it applies also to 19 | any other work released this way by its authors. You can apply it to 20 | your programs, too. 21 | 22 | When we speak of free software, we are referring to freedom, not 23 | price. Our General Public Licenses are designed to make sure that you 24 | have the freedom to distribute copies of free software (and charge for 25 | them if you wish), that you receive source code or can get it if you 26 | want it, that you can change the software or use pieces of it in new 27 | free programs, and that you know you can do these things. 28 | 29 | To protect your rights, we need to prevent others from denying you 30 | these rights or asking you to surrender the rights. Therefore, you have 31 | certain responsibilities if you distribute copies of the software, or if 32 | you modify it: responsibilities to respect the freedom of others. 33 | 34 | For example, if you distribute copies of such a program, whether 35 | gratis or for a fee, you must pass on to the recipients the same 36 | freedoms that you received. You must make sure that they, too, receive 37 | or can get the source code. And you must show them these terms so they 38 | know their rights. 39 | 40 | Developers that use the GNU GPL protect your rights with two steps: 41 | (1) assert copyright on the software, and (2) offer you this License 42 | giving you legal permission to copy, distribute and/or modify it. 43 | 44 | For the developers' and authors' protection, the GPL clearly explains 45 | that there is no warranty for this free software. For both users' and 46 | authors' sake, the GPL requires that modified versions be marked as 47 | changed, so that their problems will not be attributed erroneously to 48 | authors of previous versions. 49 | 50 | Some devices are designed to deny users access to install or run 51 | modified versions of the software inside them, although the manufacturer 52 | can do so. This is fundamentally incompatible with the aim of 53 | protecting users' freedom to change the software. The systematic 54 | pattern of such abuse occurs in the area of products for individuals to 55 | use, which is precisely where it is most unacceptable. Therefore, we 56 | have designed this version of the GPL to prohibit the practice for those 57 | products. If such problems arise substantially in other domains, we 58 | stand ready to extend this provision to those domains in future versions 59 | of the GPL, as needed to protect the freedom of users. 60 | 61 | Finally, every program is threatened constantly by software patents. 62 | States should not allow patents to restrict development and use of 63 | software on general-purpose computers, but in those that do, we wish to 64 | avoid the special danger that patents applied to a free program could 65 | make it effectively proprietary. To prevent this, the GPL assures that 66 | patents cannot be used to render the program non-free. 67 | 68 | The precise terms and conditions for copying, distribution and 69 | modification follow. 70 | 71 | TERMS AND CONDITIONS 72 | 73 | 0. Definitions. 74 | 75 | "This License" refers to version 3 of the GNU General Public License. 76 | 77 | "Copyright" also means copyright-like laws that apply to other kinds of 78 | works, such as semiconductor masks. 79 | 80 | "The Program" refers to any copyrightable work licensed under this 81 | License. Each licensee is addressed as "you". "Licensees" and 82 | "recipients" may be individuals or organizations. 83 | 84 | To "modify" a work means to copy from or adapt all or part of the work 85 | in a fashion requiring copyright permission, other than the making of an 86 | exact copy. The resulting work is called a "modified version" of the 87 | earlier work or a work "based on" the earlier work. 88 | 89 | A "covered work" means either the unmodified Program or a work based 90 | on the Program. 91 | 92 | To "propagate" a work means to do anything with it that, without 93 | permission, would make you directly or secondarily liable for 94 | infringement under applicable copyright law, except executing it on a 95 | computer or modifying a private copy. Propagation includes copying, 96 | distribution (with or without modification), making available to the 97 | public, and in some countries other activities as well. 98 | 99 | To "convey" a work means any kind of propagation that enables other 100 | parties to make or receive copies. Mere interaction with a user through 101 | a computer network, with no transfer of a copy, is not conveying. 102 | 103 | An interactive user interface displays "Appropriate Legal Notices" 104 | to the extent that it includes a convenient and prominently visible 105 | feature that (1) displays an appropriate copyright notice, and (2) 106 | tells the user that there is no warranty for the work (except to the 107 | extent that warranties are provided), that licensees may convey the 108 | work under this License, and how to view a copy of this License. If 109 | the interface presents a list of user commands or options, such as a 110 | menu, a prominent item in the list meets this criterion. 111 | 112 | 1. Source Code. 113 | 114 | The "source code" for a work means the preferred form of the work 115 | for making modifications to it. "Object code" means any non-source 116 | form of a work. 117 | 118 | A "Standard Interface" means an interface that either is an official 119 | standard defined by a recognized standards body, or, in the case of 120 | interfaces specified for a particular programming language, one that 121 | is widely used among developers working in that language. 122 | 123 | The "System Libraries" of an executable work include anything, other 124 | than the work as a whole, that (a) is included in the normal form of 125 | packaging a Major Component, but which is not part of that Major 126 | Component, and (b) serves only to enable use of the work with that 127 | Major Component, or to implement a Standard Interface for which an 128 | implementation is available to the public in source code form. A 129 | "Major Component", in this context, means a major essential component 130 | (kernel, window system, and so on) of the specific operating system 131 | (if any) on which the executable work runs, or a compiler used to 132 | produce the work, or an object code interpreter used to run it. 133 | 134 | The "Corresponding Source" for a work in object code form means all 135 | the source code needed to generate, install, and (for an executable 136 | work) run the object code and to modify the work, including scripts to 137 | control those activities. However, it does not include the work's 138 | System Libraries, or general-purpose tools or generally available free 139 | programs which are used unmodified in performing those activities but 140 | which are not part of the work. For example, Corresponding Source 141 | includes interface definition files associated with source files for 142 | the work, and the source code for shared libraries and dynamically 143 | linked subprograms that the work is specifically designed to require, 144 | such as by intimate data communication or control flow between those 145 | subprograms and other parts of the work. 146 | 147 | The Corresponding Source need not include anything that users 148 | can regenerate automatically from other parts of the Corresponding 149 | Source. 150 | 151 | The Corresponding Source for a work in source code form is that 152 | same work. 153 | 154 | 2. Basic Permissions. 155 | 156 | All rights granted under this License are granted for the term of 157 | copyright on the Program, and are irrevocable provided the stated 158 | conditions are met. This License explicitly affirms your unlimited 159 | permission to run the unmodified Program. The output from running a 160 | covered work is covered by this License only if the output, given its 161 | content, constitutes a covered work. This License acknowledges your 162 | rights of fair use or other equivalent, as provided by copyright law. 163 | 164 | You may make, run and propagate covered works that you do not 165 | convey, without conditions so long as your license otherwise remains 166 | in force. You may convey covered works to others for the sole purpose 167 | of having them make modifications exclusively for you, or provide you 168 | with facilities for running those works, provided that you comply with 169 | the terms of this License in conveying all material for which you do 170 | not control copyright. Those thus making or running the covered works 171 | for you must do so exclusively on your behalf, under your direction 172 | and control, on terms that prohibit them from making any copies of 173 | your copyrighted material outside their relationship with you. 174 | 175 | Conveying under any other circumstances is permitted solely under 176 | the conditions stated below. Sublicensing is not allowed; section 10 177 | makes it unnecessary. 178 | 179 | 3. Protecting Users' Legal Rights From Anti-Circumvention Law. 180 | 181 | No covered work shall be deemed part of an effective technological 182 | measure under any applicable law fulfilling obligations under article 183 | 11 of the WIPO copyright treaty adopted on 20 December 1996, or 184 | similar laws prohibiting or restricting circumvention of such 185 | measures. 186 | 187 | When you convey a covered work, you waive any legal power to forbid 188 | circumvention of technological measures to the extent such circumvention 189 | is effected by exercising rights under this License with respect to 190 | the covered work, and you disclaim any intention to limit operation or 191 | modification of the work as a means of enforcing, against the work's 192 | users, your or third parties' legal rights to forbid circumvention of 193 | technological measures. 194 | 195 | 4. Conveying Verbatim Copies. 196 | 197 | You may convey verbatim copies of the Program's source code as you 198 | receive it, in any medium, provided that you conspicuously and 199 | appropriately publish on each copy an appropriate copyright notice; 200 | keep intact all notices stating that this License and any 201 | non-permissive terms added in accord with section 7 apply to the code; 202 | keep intact all notices of the absence of any warranty; and give all 203 | recipients a copy of this License along with the Program. 204 | 205 | You may charge any price or no price for each copy that you convey, 206 | and you may offer support or warranty protection for a fee. 207 | 208 | 5. Conveying Modified Source Versions. 209 | 210 | You may convey a work based on the Program, or the modifications to 211 | produce it from the Program, in the form of source code under the 212 | terms of section 4, provided that you also meet all of these conditions: 213 | 214 | a) The work must carry prominent notices stating that you modified 215 | it, and giving a relevant date. 216 | 217 | b) The work must carry prominent notices stating that it is 218 | released under this License and any conditions added under section 219 | 7. This requirement modifies the requirement in section 4 to 220 | "keep intact all notices". 221 | 222 | c) You must license the entire work, as a whole, under this 223 | License to anyone who comes into possession of a copy. This 224 | License will therefore apply, along with any applicable section 7 225 | additional terms, to the whole of the work, and all its parts, 226 | regardless of how they are packaged. This License gives no 227 | permission to license the work in any other way, but it does not 228 | invalidate such permission if you have separately received it. 229 | 230 | d) If the work has interactive user interfaces, each must display 231 | Appropriate Legal Notices; however, if the Program has interactive 232 | interfaces that do not display Appropriate Legal Notices, your 233 | work need not make them do so. 234 | 235 | A compilation of a covered work with other separate and independent 236 | works, which are not by their nature extensions of the covered work, 237 | and which are not combined with it such as to form a larger program, 238 | in or on a volume of a storage or distribution medium, is called an 239 | "aggregate" if the compilation and its resulting copyright are not 240 | used to limit the access or legal rights of the compilation's users 241 | beyond what the individual works permit. Inclusion of a covered work 242 | in an aggregate does not cause this License to apply to the other 243 | parts of the aggregate. 244 | 245 | 6. Conveying Non-Source Forms. 246 | 247 | You may convey a covered work in object code form under the terms 248 | of sections 4 and 5, provided that you also convey the 249 | machine-readable Corresponding Source under the terms of this License, 250 | in one of these ways: 251 | 252 | a) Convey the object code in, or embodied in, a physical product 253 | (including a physical distribution medium), accompanied by the 254 | Corresponding Source fixed on a durable physical medium 255 | customarily used for software interchange. 256 | 257 | b) Convey the object code in, or embodied in, a physical product 258 | (including a physical distribution medium), accompanied by a 259 | written offer, valid for at least three years and valid for as 260 | long as you offer spare parts or customer support for that product 261 | model, to give anyone who possesses the object code either (1) a 262 | copy of the Corresponding Source for all the software in the 263 | product that is covered by this License, on a durable physical 264 | medium customarily used for software interchange, for a price no 265 | more than your reasonable cost of physically performing this 266 | conveying of source, or (2) access to copy the 267 | Corresponding Source from a network server at no charge. 268 | 269 | c) Convey individual copies of the object code with a copy of the 270 | written offer to provide the Corresponding Source. This 271 | alternative is allowed only occasionally and noncommercially, and 272 | only if you received the object code with such an offer, in accord 273 | with subsection 6b. 274 | 275 | d) Convey the object code by offering access from a designated 276 | place (gratis or for a charge), and offer equivalent access to the 277 | Corresponding Source in the same way through the same place at no 278 | further charge. You need not require recipients to copy the 279 | Corresponding Source along with the object code. If the place to 280 | copy the object code is a network server, the Corresponding Source 281 | may be on a different server (operated by you or a third party) 282 | that supports equivalent copying facilities, provided you maintain 283 | clear directions next to the object code saying where to find the 284 | Corresponding Source. Regardless of what server hosts the 285 | Corresponding Source, you remain obligated to ensure that it is 286 | available for as long as needed to satisfy these requirements. 287 | 288 | e) Convey the object code using peer-to-peer transmission, provided 289 | you inform other peers where the object code and Corresponding 290 | Source of the work are being offered to the general public at no 291 | charge under subsection 6d. 292 | 293 | A separable portion of the object code, whose source code is excluded 294 | from the Corresponding Source as a System Library, need not be 295 | included in conveying the object code work. 296 | 297 | A "User Product" is either (1) a "consumer product", which means any 298 | tangible personal property which is normally used for personal, family, 299 | or household purposes, or (2) anything designed or sold for incorporation 300 | into a dwelling. In determining whether a product is a consumer product, 301 | doubtful cases shall be resolved in favor of coverage. For a particular 302 | product received by a particular user, "normally used" refers to a 303 | typical or common use of that class of product, regardless of the status 304 | of the particular user or of the way in which the particular user 305 | actually uses, or expects or is expected to use, the product. A product 306 | is a consumer product regardless of whether the product has substantial 307 | commercial, industrial or non-consumer uses, unless such uses represent 308 | the only significant mode of use of the product. 309 | 310 | "Installation Information" for a User Product means any methods, 311 | procedures, authorization keys, or other information required to install 312 | and execute modified versions of a covered work in that User Product from 313 | a modified version of its Corresponding Source. The information must 314 | suffice to ensure that the continued functioning of the modified object 315 | code is in no case prevented or interfered with solely because 316 | modification has been made. 317 | 318 | If you convey an object code work under this section in, or with, or 319 | specifically for use in, a User Product, and the conveying occurs as 320 | part of a transaction in which the right of possession and use of the 321 | User Product is transferred to the recipient in perpetuity or for a 322 | fixed term (regardless of how the transaction is characterized), the 323 | Corresponding Source conveyed under this section must be accompanied 324 | by the Installation Information. But this requirement does not apply 325 | if neither you nor any third party retains the ability to install 326 | modified object code on the User Product (for example, the work has 327 | been installed in ROM). 328 | 329 | The requirement to provide Installation Information does not include a 330 | requirement to continue to provide support service, warranty, or updates 331 | for a work that has been modified or installed by the recipient, or for 332 | the User Product in which it has been modified or installed. Access to a 333 | network may be denied when the modification itself materially and 334 | adversely affects the operation of the network or violates the rules and 335 | protocols for communication across the network. 336 | 337 | Corresponding Source conveyed, and Installation Information provided, 338 | in accord with this section must be in a format that is publicly 339 | documented (and with an implementation available to the public in 340 | source code form), and must require no special password or key for 341 | unpacking, reading or copying. 342 | 343 | 7. Additional Terms. 344 | 345 | "Additional permissions" are terms that supplement the terms of this 346 | License by making exceptions from one or more of its conditions. 347 | Additional permissions that are applicable to the entire Program shall 348 | be treated as though they were included in this License, to the extent 349 | that they are valid under applicable law. If additional permissions 350 | apply only to part of the Program, that part may be used separately 351 | under those permissions, but the entire Program remains governed by 352 | this License without regard to the additional permissions. 353 | 354 | When you convey a copy of a covered work, you may at your option 355 | remove any additional permissions from that copy, or from any part of 356 | it. (Additional permissions may be written to require their own 357 | removal in certain cases when you modify the work.) You may place 358 | additional permissions on material, added by you to a covered work, 359 | for which you have or can give appropriate copyright permission. 360 | 361 | Notwithstanding any other provision of this License, for material you 362 | add to a covered work, you may (if authorized by the copyright holders of 363 | that material) supplement the terms of this License with terms: 364 | 365 | a) Disclaiming warranty or limiting liability differently from the 366 | terms of sections 15 and 16 of this License; or 367 | 368 | b) Requiring preservation of specified reasonable legal notices or 369 | author attributions in that material or in the Appropriate Legal 370 | Notices displayed by works containing it; or 371 | 372 | c) Prohibiting misrepresentation of the origin of that material, or 373 | requiring that modified versions of such material be marked in 374 | reasonable ways as different from the original version; or 375 | 376 | d) Limiting the use for publicity purposes of names of licensors or 377 | authors of the material; or 378 | 379 | e) Declining to grant rights under trademark law for use of some 380 | trade names, trademarks, or service marks; or 381 | 382 | f) Requiring indemnification of licensors and authors of that 383 | material by anyone who conveys the material (or modified versions of 384 | it) with contractual assumptions of liability to the recipient, for 385 | any liability that these contractual assumptions directly impose on 386 | those licensors and authors. 387 | 388 | All other non-permissive additional terms are considered "further 389 | restrictions" within the meaning of section 10. If the Program as you 390 | received it, or any part of it, contains a notice stating that it is 391 | governed by this License along with a term that is a further 392 | restriction, you may remove that term. If a license document contains 393 | a further restriction but permits relicensing or conveying under this 394 | License, you may add to a covered work material governed by the terms 395 | of that license document, provided that the further restriction does 396 | not survive such relicensing or conveying. 397 | 398 | If you add terms to a covered work in accord with this section, you 399 | must place, in the relevant source files, a statement of the 400 | additional terms that apply to those files, or a notice indicating 401 | where to find the applicable terms. 402 | 403 | Additional terms, permissive or non-permissive, may be stated in the 404 | form of a separately written license, or stated as exceptions; 405 | the above requirements apply either way. 406 | 407 | 8. Termination. 408 | 409 | You may not propagate or modify a covered work except as expressly 410 | provided under this License. Any attempt otherwise to propagate or 411 | modify it is void, and will automatically terminate your rights under 412 | this License (including any patent licenses granted under the third 413 | paragraph of section 11). 414 | 415 | However, if you cease all violation of this License, then your 416 | license from a particular copyright holder is reinstated (a) 417 | provisionally, unless and until the copyright holder explicitly and 418 | finally terminates your license, and (b) permanently, if the copyright 419 | holder fails to notify you of the violation by some reasonable means 420 | prior to 60 days after the cessation. 421 | 422 | Moreover, your license from a particular copyright holder is 423 | reinstated permanently if the copyright holder notifies you of the 424 | violation by some reasonable means, this is the first time you have 425 | received notice of violation of this License (for any work) from that 426 | copyright holder, and you cure the violation prior to 30 days after 427 | your receipt of the notice. 428 | 429 | Termination of your rights under this section does not terminate the 430 | licenses of parties who have received copies or rights from you under 431 | this License. If your rights have been terminated and not permanently 432 | reinstated, you do not qualify to receive new licenses for the same 433 | material under section 10. 434 | 435 | 9. Acceptance Not Required for Having Copies. 436 | 437 | You are not required to accept this License in order to receive or 438 | run a copy of the Program. Ancillary propagation of a covered work 439 | occurring solely as a consequence of using peer-to-peer transmission 440 | to receive a copy likewise does not require acceptance. However, 441 | nothing other than this License grants you permission to propagate or 442 | modify any covered work. These actions infringe copyright if you do 443 | not accept this License. Therefore, by modifying or propagating a 444 | covered work, you indicate your acceptance of this License to do so. 445 | 446 | 10. Automatic Licensing of Downstream Recipients. 447 | 448 | Each time you convey a covered work, the recipient automatically 449 | receives a license from the original licensors, to run, modify and 450 | propagate that work, subject to this License. You are not responsible 451 | for enforcing compliance by third parties with this License. 452 | 453 | An "entity transaction" is a transaction transferring control of an 454 | organization, or substantially all assets of one, or subdividing an 455 | organization, or merging organizations. If propagation of a covered 456 | work results from an entity transaction, each party to that 457 | transaction who receives a copy of the work also receives whatever 458 | licenses to the work the party's predecessor in interest had or could 459 | give under the previous paragraph, plus a right to possession of the 460 | Corresponding Source of the work from the predecessor in interest, if 461 | the predecessor has it or can get it with reasonable efforts. 462 | 463 | You may not impose any further restrictions on the exercise of the 464 | rights granted or affirmed under this License. For example, you may 465 | not impose a license fee, royalty, or other charge for exercise of 466 | rights granted under this License, and you may not initiate litigation 467 | (including a cross-claim or counterclaim in a lawsuit) alleging that 468 | any patent claim is infringed by making, using, selling, offering for 469 | sale, or importing the Program or any portion of it. 470 | 471 | 11. Patents. 472 | 473 | A "contributor" is a copyright holder who authorizes use under this 474 | License of the Program or a work on which the Program is based. The 475 | work thus licensed is called the contributor's "contributor version". 476 | 477 | A contributor's "essential patent claims" are all patent claims 478 | owned or controlled by the contributor, whether already acquired or 479 | hereafter acquired, that would be infringed by some manner, permitted 480 | by this License, of making, using, or selling its contributor version, 481 | but do not include claims that would be infringed only as a 482 | consequence of further modification of the contributor version. For 483 | purposes of this definition, "control" includes the right to grant 484 | patent sublicenses in a manner consistent with the requirements of 485 | this License. 486 | 487 | Each contributor grants you a non-exclusive, worldwide, royalty-free 488 | patent license under the contributor's essential patent claims, to 489 | make, use, sell, offer for sale, import and otherwise run, modify and 490 | propagate the contents of its contributor version. 491 | 492 | In the following three paragraphs, a "patent license" is any express 493 | agreement or commitment, however denominated, not to enforce a patent 494 | (such as an express permission to practice a patent or covenant not to 495 | sue for patent infringement). To "grant" such a patent license to a 496 | party means to make such an agreement or commitment not to enforce a 497 | patent against the party. 498 | 499 | If you convey a covered work, knowingly relying on a patent license, 500 | and the Corresponding Source of the work is not available for anyone 501 | to copy, free of charge and under the terms of this License, through a 502 | publicly available network server or other readily accessible means, 503 | then you must either (1) cause the Corresponding Source to be so 504 | available, or (2) arrange to deprive yourself of the benefit of the 505 | patent license for this particular work, or (3) arrange, in a manner 506 | consistent with the requirements of this License, to extend the patent 507 | license to downstream recipients. "Knowingly relying" means you have 508 | actual knowledge that, but for the patent license, your conveying the 509 | covered work in a country, or your recipient's use of the covered work 510 | in a country, would infringe one or more identifiable patents in that 511 | country that you have reason to believe are valid. 512 | 513 | If, pursuant to or in connection with a single transaction or 514 | arrangement, you convey, or propagate by procuring conveyance of, a 515 | covered work, and grant a patent license to some of the parties 516 | receiving the covered work authorizing them to use, propagate, modify 517 | or convey a specific copy of the covered work, then the patent license 518 | you grant is automatically extended to all recipients of the covered 519 | work and works based on it. 520 | 521 | A patent license is "discriminatory" if it does not include within 522 | the scope of its coverage, prohibits the exercise of, or is 523 | conditioned on the non-exercise of one or more of the rights that are 524 | specifically granted under this License. You may not convey a covered 525 | work if you are a party to an arrangement with a third party that is 526 | in the business of distributing software, under which you make payment 527 | to the third party based on the extent of your activity of conveying 528 | the work, and under which the third party grants, to any of the 529 | parties who would receive the covered work from you, a discriminatory 530 | patent license (a) in connection with copies of the covered work 531 | conveyed by you (or copies made from those copies), or (b) primarily 532 | for and in connection with specific products or compilations that 533 | contain the covered work, unless you entered into that arrangement, 534 | or that patent license was granted, prior to 28 March 2007. 535 | 536 | Nothing in this License shall be construed as excluding or limiting 537 | any implied license or other defenses to infringement that may 538 | otherwise be available to you under applicable patent law. 539 | 540 | 12. No Surrender of Others' Freedom. 541 | 542 | If conditions are imposed on you (whether by court order, agreement or 543 | otherwise) that contradict the conditions of this License, they do not 544 | excuse you from the conditions of this License. If you cannot convey a 545 | covered work so as to satisfy simultaneously your obligations under this 546 | License and any other pertinent obligations, then as a consequence you may 547 | not convey it at all. For example, if you agree to terms that obligate you 548 | to collect a royalty for further conveying from those to whom you convey 549 | the Program, the only way you could satisfy both those terms and this 550 | License would be to refrain entirely from conveying the Program. 551 | 552 | 13. Use with the GNU Affero General Public License. 553 | 554 | Notwithstanding any other provision of this License, you have 555 | permission to link or combine any covered work with a work licensed 556 | under version 3 of the GNU Affero General Public License into a single 557 | combined work, and to convey the resulting work. The terms of this 558 | License will continue to apply to the part which is the covered work, 559 | but the special requirements of the GNU Affero General Public License, 560 | section 13, concerning interaction through a network will apply to the 561 | combination as such. 562 | 563 | 14. Revised Versions of this License. 564 | 565 | The Free Software Foundation may publish revised and/or new versions of 566 | the GNU General Public License from time to time. Such new versions will 567 | be similar in spirit to the present version, but may differ in detail to 568 | address new problems or concerns. 569 | 570 | Each version is given a distinguishing version number. If the 571 | Program specifies that a certain numbered version of the GNU General 572 | Public License "or any later version" applies to it, you have the 573 | option of following the terms and conditions either of that numbered 574 | version or of any later version published by the Free Software 575 | Foundation. If the Program does not specify a version number of the 576 | GNU General Public License, you may choose any version ever published 577 | by the Free Software Foundation. 578 | 579 | If the Program specifies that a proxy can decide which future 580 | versions of the GNU General Public License can be used, that proxy's 581 | public statement of acceptance of a version permanently authorizes you 582 | to choose that version for the Program. 583 | 584 | Later license versions may give you additional or different 585 | permissions. However, no additional obligations are imposed on any 586 | author or copyright holder as a result of your choosing to follow a 587 | later version. 588 | 589 | 15. Disclaimer of Warranty. 590 | 591 | THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY 592 | APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT 593 | HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY 594 | OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, 595 | THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR 596 | PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM 597 | IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF 598 | ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 599 | 600 | 16. Limitation of Liability. 601 | 602 | IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING 603 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS 604 | THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY 605 | GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE 606 | USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF 607 | DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD 608 | PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), 609 | EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF 610 | SUCH DAMAGES. 611 | 612 | 17. Interpretation of Sections 15 and 16. 613 | 614 | If the disclaimer of warranty and limitation of liability provided 615 | above cannot be given local legal effect according to their terms, 616 | reviewing courts shall apply local law that most closely approximates 617 | an absolute waiver of all civil liability in connection with the 618 | Program, unless a warranty or assumption of liability accompanies a 619 | copy of the Program in return for a fee. 620 | 621 | END OF TERMS AND CONDITIONS 622 | 623 | How to Apply These Terms to Your New Programs 624 | 625 | If you develop a new program, and you want it to be of the greatest 626 | possible use to the public, the best way to achieve this is to make it 627 | free software which everyone can redistribute and change under these terms. 628 | 629 | To do so, attach the following notices to the program. It is safest 630 | to attach them to the start of each source file to most effectively 631 | state the exclusion of warranty; and each file should have at least 632 | the "copyright" line and a pointer to where the full notice is found. 633 | 634 | {one line to give the program's name and a brief idea of what it does.} 635 | Copyright (C) {year} {name of author} 636 | 637 | This program is free software: you can redistribute it and/or modify 638 | it under the terms of the GNU General Public License as published by 639 | the Free Software Foundation, either version 3 of the License, or 640 | (at your option) any later version. 641 | 642 | This program is distributed in the hope that it will be useful, 643 | but WITHOUT ANY WARRANTY; without even the implied warranty of 644 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 645 | GNU General Public License for more details. 646 | 647 | You should have received a copy of the GNU General Public License 648 | along with this program. If not, see . 649 | 650 | Also add information on how to contact you by electronic and paper mail. 651 | 652 | If the program does terminal interaction, make it output a short 653 | notice like this when it starts in an interactive mode: 654 | 655 | {project} Copyright (C) {year} {fullname} 656 | This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. 657 | This is free software, and you are welcome to redistribute it 658 | under certain conditions; type `show c' for details. 659 | 660 | The hypothetical commands `show w' and `show c' should show the appropriate 661 | parts of the General Public License. Of course, your program's commands 662 | might be different; for a GUI interface, you would use an "about box". 663 | 664 | You should also get your employer (if you work as a programmer) or school, 665 | if any, to sign a "copyright disclaimer" for the program, if necessary. 666 | For more information on this, and how to apply and follow the GNU GPL, see 667 | . 668 | 669 | The GNU General Public License does not permit incorporating your program 670 | into proprietary programs. If your program is a subroutine library, you 671 | may consider it more useful to permit linking proprietary applications with 672 | the library. If this is what you want to do, use the GNU Lesser General 673 | Public License instead of this License. But first, please read 674 | . 675 | --------------------------------------------------------------------------------