Skip to content

Free games for graphing calculators: NumWorks, TI-Nspire CX, Casio fx-CG50 and soon TI-84 Plus CE. Balatro, Celeste, Hollow Knight, Minecraft and more.

Retro-Go: Game Boy, Game Boy Color and NES games from the customizer's table

Mason363a1250a4b6868
diff --git a/Makefile b/Makefile
index dc8e38ce..7b1aa272 100644
--- a/Makefile
+++ b/Makefile
@@ -114,6 +114,13 @@ $(B)/gen/gametable.c: games/games.json tools/gen_games.py $(MODULES)
$(B)/gen/shots_%.c: games/games.json tools/shots.py $$(SHOTS_$$*) | $(B)
cd games/$* && $(PY) ../../tools/shots.py --id $* --index $(INDEX_$*) $(COLORS_$*) ../../$@ $(SHOTS_REL_$*)
+# Retro-Go's table of games (tools/romtable.py): empty, or ROMS="a.gb b.nes" to try some games
+# in a build of one's own; the customizer website makes its own table. It goes with retrogo's
+# module (numplay.ld puts it in retrogo's block of flash).
+ROMS ?=
+$(B)/arm/roms.o: FORCE | $(B)
+ $(PY) tools/romtable.py -o $@ $(ROMS)
+
# ------------------------------------------------------------------ NumPlay.nwa
ARM_OBJS = $(patsubst launcher/src/%.c,$(B)/arm/%.o,$(LAUNCHER_SRC)) $(B)/arm/gametable.o $(B)/arm/arena.o \
$(B)/arm/marks.o $(foreach g,$(GAMES),$(B)/arm/shots_$(g).o)
@@ -148,6 +155,10 @@ check: nwa apps
@for a in $(BIG_APPS); do $(NWLINK) nwa-bin --ram-length $(CUSTOM_RAM) $(B)/apps/$$a.nwa $(B)/apps/$$a.bin >/dev/null || \
{ echo "$$a.nwa needs more RAM than custom builds of 25.2 give apps ($(CUSTOM_RAM) bytes)"; exit 1; }; done; \
echo "NumPlay's games and $(BIG_APPS) fit in $(CUSTOM_RAM) bytes of RAM"
+ @for a in $(foreach g,$(OPTIONAL_GAMES),$(if $(NWA_$(g)),$(basename $(NWA_$(g))))); do \
+ $(NWLINK) nwa-bin --ram-length $(CUSTOM_RAM) $(B)/apps/$$a.nwa $(B)/apps/$$a.bin >/dev/null || \
+ { echo "$$a.nwa needs more RAM than custom builds of 25.2 give apps ($(CUSTOM_RAM) bytes)"; exit 1; }; \
+ echo "$$a.nwa (not in NumPlay.nwa: the customizer adds it) fits in $(CUSTOM_RAM) bytes of RAM"; done
@x=$$(cat $(B)/gen-upsilon/arena_extra); \
$(NWLINK) nwa-bin --ram-length $$(( $(UPSILON_RAM) - x )) $(B)/NumPlay-Upsilon.nwa $(B)/NumPlay-Upsilon.bin && \
echo "NumPlay-Upsilon.nwa installs as $$(wc -c < $(B)/NumPlay-Upsilon.bin) bytes; its RAM and any game's fit in $(UPSILON_RAM) bytes"
diff --git a/games/games.json b/games/games.json
index 46baffab..11f2fc0c 100644
--- a/games/games.json
+++ b/games/games.json
@@ -377,5 +377,33 @@
],
"colors": 48,
"repo": "https://github.com/Mason363/NumPlay/tree/main/games/numvisuals"
+ },
+ {
+ "id": "retrogo",
+ "title": "Retro-Go",
+ "tagline": "Game Boy and NES games",
+ "credit": "Based on Retro-Go by ducalex",
+ "top": "0xE84B39",
+ "bottom": "0x1E1430",
+ "accent": "0x3199DC",
+ "records": [
+ "retrogo.cfg",
+ "rg_*"
+ ],
+ "reset": [
+ "rg_*"
+ ],
+ "shots": [
+ "docs/shot.png"
+ ],
+ "app": "RetroGo.nwa",
+ "repo": "https://github.com/Mason363/NumPlay/tree/main/games/retrogo",
+ "default": false,
+ "roms": true,
+ "systems": [
+ 1,
+ 2,
+ 3
+ ]
}
]
diff --git a/games/retrogo/.gitignore b/games/retrogo/.gitignore
new file mode 100644
index 00000000..ea1472ec
--- /dev/null
+++ b/games/retrogo/.gitignore
@@ -0,0 +1 @@
+output/
diff --git a/games/retrogo/Makefile b/games/retrogo/Makefile
new file mode 100644
index 00000000..afc5055e
--- /dev/null
+++ b/games/retrogo/Makefile
@@ -0,0 +1,122 @@
+# Retro-Go: Game Boy, Game Boy Color and NES games on the calculator.
+# make build output/retrogo.nwa (RetroGo.nwa), its ROM table from ROMS (none: empty)
+# make ROMS="a.gb b.nes" the same with those games in it, to try them
+# make check link the app like the calculator does (output/retrogo.bin)
+# make test the emulators and the ROM table on this computer
+#
+# The games are in a table in flash, np_roms (section .rodata.np_roms, made by
+# ../../tools/romtable.py), that the customizer website fills; the emulators read them in place.
+# In NumPlay the app draws with the launcher's strips and fonts and saves through its file
+# functions (module.o leaves them to the launcher, and np_roms to NumPlay's own table); on its own
+# it brings them along.
+Q ?= @
+CC = arm-none-eabi-gcc
+NWLINK ?= npx --yes -- [email protected]
+PY ?= python3
+BUILD_DIR = output
+ROMS ?=
+
+GB_SRC = $(addprefix src/gb/,cpu.c hw.c mem.c lcdc.c rtc.c lcd.c gb.c)
+NES_SRC = $(addprefix src/nes/,nes6502.c nes_ppu.c nes_mmc.c mmclist.c nes_apu.c nes.c) \
+ $(sort $(wildcard src/nes/mappers/*.c))
+CORE_SRC = $(GB_SRC) $(NES_SRC)
+APP_SRC = src/main.c src/romtable.c src/pack.c
+CORE_H = $(wildcard src/*.h src/gb/*.h src/nes/*.h)
+HEADERS = $(CORE_H) ../common/epsilon_app.h ../common/epsilon_files.h ../common/np_text.h \
+ ../../launcher/src/gfx.h ../../launcher/src/np.h ../../launcher/src/font.h
+
+CFLAGS = -std=gnu11 $(shell $(NWLINK) eadk-cflags-device) -Isrc/nes
+CFLAGS += -Wall -Wextra -Wno-unused-parameter -Wno-sign-compare -Wno-implicit-fallthrough -Wno-missing-field-initializers
+# (gnuboy and nofrendo as they were written)
+CFLAGS += -Wno-old-style-declaration -Wno-misleading-indentation -Wno-unused-but-set-variable -Wno-maybe-uninitialized
+CFLAGS += -fno-math-errno -fsingle-precision-constant -fno-tree-loop-distribute-patterns
+CFLAGS += -flto -fno-fat-lto-objects -fwhole-program -fvisibility=internal
+# the emulators run at -O2, the screens at -Os
+CORE_OPT = -O2
+APP_OPT = -Os
+LDFLAGS = -Wl,--relocatable -nostartfiles --specs=nano.specs
+LDFLAGS += -Wl,-e,main -Wl,-u,eadk_app_name -Wl,-u,eadk_app_icon -Wl,-u,eadk_api_level
+LDFLAGS += -Wl,--gc-sections -flinker-output=nolto-rel
+
+CORE_O = $(patsubst src/%.c,$(BUILD_DIR)/%.o,$(CORE_SRC))
+APP_O = $(patsubst src/%.c,$(BUILD_DIR)/%.o,$(APP_SRC))
+MOD_CORE_O = $(patsubst src/%.c,$(BUILD_DIR)/mod/%.o,$(CORE_SRC))
+MOD_APP_O = $(patsubst src/%.c,$(BUILD_DIR)/mod/%.o,$(APP_SRC))
+
+.PHONY: build check clean test module sim-module FORCE
+build: $(BUILD_DIR)/retrogo.nwa
+
+check: $(BUILD_DIR)/retrogo.nwa
+ $(Q) $(NWLINK) nwa-bin $< $(BUILD_DIR)/retrogo.bin
+ @echo "BIN $(BUILD_DIR)/retrogo.bin: $$(wc -c < $(BUILD_DIR)/retrogo.bin) bytes"
+
+$(BUILD_DIR)/%.o: src/%.c $(HEADERS)
+ @mkdir -p $(dir $@)
+ @echo "CC $<"
+ $(Q) $(CC) $(CFLAGS) $(if $(filter $<,$(CORE_SRC)),$(CORE_OPT),$(APP_OPT)) -c $< -o $@
+$(BUILD_DIR)/mod/%.o: src/%.c $(HEADERS)
+ @mkdir -p $(dir $@)
+ $(Q) $(CC) $(CFLAGS) -DNP_MODULE=1 $(if $(filter $<,$(CORE_SRC)),$(CORE_OPT),$(APP_OPT)) -c $< -o $@
+$(BUILD_DIR)/gfx.o: ../../launcher/src/gfx.c $(HEADERS)
+ $(Q) $(CC) $(CFLAGS) -Os -c $< -o $@
+$(BUILD_DIR)/font_data.o: ../../launcher/src/font_data.c ../../launcher/src/font.h
+ $(Q) $(CC) $(CFLAGS) -Os -c $< -o $@
+$(BUILD_DIR)/xfont.o: ../../launcher/src/xfont.c ../../launcher/src/np_xfont.h $(HEADERS)
+ $(Q) $(CC) $(CFLAGS) -Os -c $< -o $@
+
+# the games: tools/romtable.py makes the table, empty or with ROMS. It runs at every build and leaves
+# the file as it is when it wouldn't change, so nothing is linked again for nothing.
+$(BUILD_DIR)/roms.o: FORCE
+ @mkdir -p $(BUILD_DIR)
+ $(Q) $(PY) ../../tools/romtable.py -o $@ $(ROMS)
+
+$(BUILD_DIR)/retrogo-full.nwa: $(CORE_O) $(APP_O) $(BUILD_DIR)/gfx.o $(BUILD_DIR)/font_data.o $(BUILD_DIR)/xfont.o \
+ $(BUILD_DIR)/icon.o $(BUILD_DIR)/roms.o src/roms.ld
+ @echo "LD $@"
+ $(Q) $(CC) $(CFLAGS) $(LDFLAGS) -Wl,-T,src/roms.ld $(filter %.o,$^) -o $@
+# (the same, stripped: what goes on the calculator; retrogo-full.nwa keeps its symbols, for tools/emu.py --profile)
+$(BUILD_DIR)/retrogo.nwa: $(BUILD_DIR)/retrogo-full.nwa
+ $(Q) arm-none-eabi-strip --strip-unneeded -o $@ $<
+
+$(BUILD_DIR)/icon.o: src/icon.png
+ @mkdir -p $(BUILD_DIR)
+ @echo "ICON $<"
+ $(Q) $(NWLINK) png-icon-o $< $@
+
+clean:
+ $(Q) rm -rf $(BUILD_DIR)
+
+# NumPlay launcher: the app as a module (see ../../tools/npmodule.py); np_roms stays undefined,
+# NumPlay links its own table.
+module: $(BUILD_DIR)/module.o
+$(BUILD_DIR)/module.o: $(MOD_CORE_O) $(MOD_APP_O)
+ $(Q) $(CC) $(CFLAGS) -Wl,--relocatable -nostartfiles -nostdlib -Wl,-e,main -flinker-output=nolto-rel $^ -o $@
+
+SIM_CFLAGS = -std=gnu11 -Isrc/nes -O2 -fPIC $(shell $(NWLINK) eadk-cflags-simulator) -DNP_MODULE=1 -w
+sim-module: $(BUILD_DIR)/sim-module.o
+$(BUILD_DIR)/sim-module.o: $(CORE_SRC) $(APP_SRC) $(HEADERS)
+ $(Q) mkdir -p $(BUILD_DIR)/sim
+ $(Q) cc $(SIM_CFLAGS) -Dmain=np_retrogo_main -c src/main.c -o $(BUILD_DIR)/sim/main.o
+ $(Q) for f in $(CORE_SRC) src/romtable.c src/pack.c; do cc $(SIM_CFLAGS) -c $$f -o $(BUILD_DIR)/sim/$$(echo $$f | tr / _).o || exit 1; done
+ $(Q) $(PY) ../../tools/romtable.py --c $(BUILD_DIR)/sim/roms.c $(ROMS) && cc $(SIM_CFLAGS) -c $(BUILD_DIR)/sim/roms.c -o $(BUILD_DIR)/sim/roms.o
+ $(Q) ld -r $(BUILD_DIR)/sim/*.o -exported_symbol _np_retrogo_main -o $@
+
+# ------------------------------------------------------------------ tests on this computer
+HOST_CC = cc
+HOST_CFLAGS = -std=gnu11 -Isrc/nes -O1 -g -fsanitize=address,undefined -fno-sanitize-recover=undefined \
+ -Wall -Wextra -Wno-unused-parameter -Wno-sign-compare -Wno-implicit-fallthrough -Wno-missing-field-initializers
+TEST_ROMS ?= $(HOME)/Documents/Assets/gamesrc/retrogo/roms
+$(BUILD_DIR)/host/core: tests/host_core.c $(CORE_SRC) $(CORE_H)
+ @mkdir -p $(BUILD_DIR)/host
+ $(Q) $(HOST_CC) $(HOST_CFLAGS) tests/host_core.c $(CORE_SRC) -o $@
+$(BUILD_DIR)/host/romtable: tests/host_romtable.c src/romtable.c src/romtable.h
+ @mkdir -p $(BUILD_DIR)/host
+ $(Q) $(HOST_CC) $(HOST_CFLAGS) tests/host_romtable.c src/romtable.c -o $@
+$(BUILD_DIR)/host/pack: tests/host_pack.c src/pack.c src/pack.h
+ @mkdir -p $(BUILD_DIR)/host
+ $(Q) $(HOST_CC) $(HOST_CFLAGS) tests/host_pack.c src/pack.c -o $@
+test: $(BUILD_DIR)/host/core $(BUILD_DIR)/host/romtable $(BUILD_DIR)/host/pack
+ $(Q) $(BUILD_DIR)/host/pack
+ $(Q) $(PY) tests/test_romtable.py $(BUILD_DIR)/host/romtable
+ $(Q) $(PY) tests/test_cores.py $(BUILD_DIR)/host/core $(TEST_ROMS)
+ $(Q) NWLINK="$(NWLINK)" $(PY) tests/test_app.py
diff --git a/games/retrogo/docs/shot.png b/games/retrogo/docs/shot.png
new file mode 100644
index 00000000..d81ec2ba
Binary files /dev/null and b/games/retrogo/docs/shot.png differ
diff --git a/games/retrogo/lang/fr.txt b/games/retrogo/lang/fr.txt
new file mode 100644
index 00000000..f5d0e604
--- /dev/null
+++ b/games/retrogo/lang/fr.txt
@@ -0,0 +1,95 @@
+# Retro-Go in French: the English text as in the source, a tab, the translation (see tools/lang.py).
+OK OK
+Yes Oui
+No Non
+arrows flèches
+D-pad Croix
+Back Retour
+shift shift
+Select Select
+EXE EXE
+Start Start
+Backspace Effacer
+menu menu
+Home Accueil
+quit quitter
+Off Non
+Fit Ajusté
+Full Plein
+Pocket Pocket
+Light Light
+Day Jour
+Hour Heure
+Min Min
+Sec Sec
+Auto Auto
+Never Jamais
+Always Toujours
+On Oui
+Palette Palette
+RTC config Horloge
+SRAM autosave Sauvegarde auto
+Overscan Bords
+Crop sides Rogner les côtés
+Sprite limit Limite de sprites
+Scaling Taille
+Speed Vitesse
+Emulator options Options de l'émulateur
+Options Options
+Menu Menu
+Quit Quitter
+Home (saves) Accueil (sauve)
+Controls Touches
+Retro-Go Retro-Go
+Port Portage
+Not affiliated with Retro-Go Sans lien avec Retro-Go
+About Retro-Go À propos de Retro-Go
+Slot 0 Case 0
+Slot 1 Case 1
+Slot 2 Case 2
+Slot 3 Case 3
+empty vide
+last used la dernière
+saved sauvée
+Saving... Sauvegarde...
+Save & Continue Sauver et continuer
+Save & Quit Sauver et quitter
+Load game Charger une partie
+Reset Redémarrer
+About À propos
+Save Sauver
+Not enough room Plus de place
+Delete other saves to make room. Efface d'autres sauvegardes pour faire de la place.
+Load Charger
+This save can't be read. Cette sauvegarde est illisible.
+Soft reset Redémarrage doux
+Hard reset Redémarrage complet
+Reset Emulation? Redémarrer le jeu ?
+Quit game? Quitter le jeu ?
+The battery save is kept. La sauvegarde de la cartouche est gardée.
+This cartridge type isn't supported. Ce type de cartouche n'est pas pris en charge.
+This game needs more memory than the calculator has. Ce jeu demande plus de mémoire que la calculatrice n'en a.
+This file isn't a game Retro-Go can read. Retro-Go ne sait pas lire ce fichier.
+Can't start the game Impossible de lancer le jeu
+Welcome to Retro-Go! Bienvenue dans Retro-Go !
+Add games on NumPlay's Ajoute des jeux sur le site
+customizer website: de personnalisation de NumPlay :
+Game Boy, Game Boy Color des jeux Game Boy, Game Boy Color
+and NES games. et NES.
+Home: quit Accueil : quitter
+Left/Right: system OK: games Home: quit Gauche/Droite : console OK : jeux Accueil : quitter
+OK: play Back: systems Left/Right: system OK : jouer Retour : consoles Gauche/Droite : console
+Reading... Lecture...
+Name Nom
+System Console
+Size Taille
+Close Fermer
+File properties Propriétés
+Retro-Go on the calculator plays Game Boy, Game Boy Color and NES games. Retro-Go sur la calculatrice joue aux jeux Game Boy, Game Boy Color et NES.
+Resume game Reprendre
+New game Nouvelle partie
+Delete save Effacer une sauvegarde
+Properties Propriétés
+Resume Reprendre
+Delete save? Effacer la sauvegarde ?
+Delete sram file? Effacer la sauvegarde de la cartouche ?
diff --git a/games/retrogo/lang/zh.txt b/games/retrogo/lang/zh.txt
new file mode 100644
index 00000000..d7833b2f
--- /dev/null
+++ b/games/retrogo/lang/zh.txt
@@ -0,0 +1,95 @@
+# Retro-Go in Chinese: the English text as in the source, a tab, the translation (see tools/lang.py).
+OK OK
+Yes 是
+No 否
+arrows 方向键
+D-pad 十字键
+Back 返回
+shift shift
+Select Select
+EXE EXE
+Start Start
+Backspace 退格
+menu 菜单
+Home 主页
+quit 退出
+Off 关
+Fit 适应
+Full 全屏
+Pocket Pocket
+Light Light
+Day 日
+Hour 时
+Min 分
+Sec 秒
+Auto 自动
+Never 从不
+Always 总是
+On 开
+Palette 调色板
+RTC config 时钟设置
+SRAM autosave 自动存档
+Overscan 边缘裁切
+Crop sides 裁切两侧
+Sprite limit 精灵上限
+Scaling 缩放
+Speed 速度
+Emulator options 模拟器选项
+Options 选项
+Menu 菜单
+Quit 退出
+Home (saves) 主页(会保存)
+Controls 按键
+Retro-Go Retro-Go
+Port 移植
+Not affiliated with Retro-Go 与 Retro-Go 无关
+About Retro-Go 关于 Retro-Go
+Slot 0 存档位 0
+Slot 1 存档位 1
+Slot 2 存档位 2
+Slot 3 存档位 3
+empty 空
+last used 最近使用
+saved 已保存
+Saving... 正在保存...
+Save & Continue 保存并继续
+Save & Quit 保存并退出
+Load game 读取存档
+Reset 重置
+About 关于
+Save 保存
+Not enough room 空间不足
+Delete other saves to make room. 请删除其他存档腾出空间。
+Load 读取
+This save can't be read. 无法读取这个存档。
+Soft reset 软重置
+Hard reset 硬重置
+Reset Emulation? 重置游戏?
+Quit game? 退出游戏?
+The battery save is kept. 卡带存档会保留。
+This cartridge type isn't supported. 不支持这种卡带。
+This game needs more memory than the calculator has. 这个游戏需要的内存超过了计算器的容量。
+This file isn't a game Retro-Go can read. Retro-Go 无法读取这个文件。
+Can't start the game 无法启动游戏
+Welcome to Retro-Go! 欢迎使用 Retro-Go!
+Add games on NumPlay's 请在 NumPlay 的
+customizer website: 定制网站上添加
+Game Boy, Game Boy Color Game Boy、Game Boy Color
+and NES games. 和 NES 游戏。
+Home: quit 主页:退出
+Left/Right: system OK: games Home: quit 左/右:主机 OK:游戏 主页:退出
+OK: play Back: systems Left/Right: system OK:开始 返回:主机 左/右:切换主机
+Reading... 正在读取...
+Name 名称
+System 主机
+Size 大小
+Close 关闭
+File properties 文件属性
+Retro-Go on the calculator plays Game Boy, Game Boy Color and NES games. 计算器上的 Retro-Go 可以玩 Game Boy、Game Boy Color 和 NES 游戏。
+Resume game 继续游戏
+New game 新游戏
+Delete save 删除存档
+Properties 属性
+Resume 继续
+Delete save? 删除存档?
+Delete sram file? 删除卡带存档?
diff --git a/games/retrogo/src/gb/COPYING b/games/retrogo/src/gb/COPYING
new file mode 100644
index 00000000..a43ea212
--- /dev/null
+++ b/games/retrogo/src/gb/COPYING
@@ -0,0 +1,339 @@
+ GNU GENERAL PUBLIC LICENSE
+ Version 2, June 1991
+
+ Copyright (C) 1989, 1991 Free Software Foundation, Inc.
+ 675 Mass Ave, Cambridge, MA 02139, USA
+ Everyone is permitted to copy and distribute verbatim copies
+ of this license document, but changing it is not allowed.
+
+ Preamble
+
+ The licenses for most software are designed to take away your
+freedom to share and change it. By contrast, the GNU General Public
+License is intended to guarantee your freedom to share and change free
+software--to make sure the software is free for all its users. This
+General Public License applies to most of the Free Software
+Foundation's software and to any other program whose authors commit to
+using it. (Some other Free Software Foundation software is covered by
+the GNU Library General Public License instead.) You can apply it to
+your programs, too.
+
+ When we speak of free software, we are referring to freedom, not
+price. Our General Public Licenses are designed to make sure that you
+have the freedom to distribute copies of free software (and charge for
+this service if you wish), that you receive source code or can get it
+if you want it, that you can change the software or use pieces of it
+in new free programs; and that you know you can do these things.
+
+ To protect your rights, we need to make restrictions that forbid
+anyone to deny you these rights or to ask you to surrender the rights.
+These restrictions translate to certain responsibilities for you if you
+distribute copies of the software, or if you modify it.
+
+ For example, if you distribute copies of such a program, whether
+gratis or for a fee, you must give the recipients all the rights that
+you have. You must make sure that they, too, receive or can get the
+source code. And you must show them these terms so they know their
+rights.
+
+ We protect your rights with two steps: (1) copyright the software, and
+(2) offer you this license which gives you legal permission to copy,
+distribute and/or modify the software.
+
+ Also, for each author's protection and ours, we want to make certain
+that everyone understands that there is no warranty for this free
+software. If the software is modified by someone else and passed on, we
+want its recipients to know that what they have is not the original, so
+that any problems introduced by others will not reflect on the original
+authors' reputations.
+
+ Finally, any free program is threatened constantly by software
+patents. We wish to avoid the danger that redistributors of a free
+program will individually obtain patent licenses, in effect making the
+program proprietary. To prevent this, we have made it clear that any
+patent must be licensed for everyone's free use or not licensed at all.
+
+ The precise terms and conditions for copying, distribution and
+modification follow.
+
+ GNU GENERAL PUBLIC LICENSE
+ TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION
+
+ 0. This License applies to any program or other work which contains
+a notice placed by the copyright holder saying it may be distributed
+under the terms of this General Public License. The "Program", below,
+refers to any such program or work, and a "work based on the Program"
+means either the Program or any derivative work under copyright law:
+that is to say, a work containing the Program or a portion of it,
+either verbatim or with modifications and/or translated into another
+language. (Hereinafter, translation is included without limitation in
+the term "modification".) Each licensee is addressed as "you".
+
+Activities other than copying, distribution and modification are not
+covered by this License; they are outside its scope. The act of
+running the Program is not restricted, and the output from the Program
+is covered only if its contents constitute a work based on the
+Program (independent of having been made by running the Program).
+Whether that is true depends on what the Program does.
+
+ 1. You may copy and distribute verbatim copies of the Program's
+source code as you receive it, in any medium, provided that you
+conspicuously and appropriately publish on each copy an appropriate
+copyright notice and disclaimer of warranty; keep intact all the
+notices that refer to this License and to the absence of any warranty;
+and give any other recipients of the Program a copy of this License
+along with the Program.
+
+You may charge a fee for the physical act of transferring a copy, and
+you may at your option offer warranty protection in exchange for a fee.
+
+ 2. You may modify your copy or copies of the Program or any portion
+of it, thus forming a work based on the Program, and copy and
+distribute such modifications or work under the terms of Section 1
+above, provided that you also meet all of these conditions:
+
+ a) You must cause the modified files to carry prominent notices
+ stating that you changed the files and the date of any change.
+
+ b) You must cause any work that you distribute or publish, that in
+ whole or in part contains or is derived from the Program or any
+ part thereof, to be licensed as a whole at no charge to all third
+ parties under the terms of this License.
+
+ c) If the modified program normally reads commands interactively
+ when run, you must cause it, when started running for such
+ interactive use in the most ordinary way, to print or display an
+ announcement including an appropriate copyright notice and a
+ notice that there is no warranty (or else, saying that you provide
+ a warranty) and that users may redistribute the program under
+ these conditions, and telling the user how to view a copy of this
+ License. (Exception: if the Program itself is interactive but
+ does not normally print such an announcement, your work based on
+ the Program is not required to print an announcement.)
+
+These requirements apply to the modified work as a whole. If
+identifiable sections of that work are not derived from the Program,
+and can be reasonably considered independent and separate works in
+themselves, then this License, and its terms, do not apply to those
+sections when you distribute them as separate works. But when you
+distribute the same sections as part of a whole which is a work based
+on the Program, the distribution of the whole must be on the terms of
+this License, whose permissions for other licensees extend to the
+entire whole, and thus to each and every part regardless of who wrote it.
+
+Thus, it is not the intent of this section to claim rights or contest
+your rights to work written entirely by you; rather, the intent is to
+exercise the right to control the distribution of derivative or
+collective works based on the Program.
+
+In addition, mere aggregation of another work not based on the Program
+with the Program (or with a work based on the Program) on a volume of
+a storage or distribution medium does not bring the other work under
+the scope of this License.
+
+ 3. You may copy and distribute the Program (or a work based on it,
+under Section 2) in object code or executable form under the terms of
+Sections 1 and 2 above provided that you also do one of the following:
+
+ a) Accompany it with the complete corresponding machine-readable
+ source code, which must be distributed under the terms of Sections
+ 1 and 2 above on a medium customarily used for software interchange; or,
+
+ b) Accompany it with a written offer, valid for at least three
+ years, to give any third party, for a charge no more than your
+ cost of physically performing source distribution, a complete
+ machine-readable copy of the corresponding source code, to be
+ distributed under the terms of Sections 1 and 2 above on a medium
+ customarily used for software interchange; or,
+
+ c) Accompany it with the information you received as to the offer
+ to distribute corresponding source code. (This alternative is
+ allowed only for noncommercial distribution and only if you
+ received the program in object code or executable form with such
+ an offer, in accord with Subsection b above.)
+
+The source code for a work means the preferred form of the work for
+making modifications to it. For an executable work, complete source
+code means all the source code for all modules it contains, plus any
+associated interface definition files, plus the scripts used to
+control compilation and installation of the executable. However, as a
+special exception, the source code distributed need not include
+anything that is normally distributed (in either source or binary
+form) with the major components (compiler, kernel, and so on) of the
+operating system on which the executable runs, unless that component
+itself accompanies the executable.
+
+If distribution of executable or object code is made by offering
+access to copy from a designated place, then offering equivalent
+access to copy the source code from the same place counts as
+distribution of the source code, even though third parties are not
+compelled to copy the source along with the object code.
+
+ 4. You may not copy, modify, sublicense, or distribute the Program
+except as expressly provided under this License. Any attempt
+otherwise to copy, modify, sublicense or distribute the Program is
+void, and will automatically terminate your rights under this License.
+However, parties who have received copies, or rights, from you under
+this License will not have their licenses terminated so long as such
+parties remain in full compliance.
+
+ 5. You are not required to accept this License, since you have not
+signed it. However, nothing else grants you permission to modify or
+distribute the Program or its derivative works. These actions are
+prohibited by law if you do not accept this License. Therefore, by
+modifying or distributing the Program (or any work based on the
+Program), you indicate your acceptance of this License to do so, and
+all its terms and conditions for copying, distributing or modifying
+the Program or works based on it.
+
+ 6. Each time you redistribute the Program (or any work based on the
+Program), the recipient automatically receives a license from the
+original licensor to copy, distribute or modify the Program subject to
+these terms and conditions. You may not impose any further
+restrictions on the recipients' exercise of the rights granted herein.
+You are not responsible for enforcing compliance by third parties to
+this License.
+
+ 7. If, as a consequence of a court judgment or allegation of patent
+infringement or for any other reason (not limited to patent issues),
+conditions are imposed on you (whether by court order, agreement or
+otherwise) that contradict the conditions of this License, they do not
+excuse you from the conditions of this License. If you cannot
+distribute so as to satisfy simultaneously your obligations under this
+License and any other pertinent obligations, then as a consequence you
+may not distribute the Program at all. For example, if a patent
+license would not permit royalty-free redistribution of the Program by
+all those who receive copies directly or indirectly through you, then
+the only way you could satisfy both it and this License would be to
+refrain entirely from distribution of the Program.
+
+If any portion of this section is held invalid or unenforceable under
+any particular circumstance, the balance of the section is intended to
+apply and the section as a whole is intended to apply in other
+circumstances.
+
+It is not the purpose of this section to induce you to infringe any
+patents or other property right claims or to contest validity of any
+such claims; this section has the sole purpose of protecting the
+integrity of the free software distribution system, which is
+implemented by public license practices. Many people have made
+generous contributions to the wide range of software distributed
+through that system in reliance on consistent application of that
+system; it is up to the author/donor to decide if he or she is willing
+to distribute software through any other system and a licensee cannot
+impose that choice.
+
+This section is intended to make thoroughly clear what is believed to
+be a consequence of the rest of this License.
+
+ 8. If the distribution and/or use of the Program is restricted in
+certain countries either by patents or by copyrighted interfaces, the
+original copyright holder who places the Program under this License
+may add an explicit geographical distribution limitation excluding
+those countries, so that distribution is permitted only in or among
+countries not thus excluded. In such case, this License incorporates
+the limitation as if written in the body of this License.
+
+ 9. The Free Software Foundation may publish revised and/or new versions
+of the General Public License from time to time. Such new versions will
+be similar in spirit to the present version, but may differ in detail to
+address new problems or concerns.
+
+Each version is given a distinguishing version number. If the Program
+specifies a version number of this License which applies to it and "any
+later version", you have the option of following the terms and conditions
+either of that version or of any later version published by the Free
+Software Foundation. If the Program does not specify a version number of
+this License, you may choose any version ever published by the Free Software
+Foundation.
+
+ 10. If you wish to incorporate parts of the Program into other free
+programs whose distribution conditions are different, write to the author
+to ask for permission. For software which is copyrighted by the Free
+Software Foundation, write to the Free Software Foundation; we sometimes
+make exceptions for this. Our decision will be guided by the two goals
+of preserving the free status of all derivatives of our free software and
+of promoting the sharing and reuse of software generally.
+
+ NO WARRANTY
+
+ 11. BECAUSE THE PROGRAM IS LICENSED FREE OF CHARGE, THERE IS NO WARRANTY
+FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN
+OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES
+PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED
+OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
+MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS
+TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE
+PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING,
+REPAIR OR CORRECTION.
+
+ 12. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
+WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY AND/OR
+REDISTRIBUTE THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES,
+INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING
+OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED
+TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY
+YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER
+PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE
+POSSIBILITY OF SUCH DAMAGES.
+
+ END OF TERMS AND CONDITIONS
+
+ Appendix: How to Apply These Terms to Your New Programs
+
+ If you develop a new program, and you want it to be of the greatest
+possible use to the public, the best way to achieve this is to make it
+free software which everyone can redistribute and change under these terms.
+
+ To do so, attach the following notices to the program. It is safest
+to attach them to the start of each source file to most effectively
+convey the exclusion of warranty; and each file should have at least
+the "copyright" line and a pointer to where the full notice is found.
+
+ <one line to give the program's name and a brief idea of what it does.>
+ Copyright (C) 19yy <name of author>
+
+ This program is free software; you can redistribute it and/or modify
+ it under the terms of the GNU General Public License as published by
+ the Free Software Foundation; either version 2 of the License, or
+ (at your option) any later version.
+
+ This program is distributed in the hope that it will be useful,
+ but WITHOUT ANY WARRANTY; without even the implied warranty of
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ GNU General Public License for more details.
+
+ You should have received a copy of the GNU General Public License
+ along with this program; if not, write to the Free Software
+ Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
+
+Also add information on how to contact you by electronic and paper mail.
+
+If the program is interactive, make it output a short notice like this
+when it starts in an interactive mode:
+
+ Gnomovision version 69, Copyright (C) 19yy name of author
+ Gnomovision comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
+ This is free software, and you are welcome to redistribute it
+ under certain conditions; type `show c' for details.
+
+The hypothetical commands `show w' and `show c' should show the appropriate
+parts of the General Public License. Of course, the commands you use may
+be called something other than `show w' and `show c'; they could even be
+mouse-clicks or menu items--whatever suits your program.
+
+You should also get your employer (if you work as a programmer) or your
+school, if any, to sign a "copyright disclaimer" for the program, if
+necessary. Here is a sample; alter the names:
+
+ Yoyodyne, Inc., hereby disclaims all copyright interest in the program
+ `Gnomovision' (which makes passes at compilers) written by James Hacker.
+
+ <signature of Ty Coon>, 1 April 1989
+ Ty Coon, President of Vice
+
+This General Public License does not permit incorporating your program into
+proprietary programs. If your program is a subroutine library, you may
+consider it more useful to permit linking proprietary applications with the
+library. If this is what you want to do, use the GNU Library General
+Public License instead of this License.
diff --git a/games/retrogo/src/gb/cpu.c b/games/retrogo/src/gb/cpu.c
new file mode 100644
index 00000000..95f20a3a
--- /dev/null
+++ b/games/retrogo/src/gb/cpu.c
@@ -0,0 +1,922 @@
+/* From gnuboy 1.0.3 (rofl0r's tree) by Laguna and Gilgamesh and gnuboy's contributors,
+ * GPL-2.0-or-later (see COPYING in this folder); changed for Retro-Go on NumPlay. */
+#include "defs.h"
+#include "regs.h"
+#include "hw.h"
+#include "cpu.h"
+#include "mem.h"
+#include "fastmem.h"
+#include "cpuregs.h"
+#include "cpucore.h"
+#include "lcdc.h"
+
+
+
+struct cpu cpu;
+
+
+
+
+#define ZFLAG(n) ( (n) ? 0 : FZ )
+#define HFLAG(n) ( (n) ? 0 : FH )
+#define CFLAG(n) ( (n) ? 0 : FC )
+
+
+#define PUSH(w) ( (SP -= 2), (writew(xSP, (w))) )
+#define POP(w) ( ((w) = readw(xSP)), (SP += 2) )
+
+
+#define FETCH_OLD ( mbc.rmap[PC>>12] \
+? mbc.rmap[PC>>12][PC++] \
+: mem_read(PC++) )
+
+#define FETCH (readb(PC++))
+
+
+#define INC(r) { ((r)++); \
+F = (F & (FL|FC)) | incflag_table[(r)]; }
+
+#define DEC(r) { ((r)--); \
+F = (F & (FL|FC)) | decflag_table[(r)]; }
+
+#define INCW(r) ( (r)++ )
+
+#define DECW(r) ( (r)-- )
+
+#define ADD(n) { \
+W(acc) = (un16)A + (un16)(n); \
+F = (ZFLAG(LB(acc))) \
+| (FH & ((A ^ (n) ^ LB(acc)) << 1)) \
+| (HB(acc) << 4); \
+A = LB(acc); }
+
+#define ADC(n) { \
+W(acc) = (un16)A + (un16)(n) + (un16)((F&FC)>>4); \
+F = (ZFLAG(LB(acc))) \
+| (FH & ((A ^ (n) ^ LB(acc)) << 1)) \
+| (HB(acc) << 4); \
+A = LB(acc); }
+
+#define ADDW(n) { \
+DW(acc) = (un32)HL + (un32)(n); \
+F = (F & (FZ)) \
+| (FH & ((H ^ ((n)>>8) ^ HB(acc)) << 1)) \
+| (acc.b[HI][LO] << 4); \
+HL = W(acc); }
+
+#define ADDSP(n) { \
+DW(acc) = (un32)SP + (un32)(n8)(n); \
+F = (FH & (((SP>>8) ^ ((n)>>8) ^ HB(acc)) << 1)) \
+| (acc.b[HI][LO] << 4); \
+SP = W(acc); }
+
+#define LDHLSP(n) { \
+DW(acc) = (un32)SP + (un32)(n8)(n); \
+F = (FH & (((SP>>8) ^ ((n)>>8) ^ HB(acc)) << 1)) \
+| (acc.b[HI][LO] << 4); \
+HL = W(acc); }
+
+#define CP(n) { \
+W(acc) = (un16)A - (un16)(n); \
+F = FN \
+| (ZFLAG(LB(acc))) \
+| (FH & ((A ^ (n) ^ LB(acc)) << 1)) \
+| ((un8)(-(n8)HB(acc)) << 4); }
+
+#define SUB(n) { CP((n)); A = LB(acc); }
+
+#define SBC(n) { \
+W(acc) = (un16)A - (un16)(n) - (un16)((F&FC)>>4); \
+F = FN \
+| (ZFLAG((n8)LB(acc))) \
+| (FH & ((A ^ (n) ^ LB(acc)) << 1)) \
+| ((un8)(-(n8)HB(acc)) << 4); \
+A = LB(acc); }
+
+#define AND(n) { A &= (n); \
+F = ZFLAG(A) | FH; }
+
+#define XOR(n) { A ^= (n); \
+F = ZFLAG(A); }
+
+#define OR(n) { A |= (n); \
+F = ZFLAG(A); }
+
+#define RLCA(r) { (r) = ((r)>>7) | ((r)<<1); \
+F = (((r)&0x01)<<4); }
+
+#define RRCA(r) { (r) = ((r)<<7) | ((r)>>1); \
+F = (((r)&0x80)>>3); }
+
+#define RLA(r) { \
+LB(acc) = (((r)&0x80)>>3); \
+(r) = ((r)<<1) | ((F&FC)>>4); \
+F = LB(acc); }
+
+#define RRA(r) { \
+LB(acc) = (((r)&0x01)<<4); \
+(r) = ((r)>>1) | ((F&FC)<<3); \
+F = LB(acc); }
+
+#define RLC(r) { RLCA(r); F |= ZFLAG(r); }
+#define RRC(r) { RRCA(r); F |= ZFLAG(r); }
+#define RL(r) { RLA(r); F |= ZFLAG(r); }
+#define RR(r) { RRA(r); F |= ZFLAG(r); }
+
+#define SLA(r) { \
+LB(acc) = (((r)&0x80)>>3); \
+(r) <<= 1; \
+F = ZFLAG((r)) | LB(acc); }
+
+#define SRA(r) { \
+LB(acc) = (((r)&0x01)<<4); \
+(r) = (un8)(((n8)(r))>>1); \
+F = ZFLAG((r)) | LB(acc); }
+
+#define SRL(r) { \
+LB(acc) = (((r)&0x01)<<4); \
+(r) >>= 1; \
+F = ZFLAG((r)) | LB(acc); }
+
+#define CPL(r) { \
+(r) = ~(r); \
+F |= (FH|FN); }
+
+#define SCF { F = (F & (FZ)) | FC; }
+
+#define CCF { F = (F & (FZ|FC)) ^ FC; }
+
+#define DAA { \
+A += (LB(acc) = daa_table[((((int)F)&0x70)<<4) | A]); \
+F = (F & (FN)) | ZFLAG(A) | daa_carry_table[LB(acc)>>2]; }
+
+#define SWAP(r) { \
+(r) = swap_table[(r)]; \
+F = ZFLAG((r)); }
+
+#define BIT(n,r) { F = (F & FC) | ZFLAG(((r) & (1 << (n)))) | FH; }
+#define RES(n,r) { (r) &= ~(1 << (n)); }
+#define SET(n,r) { (r) |= (1 << (n)); }
+
+#define CB_REG_CASES(r, n) \
+case 0x00|(n): RLC(r); break; \
+case 0x08|(n): RRC(r); break; \
+case 0x10|(n): RL(r); break; \
+case 0x18|(n): RR(r); break; \
+case 0x20|(n): SLA(r); break; \
+case 0x28|(n): SRA(r); break; \
+case 0x30|(n): SWAP(r); break; \
+case 0x38|(n): SRL(r); break; \
+case 0x40|(n): BIT(0, r); break; \
+case 0x48|(n): BIT(1, r); break; \
+case 0x50|(n): BIT(2, r); break; \
+case 0x58|(n): BIT(3, r); break; \
+case 0x60|(n): BIT(4, r); break; \
+case 0x68|(n): BIT(5, r); break; \
+case 0x70|(n): BIT(6, r); break; \
+case 0x78|(n): BIT(7, r); break; \
+case 0x80|(n): RES(0, r); break; \
+case 0x88|(n): RES(1, r); break; \
+case 0x90|(n): RES(2, r); break; \
+case 0x98|(n): RES(3, r); break; \
+case 0xA0|(n): RES(4, r); break; \
+case 0xA8|(n): RES(5, r); break; \
+case 0xB0|(n): RES(6, r); break; \
+case 0xB8|(n): RES(7, r); break; \
+case 0xC0|(n): SET(0, r); break; \
+case 0xC8|(n): SET(1, r); break; \
+case 0xD0|(n): SET(2, r); break; \
+case 0xD8|(n): SET(3, r); break; \
+case 0xE0|(n): SET(4, r); break; \
+case 0xE8|(n): SET(5, r); break; \
+case 0xF0|(n): SET(6, r); break; \
+case 0xF8|(n): SET(7, r); break;
+
+
+#define ALU_CASES(base, imm, op, label) \
+case (imm): b = FETCH; goto label; \
+case (base): b = B; goto label; \
+case (base)+1: b = C; goto label; \
+case (base)+2: b = D; goto label; \
+case (base)+3: b = E; goto label; \
+case (base)+4: b = H; goto label; \
+case (base)+5: b = L; goto label; \
+case (base)+6: b = readb(HL); goto label; \
+case (base)+7: b = A; \
+label: op(b); break;
+
+
+
+
+
+
+
+
+#define JR ( PC += 1+(n8)readb(PC) )
+#define JP ( PC = readw(PC) )
+
+#define CALL ( PUSH(PC+2), JP )
+
+#define NOJR ( clen--, PC++ )
+#define NOJP ( clen--, PC+=2 )
+#define NOCALL ( clen-=3, PC+=2 )
+#define NORET ( clen-=3 )
+
+#define RST(n) { PUSH(PC); PC = (n); }
+
+#define RET ( POP(PC) )
+
+#define EI ( IMA = 1 )
+#define DI ( cpu.halt = IMA = IME = 0 )
+
+
+
+#define PRE_INT ( DI, PUSH(PC) )
+#define THROW_INT(n) ( (IF &= ~(1<<(n))), (PC = 0x40+((n)<<3)) )
+
+
+
+
+void cpu_reset()
+{
+ cpu.speed = 0;
+ cpu.halt = 0;
+ cpu.div = 0;
+ cpu.tim = 0;
+ cpu.lcdc = 40;
+
+ IME = 0;
+ IMA = 0;
+
+ PC = 0x0100;
+ SP = 0xFFFE;
+ AF = 0x01B0;
+ BC = 0x0013;
+ DE = 0x00D8;
+ HL = 0x014D;
+
+ if (hw.cgb) A = 0x11;
+ if (hw.gba) B = 0x01;
+}
+
+
+void div_advance(int cnt)
+{
+ cpu.div += (cnt<<1);
+ if (cpu.div >= 256)
+ {
+ R_DIV += (cpu.div >> 8);
+ cpu.div &= 0xff;
+ }
+}
+
+void timer_advance(int cnt)
+{
+ int unit, tima;
+
+ if (!(R_TAC & 0x04)) return;
+
+ unit = ((-R_TAC) & 3) << 1;
+ cpu.tim += (cnt<<unit);
+
+ if (cpu.tim >= 512)
+ {
+ tima = R_TIMA + (cpu.tim >> 9);
+ cpu.tim &= 0x1ff;
+ if (tima >= 256)
+ {
+ hw_interrupt(IF_TIMER, IF_TIMER);
+ hw_interrupt(0, IF_TIMER);
+ }
+ while (tima >= 256)
+ tima = tima - 256 + R_TMA;
+ R_TIMA = tima;
+ }
+}
+
+void lcdc_advance(int cnt)
+{
+ cpu.lcdc -= cnt;
+ if (cpu.lcdc <= 0) lcdc_trans();
+}
+
+
+void cpu_timers(int cnt)
+{
+ div_advance(cnt << cpu.speed);
+ timer_advance(cnt << cpu.speed);
+ lcdc_advance(cnt);
+}
+
+int cpu_idle(int max)
+{
+ int cnt, unit;
+
+ /* (HALT waits for an interrupt request with IME off too: it then goes on without serving it) */
+ if (!cpu.halt) return 0;
+ if (R_IF & R_IE)
+ {
+ cpu.halt = 0;
+ return 0;
+ }
+
+ /* Make sure we don't miss lcdc status events! */
+ if ((R_IE & (IF_VBLANK | IF_STAT)) && (max > cpu.lcdc))
+ max = cpu.lcdc;
+
+ /* If timer interrupt cannot happen, this is very simple! */
+ if (!((R_IE & IF_TIMER) && (R_TAC & 0x04)))
+ {
+ cpu_timers(max);
+ return max;
+ }
+
+ /* Figure out when the next timer interrupt will happen */
+ unit = ((-R_TAC) & 3) << 1;
+ cnt = (511 - cpu.tim + (1<<unit)) >> unit;
+ cnt += (255 - R_TIMA) << (9 - unit);
+
+ if (max < cnt)
+ cnt = max;
+
+ cpu_timers(cnt);
+ return cnt;
+}
+
+#ifndef ASM_CPU_EMULATE
+
+
+int cpu_emulate(int cycles)
+{
+ int i;
+ byte op, cbop;
+ int clen;
+ static union reg acc;
+ static byte b;
+ static word w;
+
+ i = cycles;
+next:
+ if ((clen = cpu_idle(i)))
+ {
+ i -= clen;
+ if (i > 0) goto next;
+ return cycles-i;
+ }
+
+ if (IME && (IF & IE))
+ {
+ PRE_INT;
+ switch ((byte)(IF & IE))
+ {
+ case 0x01: case 0x03: case 0x05: case 0x07:
+ case 0x09: case 0x0B: case 0x0D: case 0x0F:
+ case 0x11: case 0x13: case 0x15: case 0x17:
+ case 0x19: case 0x1B: case 0x1D: case 0x1F:
+ THROW_INT(0); break;
+ case 0x02: case 0x06: case 0x0A: case 0x0E:
+ case 0x12: case 0x16: case 0x1A: case 0x1E:
+ THROW_INT(1); break;
+ case 0x04: case 0x0C: case 0x14: case 0x1C:
+ THROW_INT(2); break;
+ case 0x08: case 0x18:
+ THROW_INT(3); break;
+ case 0x10:
+ THROW_INT(4); break;
+ }
+ }
+ IME = IMA;
+
+ op = FETCH;
+ clen = cycles_table[op];
+
+ switch(op)
+ {
+ case 0x00: /* NOP */
+ case 0x40: /* LD B,B */
+ case 0x49: /* LD C,C */
+ case 0x52: /* LD D,D */
+ case 0x5B: /* LD E,E */
+ case 0x64: /* LD H,H */
+ case 0x6D: /* LD L,L */
+ case 0x7F: /* LD A,A */
+ break;
+
+ case 0x41: /* LD B,C */
+ B = C; break;
+ case 0x42: /* LD B,D */
+ B = D; break;
+ case 0x43: /* LD B,E */
+ B = E; break;
+ case 0x44: /* LD B,H */
+ B = H; break;
+ case 0x45: /* LD B,L */
+ B = L; break;
+ case 0x46: /* LD B,(HL) */
+ B = readb(xHL); break;
+ case 0x47: /* LD B,A */
+ B = A; break;
+
+ case 0x48: /* LD C,B */
+ C = B; break;
+ case 0x4A: /* LD C,D */
+ C = D; break;
+ case 0x4B: /* LD C,E */
+ C = E; break;
+ case 0x4C: /* LD C,H */
+ C = H; break;
+ case 0x4D: /* LD C,L */
+ C = L; break;
+ case 0x4E: /* LD C,(HL) */
+ C = readb(xHL); break;
+ case 0x4F: /* LD C,A */
+ C = A; break;
+
+ case 0x50: /* LD D,B */
+ D = B; break;
+ case 0x51: /* LD D,C */
+ D = C; break;
+ case 0x53: /* LD D,E */
+ D = E; break;
+ case 0x54: /* LD D,H */
+ D = H; break;
+ case 0x55: /* LD D,L */
+ D = L; break;
+ case 0x56: /* LD D,(HL) */
+ D = readb(xHL); break;
+ case 0x57: /* LD D,A */
+ D = A; break;
+
+ case 0x58: /* LD E,B */
+ E = B; break;
+ case 0x59: /* LD E,C */
+ E = C; break;
+ case 0x5A: /* LD E,D */
+ E = D; break;
+ case 0x5C: /* LD E,H */
+ E = H; break;
+ case 0x5D: /* LD E,L */
+ E = L; break;
+ case 0x5E: /* LD E,(HL) */
+ E = readb(xHL); break;
+ case 0x5F: /* LD E,A */
+ E = A; break;
+
+ case 0x60: /* LD H,B */
+ H = B; break;
+ case 0x61: /* LD H,C */
+ H = C; break;
+ case 0x62: /* LD H,D */
+ H = D; break;
+ case 0x63: /* LD H,E */
+ H = E; break;
+ case 0x65: /* LD H,L */
+ H = L; break;
+ case 0x66: /* LD H,(HL) */
+ H = readb(xHL); break;
+ case 0x67: /* LD H,A */
+ H = A; break;
+
+ case 0x68: /* LD L,B */
+ L = B; break;
+ case 0x69: /* LD L,C */
+ L = C; break;
+ case 0x6A: /* LD L,D */
+ L = D; break;
+ case 0x6B: /* LD L,E */
+ L = E; break;
+ case 0x6C: /* LD L,H */
+ L = H; break;
+ case 0x6E: /* LD L,(HL) */
+ L = readb(xHL); break;
+ case 0x6F: /* LD L,A */
+ L = A; break;
+
+ case 0x70: /* LD (HL),B */
+ b = B; goto __LD_HL;
+ case 0x71: /* LD (HL),C */
+ b = C; goto __LD_HL;
+ case 0x72: /* LD (HL),D */
+ b = D; goto __LD_HL;
+ case 0x73: /* LD (HL),E */
+ b = E; goto __LD_HL;
+ case 0x74: /* LD (HL),H */
+ b = H; goto __LD_HL;
+ case 0x75: /* LD (HL),L */
+ b = L; goto __LD_HL;
+ case 0x77: /* LD (HL),A */
+ b = A;
+ __LD_HL:
+ writeb(xHL,b);
+ break;
+
+ case 0x78: /* LD A,B */
+ A = B; break;
+ case 0x79: /* LD A,C */
+ A = C; break;
+ case 0x7A: /* LD A,D */
+ A = D; break;
+ case 0x7B: /* LD A,E */
+ A = E; break;
+ case 0x7C: /* LD A,H */
+ A = H; break;
+ case 0x7D: /* LD A,L */
+ A = L; break;
+ case 0x7E: /* LD A,(HL) */
+ A = readb(xHL); break;
+
+ case 0x01: /* LD BC,imm */
+ BC = readw(xPC); PC += 2; break;
+ case 0x11: /* LD DE,imm */
+ DE = readw(xPC); PC += 2; break;
+ case 0x21: /* LD HL,imm */
+ HL = readw(xPC); PC += 2; break;
+ case 0x31: /* LD SP,imm */
+ SP = readw(xPC); PC += 2; break;
+
+ case 0x02: /* LD (BC),A */
+ writeb(xBC, A); break;
+ case 0x0A: /* LD A,(BC) */
+ A = readb(xBC); break;
+ case 0x12: /* LD (DE),A */
+ writeb(xDE, A); break;
+ case 0x1A: /* LD A,(DE) */
+ A = readb(xDE); break;
+
+ case 0x22: /* LDI (HL),A */
+ writeb(xHL, A); HL++; break;
+ case 0x2A: /* LDI A,(HL) */
+ A = readb(xHL); HL++; break;
+ case 0x32: /* LDD (HL),A */
+ writeb(xHL, A); HL--; break;
+ case 0x3A: /* LDD A,(HL) */
+ A = readb(xHL); HL--; break;
+
+ case 0x06: /* LD B,imm */
+ B = FETCH; break;
+ case 0x0E: /* LD C,imm */
+ C = FETCH; break;
+ case 0x16: /* LD D,imm */
+ D = FETCH; break;
+ case 0x1E: /* LD E,imm */
+ E = FETCH; break;
+ case 0x26: /* LD H,imm */
+ H = FETCH; break;
+ case 0x2E: /* LD L,imm */
+ L = FETCH; break;
+ case 0x36: /* LD (HL),imm */
+ b = FETCH; writeb(xHL, b); break;
+ case 0x3E: /* LD A,imm */
+ A = FETCH; break;
+
+ case 0x08: /* LD (imm),SP */
+ writew(readw(xPC), SP); PC += 2; break;
+ case 0xEA: /* LD (imm),A */
+ writeb(readw(xPC), A); PC += 2; break;
+
+ case 0xE0: /* LDH (imm),A */
+ writehi(FETCH, A); break;
+ case 0xE2: /* LDH (C),A */
+ writehi(C, A); break;
+ case 0xF0: /* LDH A,(imm) */
+ A = readhi(FETCH); break;
+ case 0xF2: /* LDH A,(C) (undocumented) */
+ A = readhi(C); break;
+
+
+ case 0xF8: /* LD HL,SP+imm */
+ {
+ /* https://gammpei.github.io/blog/posts/2018-03-04/how-to-write-a-game-boy-emulator-part-8-blarggs-cpu-test-roms-1-3-4-5-7-8-9-10-11.html */
+ signed char v = (signed char) FETCH;
+ int temp = (int)(SP) + (int)v;
+
+ byte half_carry = ((SP & 0xff) ^ v ^ temp) & 0x10;
+
+ F &= ~(FZ | FN | FH | FC);
+
+ if (half_carry) F |= FH;
+ if ((SP & 0xff) + (byte)v > 0xff) F |= FC;
+
+ HL = temp & 0xffff;
+ }
+ break;
+ case 0xF9: /* LD SP,HL */
+ SP = HL; break;
+ case 0xFA: /* LD A,(imm) */
+ A = readb(readw(xPC)); PC += 2; break;
+
+ ALU_CASES(0x80, 0xC6, ADD, __ADD)
+ ALU_CASES(0x88, 0xCE, ADC, __ADC)
+ ALU_CASES(0x90, 0xD6, SUB, __SUB)
+ ALU_CASES(0x98, 0xDE, SBC, __SBC)
+ ALU_CASES(0xA0, 0xE6, AND, __AND)
+ ALU_CASES(0xA8, 0xEE, XOR, __XOR)
+ ALU_CASES(0xB0, 0xF6, OR, __OR)
+ ALU_CASES(0xB8, 0xFE, CP, __CP)
+
+ case 0x09: /* ADD HL,BC */
+ w = BC; goto __ADDW;
+ case 0x19: /* ADD HL,DE */
+ w = DE; goto __ADDW;
+ case 0x39: /* ADD HL,SP */
+ w = SP; goto __ADDW;
+ case 0x29: /* ADD HL,HL */
+ w = HL;
+ __ADDW:
+ ADDW(w);
+ break;
+
+ case 0x04: /* INC B */
+ INC(B); break;
+ case 0x0C: /* INC C */
+ INC(C); break;
+ case 0x14: /* INC D */
+ INC(D); break;
+ case 0x1C: /* INC E */
+ INC(E); break;
+ case 0x24: /* INC H */
+ INC(H); break;
+ case 0x2C: /* INC L */
+ INC(L); break;
+ case 0x34: /* INC (HL) */
+ b = readb(xHL);
+ INC(b);
+ writeb(xHL, b);
+ break;
+ case 0x3C: /* INC A */
+ INC(A); break;
+
+ case 0x03: /* INC BC */
+ INCW(BC); break;
+ case 0x13: /* INC DE */
+ INCW(DE); break;
+ case 0x23: /* INC HL */
+ INCW(HL); break;
+ case 0x33: /* INC SP */
+ INCW(SP); break;
+
+ case 0x05: /* DEC B */
+ DEC(B); break;
+ case 0x0D: /* DEC C */
+ DEC(C); break;
+ case 0x15: /* DEC D */
+ DEC(D); break;
+ case 0x1D: /* DEC E */
+ DEC(E); break;
+ case 0x25: /* DEC H */
+ DEC(H); break;
+ case 0x2D: /* DEC L */
+ DEC(L); break;
+ case 0x35: /* DEC (HL) */
+ b = readb(xHL);
+ DEC(b);
+ writeb(xHL, b);
+ break;
+ case 0x3D: /* DEC A */
+ DEC(A); break;
+
+ case 0x0B: /* DEC BC */
+ DECW(BC); break;
+ case 0x1B: /* DEC DE */
+ DECW(DE); break;
+ case 0x2B: /* DEC HL */
+ DECW(HL); break;
+ case 0x3B: /* DEC SP */
+ DECW(SP); break;
+
+ case 0x07: /* RLCA */
+ RLCA(A); break;
+ case 0x0F: /* RRCA */
+ RRCA(A); break;
+ case 0x17: /* RLA */
+ RLA(A); break;
+ case 0x1F: /* RRA */
+ RRA(A); break;
+
+ case 0x27: /* DAA */
+ {
+ int a = A;
+ if (!(F & FN))
+ {
+ if ((F & FH) || ((a & 0x0f) > 9)) a += 0x06;
+
+ if ((F & FC) || (a > 0x9f)) a += 0x60;
+ }
+ else
+ {
+ if (F & FH) a = (a - 6) & 0xff;
+ if (F & FC) a -= 0x60;
+ }
+
+ F &= ~(FH | FZ);
+
+ if (a & 0x100) F |= FC;
+
+ a &= 0xff;
+
+ if (!a) F |= FZ;
+
+ A = (byte)a;
+ }
+ break;
+ case 0x2F: /* CPL */
+ CPL(A); break;
+
+ case 0x18: /* JR */
+ __JR:
+ JR; break;
+ case 0x20: /* JR NZ */
+ if (!(F&FZ)) goto __JR; NOJR; break;
+ case 0x28: /* JR Z */
+ if (F&FZ) goto __JR; NOJR; break;
+ case 0x30: /* JR NC */
+ if (!(F&FC)) goto __JR; NOJR; break;
+ case 0x38: /* JR C */
+ if (F&FC) goto __JR; NOJR; break;
+
+ case 0xC3: /* JP */
+ __JP:
+ JP; break;
+ case 0xC2: /* JP NZ */
+ if (!(F&FZ)) goto __JP; NOJP; break;
+ case 0xCA: /* JP Z */
+ if (F&FZ) goto __JP; NOJP; break;
+ case 0xD2: /* JP NC */
+ if (!(F&FC)) goto __JP; NOJP; break;
+ case 0xDA: /* JP C */
+ if (F&FC) goto __JP; NOJP; break;
+ case 0xE9: /* JP HL */
+ PC = HL; break;
+
+ case 0xC9: /* RET */
+ __RET:
+ RET; break;
+ case 0xC0: /* RET NZ */
+ if (!(F&FZ)) goto __RET; NORET; break;
+ case 0xC8: /* RET Z */
+ if (F&FZ) goto __RET; NORET; break;
+ case 0xD0: /* RET NC */
+ if (!(F&FC)) goto __RET; NORET; break;
+ case 0xD8: /* RET C */
+ if (F&FC) goto __RET; NORET; break;
+ case 0xD9: /* RETI */
+ IME = IMA = 1; goto __RET;
+
+ case 0xCD: /* CALL */
+ __CALL:
+ CALL; break;
+ case 0xC4: /* CALL NZ */
+ if (!(F&FZ)) goto __CALL; NOCALL; break;
+ case 0xCC: /* CALL Z */
+ if (F&FZ) goto __CALL; NOCALL; break;
+ case 0xD4: /* CALL NC */
+ if (!(F&FC)) goto __CALL; NOCALL; break;
+ case 0xDC: /* CALL C */
+ if (F&FC) goto __CALL; NOCALL; break;
+
+ case 0xC7: /* RST 0 */
+ b = 0x00; goto __RST;
+ case 0xCF: /* RST 8 */
+ b = 0x08; goto __RST;
+ case 0xD7: /* RST 10 */
+ b = 0x10; goto __RST;
+ case 0xDF: /* RST 18 */
+ b = 0x18; goto __RST;
+ case 0xE7: /* RST 20 */
+ b = 0x20; goto __RST;
+ case 0xEF: /* RST 28 */
+ b = 0x28; goto __RST;
+ case 0xF7: /* RST 30 */
+ b = 0x30; goto __RST;
+ case 0xFF: /* RST 38 */
+ b = 0x38;
+ __RST:
+ RST(b); break;
+
+ case 0xC1: /* POP BC */
+ POP(BC); break;
+ case 0xC5: /* PUSH BC */
+ PUSH(BC); break;
+ case 0xD1: /* POP DE */
+ POP(DE); break;
+ case 0xD5: /* PUSH DE */
+ PUSH(DE); break;
+ case 0xE1: /* POP HL */
+ POP(HL); break;
+ case 0xE5: /* PUSH HL */
+ PUSH(HL); break;
+ case 0xF1: /* POP AF */
+ POP(AF); AF &= 0xfff0; break;
+ case 0xF5: /* PUSH AF */
+ PUSH(AF); break;
+
+ case 0xE8: /* ADD SP,imm */
+ {
+ /* https://gammpei.github.io/blog/posts/2018-03-04/how-to-write-a-game-boy-emulator-part-8-blarggs-cpu-test-roms-1-3-4-5-7-8-9-10-11.html */
+ signed char v = (signed char) FETCH;
+ int temp = (int)(SP) + (int)v;
+
+ byte half_carry = ((SP & 0xff) ^ v ^ temp) & 0x10;
+
+ F &= ~(FZ | FN | FH | FC);
+
+ if (half_carry) F |= FH;
+ if ((SP & 0xff) + (byte)v > 0xff) F |= FC;
+
+ SP = temp & 0xffff;
+ }
+ break;
+
+
+ case 0xF3: /* DI */
+ DI; break;
+ case 0xFB: /* EI */
+ EI; break;
+
+ case 0x37: /* SCF */
+ SCF; break;
+ case 0x3F: /* CCF */
+ CCF; break;
+
+ case 0x10: /* STOP */
+ PC++;
+ if (R_KEY1 & 1)
+ {
+ cpu.speed = cpu.speed ^ 1;
+ R_KEY1 = (R_KEY1 & 0x7E) | (cpu.speed << 7);
+ break;
+ }
+ /* NOTE - we do not implement dmg STOP whatsoever */
+ break;
+
+ case 0x76: /* HALT */
+ cpu.halt = 1;
+ break;
+
+ case 0xCB: /* CB prefix */
+ cbop = FETCH;
+ clen = cb_cycles_table[cbop];
+ switch (cbop)
+ {
+ CB_REG_CASES(B, 0);
+ CB_REG_CASES(C, 1);
+ CB_REG_CASES(D, 2);
+ CB_REG_CASES(E, 3);
+ CB_REG_CASES(H, 4);
+ CB_REG_CASES(L, 5);
+ CB_REG_CASES(A, 7);
+ default:
+ b = readb(xHL);
+ switch(cbop)
+ {
+ CB_REG_CASES(b, 6);
+ }
+ if ((cbop & 0xC0) != 0x40) /* exclude BIT */
+ writeb(xHL, b);
+ break;
+ }
+ break;
+
+ default:
+ /* an opcode the CPU doesn't have locks it up: it stays there, and time goes on */
+ PC--;
+ clen = 1;
+ break;
+ }
+
+ clen <<= 1;
+ div_advance(clen);
+ timer_advance(clen);
+ clen >>= cpu.speed;
+ lcdc_advance(clen);
+
+ i -= clen;
+ if (i > 0) goto next;
+ return cycles-i;
+}
+
+#endif /* ASM_CPU_EMULATE */
+
+
+#ifndef ASM_CPU_STEP
+
+int cpu_step(int max)
+{
+ int cnt;
+ if ((cnt = cpu_idle(max))) return cnt;
+ return cpu_emulate(1);
+}
+
+#endif /* ASM_CPU_STEP */
+
+
+
+
+
+
+
+
+
+
+
+
diff --git a/games/retrogo/src/gb/cpu.h b/games/retrogo/src/gb/cpu.h
new file mode 100644
index 00000000..e5b998d2
--- /dev/null
+++ b/games/retrogo/src/gb/cpu.h
@@ -0,0 +1,40 @@
+/* From gnuboy 1.0.3 (rofl0r's tree) by Laguna and Gilgamesh and gnuboy's contributors,
+ * GPL-2.0-or-later (see COPYING in this folder); changed for Retro-Go on NumPlay. */
+#ifndef __CPU_H__
+#define __CPU_H__
+
+
+
+#include "defs.h"
+
+
+union reg
+{
+ byte b[2][2];
+ word w[2];
+ un32 d; /* padding for alignment, carry */
+};
+
+struct cpu
+{
+ union reg pc, sp, bc, de, hl, af;
+ int ime, ima;
+ int speed;
+ int halt;
+ int div, tim;
+ int lcdc;
+ int snd;
+};
+
+extern struct cpu cpu;
+
+void cpu_reset();
+void div_advance(int cnt);
+void timer_advance(int cnt);
+void lcdc_advance(int cnt);
+void cpu_timers(int cnt);
+int cpu_emulate(int cycles);
+
+#endif
+
+
diff --git a/games/retrogo/src/gb/cpucore.h b/games/retrogo/src/gb/cpucore.h
new file mode 100644
index 00000000..d8a82ea0
--- /dev/null
+++ b/games/retrogo/src/gb/cpucore.h
@@ -0,0 +1,291 @@
+/* From gnuboy 1.0.3 (rofl0r's tree) by Laguna and Gilgamesh and gnuboy's contributors,
+ * GPL-2.0-or-later (see COPYING in this folder); changed for Retro-Go on NumPlay. */
+#include "defs.h"
+
+
+const static byte cycles_table[256] =
+{
+ 1, 3, 2, 2, 1, 1, 2, 1, 5, 2, 2, 2, 1, 1, 2, 1,
+ 1, 3, 2, 2, 1, 1, 2, 1, 3, 2, 2, 2, 1, 1, 2, 1,
+ 3, 3, 2, 2, 1, 1, 2, 1, 3, 2, 2, 2, 1, 1, 2, 1,
+ 3, 3, 2, 2, 3, 3, 3, 1, 3, 2, 2, 2, 1, 1, 2, 1,
+
+ 1, 1, 1, 1, 1, 1, 2, 1, 1, 1, 1, 1, 1, 1, 2, 1,
+ 1, 1, 1, 1, 1, 1, 2, 1, 1, 1, 1, 1, 1, 1, 2, 1,
+ 1, 1, 1, 1, 1, 1, 2, 1, 1, 1, 1, 1, 1, 1, 2, 1,
+ 2, 2, 2, 2, 2, 2, 1, 2, 1, 1, 1, 1, 1, 1, 2, 1,
+
+ 1, 1, 1, 1, 1, 1, 2, 1, 1, 1, 1, 1, 1, 1, 2, 1,
+ 1, 1, 1, 1, 1, 1, 2, 1, 1, 1, 1, 1, 1, 1, 2, 1,
+ 1, 1, 1, 1, 1, 1, 2, 1, 1, 1, 1, 1, 1, 1, 2, 1,
+ 1, 1, 1, 1, 1, 1, 2, 1, 1, 1, 1, 1, 1, 1, 2, 1,
+
+ 5, 3, 4, 4, 6, 4, 2, 4, 5, 4, 4, 1, 6, 6, 2, 4,
+ 5, 3, 4, 0, 6, 4, 2, 4, 5, 4, 4, 0, 6, 0, 2, 4,
+ 3, 3, 2, 0, 0, 4, 2, 4, 4, 1, 4, 0, 0, 0, 2, 4,
+ 3, 3, 2, 1, 0, 4, 2, 4, 3, 2, 4, 1, 0, 0, 2, 4,
+};
+
+const static byte cb_cycles_table[256] =
+{
+ 2, 2, 2, 2, 2, 2, 4, 2, 2, 2, 2, 2, 2, 2, 4, 2,
+ 2, 2, 2, 2, 2, 2, 4, 2, 2, 2, 2, 2, 2, 2, 4, 2,
+ 2, 2, 2, 2, 2, 2, 4, 2, 2, 2, 2, 2, 2, 2, 4, 2,
+ 2, 2, 2, 2, 2, 2, 4, 2, 2, 2, 2, 2, 2, 2, 4, 2,
+
+ 2, 2, 2, 2, 2, 2, 3, 2, 2, 2, 2, 2, 2, 2, 3, 2,
+ 2, 2, 2, 2, 2, 2, 3, 2, 2, 2, 2, 2, 2, 2, 3, 2,
+ 2, 2, 2, 2, 2, 2, 3, 2, 2, 2, 2, 2, 2, 2, 3, 2,
+ 2, 2, 2, 2, 2, 2, 3, 2, 2, 2, 2, 2, 2, 2, 3, 2,
+
+ 2, 2, 2, 2, 2, 2, 4, 2, 2, 2, 2, 2, 2, 2, 4, 2,
+ 2, 2, 2, 2, 2, 2, 4, 2, 2, 2, 2, 2, 2, 2, 4, 2,
+ 2, 2, 2, 2, 2, 2, 4, 2, 2, 2, 2, 2, 2, 2, 4, 2,
+ 2, 2, 2, 2, 2, 2, 4, 2, 2, 2, 2, 2, 2, 2, 4, 2,
+
+ 2, 2, 2, 2, 2, 2, 4, 2, 2, 2, 2, 2, 2, 2, 4, 2,
+ 2, 2, 2, 2, 2, 2, 4, 2, 2, 2, 2, 2, 2, 2, 4, 2,
+ 2, 2, 2, 2, 2, 2, 4, 2, 2, 2, 2, 2, 2, 2, 4, 2,
+ 2, 2, 2, 2, 2, 2, 4, 2, 2, 2, 2, 2, 2, 2, 4, 2,
+};
+
+
+
+const static byte zflag_table[256] =
+{
+ FZ, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
+ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
+ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
+ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
+ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
+ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
+ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
+ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
+ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
+ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
+ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
+ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
+ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
+ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
+ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
+ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0
+};
+
+const static byte incflag_table[256] =
+{
+ FZ|FH, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
+ FH, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
+ FH, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
+ FH, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
+ FH, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
+ FH, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
+ FH, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
+ FH, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
+ FH, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
+ FH, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
+ FH, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
+ FH, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
+ FH, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
+ FH, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
+ FH, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
+ FH, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0
+};
+
+const static byte decflag_table[256] =
+{
+ FZ|FN, FN, FN, FN, FN, FN, FN, FN, FN, FN, FN, FN, FN, FN, FN, FN|FH,
+ FN, FN, FN, FN, FN, FN, FN, FN, FN, FN, FN, FN, FN, FN, FN, FN|FH,
+ FN, FN, FN, FN, FN, FN, FN, FN, FN, FN, FN, FN, FN, FN, FN, FN|FH,
+ FN, FN, FN, FN, FN, FN, FN, FN, FN, FN, FN, FN, FN, FN, FN, FN|FH,
+ FN, FN, FN, FN, FN, FN, FN, FN, FN, FN, FN, FN, FN, FN, FN, FN|FH,
+ FN, FN, FN, FN, FN, FN, FN, FN, FN, FN, FN, FN, FN, FN, FN, FN|FH,
+ FN, FN, FN, FN, FN, FN, FN, FN, FN, FN, FN, FN, FN, FN, FN, FN|FH,
+ FN, FN, FN, FN, FN, FN, FN, FN, FN, FN, FN, FN, FN, FN, FN, FN|FH,
+ FN, FN, FN, FN, FN, FN, FN, FN, FN, FN, FN, FN, FN, FN, FN, FN|FH,
+ FN, FN, FN, FN, FN, FN, FN, FN, FN, FN, FN, FN, FN, FN, FN, FN|FH,
+ FN, FN, FN, FN, FN, FN, FN, FN, FN, FN, FN, FN, FN, FN, FN, FN|FH,
+ FN, FN, FN, FN, FN, FN, FN, FN, FN, FN, FN, FN, FN, FN, FN, FN|FH,
+ FN, FN, FN, FN, FN, FN, FN, FN, FN, FN, FN, FN, FN, FN, FN, FN|FH,
+ FN, FN, FN, FN, FN, FN, FN, FN, FN, FN, FN, FN, FN, FN, FN, FN|FH,
+ FN, FN, FN, FN, FN, FN, FN, FN, FN, FN, FN, FN, FN, FN, FN, FN|FH,
+ FN, FN, FN, FN, FN, FN, FN, FN, FN, FN, FN, FN, FN, FN, FN, FN|FH
+};
+
+const static byte swap_table[256] =
+{
+ 0x00, 0x10, 0x20, 0x30, 0x40, 0x50, 0x60, 0x70, 0x80, 0x90, 0xA0, 0xB0, 0xC0, 0xD0, 0xE0, 0xF0,
+ 0x01, 0x11, 0x21, 0x31, 0x41, 0x51, 0x61, 0x71, 0x81, 0x91, 0xA1, 0xB1, 0xC1, 0xD1, 0xE1, 0xF1,
+ 0x02, 0x12, 0x22, 0x32, 0x42, 0x52, 0x62, 0x72, 0x82, 0x92, 0xA2, 0xB2, 0xC2, 0xD2, 0xE2, 0xF2,
+ 0x03, 0x13, 0x23, 0x33, 0x43, 0x53, 0x63, 0x73, 0x83, 0x93, 0xA3, 0xB3, 0xC3, 0xD3, 0xE3, 0xF3,
+ 0x04, 0x14, 0x24, 0x34, 0x44, 0x54, 0x64, 0x74, 0x84, 0x94, 0xA4, 0xB4, 0xC4, 0xD4, 0xE4, 0xF4,
+ 0x05, 0x15, 0x25, 0x35, 0x45, 0x55, 0x65, 0x75, 0x85, 0x95, 0xA5, 0xB5, 0xC5, 0xD5, 0xE5, 0xF5,
+ 0x06, 0x16, 0x26, 0x36, 0x46, 0x56, 0x66, 0x76, 0x86, 0x96, 0xA6, 0xB6, 0xC6, 0xD6, 0xE6, 0xF6,
+ 0x07, 0x17, 0x27, 0x37, 0x47, 0x57, 0x67, 0x77, 0x87, 0x97, 0xA7, 0xB7, 0xC7, 0xD7, 0xE7, 0xF7,
+ 0x08, 0x18, 0x28, 0x38, 0x48, 0x58, 0x68, 0x78, 0x88, 0x98, 0xA8, 0xB8, 0xC8, 0xD8, 0xE8, 0xF8,
+ 0x09, 0x19, 0x29, 0x39, 0x49, 0x59, 0x69, 0x79, 0x89, 0x99, 0xA9, 0xB9, 0xC9, 0xD9, 0xE9, 0xF9,
+ 0x0A, 0x1A, 0x2A, 0x3A, 0x4A, 0x5A, 0x6A, 0x7A, 0x8A, 0x9A, 0xAA, 0xBA, 0xCA, 0xDA, 0xEA, 0xFA,
+ 0x0B, 0x1B, 0x2B, 0x3B, 0x4B, 0x5B, 0x6B, 0x7B, 0x8B, 0x9B, 0xAB, 0xBB, 0xCB, 0xDB, 0xEB, 0xFB,
+ 0x0C, 0x1C, 0x2C, 0x3C, 0x4C, 0x5C, 0x6C, 0x7C, 0x8C, 0x9C, 0xAC, 0xBC, 0xCC, 0xDC, 0xEC, 0xFC,
+ 0x0D, 0x1D, 0x2D, 0x3D, 0x4D, 0x5D, 0x6D, 0x7D, 0x8D, 0x9D, 0xAD, 0xBD, 0xCD, 0xDD, 0xED, 0xFD,
+ 0x0E, 0x1E, 0x2E, 0x3E, 0x4E, 0x5E, 0x6E, 0x7E, 0x8E, 0x9E, 0xAE, 0xBE, 0xCE, 0xDE, 0xEE, 0xFE,
+ 0x0F, 0x1F, 0x2F, 0x3F, 0x4F, 0x5F, 0x6F, 0x7F, 0x8F, 0x9F, 0xAF, 0xBF, 0xCF, 0xDF, 0xEF, 0xFF,
+};
+
+const static byte daa_table[4096] =
+{
+ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x06, 0x06, 0x06, 0x06, 0x06, 0x06,
+ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x06, 0x06, 0x06, 0x06, 0x06, 0x06,
+ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x06, 0x06, 0x06, 0x06, 0x06, 0x06,
+ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x06, 0x06, 0x06, 0x06, 0x06, 0x06,
+ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x06, 0x06, 0x06, 0x06, 0x06, 0x06,
+ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x06, 0x06, 0x06, 0x06, 0x06, 0x06,
+ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x06, 0x06, 0x06, 0x06, 0x06, 0x06,
+ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x06, 0x06, 0x06, 0x06, 0x06, 0x06,
+ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x06, 0x06, 0x06, 0x06, 0x06, 0x06,
+ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x66, 0x66, 0x66, 0x66, 0x66, 0x66,
+ 0x60, 0x60, 0x60, 0x60, 0x60, 0x60, 0x60, 0x60, 0x60, 0x60, 0x66, 0x66, 0x66, 0x66, 0x66, 0x66,
+ 0x60, 0x60, 0x60, 0x60, 0x60, 0x60, 0x60, 0x60, 0x60, 0x60, 0x66, 0x66, 0x66, 0x66, 0x66, 0x66,
+ 0x60, 0x60, 0x60, 0x60, 0x60, 0x60, 0x60, 0x60, 0x60, 0x60, 0x66, 0x66, 0x66, 0x66, 0x66, 0x66,
+ 0x60, 0x60, 0x60, 0x60, 0x60, 0x60, 0x60, 0x60, 0x60, 0x60, 0x66, 0x66, 0x66, 0x66, 0x66, 0x66,
+ 0x60, 0x60, 0x60, 0x60, 0x60, 0x60, 0x60, 0x60, 0x60, 0x60, 0x66, 0x66, 0x66, 0x66, 0x66, 0x66,
+ 0x60, 0x60, 0x60, 0x60, 0x60, 0x60, 0x60, 0x60, 0x60, 0x60, 0x66, 0x66, 0x66, 0x66, 0x66, 0x66,
+
+ 0x60, 0x60, 0x60, 0x60, 0x60, 0x60, 0x60, 0x60, 0x60, 0x60, 0x66, 0x66, 0x66, 0x66, 0x66, 0x66,
+ 0x60, 0x60, 0x60, 0x60, 0x60, 0x60, 0x60, 0x60, 0x60, 0x60, 0x66, 0x66, 0x66, 0x66, 0x66, 0x66,
+ 0x60, 0x60, 0x60, 0x60, 0x60, 0x60, 0x60, 0x60, 0x60, 0x60, 0x66, 0x66, 0x66, 0x66, 0x66, 0x66,
+ 0x60, 0x60, 0x60, 0x60, 0x60, 0x60, 0x60, 0x60, 0x60, 0x60, 0x66, 0x66, 0x66, 0x66, 0x66, 0x66,
+ 0x60, 0x60, 0x60, 0x60, 0x60, 0x60, 0x60, 0x60, 0x60, 0x60, 0x66, 0x66, 0x66, 0x66, 0x66, 0x66,
+ 0x60, 0x60, 0x60, 0x60, 0x60, 0x60, 0x60, 0x60, 0x60, 0x60, 0x66, 0x66, 0x66, 0x66, 0x66, 0x66,
+ 0x60, 0x60, 0x60, 0x60, 0x60, 0x60, 0x60, 0x60, 0x60, 0x60, 0x66, 0x66, 0x66, 0x66, 0x66, 0x66,
+ 0x60, 0x60, 0x60, 0x60, 0x60, 0x60, 0x60, 0x60, 0x60, 0x60, 0x66, 0x66, 0x66, 0x66, 0x66, 0x66,
+ 0x60, 0x60, 0x60, 0x60, 0x60, 0x60, 0x60, 0x60, 0x60, 0x60, 0x66, 0x66, 0x66, 0x66, 0x66, 0x66,
+ 0x60, 0x60, 0x60, 0x60, 0x60, 0x60, 0x60, 0x60, 0x60, 0x60, 0x66, 0x66, 0x66, 0x66, 0x66, 0x66,
+ 0x60, 0x60, 0x60, 0x60, 0x60, 0x60, 0x60, 0x60, 0x60, 0x60, 0x66, 0x66, 0x66, 0x66, 0x66, 0x66,
+ 0x60, 0x60, 0x60, 0x60, 0x60, 0x60, 0x60, 0x60, 0x60, 0x60, 0x66, 0x66, 0x66, 0x66, 0x66, 0x66,
+ 0x60, 0x60, 0x60, 0x60, 0x60, 0x60, 0x60, 0x60, 0x60, 0x60, 0x66, 0x66, 0x66, 0x66, 0x66, 0x66,
+ 0x60, 0x60, 0x60, 0x60, 0x60, 0x60, 0x60, 0x60, 0x60, 0x60, 0x66, 0x66, 0x66, 0x66, 0x66, 0x66,
+ 0x60, 0x60, 0x60, 0x60, 0x60, 0x60, 0x60, 0x60, 0x60, 0x60, 0x66, 0x66, 0x66, 0x66, 0x66, 0x66,
+ 0x60, 0x60, 0x60, 0x60, 0x60, 0x60, 0x60, 0x60, 0x60, 0x60, 0x66, 0x66, 0x66, 0x66, 0x66, 0x66,
+
+ 0x06, 0x06, 0x06, 0x06, 0x06, 0x06, 0x06, 0x06, 0x06, 0x06, 0x06, 0x06, 0x06, 0x06, 0x06, 0x06,
+ 0x06, 0x06, 0x06, 0x06, 0x06, 0x06, 0x06, 0x06, 0x06, 0x06, 0x06, 0x06, 0x06, 0x06, 0x06, 0x06,
+ 0x06, 0x06, 0x06, 0x06, 0x06, 0x06, 0x06, 0x06, 0x06, 0x06, 0x06, 0x06, 0x06, 0x06, 0x06, 0x06,
+ 0x06, 0x06, 0x06, 0x06, 0x06, 0x06, 0x06, 0x06, 0x06, 0x06, 0x06, 0x06, 0x06, 0x06, 0x06, 0x06,
+ 0x06, 0x06, 0x06, 0x06, 0x06, 0x06, 0x06, 0x06, 0x06, 0x06, 0x06, 0x06, 0x06, 0x06, 0x06, 0x06,
+ 0x06, 0x06, 0x06, 0x06, 0x06, 0x06, 0x06, 0x06, 0x06, 0x06, 0x06, 0x06, 0x06, 0x06, 0x06, 0x06,
+ 0x06, 0x06, 0x06, 0x06, 0x06, 0x06, 0x06, 0x06, 0x06, 0x06, 0x06, 0x06, 0x06, 0x06, 0x06, 0x06,
+ 0x06, 0x06, 0x06, 0x06, 0x06, 0x06, 0x06, 0x06, 0x06, 0x06, 0x06, 0x06, 0x06, 0x06, 0x06, 0x06,
+ 0x06, 0x06, 0x06, 0x06, 0x06, 0x06, 0x06, 0x06, 0x06, 0x06, 0x06, 0x06, 0x06, 0x06, 0x06, 0x06,
+ 0x06, 0x06, 0x06, 0x06, 0x06, 0x06, 0x06, 0x06, 0x06, 0x06, 0x06, 0x06, 0x06, 0x06, 0x06, 0x06,
+ 0x66, 0x66, 0x66, 0x66, 0x66, 0x66, 0x66, 0x66, 0x66, 0x66, 0x66, 0x66, 0x66, 0x66, 0x66, 0x66,
+ 0x66, 0x66, 0x66, 0x66, 0x66, 0x66, 0x66, 0x66, 0x66, 0x66, 0x66, 0x66, 0x66, 0x66, 0x66, 0x66,
+ 0x66, 0x66, 0x66, 0x66, 0x66, 0x66, 0x66, 0x66, 0x66, 0x66, 0x66, 0x66, 0x66, 0x66, 0x66, 0x66,
+ 0x66, 0x66, 0x66, 0x66, 0x66, 0x66, 0x66, 0x66, 0x66, 0x66, 0x66, 0x66, 0x66, 0x66, 0x66, 0x66,
+ 0x66, 0x66, 0x66, 0x66, 0x66, 0x66, 0x66, 0x66, 0x66, 0x66, 0x66, 0x66, 0x66, 0x66, 0x66, 0x66,
+ 0x66, 0x66, 0x66, 0x66, 0x66, 0x66, 0x66, 0x66, 0x66, 0x66, 0x66, 0x66, 0x66, 0x66, 0x66, 0x66,
+
+ 0x66, 0x66, 0x66, 0x66, 0x66, 0x66, 0x66, 0x66, 0x66, 0x66, 0x66, 0x66, 0x66, 0x66, 0x66, 0x66,
+ 0x66, 0x66, 0x66, 0x66, 0x66, 0x66, 0x66, 0x66, 0x66, 0x66, 0x66, 0x66, 0x66, 0x66, 0x66, 0x66,
+ 0x66, 0x66, 0x66, 0x66, 0x66, 0x66, 0x66, 0x66, 0x66, 0x66, 0x66, 0x66, 0x66, 0x66, 0x66, 0x66,
+ 0x66, 0x66, 0x66, 0x66, 0x66, 0x66, 0x66, 0x66, 0x66, 0x66, 0x66, 0x66, 0x66, 0x66, 0x66, 0x66,
+ 0x66, 0x66, 0x66, 0x66, 0x66, 0x66, 0x66, 0x66, 0x66, 0x66, 0x66, 0x66, 0x66, 0x66, 0x66, 0x66,
+ 0x66, 0x66, 0x66, 0x66, 0x66, 0x66, 0x66, 0x66, 0x66, 0x66, 0x66, 0x66, 0x66, 0x66, 0x66, 0x66,
+ 0x66, 0x66, 0x66, 0x66, 0x66, 0x66, 0x66, 0x66, 0x66, 0x66, 0x66, 0x66, 0x66, 0x66, 0x66, 0x66,
+ 0x66, 0x66, 0x66, 0x66, 0x66, 0x66, 0x66, 0x66, 0x66, 0x66, 0x66, 0x66, 0x66, 0x66, 0x66, 0x66,
+ 0x66, 0x66, 0x66, 0x66, 0x66, 0x66, 0x66, 0x66, 0x66, 0x66, 0x66, 0x66, 0x66, 0x66, 0x66, 0x66,
+ 0x66, 0x66, 0x66, 0x66, 0x66, 0x66, 0x66, 0x66, 0x66, 0x66, 0x66, 0x66, 0x66, 0x66, 0x66, 0x66,
+ 0x66, 0x66, 0x66, 0x66, 0x66, 0x66, 0x66, 0x66, 0x66, 0x66, 0x66, 0x66, 0x66, 0x66, 0x66, 0x66,
+ 0x66, 0x66, 0x66, 0x66, 0x66, 0x66, 0x66, 0x66, 0x66, 0x66, 0x66, 0x66, 0x66, 0x66, 0x66, 0x66,
+ 0x66, 0x66, 0x66, 0x66, 0x66, 0x66, 0x66, 0x66, 0x66, 0x66, 0x66, 0x66, 0x66, 0x66, 0x66, 0x66,
+ 0x66, 0x66, 0x66, 0x66, 0x66, 0x66, 0x66, 0x66, 0x66, 0x66, 0x66, 0x66, 0x66, 0x66, 0x66, 0x66,
+ 0x66, 0x66, 0x66, 0x66, 0x66, 0x66, 0x66, 0x66, 0x66, 0x66, 0x66, 0x66, 0x66, 0x66, 0x66, 0x66,
+ 0x66, 0x66, 0x66, 0x66, 0x66, 0x66, 0x66, 0x66, 0x66, 0x66, 0x66, 0x66, 0x66, 0x66, 0x66, 0x66,
+
+ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
+ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
+ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
+ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
+ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
+ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
+ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
+ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
+ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
+ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
+ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
+ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
+ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
+ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
+ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
+ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
+
+ 0xA0, 0xA0, 0xA0, 0xA0, 0xA0, 0xA0, 0xA0, 0xA0, 0xA0, 0xA0, 0xA0, 0xA0, 0xA0, 0xA0, 0xA0, 0xA0,
+ 0xA0, 0xA0, 0xA0, 0xA0, 0xA0, 0xA0, 0xA0, 0xA0, 0xA0, 0xA0, 0xA0, 0xA0, 0xA0, 0xA0, 0xA0, 0xA0,
+ 0xA0, 0xA0, 0xA0, 0xA0, 0xA0, 0xA0, 0xA0, 0xA0, 0xA0, 0xA0, 0xA0, 0xA0, 0xA0, 0xA0, 0xA0, 0xA0,
+ 0xA0, 0xA0, 0xA0, 0xA0, 0xA0, 0xA0, 0xA0, 0xA0, 0xA0, 0xA0, 0xA0, 0xA0, 0xA0, 0xA0, 0xA0, 0xA0,
+ 0xA0, 0xA0, 0xA0, 0xA0, 0xA0, 0xA0, 0xA0, 0xA0, 0xA0, 0xA0, 0xA0, 0xA0, 0xA0, 0xA0, 0xA0, 0xA0,
+ 0xA0, 0xA0, 0xA0, 0xA0, 0xA0, 0xA0, 0xA0, 0xA0, 0xA0, 0xA0, 0xA0, 0xA0, 0xA0, 0xA0, 0xA0, 0xA0,
+ 0xA0, 0xA0, 0xA0, 0xA0, 0xA0, 0xA0, 0xA0, 0xA0, 0xA0, 0xA0, 0xA0, 0xA0, 0xA0, 0xA0, 0xA0, 0xA0,
+ 0xA0, 0xA0, 0xA0, 0xA0, 0xA0, 0xA0, 0xA0, 0xA0, 0xA0, 0xA0, 0xA0, 0xA0, 0xA0, 0xA0, 0xA0, 0xA0,
+ 0xA0, 0xA0, 0xA0, 0xA0, 0xA0, 0xA0, 0xA0, 0xA0, 0xA0, 0xA0, 0xA0, 0xA0, 0xA0, 0xA0, 0xA0, 0xA0,
+ 0xA0, 0xA0, 0xA0, 0xA0, 0xA0, 0xA0, 0xA0, 0xA0, 0xA0, 0xA0, 0xA0, 0xA0, 0xA0, 0xA0, 0xA0, 0xA0,
+ 0xA0, 0xA0, 0xA0, 0xA0, 0xA0, 0xA0, 0xA0, 0xA0, 0xA0, 0xA0, 0xA0, 0xA0, 0xA0, 0xA0, 0xA0, 0xA0,
+ 0xA0, 0xA0, 0xA0, 0xA0, 0xA0, 0xA0, 0xA0, 0xA0, 0xA0, 0xA0, 0xA0, 0xA0, 0xA0, 0xA0, 0xA0, 0xA0,
+ 0xA0, 0xA0, 0xA0, 0xA0, 0xA0, 0xA0, 0xA0, 0xA0, 0xA0, 0xA0, 0xA0, 0xA0, 0xA0, 0xA0, 0xA0, 0xA0,
+ 0xA0, 0xA0, 0xA0, 0xA0, 0xA0, 0xA0, 0xA0, 0xA0, 0xA0, 0xA0, 0xA0, 0xA0, 0xA0, 0xA0, 0xA0, 0xA0,
+ 0xA0, 0xA0, 0xA0, 0xA0, 0xA0, 0xA0, 0xA0, 0xA0, 0xA0, 0xA0, 0xA0, 0xA0, 0xA0, 0xA0, 0xA0, 0xA0,
+ 0xA0, 0xA0, 0xA0, 0xA0, 0xA0, 0xA0, 0xA0, 0xA0, 0xA0, 0xA0, 0xA0, 0xA0, 0xA0, 0xA0, 0xA0, 0xA0,
+
+ 0xFA, 0xFA, 0xFA, 0xFA, 0xFA, 0xFA, 0xFA, 0xFA, 0xFA, 0xFA, 0xFA, 0xFA, 0xFA, 0xFA, 0xFA, 0xFA,
+ 0xFA, 0xFA, 0xFA, 0xFA, 0xFA, 0xFA, 0xFA, 0xFA, 0xFA, 0xFA, 0xFA, 0xFA, 0xFA, 0xFA, 0xFA, 0xFA,
+ 0xFA, 0xFA, 0xFA, 0xFA, 0xFA, 0xFA, 0xFA, 0xFA, 0xFA, 0xFA, 0xFA, 0xFA, 0xFA, 0xFA, 0xFA, 0xFA,
+ 0xFA, 0xFA, 0xFA, 0xFA, 0xFA, 0xFA, 0xFA, 0xFA, 0xFA, 0xFA, 0xFA, 0xFA, 0xFA, 0xFA, 0xFA, 0xFA,
+ 0xFA, 0xFA, 0xFA, 0xFA, 0xFA, 0xFA, 0xFA, 0xFA, 0xFA, 0xFA, 0xFA, 0xFA, 0xFA, 0xFA, 0xFA, 0xFA,
+ 0xFA, 0xFA, 0xFA, 0xFA, 0xFA, 0xFA, 0xFA, 0xFA, 0xFA, 0xFA, 0xFA, 0xFA, 0xFA, 0xFA, 0xFA, 0xFA,
+ 0xFA, 0xFA, 0xFA, 0xFA, 0xFA, 0xFA, 0xFA, 0xFA, 0xFA, 0xFA, 0xFA, 0xFA, 0xFA, 0xFA, 0xFA, 0xFA,
+ 0xFA, 0xFA, 0xFA, 0xFA, 0xFA, 0xFA, 0xFA, 0xFA, 0xFA, 0xFA, 0xFA, 0xFA, 0xFA, 0xFA, 0xFA, 0xFA,
+ 0xFA, 0xFA, 0xFA, 0xFA, 0xFA, 0xFA, 0xFA, 0xFA, 0xFA, 0xFA, 0xFA, 0xFA, 0xFA, 0xFA, 0xFA, 0xFA,
+ 0xFA, 0xFA, 0xFA, 0xFA, 0xFA, 0xFA, 0xFA, 0xFA, 0xFA, 0xFA, 0xFA, 0xFA, 0xFA, 0xFA, 0xFA, 0xFA,
+ 0xFA, 0xFA, 0xFA, 0xFA, 0xFA, 0xFA, 0xFA, 0xFA, 0xFA, 0xFA, 0xFA, 0xFA, 0xFA, 0xFA, 0xFA, 0xFA,
+ 0xFA, 0xFA, 0xFA, 0xFA, 0xFA, 0xFA, 0xFA, 0xFA, 0xFA, 0xFA, 0xFA, 0xFA, 0xFA, 0xFA, 0xFA, 0xFA,
+ 0xFA, 0xFA, 0xFA, 0xFA, 0xFA, 0xFA, 0xFA, 0xFA, 0xFA, 0xFA, 0xFA, 0xFA, 0xFA, 0xFA, 0xFA, 0xFA,
+ 0xFA, 0xFA, 0xFA, 0xFA, 0xFA, 0xFA, 0xFA, 0xFA, 0xFA, 0xFA, 0xFA, 0xFA, 0xFA, 0xFA, 0xFA, 0xFA,
+ 0xFA, 0xFA, 0xFA, 0xFA, 0xFA, 0xFA, 0xFA, 0xFA, 0xFA, 0xFA, 0xFA, 0xFA, 0xFA, 0xFA, 0xFA, 0xFA,
+ 0xFA, 0xFA, 0xFA, 0xFA, 0xFA, 0xFA, 0xFA, 0xFA, 0xFA, 0xFA, 0xFA, 0xFA, 0xFA, 0xFA, 0xFA, 0xFA,
+
+ 0x9A, 0x9A, 0x9A, 0x9A, 0x9A, 0x9A, 0x9A, 0x9A, 0x9A, 0x9A, 0x9A, 0x9A, 0x9A, 0x9A, 0x9A, 0x9A,
+ 0x9A, 0x9A, 0x9A, 0x9A, 0x9A, 0x9A, 0x9A, 0x9A, 0x9A, 0x9A, 0x9A, 0x9A, 0x9A, 0x9A, 0x9A, 0x9A,
+ 0x9A, 0x9A, 0x9A, 0x9A, 0x9A, 0x9A, 0x9A, 0x9A, 0x9A, 0x9A, 0x9A, 0x9A, 0x9A, 0x9A, 0x9A, 0x9A,
+ 0x9A, 0x9A, 0x9A, 0x9A, 0x9A, 0x9A, 0x9A, 0x9A, 0x9A, 0x9A, 0x9A, 0x9A, 0x9A, 0x9A, 0x9A, 0x9A,
+ 0x9A, 0x9A, 0x9A, 0x9A, 0x9A, 0x9A, 0x9A, 0x9A, 0x9A, 0x9A, 0x9A, 0x9A, 0x9A, 0x9A, 0x9A, 0x9A,
+ 0x9A, 0x9A, 0x9A, 0x9A, 0x9A, 0x9A, 0x9A, 0x9A, 0x9A, 0x9A, 0x9A, 0x9A, 0x9A, 0x9A, 0x9A, 0x9A,
+ 0x9A, 0x9A, 0x9A, 0x9A, 0x9A, 0x9A, 0x9A, 0x9A, 0x9A, 0x9A, 0x9A, 0x9A, 0x9A, 0x9A, 0x9A, 0x9A,
+ 0x9A, 0x9A, 0x9A, 0x9A, 0x9A, 0x9A, 0x9A, 0x9A, 0x9A, 0x9A, 0x9A, 0x9A, 0x9A, 0x9A, 0x9A, 0x9A,
+ 0x9A, 0x9A, 0x9A, 0x9A, 0x9A, 0x9A, 0x9A, 0x9A, 0x9A, 0x9A, 0x9A, 0x9A, 0x9A, 0x9A, 0x9A, 0x9A,
+ 0x9A, 0x9A, 0x9A, 0x9A, 0x9A, 0x9A, 0x9A, 0x9A, 0x9A, 0x9A, 0x9A, 0x9A, 0x9A, 0x9A, 0x9A, 0x9A,
+ 0x9A, 0x9A, 0x9A, 0x9A, 0x9A, 0x9A, 0x9A, 0x9A, 0x9A, 0x9A, 0x9A, 0x9A, 0x9A, 0x9A, 0x9A, 0x9A,
+ 0x9A, 0x9A, 0x9A, 0x9A, 0x9A, 0x9A, 0x9A, 0x9A, 0x9A, 0x9A, 0x9A, 0x9A, 0x9A, 0x9A, 0x9A, 0x9A,
+ 0x9A, 0x9A, 0x9A, 0x9A, 0x9A, 0x9A, 0x9A, 0x9A, 0x9A, 0x9A, 0x9A, 0x9A, 0x9A, 0x9A, 0x9A, 0x9A,
+ 0x9A, 0x9A, 0x9A, 0x9A, 0x9A, 0x9A, 0x9A, 0x9A, 0x9A, 0x9A, 0x9A, 0x9A, 0x9A, 0x9A, 0x9A, 0x9A,
+ 0x9A, 0x9A, 0x9A, 0x9A, 0x9A, 0x9A, 0x9A, 0x9A, 0x9A, 0x9A, 0x9A, 0x9A, 0x9A, 0x9A, 0x9A, 0x9A,
+ 0x9A, 0x9A, 0x9A, 0x9A, 0x9A, 0x9A, 0x9A, 0x9A, 0x9A, 0x9A, 0x9A, 0x9A, 0x9A, 0x9A, 0x9A, 0x9A,
+};
+
+const static byte daa_carry_table[64] =
+{
+ 00, 00, 00, 00, 00, 00, 00, 00, 00, 00, 00, 00, 00, 00, 00, 00,
+ 00, 00, 00, 00, 00, 00, 00, 00, FC, FC, 00, 00, 00, 00, 00, 00,
+ FC, FC, FC, FC, FC, FC, FC, FC, FC, FC, FC, FC, FC, FC, FC, FC,
+ FC, FC, FC, FC, FC, FC, FC, FC, FC, FC, FC, FC, FC, FC, 00, FC,
+};
+
+
+
+
+
+
+
+
+
+
+
+
diff --git a/games/retrogo/src/gb/cpuregs.h b/games/retrogo/src/gb/cpuregs.h
new file mode 100644
index 00000000..3b691ebc
--- /dev/null
+++ b/games/retrogo/src/gb/cpuregs.h
@@ -0,0 +1,56 @@
+/* From gnuboy 1.0.3 (rofl0r's tree) by Laguna and Gilgamesh and gnuboy's contributors,
+ * GPL-2.0-or-later (see COPYING in this folder); changed for Retro-Go on NumPlay. */
+#ifndef __CPUREGS_H__
+
+#define __CPUREGS_H__
+
+
+
+#include "defs.h"
+#include "cpu.h"
+
+#define LB(r) ((r).b[LO][LO])
+#define HB(r) ((r).b[LO][HI])
+#define W(r) ((r).w[LO])
+#define DW(r) ((r).d)
+
+#define A HB(cpu.af)
+#define F LB(cpu.af)
+#define B HB(cpu.bc)
+#define C LB(cpu.bc)
+#define D HB(cpu.de)
+#define E LB(cpu.de)
+#define H HB(cpu.hl)
+#define L LB(cpu.hl)
+
+#define AF W(cpu.af)
+#define BC W(cpu.bc)
+#define DE W(cpu.de)
+#define HL W(cpu.hl)
+
+#define PC W(cpu.pc)
+#define SP W(cpu.sp)
+
+#define xAF DW(cpu.af)
+#define xBC DW(cpu.bc)
+#define xDE DW(cpu.de)
+#define xHL DW(cpu.hl)
+
+#define xPC DW(cpu.pc)
+#define xSP DW(cpu.sp)
+
+#define IMA cpu.ima
+#define IME cpu.ime
+#define IF R_IF
+#define IE R_IE
+
+#define FZ 0x80
+#define FN 0x40
+#define FH 0x20
+#define FC 0x10
+#define FL 0x0F /* low unused portion of flags */
+
+
+#endif /* __CPUREGS_H__ */
+
+
diff --git a/games/retrogo/src/gb/defs.h b/games/retrogo/src/gb/defs.h
new file mode 100644
index 00000000..a39d9844
--- /dev/null
+++ b/games/retrogo/src/gb/defs.h
@@ -0,0 +1,24 @@
+/* gnuboy's basic types. From gnuboy 1.0.3 (rofl0r's tree), GPL-2.0-or-later; see COPYING and
+ * README.md in this folder. Trimmed for Retro-Go on NumPlay. */
+#ifndef __DEFS_H__
+#define __DEFS_H__
+
+#define IS_LITTLE_ENDIAN 1
+#define LO 0
+#define HI 1
+#define LIL(x) (x)
+
+typedef unsigned char byte;
+
+typedef unsigned char un8;
+typedef unsigned short un16;
+typedef unsigned int un32;
+
+typedef signed char n8;
+typedef signed short n16;
+typedef signed int n32;
+
+typedef un16 word;
+typedef word addr;
+
+#endif
diff --git a/games/retrogo/src/gb/fastmem.h b/games/retrogo/src/gb/fastmem.h
new file mode 100644
index 00000000..aa4c8443
--- /dev/null
+++ b/games/retrogo/src/gb/fastmem.h
@@ -0,0 +1,100 @@
+/* From gnuboy 1.0.3 (rofl0r's tree) by Laguna and Gilgamesh and gnuboy's contributors,
+ * GPL-2.0-or-later (see COPYING in this folder); changed for Retro-Go on NumPlay. */
+#ifndef __FASTMEM_H__
+#define __FASTMEM_H__
+
+
+#include "defs.h"
+#include "mem.h"
+
+
+static inline byte readb(int a)
+{
+ byte *p = mbc.rmap[a>>12];
+ if (p) return p[a];
+ else return mem_read(a);
+}
+
+static inline void writeb(int a, byte b)
+{
+ byte *p = mbc.wmap[a>>12];
+ if (p) p[a] = b;
+ else mem_write(a, b);
+}
+
+static inline int readw(int a)
+{
+ if ((a+1) & 0xfff)
+ {
+ byte *p = mbc.rmap[a>>12];
+ if (p)
+ {
+#ifdef IS_LITTLE_ENDIAN
+#ifndef ALLOW_UNALIGNED_IO
+ if (a&1) return p[a] | (p[a+1]<<8);
+#endif
+ return *(word *)(p+a);
+#else
+ return p[a] | (p[a+1]<<8);
+#endif
+ }
+ }
+ return mem_read(a) | (mem_read(a+1)<<8);
+}
+
+static inline void writew(int a, int w)
+{
+ if ((a+1) & 0xfff)
+ {
+ byte *p = mbc.wmap[a>>12];
+ if (p)
+ {
+#ifdef IS_LITTLE_ENDIAN
+#ifndef ALLOW_UNALIGNED_IO
+ if (a&1)
+ {
+ p[a] = w;
+ p[a+1] = w >> 8;
+ return;
+ }
+#endif
+ *(word *)(p+a) = w;
+ return;
+#else
+ p[a] = w;
+ p[a+1] = w >> 8;
+ return;
+#endif
+ }
+ }
+ mem_write(a, w);
+ mem_write(a+1, w>>8);
+}
+
+static inline byte readhi(int a)
+{
+ return readb(a | 0xff00);
+}
+
+static inline void writehi(int a, byte b)
+{
+ writeb(a | 0xff00, b);
+}
+
+#if 0
+static inline byte readhi(int a)
+{
+ byte (*rd)() = hi_read[a];
+ return rd ? rd(a) : (ram.hi[a] | himask[a]);
+}
+
+static inline void writehi(int a, byte b)
+{
+ byte (*wr)() = hi_write[a];
+ if (wr) wr(a, b);
+ else ram.hi[a] = b & ~himask[a];
+}
+#endif
+
+
+#endif
diff --git a/games/retrogo/src/gb/gb.c b/games/retrogo/src/gb/gb.c
new file mode 100644
index 00000000..938894c5
--- /dev/null
+++ b/games/retrogo/src/gb/gb.c
@@ -0,0 +1,232 @@
+/* The Game Boy as Retro-Go runs it: loading a cartridge read in place, a frame at a time, the
+ * pad, the battery RAM and the parts of a save state. Built on gnuboy 1.0.3 (rofl0r's tree) by
+ * Laguna and Gilgamesh, GPL-2.0-or-later: the cartridge header tables and the frame loop follow
+ * its loader.c and emu.c. The sound registers are kept (games read them back) but not played:
+ * the calculator has no speaker. */
+#include <stddef.h>
+#include <string.h>
+#include "defs.h"
+#include "regs.h"
+#include "hw.h"
+#include "cpu.h"
+#include "mem.h"
+#include "lcd.h"
+#include "rtc.h"
+#include "gb.h"
+
+/* cartridge types (header byte 0x147): the bank controller, a battery, a clock */
+static const byte mbc_table[256] = {
+ 0, 1, 1, 1, 0, 2, 2, 0, 0, 0, 0, 0, 0, 0, 0, 3,
+ 3, 3, 3, 3, 0, 0, 0, 0, 0, 5, 5, 5, MBC_RUMBLE, MBC_RUMBLE, MBC_RUMBLE, 0,
+ [0xFE] = MBC_HUC3, [0xFF] = MBC_HUC1,
+};
+static const byte batt_table[256] = {
+ 0, 0, 0, 1, 0, 0, 1, 0, 0, 1, 0, 0, 0, 1, 0, 1,
+ 1, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 1, 0,
+ [0xFE] = 1, [0xFF] = 1,
+};
+/* the cartridge RAM's size (header byte 0x149), in bytes, as the game sees it */
+static const un32 ram_bytes[6] = {0, 2048, 8192, 32768, 131072, 65536};
+
+static int rom_type, rom_banks, ram_banks, sram_size, has_rtc;
+static byte sound_regs[0x30];
+
+int gb_load(const uint8_t *data, uint32_t size)
+{
+ if (!data || size < 0x8000 || size > 8u << 20) return RG_ERR_ROM;
+ int c = data[0x147];
+ rom_type = mbc_table[c];
+ if (rom_type == MBC_NONE && c != 0x00 && c != 0x08 && c != 0x09) return RG_ERR_MAPPER;
+ /* every bank the header names, the ones the file lacks repeating the others; a power of two
+ so that a bank number can always be masked */
+ int have = (int)(size / 16384), want = data[0x148] <= 8 ? 2 << data[0x148] : have;
+ if (want < have) want = have;
+ rom_banks = 2;
+ while (rom_banks < want) rom_banks <<= 1;
+ if (rom_banks > ROM_MAX_BANKS) return RG_ERR_ROM;
+ memset(&rom, 0, sizeof rom);
+ for (int i = 0; i < rom_banks; i++) rom.bank[i] = data + (i % have) * 16384;
+ memcpy(rom.name, data + 0x134, 16);
+
+ int rcode = data[0x149] < 6 ? data[0x149] : 0;
+ sram_size = rom_type == MBC_MBC2 ? 512 : (int)ram_bytes[rcode];
+ if (sram_size > 32768) return RG_ERR_MEMORY;
+ ram_banks = sram_size > 8192 ? sram_size / 8192 : 1;
+ has_rtc = (c == 0x0F || c == 0x10) && rom_type == MBC_MBC3;
+
+ memset(&hw, 0, sizeof hw);
+ hw.cgb = (data[0x143] & 0x80) != 0;
+ rg_alloc_reset();
+ memset(&ram, 0, sizeof ram);
+ memset(&lcd, 0, sizeof lcd);
+ ram.ibank = rg_alloc(4096 * (hw.cgb ? 8 : 2));
+ lcd.vbank[0] = rg_alloc(8192 * (hw.cgb ? 2 : 1));
+ lcd.vbank[1] = hw.cgb ? lcd.vbank[0] + 8192 : lcd.vbank[0];
+ ram.sbank = rom_type == MBC_NONE && !sram_size ? NULL : rg_alloc(8192 * ram_banks);
+ if (!ram.ibank || !lcd.vbank[0] || (!ram.sbank && (rom_type != MBC_NONE || sram_size)))
+ return RG_ERR_MEMORY;
+
+ memset(&mbc, 0, sizeof mbc);
+ mbc.type = rom_type;
+ mbc.batt = batt_table[c];
+ mbc.romsize = rom_banks;
+ mbc.ramsize = ram_banks;
+ memset(&rtc, 0, sizeof rtc);
+ rtc.batt = has_rtc;
+ if (ram.sbank) memset(ram.sbank, 0xFF, 8192 * ram_banks); /* (a new cartridge's RAM) */
+ gb_reset(true);
+ return RG_OK;
+}
+
+void gb_reset(bool hard)
+{
+ if (hard)
+ {
+ memset(ram.ibank, 0, 4096 * (hw.cgb ? 8 : 2));
+ memset(&cpu, 0, sizeof cpu);
+ }
+ hw_reset();
+ lcd_reset();
+ cpu_reset();
+ mbc_reset();
+ memset(sound_regs, 0, sizeof sound_regs);
+ sound_regs[0x26 - 0x10] = 0xF1; /* (on at power up) */
+}
+
+bool gb_is_cgb(void) { return hw.cgb != 0; }
+
+void gb_set_pad(int p)
+{
+ int pad = 0;
+ if (p & RG_PAD_RIGHT) pad |= PAD_RIGHT;
+ if (p & RG_PAD_LEFT) pad |= PAD_LEFT;
+ if (p & RG_PAD_UP) pad |= PAD_UP;
+ if (p & RG_PAD_DOWN) pad |= PAD_DOWN;
+ if (p & RG_PAD_A) pad |= PAD_A;
+ if (p & RG_PAD_B) pad |= PAD_B;
+ if (p & RG_PAD_SELECT) pad |= PAD_SELECT;
+ if (p & RG_PAD_START) pad |= PAD_START;
+ if (pad == hw.pad) return;
+ hw.pad = (byte)pad;
+ pad_refresh();
+}
+
+/* One frame, from line 0 to the end of the vertical blank (gnuboy's emu_run). */
+void gb_run_frame(bool draw)
+{
+ /* (never more than a few frames' time, whatever a save state left: LY only moves with the LCD on) */
+ int budget = 4 * 35112;
+ gb_draw = draw;
+ budget -= cpu_emulate(2280);
+ while ((R_LCDC & 0x80) && R_LY > 0 && R_LY < 144 && budget > 0)
+ budget -= cpu_emulate(cpu.lcdc);
+ rtc_tick();
+ if (!(R_LCDC & 0x80))
+ cpu_emulate(32832);
+ while ((R_LCDC & 0x80) && R_LY > 0 && budget > 0)
+ budget -= cpu_emulate(cpu.lcdc);
+}
+
+/* ------------------------------------------------------------ sound registers */
+/* the bits that read back as 1 (Pan Docs) */
+static const byte sound_mask[0x30] = {
+ 0x80, 0x3F, 0x00, 0xFF, 0xBF, 0xFF, 0x3F, 0x00, 0xFF, 0xBF, 0x7F, 0xFF, 0x9F, 0xFF, 0xBF, 0xFF,
+ 0xFF, 0x00, 0x00, 0xBF, 0x00, 0x00, 0x70, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF,
+};
+
+unsigned char gb_sound_read(unsigned char r)
+{
+ if (r < 0x10 || r >= 0x40) return 0xFF;
+ if (r == 0x26) return (sound_regs[0x16] & 0x80) | 0x70; /* on, no channel playing */
+ return sound_regs[r - 0x10] | sound_mask[r - 0x10];
+}
+
+void gb_sound_write(unsigned char r, unsigned char b)
+{
+ if (r < 0x10 || r >= 0x40) return;
+ sound_regs[r - 0x10] = b;
+}
+
+/* ------------------------------------------------------------ battery */
+uint8_t *gb_sram(uint32_t *size)
+{
+ *size = (uint32_t)sram_size;
+ return mbc.batt && ram.sbank ? ram.sbank[0] : NULL;
+}
+
+bool gb_sram_dirty(void) { return mbc.batt && ram.sram_dirty; }
+void gb_sram_saved(void) { ram.sram_dirty = 0; }
+bool gb_has_rtc(void) { return has_rtc; }
+
+void *gb_rtc_state(uint32_t *size)
+{
+ *size = sizeof rtc;
+ return &rtc;
+}
+
+void gb_rtc_loaded(void)
+{
+ rtc.batt = has_rtc;
+ rtc_check();
+}
+
+void gb_get_time(int *d, int *h, int *m, int *s)
+{
+ if (d) *d = rtc.d;
+ if (h) *h = rtc.h;
+ if (m) *m = rtc.m;
+ if (s) *s = rtc.s;
+}
+
+void gb_set_time(int d, int h, int m, int s)
+{
+ rtc.d = d, rtc.h = h, rtc.m = m, rtc.s = s, rtc.t = 0;
+ rtc_check();
+}
+
+/* ------------------------------------------------------------ save states */
+int gb_state_chunks(rg_chunk_t *out)
+{
+ int n = 0;
+ out[n++] = (rg_chunk_t){&cpu, sizeof cpu};
+ out[n++] = (rg_chunk_t){&hw, sizeof hw};
+ out[n++] = (rg_chunk_t){&mbc, offsetof(struct mbc, rmap)};
+ out[n++] = (rg_chunk_t){&rtc, sizeof rtc};
+ out[n++] = (rg_chunk_t){sound_regs, sizeof sound_regs};
+ out[n++] = (rg_chunk_t){ram.hi, sizeof ram.hi};
+ out[n++] = (rg_chunk_t){LCD_STATE_AT(lcd), LCD_STATE_SIZE};
+ out[n++] = (rg_chunk_t){ram.ibank, 4096 * (hw.cgb ? 8 : 2)};
+ out[n++] = (rg_chunk_t){lcd.vbank[0], 8192 * (hw.cgb ? 2 : 1)};
+ if (ram.sbank) out[n++] = (rg_chunk_t){ram.sbank, 8192 * ram_banks};
+ return n;
+}
+
+/* whatever a state held, a machine this cartridge can be */
+void gb_state_loaded(void)
+{
+ /* (the registers are 16 bits: the words above them stay clear) */
+ union reg *regs[6] = {&cpu.pc, &cpu.sp, &cpu.bc, &cpu.de, &cpu.hl, &cpu.af};
+ for (int i = 0; i < 6; i++) regs[i]->w[HI] = 0;
+ cpu.af.b[LO][LO] &= 0xF0; /* (F's low bits are always 0) */
+ hw.cgb = (rom.bank[0][0x143] & 0x80) != 0;
+ hw.gba = 0;
+ hw.pad = 0;
+ mbc.type = rom_type;
+ mbc.romsize = rom_banks;
+ mbc.ramsize = ram_banks;
+ mbc.batt = batt_table[rom.bank[0][0x147]];
+ cpu.speed &= hw.cgb ? 1 : 0;
+ cpu.ime &= 1;
+ cpu.ima &= 1;
+ if (cpu.lcdc < -1000 || cpu.lcdc > 1000) cpu.lcdc = 40;
+ cpu.div &= 0xFF;
+ cpu.tim &= 0x1FF;
+ rtc.batt = has_rtc;
+ rtc_check();
+ lcd.wline &= 0xFF;
+ lcd.wy_hit &= 1;
+ if (!(R_LCDC & 0x80)) R_LY = 0; /* (the LCD off holds line 0) */
+ mem_updatemap();
+ pal_dirty();
+ ram.sram_dirty = 1;
+}
diff --git a/games/retrogo/src/gb/gb.h b/games/retrogo/src/gb/gb.h
new file mode 100644
index 00000000..ae7771c8
--- /dev/null
+++ b/games/retrogo/src/gb/gb.h
@@ -0,0 +1,41 @@
+/* The Game Boy and Game Boy Color emulator (gnuboy), as Retro-Go's screens drive it. */
+#ifndef GB_H
+#define GB_H
+#include "../rg.h"
+
+#define GB_WIDTH 160
+#define GB_HEIGHT 144
+
+/* the DMG palettes the Options offer, as Retro-Go names them */
+enum { GB_PAL_DMG, GB_PAL_POCKET, GB_PAL_LIGHT, GB_PAL_GBC, GB_PAL_SGB, GB_PAL_COUNT };
+
+/* Loads a ROM read in place (it stays where it is); RG_OK or an RG_ERR_ code. */
+int gb_load(const uint8_t *data, uint32_t size);
+void gb_reset(bool hard);
+void gb_run_frame(bool draw);
+void gb_set_pad(int rg_pad);
+bool gb_is_cgb(void);
+void gb_set_palette(int pal);
+
+/* the cartridge's battery RAM (and its clock): NULL when it has no battery */
+uint8_t *gb_sram(uint32_t *size);
+bool gb_sram_dirty(void);
+void gb_sram_saved(void);
+bool gb_has_rtc(void);
+/* the clock's state, kept with the battery RAM */
+void *gb_rtc_state(uint32_t *size);
+void gb_rtc_loaded(void);
+void gb_get_time(int *d, int *h, int *m, int *s);
+void gb_set_time(int d, int h, int m, int s);
+
+/* save states: the parts of the machine, and putting it back together after they were read */
+int gb_state_chunks(rg_chunk_t *out);
+void gb_state_loaded(void);
+
+/* (for the core) the sound registers, kept but not played */
+unsigned char gb_sound_read(unsigned char r);
+void gb_sound_write(unsigned char r, unsigned char b);
+extern int gb_draw; /* this frame is drawn */
+/* the last frame drawn, line by line through rg_line again (under the menus) */
+void gb_redraw(void);
+#endif
diff --git a/games/retrogo/src/gb/hw.c b/games/retrogo/src/gb/hw.c
new file mode 100644
index 00000000..ba80c988
--- /dev/null
+++ b/games/retrogo/src/gb/hw.c
@@ -0,0 +1,184 @@
+/* From gnuboy 1.0.3 (rofl0r's tree) by Laguna and Gilgamesh and gnuboy's contributors,
+ * GPL-2.0-or-later (see COPYING in this folder); changed for Retro-Go on NumPlay. */
+#include <string.h>
+
+
+#include "defs.h"
+#include "cpu.h"
+#include "hw.h"
+#include "regs.h"
+#include "lcd.h"
+#include "mem.h"
+#include "fastmem.h"
+
+
+struct hw hw;
+
+
+
+/*
+ * hw_interrupt changes the virtual interrupt lines included in the
+ * specified mask to the values the corresponding bits in i take, and
+ * in doing so, raises the appropriate bit of R_IF for any interrupt
+ * lines that transition from low to high.
+ */
+
+void hw_interrupt(byte i, byte mask)
+{
+ byte oldif = R_IF;
+ i &= 0x1F & mask;
+ R_IF |= i & (hw.ilines ^ i);
+
+ /* FIXME - is this correct? not sure the docs understand... */
+ if (R_IF & (R_IF ^ oldif) & R_IE) cpu.halt = 0;
+ /* if ((i & (hw.ilines ^ i) & R_IE) && cpu.ime) cpu.halt = 0; */
+ /* if ((i & R_IE) && cpu.ime) cpu.halt = 0; */
+
+ hw.ilines &= ~mask;
+ hw.ilines |= i;
+}
+
+
+/*
+ * hw_dma performs plain old memory-to-oam dma, the original dmg
+ * dma. Although on the hardware it takes a good deal of time, the cpu
+ * continues running during this mode of dma, so no special tricks to
+ * stall the cpu are necessary.
+ */
+
+void hw_dma(byte b)
+{
+ int i;
+ addr a;
+
+ a = ((addr)b) << 8;
+ for (i = 0; i < 160; i++, a++)
+ lcd.oam.mem[i] = readb(a);
+}
+
+
+
+void hw_hdma_cmd(byte c)
+{
+ int cnt;
+ addr sa;
+ int da;
+
+ /* Begin or cancel HDMA */
+ if ((hw.hdma|c) & 0x80)
+ {
+ hw.hdma = c;
+ R_HDMA5 = c & 0x7f;
+ return;
+ }
+
+ /* Perform GDMA */
+ sa = ((addr)R_HDMA1 << 8) | (R_HDMA2&0xf0);
+ da = 0x8000 | ((int)(R_HDMA3&0x1f) << 8) | (R_HDMA4&0xf0);
+ cnt = ((int)c)+1;
+ /* FIXME - this should use cpu time! */
+ /*cpu_timers(102 * cnt);*/
+ cnt <<= 4;
+ while (cnt--)
+ writeb(da++, readb(sa++));
+ R_HDMA1 = sa >> 8;
+ R_HDMA2 = sa & 0xF0;
+ R_HDMA3 = 0x1F & (da >> 8);
+ R_HDMA4 = da & 0xF0;
+ R_HDMA5 = 0xFF;
+}
+
+
+void hw_hdma()
+{
+ int cnt;
+ addr sa;
+ int da;
+
+ sa = ((addr)R_HDMA1 << 8) | (R_HDMA2&0xf0);
+ da = 0x8000 | ((int)(R_HDMA3&0x1f) << 8) | (R_HDMA4&0xf0);
+ cnt = 16;
+ while (cnt--)
+ writeb(da++, readb(sa++));
+ R_HDMA1 = sa >> 8;
+ R_HDMA2 = sa & 0xF0;
+ R_HDMA3 = 0x1F & (da >> 8);
+ R_HDMA4 = da & 0xF0;
+ R_HDMA5--;
+ hw.hdma--;
+}
+
+
+/*
+ * pad_refresh updates the P1 register from the pad states, generating
+ * the appropriate interrupts (by quickly raising and lowering the
+ * interrupt line) if a transition has been made.
+ */
+
+void pad_refresh()
+{
+ byte oldp1;
+ oldp1 = R_P1;
+ R_P1 &= 0x30;
+ R_P1 |= 0xc0;
+ if (!(R_P1 & 0x10))
+ R_P1 |= (hw.pad & 0x0F);
+ if (!(R_P1 & 0x20))
+ R_P1 |= (hw.pad >> 4);
+ R_P1 ^= 0x0F;
+ if (oldp1 & ~R_P1 & 0x0F)
+ {
+ hw_interrupt(IF_PAD, IF_PAD);
+ hw_interrupt(0, IF_PAD);
+ }
+}
+
+
+/*
+ * These simple functions just update the state of a button on the
+ * pad.
+ */
+
+void pad_press(byte k)
+{
+ if (hw.pad & k)
+ return;
+ hw.pad |= k;
+ pad_refresh();
+}
+
+void pad_release(byte k)
+{
+ if (!(hw.pad & k))
+ return;
+ hw.pad &= ~k;
+ pad_refresh();
+}
+
+void pad_set(byte k, int st)
+{
+ st ? pad_press(k) : pad_release(k);
+}
+
+void hw_reset()
+{
+ hw.ilines = hw.pad = 0;
+
+ memset(ram.hi, 0, sizeof ram.hi);
+
+ R_P1 = 0xFF;
+ R_LCDC = 0x91;
+ R_BGP = 0xFC;
+ R_OBP0 = 0xFF;
+ R_OBP1 = 0xFF;
+ R_SVBK = 0x01;
+ R_HDMA5 = 0xFF;
+ R_VBK = 0xFE;
+}
+
+
+
+
+
+
+
diff --git a/games/retrogo/src/gb/hw.h b/games/retrogo/src/gb/hw.h
new file mode 100644
index 00000000..5987d635
--- /dev/null
+++ b/games/retrogo/src/gb/hw.h
@@ -0,0 +1,46 @@
+/* From gnuboy 1.0.3 (rofl0r's tree) by Laguna and Gilgamesh and gnuboy's contributors,
+ * GPL-2.0-or-later (see COPYING in this folder); changed for Retro-Go on NumPlay. */
+#ifndef __HW_H__
+#define __HW_H__
+
+
+#include "defs.h"
+
+
+#define PAD_RIGHT 0x01
+#define PAD_LEFT 0x02
+#define PAD_UP 0x04
+#define PAD_DOWN 0x08
+#define PAD_A 0x10
+#define PAD_B 0x20
+#define PAD_SELECT 0x40
+#define PAD_START 0x80
+
+#define IF_VBLANK 0x01
+#define IF_STAT 0x02
+#define IF_TIMER 0x04
+#define IF_SERIAL 0x08
+#define IF_PAD 0x10
+
+struct hw
+{
+ byte ilines;
+ byte pad;
+ int cgb, gba;
+ int hdma;
+};
+
+
+extern struct hw hw;
+
+void hw_interrupt(byte i, byte mask);
+void hw_dma(byte b);
+void hw_hdma();
+void hw_hdma_cmd(byte c);
+void hw_reset();
+void pad_refresh();
+void pad_set(byte k, int st);
+
+#endif
+
+
diff --git a/games/retrogo/src/gb/lcd.c b/games/retrogo/src/gb/lcd.c
new file mode 100644
index 00000000..ddf6ecc5
--- /dev/null
+++ b/games/retrogo/src/gb/lcd.c
@@ -0,0 +1,249 @@
+/* The Game Boy's picture, one line at a time, as the PPU builds it: the background and the
+ * window from the tile maps, then the sprites, 10 a line at most, sorted the DMG's way (lower X
+ * first) or the CGB's (OAM order), each pixel resolved against the background's priority. Lines
+ * are handed to Retro-Go's screen in RGB565 as soon as they are drawn.
+ *
+ * Written for Retro-Go on NumPlay in place of gnuboy's lcd.c, whose 256 KB cache of decoded
+ * tiles doesn't fit the calculator: tiles are decoded as they are drawn. GPL-3.0-or-later. */
+#include <stddef.h>
+#include <string.h>
+#include "defs.h"
+#include "regs.h"
+#include "hw.h"
+#include "mem.h"
+#include "lcd.h"
+#include "gb.h"
+
+struct lcd lcd;
+int gb_draw = 1;
+
+static un16 pal565[64]; /* the 8 BG palettes' colours (4 each), then the 8 OBJ palettes' */
+static un16 line[160];
+
+/* the DMG palettes: for the background, then the two sprite palettes, lightest first */
+static const un32 dmg_colors[GB_PAL_COUNT][3][4] = {
+ {{0x9BBC0F, 0x8BAC0F, 0x306230, 0x0F380F}, {0x9BBC0F, 0x8BAC0F, 0x306230, 0x0F380F},
+ {0x9BBC0F, 0x8BAC0F, 0x306230, 0x0F380F}}, /* DMG */
+ {{0xC4CFA1, 0x8B956D, 0x4D533C, 0x1F1F1F}, {0xC4CFA1, 0x8B956D, 0x4D533C, 0x1F1F1F},
+ {0xC4CFA1, 0x8B956D, 0x4D533C, 0x1F1F1F}}, /* Pocket */
+ {{0x6CF1C3, 0x00B581, 0x008D61, 0x004F3B}, {0x6CF1C3, 0x00B581, 0x008D61, 0x004F3B},
+ {0x6CF1C3, 0x00B581, 0x008D61, 0x004F3B}}, /* Light */
+ {{0xFFFFFF, 0x7BFF31, 0x0063C5, 0x000000}, {0xFFFFFF, 0xFF8484, 0x943A3A, 0x000000},
+ {0xFFFFFF, 0xFF8484, 0x943A3A, 0x000000}}, /* GBC, its colours for a black and white game */
+ {{0xF7E7C6, 0xD68E49, 0xA63725, 0x331E50}, {0xF7E7C6, 0xD68E49, 0xA63725, 0x331E50},
+ {0xF7E7C6, 0xD68E49, 0xA63725, 0x331E50}}, /* SGB */
+};
+static int dmg_palette;
+
+static un16 rgb565(un32 c)
+{
+ return (un16)(((c >> 8) & 0xF800) | ((c >> 5) & 0x07E0) | ((c >> 3) & 0x001F));
+}
+
+void gb_set_palette(int p)
+{
+ dmg_palette = p >= 0 && p < GB_PAL_COUNT ? p : 0;
+ pal_dirty();
+}
+
+/* the DMG's three palette registers into colours */
+void pal_dmg_dirty()
+{
+ if (hw.cgb) return;
+ const un32 (*c)[4] = dmg_colors[dmg_palette];
+ for (int i = 0; i < 4; i++)
+ {
+ pal565[i] = rgb565(c[0][(R_BGP >> (2 * i)) & 3]);
+ pal565[32 + i] = rgb565(c[1][(R_OBP0 >> (2 * i)) & 3]);
+ pal565[36 + i] = rgb565(c[2][(R_OBP1 >> (2 * i)) & 3]);
+ }
+}
+
+/* one CGB colour: 15 bits, red lowest */
+static void updatepalette(int i)
+{
+ int c = (lcd.pal[i << 1] | lcd.pal[(i << 1) | 1] << 8) & 0x7FFF;
+ int r = c & 31, g = (c >> 5) & 31, b = (c >> 10) & 31;
+ pal565[i] = (un16)(r << 11 | (g << 1 | g >> 4) << 5 | b);
+}
+
+void pal_write(int i, byte b)
+{
+ i &= 127;
+ if (lcd.pal[i] == b) return;
+ lcd.pal[i] = b;
+ if (hw.cgb) updatepalette(i >> 1);
+}
+
+void pal_dirty()
+{
+ if (hw.cgb)
+ for (int i = 0; i < 64; i++) updatepalette(i);
+ else
+ pal_dmg_dirty();
+}
+
+void lcd_begin()
+{
+ lcd.wline = 0;
+ lcd.wy_hit = 0;
+}
+
+void lcd_reset()
+{
+ memset(LCD_STATE_AT(lcd), 0, LCD_STATE_SIZE);
+ for (int i = 0; i < 2; i++)
+ if (lcd.vbank[i]) memset(lcd.vbank[i], 0, 8192);
+ lcd_begin();
+ pal_dirty();
+}
+
+/* every byte with its bits in the other order */
+#define R2(n) n, n + 2 * 64, n + 1 * 64, n + 3 * 64
+#define R4(n) R2(n), R2(n + 2 * 16), R2(n + 1 * 16), R2(n + 3 * 16)
+#define R6(n) R4(n), R4(n + 2 * 4), R4(n + 1 * 4), R4(n + 3 * 4)
+static const byte reversed[256] = {R6(0), R6(2), R6(1), R6(3)};
+
+/* n pixels of a tile map, from its pixel (sx, sy): colour (bits 0-1), CGB palette (2-4) and the
+ CGB "BG over sprites" flag (bit 7) */
+static void tiles(byte *out, int n, int map, int sx, int sy)
+{
+ const byte *v0 = lcd.vbank[0], *v1 = lcd.vbank[1];
+ const byte *row = v0 + map + ((sy >> 3) & 31) * 32, *attrs = v1 + map + ((sy >> 3) & 31) * 32;
+ int signed_ids = !(R_LCDC & LCDC_BIT_TILE_SEL), ty = sy & 7, tx = (sx >> 3) & 31, skip = sx & 7;
+ while (n > 0)
+ {
+ int t = row[tx], attr = hw.cgb ? attrs[tx] : 0;
+ int at = (signed_ids ? 0x1000 + (n8)t * 16 : t * 16) + ((attr & 0x40) ? 7 - ty : ty) * 2;
+ const byte *data = (attr & 0x08) ? v1 : v0;
+ int lo = data[at], hi = data[at + 1], extra = ((attr & 7) << 2) | (attr & 0x80);
+ if (attr & 0x20) /* flipped: the lowest bit is the leftmost pixel */
+ lo = reversed[lo], hi = reversed[hi];
+ for (int i = skip; i < 8 && n > 0; i++, n--)
+ *out++ = (byte)((((hi << i) >> 6) & 2) | (((lo << i) >> 7) & 1) | extra);
+ skip = 0;
+ tx = (tx + 1) & 31;
+ }
+}
+
+/* what a line was drawn with: kept for each line of the last frame drawn, so that the picture can
+ be drawn again under Retro-Go's menus (gb_redraw) */
+struct line_regs
+{
+ byte lcdc, scx, scy, wx, bgp, obp0, obp1, win, wl, drawn;
+};
+static struct line_regs snap[144];
+
+static void draw_line(int L, const struct line_regs *r)
+{
+ int lcdc = r->lcdc, wx = r->wx - 7;
+ un16 dmg[12]; /* (the DMG's palettes as they were on this line) */
+ const un16 *bgpal = pal565, *objpal = pal565 + 32;
+ if (!hw.cgb)
+ {
+ const un32 (*c)[4] = dmg_colors[dmg_palette];
+ for (int i = 0; i < 4; i++)
+ {
+ dmg[i] = rgb565(c[0][(r->bgp >> (2 * i)) & 3]);
+ dmg[4 + i] = rgb565(c[1][(r->obp0 >> (2 * i)) & 3]);
+ dmg[8 + i] = rgb565(c[2][(r->obp1 >> (2 * i)) & 3]);
+ }
+ bgpal = dmg, objpal = dmg + 4;
+ }
+
+ byte bg[160];
+ if (!hw.cgb && !(lcdc & LCDC_BIT_BG_EN))
+ {
+ memset(bg, 0, sizeof bg);
+ un16 white = rgb565(dmg_colors[dmg_palette][0][0]);
+ for (int x = 0; x < 160; x++) line[x] = white;
+ }
+ else
+ {
+ int split = r->win ? (wx < 0 ? 0 : wx) : 160;
+ if (split > 0)
+ tiles(bg, split, (lcdc & LCDC_BIT_BG_MAP) ? 0x1C00 : 0x1800, r->scx, (r->scy + L) & 255);
+ if (split < 160)
+ tiles(bg + split, 160 - split, (lcdc & LCDC_BIT_WIN_MAP) ? 0x1C00 : 0x1800, split - wx, r->wl);
+ for (int x = 0; x < 160; x++) line[x] = bgpal[bg[x] & 0x1F];
+ }
+
+ if (lcdc & LCDC_BIT_OBJ_EN)
+ {
+ int h = (lcdc & LCDC_BIT_OBJ_SIZE) ? 16 : 8, ns = 0;
+ byte sel[10], taken[160];
+ /* the first 10 sprites in OAM on this line */
+ for (int i = 0; i < 40 && ns < 10; i++)
+ {
+ int y = lcd.oam.obj[i].y - 16;
+ if (L >= y && L < y + h) sel[ns++] = (byte)i;
+ }
+ /* the DMG draws the one further left on top, then the first in OAM */
+ if (!hw.cgb)
+ for (int i = 1; i < ns; i++)
+ for (int j = i; j > 0 && lcd.oam.obj[sel[j]].x < lcd.oam.obj[sel[j - 1]].x; j--)
+ {
+ byte t = sel[j];
+ sel[j] = sel[j - 1];
+ sel[j - 1] = t;
+ }
+ memset(taken, 0, sizeof taken);
+ for (int k = 0; k < ns; k++)
+ {
+ const struct obj *o = &lcd.oam.obj[sel[k]];
+ int f = o->flags, sx = o->x - 8, row = L - (o->y - 16), t = o->pat;
+ if (f & 0x40) row = h - 1 - row;
+ if (h == 16) t &= 0xFE;
+ const byte *data = (hw.cgb && (f & 0x08)) ? lcd.vbank[1] : lcd.vbank[0];
+ int lo = data[t * 16 + row * 2], hi = data[t * 16 + row * 2 + 1];
+ int base = hw.cgb ? (f & 7) * 4 : (f & 0x10) ? 4 : 0;
+ for (int i = 0; i < 8; i++)
+ {
+ int x = sx + i, b = (f & 0x20) ? i : 7 - i;
+ if (x < 0 || x >= 160) continue;
+ int c = ((hi >> b) & 1) << 1 | ((lo >> b) & 1);
+ if (!c || taken[x]) continue;
+ taken[x] = 1;
+ int under = bg[x];
+ if ((under & 3) && ((hw.cgb && (lcdc & LCDC_BIT_BG_EN) && (under & 0x80)) ||
+ ((f & 0x80) && (!hw.cgb || (lcdc & LCDC_BIT_BG_EN)))))
+ continue; /* behind the background */
+ line[x] = objpal[base + c];
+ }
+ }
+ }
+ rg_line(L, line);
+}
+
+void lcd_refreshline()
+{
+ int L = R_LY, lcdc = R_LCDC;
+ if (!(lcdc & LCDC_BIT_LCD_EN) || L >= 144) return;
+
+ /* the window: once LY has met WY in a frame, it shows on every line it is on for, and
+ counts those lines itself */
+ if (L == R_WY) lcd.wy_hit = 1;
+ int win = (lcdc & LCDC_BIT_WIN_EN) && lcd.wy_hit && R_WX <= 166 && (hw.cgb || (lcdc & LCDC_BIT_BG_EN));
+ struct line_regs r = {(byte)lcdc, R_SCX, R_SCY, R_WX, R_BGP, R_OBP0, R_OBP1, (byte)win, (byte)lcd.wline, 1};
+ if (win) lcd.wline++;
+ if (!gb_draw) return;
+ if (L == 0) memset(snap, 0, sizeof snap);
+ snap[L] = r;
+ draw_line(L, &r);
+}
+
+/* the last frame drawn, again (lines the LCD didn't draw are white) */
+void gb_redraw(void)
+{
+ for (int L = 0; L < 144; L++)
+ {
+ if (snap[L].drawn)
+ draw_line(L, &snap[L]);
+ else
+ {
+ un16 white = hw.cgb ? 0xFFFF : rgb565(dmg_colors[dmg_palette][0][0]);
+ for (int x = 0; x < 160; x++) line[x] = white;
+ rg_line(L, line);
+ }
+ }
+}
diff --git a/games/retrogo/src/gb/lcd.h b/games/retrogo/src/gb/lcd.h
new file mode 100644
index 00000000..f87c3e3c
--- /dev/null
+++ b/games/retrogo/src/gb/lcd.h
@@ -0,0 +1,50 @@
+/* The Game Boy's picture: VRAM, OAM, palettes, and the line renderer (lcd.c). */
+#ifndef __LCD_H__
+#define __LCD_H__
+
+#include "defs.h"
+
+struct obj
+{
+ byte y;
+ byte x;
+ byte pat;
+ byte flags;
+};
+
+struct lcd
+{
+ byte *vbank[2]; /* 8 KB each; the DMG has one, both point to it */
+ /* (from here on, what a save state keeps) */
+ union
+ {
+ byte mem[256];
+ struct obj obj[40];
+ } oam;
+ byte pal[128]; /* CGB palette RAM: 8 BG palettes, then 8 OBJ ones, 4 colours of 2 bytes */
+ int wline; /* the window's own line counter */
+ int wy_hit; /* WY matched LY in this frame: the window may show */
+};
+#define LCD_STATE_AT(l) ((byte *)&(l).oam)
+#define LCD_STATE_SIZE (sizeof(struct lcd) - offsetof(struct lcd, oam))
+
+extern struct lcd lcd;
+
+void lcd_begin();
+void lcd_refreshline();
+void pal_write(int i, byte b);
+void pal_dmg_dirty();
+void pal_dirty();
+void lcd_reset();
+
+#define LCDC_BIT_BG_EN (1<<0) /* BG display off or on - CGB: always on */
+#define LCDC_BIT_OBJ_EN (1<<1) /* OBJs off or on */
+#define LCDC_BIT_OBJ_SIZE (1<<2) /* OBJ size: 0:8x8 1:8x16 */
+#define LCDC_BIT_BG_MAP (1<<3) /* BG code area 0:9800-9bff, 1:9c00-9fff */
+#define LCDC_BIT_TILE_SEL (1<<4) /* BG char data 0:8800-97ff, 1:8000-8fff */
+#define LCDC_BIT_WIN_EN (1<<5) /* WIN off or on */
+#define LCDC_BIT_WIN_MAP (1<<6) /* WIN code area 0:9800-9bff, 1:9c00-9fff */
+#define LCDC_BIT_LCD_EN (1<<7) /* LCD controller off or on */
+
+
+#endif
diff --git a/games/retrogo/src/gb/lcdc.c b/games/retrogo/src/gb/lcdc.c
new file mode 100644
index 00000000..1e7c01f7
--- /dev/null
+++ b/games/retrogo/src/gb/lcdc.c
@@ -0,0 +1,179 @@
+/* From gnuboy 1.0.3 (rofl0r's tree) by Laguna and Gilgamesh and gnuboy's contributors,
+ * GPL-2.0-or-later (see COPYING in this folder); changed for Retro-Go on NumPlay. */
+#include <stdlib.h>
+
+#include "defs.h"
+#include "hw.h"
+#include "cpu.h"
+#include "regs.h"
+#include "lcd.h"
+
+#define C (cpu.lcdc)
+
+
+/*
+ * stat_trigger updates the STAT interrupt line to reflect whether any
+ * of the conditions set to be tested (by bits 3-6 of R_STAT) are met.
+ * This function should be called whenever any of the following occur:
+ * 1) LY or LYC changes.
+ * 2) A state transition affects the low 2 bits of R_STAT (see below).
+ * 3) The program writes to the upper bits of R_STAT.
+ * stat_trigger also updates bit 2 of R_STAT to reflect whether LY=LYC.
+ */
+
+void stat_trigger()
+{
+ static const int condbits[4] = { 0x08, 0x10, 0x20, 0x00 };
+ int flag = 0;
+
+ if (R_LY == R_LYC)
+ {
+ R_STAT |= 0x04;
+ if (R_STAT & 0x40) flag = IF_STAT;
+ }
+ else R_STAT &= ~0x04;
+
+ if (R_STAT & condbits[R_STAT&3]) flag = IF_STAT;
+
+ if (!(R_LCDC & 0x80)) flag = 0;
+
+ hw_interrupt(flag, IF_STAT);
+}
+
+void stat_write(byte b)
+{
+ R_STAT = (R_STAT & 0x07) | (b & 0x78);
+ if (!hw.cgb && !(R_STAT & 2)) /* DMG STAT write bug => interrupt */
+ hw_interrupt(IF_STAT, IF_STAT);
+ stat_trigger();
+}
+
+
+/*
+ * stat_change is called when a transition results in a change to the
+ * LCD STAT condition (the low 2 bits of R_STAT). It raises or lowers
+ * the VBLANK interrupt line appropriately and calls stat_trigger to
+ * update the STAT interrupt line.
+ */
+
+static void stat_change(int stat)
+{
+ stat &= 3;
+ R_STAT = (R_STAT & 0x7C) | stat;
+
+ if (stat != 1) hw_interrupt(0, IF_VBLANK);
+ /* hw_interrupt((stat == 1) ? IF_VBLANK : 0, IF_VBLANK); */
+ stat_trigger();
+}
+
+
+void lcdc_change(byte b)
+{
+ byte old = R_LCDC;
+ R_LCDC = b;
+ if ((R_LCDC ^ old) & 0x80) /* lcd on/off change */
+ {
+ R_LY = 0;
+ stat_change(2);
+ C = 40;
+ lcd_begin();
+ }
+}
+
+
+void lcdc_trans()
+{
+ if (!(R_LCDC & 0x80))
+ {
+ while (C <= 0)
+ {
+ switch ((byte)(R_STAT & 3))
+ {
+ case 0:
+ case 1:
+ stat_change(2);
+ C += 40;
+ break;
+ case 2:
+ stat_change(3);
+ C += 86;
+ break;
+ case 3:
+ stat_change(0);
+ if (hw.hdma & 0x80)
+ hw_hdma();
+ else
+ C += 102;
+ break;
+ }
+ return;
+ }
+ }
+ while (C <= 0)
+ {
+ switch ((byte)(R_STAT & 3))
+ {
+ case 1:
+ if (!(hw.ilines & IF_VBLANK))
+ {
+ C += 218;
+ hw_interrupt(IF_VBLANK, IF_VBLANK);
+ break;
+ }
+ if (R_LY == 0)
+ {
+ lcd_begin();
+ stat_change(2);
+ C += 40;
+ break;
+ }
+ else if (R_LY < 152)
+ C += 228;
+ else if (R_LY == 152)
+ C += 28;
+ else
+ {
+ R_LY = -1;
+ C += 200;
+ }
+ R_LY++;
+ stat_trigger();
+ break;
+ case 2:
+ lcd_refreshline();
+ stat_change(3);
+ C += 86;
+ break;
+ case 3:
+ stat_change(0);
+ if (hw.hdma & 0x80)
+ hw_hdma();
+ /* FIXME -- how much of the hblank does hdma use?? */
+ /* else */
+ C += 102;
+ break;
+ case 0:
+ if (++R_LY >= 144)
+ {
+ if (cpu.halt)
+ {
+ hw_interrupt(IF_VBLANK, IF_VBLANK);
+ C += 228;
+ }
+ else C += 10;
+ stat_change(1);
+ break;
+ }
+ stat_change(2);
+ C += 40;
+ break;
+ }
+ }
+}
+
+
+
+
+
+
+
diff --git a/games/retrogo/src/gb/lcdc.h b/games/retrogo/src/gb/lcdc.h
new file mode 100644
index 00000000..31793fb4
--- /dev/null
+++ b/games/retrogo/src/gb/lcdc.h
@@ -0,0 +1,13 @@
+/* From gnuboy 1.0.3 (rofl0r's tree) by Laguna and Gilgamesh and gnuboy's contributors,
+ * GPL-2.0-or-later (see COPYING in this folder); changed for Retro-Go on NumPlay. */
+#ifndef LCDC_H
+#define LCDC_H
+
+void lcdc_change(byte b);
+void lcdc_trans();
+void stat_write(byte b);
+void stat_trigger();
+
+#endif
+
+
diff --git a/games/retrogo/src/gb/mem.c b/games/retrogo/src/gb/mem.c
new file mode 100644
index 00000000..819e6580
--- /dev/null
+++ b/games/retrogo/src/gb/mem.c
@@ -0,0 +1,571 @@
+/* gnuboy's memory map and bank controllers. From gnuboy 1.0.3 (rofl0r's tree) by Laguna and
+ * Gilgamesh, GPL-2.0-or-later (see COPYING). Changed for Retro-Go on NumPlay: the ROM is read in
+ * place, the RAM comes from Retro-Go's memory block, every bank number stays inside what was
+ * given (a game, or a damaged save state, can't reach past it), and the cartridge's RAM is
+ * written through mem_write so its battery save knows when it changed. */
+#include "defs.h"
+#include "hw.h"
+#include "regs.h"
+#include "mem.h"
+#include "rtc.h"
+#include "lcd.h"
+#include "lcdc.h"
+#include "gb.h"
+
+struct mbc mbc;
+struct rom rom;
+struct ram ram;
+
+/*
+ * In order to make reads and writes efficient, we keep tables
+ * (indexed by the high nibble of the address) specifying which
+ * regions can be read/written without a function call. For such
+ * ranges, the pointer in the map table points to the base of the
+ * region in host system memory. For ranges that require special
+ * processing, the pointer is NULL.
+ *
+ * mem_updatemap is called whenever bank changes or other operations
+ * make the old maps potentially invalid.
+ */
+
+#define WBANK() (hw.cgb && (R_SVBK & 7) ? (R_SVBK & 7) : 1)
+#define VBANK() (hw.cgb ? (R_VBK & 1) : 0)
+#define SRAM_ON() (mbc.enableram && ram.sbank && !(rtc.sel & 8))
+
+void mem_updatemap()
+{
+ int n;
+ byte **map;
+
+ mbc.rombank &= (mbc.romsize - 1);
+ mbc.rambank &= (mbc.ramsize - 1);
+
+ map = mbc.rmap;
+ map[0x0] = (byte *)rom.bank[0];
+ map[0x1] = (byte *)rom.bank[0];
+ map[0x2] = (byte *)rom.bank[0];
+ map[0x3] = (byte *)rom.bank[0];
+ map[0x4] = (byte *)rom.bank[mbc.rombank] - 0x4000;
+ map[0x5] = (byte *)rom.bank[mbc.rombank] - 0x4000;
+ map[0x6] = (byte *)rom.bank[mbc.rombank] - 0x4000;
+ map[0x7] = (byte *)rom.bank[mbc.rombank] - 0x4000;
+ map[0x8] = lcd.vbank[VBANK()] - 0x8000;
+ map[0x9] = lcd.vbank[VBANK()] - 0x8000;
+ if (SRAM_ON() && mbc.type != MBC_MBC2)
+ {
+ map[0xA] = (byte *)ram.sbank[mbc.rambank] - 0xA000;
+ map[0xB] = (byte *)ram.sbank[mbc.rambank] - 0xA000;
+ }
+ else map[0xA] = map[0xB] = NULL;
+ map[0xC] = (byte *)ram.ibank[0] - 0xC000;
+ n = WBANK();
+ map[0xD] = (byte *)ram.ibank[n] - 0xD000;
+ map[0xE] = (byte *)ram.ibank[0] - 0xE000;
+ map[0xF] = NULL;
+
+ map = mbc.wmap;
+ map[0x0] = map[0x1] = map[0x2] = map[0x3] = NULL;
+ map[0x4] = map[0x5] = map[0x6] = map[0x7] = NULL;
+ map[0x8] = map[0x9] = NULL;
+ map[0xA] = map[0xB] = NULL;
+ map[0xC] = (byte *)ram.ibank[0] - 0xC000;
+ map[0xD] = (byte *)ram.ibank[n] - 0xD000;
+ map[0xE] = (byte *)ram.ibank[0] - 0xE000;
+ map[0xF] = NULL;
+}
+
+
+/*
+ * ioreg_write handles output to io registers in the FF00-FF7F,FFFF
+ * range. It takes the register number (low byte of the address) and a
+ * byte value to be written.
+ */
+
+void ioreg_write(byte r, byte b)
+{
+ if (!hw.cgb)
+ {
+ switch (r)
+ {
+ case RI_VBK:
+ case RI_BCPS:
+ case RI_OCPS:
+ case RI_BCPD:
+ case RI_OCPD:
+ case RI_SVBK:
+ case RI_KEY1:
+ case RI_HDMA1:
+ case RI_HDMA2:
+ case RI_HDMA3:
+ case RI_HDMA4:
+ case RI_HDMA5:
+ return;
+ }
+ }
+
+ switch(r)
+ {
+ case RI_TIMA:
+ case RI_TMA:
+ case RI_TAC:
+ case RI_SCY:
+ case RI_SCX:
+ case RI_WY:
+ case RI_WX:
+ REG(r) = b;
+ break;
+ case RI_BGP:
+ case RI_OBP0:
+ case RI_OBP1:
+ if (REG(r) == b) break;
+ REG(r) = b;
+ pal_dmg_dirty();
+ break;
+ case RI_IF:
+ case RI_IE:
+ REG(r) = b & 0x1F;
+ break;
+ case RI_P1:
+ REG(r) = b;
+ pad_refresh();
+ break;
+ case RI_SC:
+ /* FIXME - this is a hack for stupid roms that probe serial */
+ if ((b & 0x81) == 0x81)
+ {
+ R_SB = 0xff;
+ hw_interrupt(IF_SERIAL, IF_SERIAL);
+ hw_interrupt(0, IF_SERIAL);
+ }
+ R_SC = b; /* & 0x7f; */
+ break;
+ case RI_SB:
+ REG(r) = b;
+ break;
+ case RI_DIV:
+ REG(r) = 0;
+ break;
+ case RI_LCDC:
+ lcdc_change(b);
+ break;
+ case RI_STAT:
+ stat_write(b);
+ break;
+ case RI_LYC:
+ REG(r) = b;
+ stat_trigger();
+ break;
+ case RI_VBK:
+ REG(r) = b | 0xFE;
+ mem_updatemap();
+ break;
+ case RI_BCPS:
+ R_BCPS = b & 0xBF;
+ R_BCPD = lcd.pal[b & 0x3F];
+ break;
+ case RI_OCPS:
+ R_OCPS = b & 0xBF;
+ R_OCPD = lcd.pal[64 + (b & 0x3F)];
+ break;
+ case RI_BCPD:
+ R_BCPD = b;
+ pal_write(R_BCPS & 0x3F, b);
+ if (R_BCPS & 0x80) R_BCPS = (R_BCPS+1) & 0xBF;
+ break;
+ case RI_OCPD:
+ R_OCPD = b;
+ pal_write(64 + (R_OCPS & 0x3F), b);
+ if (R_OCPS & 0x80) R_OCPS = (R_OCPS+1) & 0xBF;
+ break;
+ case RI_SVBK:
+ REG(r) = b & 0x07;
+ mem_updatemap();
+ break;
+ case RI_DMA:
+ hw_dma(b);
+ break;
+ case RI_KEY1:
+ REG(r) = (REG(r) & 0x80) | (b & 0x01);
+ break;
+ case RI_HDMA1:
+ REG(r) = b;
+ break;
+ case RI_HDMA2:
+ REG(r) = b & 0xF0;
+ break;
+ case RI_HDMA3:
+ REG(r) = b & 0x1F;
+ break;
+ case RI_HDMA4:
+ REG(r) = b & 0xF0;
+ break;
+ case RI_HDMA5:
+ hw_hdma_cmd(b);
+ break;
+ }
+ switch (r)
+ {
+ case RI_BGP:
+ case RI_OBP0:
+ case RI_OBP1:
+ /* printf("palette reg %02X write %02X at LY=%02X\n", r, b, R_LY); */
+ case RI_HDMA1:
+ case RI_HDMA2:
+ case RI_HDMA3:
+ case RI_HDMA4:
+ case RI_HDMA5:
+ /* printf("HDMA %d: %02X\n", r - RI_HDMA1 + 1, b); */
+ break;
+ }
+ /* printf("reg %02X => %02X (%02X)\n", r, REG(r), b); */
+}
+
+
+byte ioreg_read(byte r)
+{
+ switch(r)
+ {
+ case RI_SC:
+ r = R_SC;
+ R_SC &= 0x7f;
+ return r;
+ case RI_P1:
+ case RI_SB:
+ case RI_DIV:
+ case RI_TIMA:
+ case RI_TMA:
+ case RI_TAC:
+ case RI_LCDC:
+ case RI_STAT:
+ case RI_SCY:
+ case RI_SCX:
+ case RI_LY:
+ case RI_LYC:
+ case RI_BGP:
+ case RI_OBP0:
+ case RI_OBP1:
+ case RI_WY:
+ case RI_WX:
+ case RI_IE:
+ case RI_IF:
+ return REG(r);
+ case RI_VBK:
+ case RI_BCPS:
+ case RI_OCPS:
+ case RI_BCPD:
+ case RI_OCPD:
+ case RI_SVBK:
+ case RI_KEY1:
+ case RI_HDMA1:
+ case RI_HDMA2:
+ case RI_HDMA3:
+ case RI_HDMA4:
+ case RI_HDMA5:
+ if (hw.cgb) return REG(r);
+ default:
+ return 0xff;
+ }
+}
+
+
+
+/*
+ * Memory bank controllers typically intercept write attempts to
+ * 0000-7FFF, using the address and byte written as instructions to
+ * change rom or sram banks, control special hardware, etc.
+ *
+ * mbc_write takes an address (which should be in the proper range)
+ * and a byte value written to the address.
+ */
+
+void mbc_write(int a, byte b)
+{
+ byte ha = (a>>12);
+
+ /* printf("mbc %d: rom bank %02X -[%04X:%02X]-> ", mbc.type, mbc.rombank, a, b); */
+ switch (mbc.type)
+ {
+ case MBC_MBC1:
+ switch (ha & 0xE)
+ {
+ case 0x0:
+ mbc.enableram = ((b & 0x0F) == 0x0A);
+ break;
+ case 0x2:
+ if ((b & 0x1F) == 0) b = 0x01;
+ mbc.rombank = (mbc.rombank & 0x60) | (b & 0x1F);
+ break;
+ case 0x4:
+ if (mbc.model)
+ {
+ mbc.rambank = b & 0x03;
+ break;
+ }
+ mbc.rombank = (mbc.rombank & 0x1F) | ((int)(b&3)<<5);
+ break;
+ case 0x6:
+ mbc.model = b & 0x1;
+ break;
+ }
+ break;
+ case MBC_MBC2: /* is this at all right? */
+ if ((a & 0x0100) == 0x0000)
+ {
+ mbc.enableram = ((b & 0x0F) == 0x0A);
+ break;
+ }
+ if ((a & 0xE100) == 0x2100)
+ {
+ mbc.rombank = b & 0x0F;
+ break;
+ }
+ break;
+ case MBC_MBC3:
+ switch (ha & 0xE)
+ {
+ case 0x0:
+ mbc.enableram = ((b & 0x0F) == 0x0A);
+ break;
+ case 0x2:
+ if ((b & 0x7F) == 0) b = 0x01;
+ mbc.rombank = b & 0x7F;
+ break;
+ case 0x4:
+ rtc.sel = b & 0x0f;
+ mbc.rambank = b & 0x03;
+ break;
+ case 0x6:
+ rtc_latch(b);
+ break;
+ }
+ break;
+ case MBC_RUMBLE:
+ switch (ha & 0xF)
+ {
+ case 0x4:
+ case 0x5:
+ /* FIXME - save high bit as rumble state */
+ /* mask off high bit */
+ b &= 0x7;
+ break;
+ }
+ /* fall thru */
+ case MBC_MBC5:
+ switch (ha & 0xF)
+ {
+ case 0x0:
+ case 0x1:
+ mbc.enableram = ((b & 0x0F) == 0x0A);
+ break;
+ case 0x2:
+ if ((b & 0xFF) == 0) b = 0x01;
+ mbc.rombank = (mbc.rombank & 0x100) | (b & 0xFF);
+ break;
+ case 0x3:
+ mbc.rombank = (mbc.rombank & 0xFF) | ((int)(b&1)<<8);
+ break;
+ case 0x4:
+ case 0x5:
+ mbc.rambank = b & 0x0f;
+ break;
+ }
+ break;
+ case MBC_HUC1: /* FIXME - this is all guesswork -- is it right??? */
+ switch (ha & 0xE)
+ {
+ case 0x0:
+ mbc.enableram = ((b & 0x0F) == 0x0A);
+ break;
+ case 0x2:
+ if ((b & 0x1F) == 0) b = 0x01;
+ mbc.rombank = (mbc.rombank & 0x60) | (b & 0x1F);
+ break;
+ case 0x4:
+ if (mbc.model)
+ {
+ mbc.rambank = b & 0x03;
+ break;
+ }
+ mbc.rombank = (mbc.rombank & 0x1F) | ((int)(b&3)<<5);
+ break;
+ case 0x6:
+ mbc.model = b & 0x1;
+ break;
+ }
+ break;
+ case MBC_HUC3:
+ switch (ha & 0xE)
+ {
+ case 0x0:
+ mbc.enableram = ((b & 0x0F) == 0x0A);
+ break;
+ case 0x2:
+ b &= 0x7F;
+ mbc.rombank = b ? b : 1;
+ break;
+ case 0x4:
+ rtc.sel = b & 0x0f;
+ mbc.rambank = b & 0x03;
+ break;
+ case 0x6:
+ rtc_latch(b);
+ break;
+ }
+ break;
+ }
+ /* printf("%02X\n", mbc.rombank); */
+ mem_updatemap();
+}
+
+
+/*
+ * mem_write is the basic write function. Although it should only be
+ * called when the write map contains a NULL for the requested address
+ * region, it accepts writes to any address.
+ */
+
+void mem_write(int a, byte b)
+{
+ int n;
+ a &= 0xFFFF; /* (a word read or written at $FFFF ends at $0000) */
+ byte ha = (a>>12) & 0xE;
+
+ /* printf("write to 0x%04X: 0x%02X\n", a, b); */
+ switch (ha)
+ {
+ case 0x0:
+ case 0x2:
+ case 0x4:
+ case 0x6:
+ mbc_write(a, b);
+ break;
+ case 0x8:
+ lcd.vbank[VBANK()][a & 0x1FFF] = b;
+ break;
+ case 0xA:
+ if (!mbc.enableram) break;
+ if (rtc.sel&8)
+ {
+ if (mbc.type == MBC_MBC3) rtc_write(b);
+ break;
+ }
+ if (!ram.sbank) break;
+ if (mbc.type == MBC_MBC2) /* 512 half bytes, repeated */
+ {
+ a &= 0x1FF;
+ b |= 0xF0;
+ }
+ if (ram.sbank[mbc.rambank][a & 0x1FFF] != b)
+ {
+ ram.sbank[mbc.rambank][a & 0x1FFF] = b;
+ ram.sram_dirty = 1;
+ }
+ break;
+ case 0xC:
+ if ((a & 0xF000) == 0xC000)
+ {
+ ram.ibank[0][a & 0x0FFF] = b;
+ break;
+ }
+ n = WBANK();
+ ram.ibank[n][a & 0x0FFF] = b;
+ break;
+ case 0xE:
+ if (a < 0xFE00)
+ {
+ mem_write(a & 0xDFFF, b);
+ break;
+ }
+ if ((a & 0xFF00) == 0xFE00)
+ {
+ /* if (R_STAT & 0x02) break; */
+ if (a < 0xFEA0) lcd.oam.mem[a & 0xFF] = b;
+ break;
+ }
+ /* return writehi(a & 0xFF, b); */
+ if (a >= 0xFF10 && a <= 0xFF3F)
+ {
+ gb_sound_write(a & 0xFF, b);
+ break;
+ }
+ if ((a & 0xFF80) == 0xFF80 && a != 0xFFFF)
+ {
+ ram.hi[a & 0xFF] = b;
+ break;
+ }
+ ioreg_write(a & 0xFF, b);
+ }
+}
+
+
+/*
+ * mem_read is the basic read function...not useful for much anymore
+ * with the read map, but it's still necessary for the final messy
+ * region.
+ */
+
+byte mem_read(int a)
+{
+ int n;
+ a &= 0xFFFF;
+ byte ha = (a>>12) & 0xE;
+
+ /* printf("read %04x\n", a); */
+ switch (ha)
+ {
+ case 0x0:
+ case 0x2:
+ return rom.bank[0][a];
+ case 0x4:
+ case 0x6:
+ return rom.bank[mbc.rombank][a & 0x3FFF];
+ case 0x8:
+ return lcd.vbank[VBANK()][a & 0x1FFF];
+ case 0xA:
+ if (!mbc.enableram && mbc.type == MBC_HUC3)
+ return 0x01;
+ if (!mbc.enableram)
+ return 0xFF;
+ if (rtc.sel&8)
+ return mbc.type == MBC_MBC3 ? rtc.regs[rtc.sel&7] : 0xFF;
+ if (!ram.sbank)
+ return 0xFF;
+ if (mbc.type == MBC_MBC2)
+ return ram.sbank[0][a & 0x1FF] | 0xF0;
+ return ram.sbank[mbc.rambank][a & 0x1FFF];
+ case 0xC:
+ if ((a & 0xF000) == 0xC000)
+ return ram.ibank[0][a & 0x0FFF];
+ n = WBANK();
+ return ram.ibank[n][a & 0x0FFF];
+ case 0xE:
+ if (a < 0xFE00) return mem_read(a & 0xDFFF);
+ if ((a & 0xFF00) == 0xFE00)
+ {
+ /* if (R_STAT & 0x02) return 0xFF; */
+ if (a < 0xFEA0) return lcd.oam.mem[a & 0xFF];
+ return 0xFF;
+ }
+ /* return readhi(a & 0xFF); */
+ if (a == 0xFFFF) return REG(0xFF);
+ if (a >= 0xFF10 && a <= 0xFF3F)
+ return gb_sound_read(a & 0xFF);
+ if ((a & 0xFF80) == 0xFF80)
+ return ram.hi[a & 0xFF];
+ return ioreg_read(a & 0xFF);
+ }
+ return 0xff; /* not reached */
+}
+
+void mbc_reset()
+{
+ mbc.rombank = 1;
+ mbc.rambank = 0;
+ mbc.enableram = mbc.type == MBC_NONE; /* (a cartridge with RAM and no controller: always on) */
+ mem_updatemap();
+}
+
+
+
+
+
diff --git a/games/retrogo/src/gb/mem.h b/games/retrogo/src/gb/mem.h
new file mode 100644
index 00000000..0f100955
--- /dev/null
+++ b/games/retrogo/src/gb/mem.h
@@ -0,0 +1,79 @@
+#ifndef __MEM_H__
+#define __MEM_H__
+
+
+#include "defs.h"
+
+
+
+#define MBC_NONE 0
+#define MBC_MBC1 1
+#define MBC_MBC2 2
+#define MBC_MBC3 3
+#define MBC_MBC5 5
+#define MBC_RUMBLE 15
+#define MBC_HUC1 0xC1
+#define MBC_HUC3 0xC3
+
+struct mbc
+{
+ int type;
+ int model;
+ int rombank;
+ int rambank;
+ int romsize;
+ int ramsize;
+ int enableram;
+ int batt;
+ byte *rmap[0x10], *wmap[0x10];
+};
+
+/* The cartridge is read where it is (in the calculator's flash): bank[n] points at its n-th
+ 16 KB bank, read only; the banks a ROM file lacks repeat the ones it has. */
+#define ROM_MAX_BANKS 512
+struct rom
+{
+ const byte *bank[ROM_MAX_BANKS];
+ char name[20];
+};
+
+/* The work RAM (2 banks of 4 KB on the DMG, 8 on the CGB) and the cartridge's RAM come from
+ Retro-Go's memory block. The cartridge's RAM is written through mem_write only, so that its
+ battery save knows when it changed. */
+struct ram
+{
+ byte hi[256];
+ byte (*ibank)[4096];
+ byte (*sbank)[8192];
+ int sram_dirty;
+};
+
+
+extern struct mbc mbc;
+extern struct rom rom;
+extern struct ram ram;
+
+
+
+void mem_updatemap();
+void ioreg_write(byte r, byte b);
+void mbc_write(int a, byte b);
+void mem_write(int a, byte b);
+byte mem_read(int a);
+void mbc_reset();
+
+
+#define READB(a) ( mbc.rmap[(a)>>12] \
+? mbc.rmap[(a)>>12][(a)] \
+: mem_read((a)) )
+#define READW(a) ( READB((a)) | ((word)READB((a)+1)<<8) )
+
+#define WRITEB(a, b) ( mbc.wmap[(a)>>12] \
+? ( mbc.wmap[(a)>>12][(a)] = (b) ) \
+: ( mem_write((a), (b)), (b) ) )
+#define WRITEW(a, w) ( WRITEB((a), (w)&0xFF), WRITEB((a)+1, (w)>>8) )
+
+
+
+
+#endif
diff --git a/games/retrogo/src/gb/regs.h b/games/retrogo/src/gb/regs.h
new file mode 100644
index 00000000..b09e12b8
--- /dev/null
+++ b/games/retrogo/src/gb/regs.h
@@ -0,0 +1,184 @@
+/* From gnuboy 1.0.3 (rofl0r's tree) by Laguna and Gilgamesh and gnuboy's contributors,
+ * GPL-2.0-or-later (see COPYING in this folder); changed for Retro-Go on NumPlay. */
+#ifndef __REGS_H__
+#define __REGS_H__
+
+
+#include "mem.h"
+
+/* General internal/io stuff */
+
+#define RI_P1 0x00
+#define RI_SB 0x01
+#define RI_SC 0x02
+#define RI_DIV 0x04
+#define RI_TIMA 0x05
+#define RI_TMA 0x06
+#define RI_TAC 0x07
+
+#define RI_KEY1 0x4D
+
+#define RI_BOOT 0x50
+
+#define RI_RP 0x56
+
+#define RI_SVBK 0x70
+
+
+
+/* Interrupts flags */
+
+#define RI_IF 0x0F
+#define RI_IE 0xFF
+
+
+
+
+/* LCDC */
+
+#define RI_LCDC 0x40
+#define RI_STAT 0x41
+#define RI_SCY 0x42
+#define RI_SCX 0x43
+#define RI_LY 0x44
+#define RI_LYC 0x45
+#define RI_DMA 0x46
+#define RI_BGP 0x47
+#define RI_OBP0 0x48
+#define RI_OBP1 0x49
+#define RI_WY 0x4A
+#define RI_WX 0x4B
+
+#define RI_VBK 0x4F
+
+#define RI_HDMA1 0x51
+#define RI_HDMA2 0x52
+#define RI_HDMA3 0x53
+#define RI_HDMA4 0x54
+#define RI_HDMA5 0x55
+
+#define RI_BCPS 0x68
+#define RI_BCPD 0x69
+#define RI_OCPS 0x6A
+#define RI_OCPD 0x6B
+
+
+
+/* Sound */
+
+#define RI_NR10 0x10
+#define RI_NR11 0x11
+#define RI_NR12 0x12
+#define RI_NR13 0x13
+#define RI_NR14 0x14
+#define RI_NR21 0x16
+#define RI_NR22 0x17
+#define RI_NR23 0x18
+#define RI_NR24 0x19
+#define RI_NR30 0x1A
+#define RI_NR31 0x1B
+#define RI_NR32 0x1C
+#define RI_NR33 0x1D
+#define RI_NR34 0x1E
+#define RI_NR41 0x20
+#define RI_NR42 0x21
+#define RI_NR43 0x22
+#define RI_NR44 0x23
+#define RI_NR50 0x24
+#define RI_NR51 0x25
+#define RI_NR52 0x26
+
+
+
+#define REG(n) ram.hi[(n)]
+
+
+
+/* General internal/io stuff */
+
+#define R_P1 REG(RI_P1)
+#define R_SB REG(RI_SB)
+#define R_SC REG(RI_SC)
+#define R_DIV REG(RI_DIV)
+#define R_TIMA REG(RI_TIMA)
+#define R_TMA REG(RI_TMA)
+#define R_TAC REG(RI_TAC)
+
+#define R_KEY1 REG(RI_KEY1)
+
+#define R_RP REG(RI_RP)
+
+#define R_SVBK REG(RI_SVBK)
+
+
+
+/* Interrupts flags */
+
+#define R_IF REG(RI_IF)
+#define R_IE REG(RI_IE)
+
+
+
+
+/* LCDC */
+
+#define R_LCDC REG(RI_LCDC)
+#define R_STAT REG(RI_STAT)
+#define R_SCY REG(RI_SCY)
+#define R_SCX REG(RI_SCX)
+#define R_LY REG(RI_LY)
+#define R_LYC REG(RI_LYC)
+#define R_DMA REG(RI_DMA)
+#define R_BGP REG(RI_BGP)
+#define R_OBP0 REG(RI_OBP0)
+#define R_OBP1 REG(RI_OBP1)
+#define R_WY REG(RI_WY)
+#define R_WX REG(RI_WX)
+
+#define R_VBK REG(RI_VBK)
+
+#define R_HDMA1 REG(RI_HDMA1)
+#define R_HDMA2 REG(RI_HDMA2)
+#define R_HDMA3 REG(RI_HDMA3)
+#define R_HDMA4 REG(RI_HDMA4)
+#define R_HDMA5 REG(RI_HDMA5)
+
+#define R_BCPS REG(RI_BCPS)
+#define R_BCPD REG(RI_BCPD)
+#define R_OCPS REG(RI_OCPS)
+#define R_OCPD REG(RI_OCPD)
+
+
+
+/* Sound */
+
+#define R_NR10 REG(RI_NR10)
+#define R_NR11 REG(RI_NR11)
+#define R_NR12 REG(RI_NR12)
+#define R_NR13 REG(RI_NR13)
+#define R_NR14 REG(RI_NR14)
+#define R_NR21 REG(RI_NR21)
+#define R_NR22 REG(RI_NR22)
+#define R_NR23 REG(RI_NR23)
+#define R_NR24 REG(RI_NR24)
+#define R_NR30 REG(RI_NR30)
+#define R_NR31 REG(RI_NR31)
+#define R_NR32 REG(RI_NR32)
+#define R_NR33 REG(RI_NR33)
+#define R_NR34 REG(RI_NR34)
+#define R_NR41 REG(RI_NR41)
+#define R_NR42 REG(RI_NR42)
+#define R_NR43 REG(RI_NR43)
+#define R_NR44 REG(RI_NR44)
+#define R_NR50 REG(RI_NR50)
+#define R_NR51 REG(RI_NR51)
+#define R_NR52 REG(RI_NR52)
+
+
+
+#endif
+
+
+
+
+
diff --git a/games/retrogo/src/gb/rtc.c b/games/retrogo/src/gb/rtc.c
new file mode 100644
index 00000000..a75e3daa
--- /dev/null
+++ b/games/retrogo/src/gb/rtc.c
@@ -0,0 +1,95 @@
+/* The MBC3's real-time clock. From gnuboy 1.0.3 (rofl0r's tree), GPL-2.0-or-later (see COPYING).
+ * Changed for Retro-Go on NumPlay: the day counter has its 9 bits and sets the carry when it
+ * passes 511, as on the cartridge; no files (the clock is kept with the battery save). The
+ * calculator has no clock of its own for apps: time goes on while the game runs, and the
+ * Options can set it, as in Retro-Go. */
+#include "defs.h"
+#include "mem.h"
+#include "rtc.h"
+
+struct rtc rtc;
+
+void rtc_latch(byte b)
+{
+ if ((rtc.latch ^ b) & b & 1)
+ {
+ rtc.regs[0] = rtc.s;
+ rtc.regs[1] = rtc.m;
+ rtc.regs[2] = rtc.h;
+ rtc.regs[3] = rtc.d;
+ rtc.regs[4] = ((rtc.d>>8)&1) | (rtc.stop<<6) | (rtc.carry<<7);
+ rtc.regs[5] = 0xff;
+ rtc.regs[6] = 0xff;
+ rtc.regs[7] = 0xff;
+ }
+ rtc.latch = b;
+}
+
+void rtc_write(byte b)
+{
+ if (!(rtc.sel & 8)) return;
+ switch (rtc.sel & 7)
+ {
+ case 0:
+ rtc.s = rtc.regs[0] = b;
+ while (rtc.s >= 60) rtc.s -= 60;
+ break;
+ case 1:
+ rtc.m = rtc.regs[1] = b;
+ while (rtc.m >= 60) rtc.m -= 60;
+ break;
+ case 2:
+ rtc.h = rtc.regs[2] = b;
+ while (rtc.h >= 24) rtc.h -= 24;
+ break;
+ case 3:
+ rtc.regs[3] = b;
+ rtc.d = (rtc.d & 0x100) | b;
+ break;
+ case 4:
+ rtc.regs[4] = b;
+ rtc.d = (rtc.d & 0xff) | ((b&1)<<8);
+ rtc.stop = (b>>6)&1;
+ rtc.carry = (b>>7)&1;
+ break;
+ }
+}
+
+void rtc_tick()
+{
+ if (rtc.stop) return;
+ if (++rtc.t >= 60)
+ {
+ if (++rtc.s >= 60)
+ {
+ if (++rtc.m >= 60)
+ {
+ if (++rtc.h >= 24)
+ {
+ if (++rtc.d >= 512)
+ {
+ rtc.d = 0;
+ rtc.carry = 1;
+ }
+ rtc.h = 0;
+ }
+ rtc.m = 0;
+ }
+ rtc.s = 0;
+ }
+ rtc.t = 0;
+ }
+}
+
+/* after a save brought the clock back: whatever it held, a time the clock can show */
+void rtc_check()
+{
+ if (rtc.t < 0 || rtc.t >= 60) rtc.t = 0;
+ if (rtc.s < 0 || rtc.s >= 60) rtc.s = 0;
+ if (rtc.m < 0 || rtc.m >= 60) rtc.m = 0;
+ if (rtc.h < 0 || rtc.h >= 24) rtc.h = 0;
+ if (rtc.d < 0 || rtc.d >= 512) rtc.d = 0;
+ rtc.stop &= 1;
+ rtc.carry &= 1;
+ rtc.sel &= 0x0f;
+}
diff --git a/games/retrogo/src/gb/rtc.h b/games/retrogo/src/gb/rtc.h
new file mode 100644
index 00000000..26533a67
--- /dev/null
+++ b/games/retrogo/src/gb/rtc.h
@@ -0,0 +1,23 @@
+#ifndef __RTC_H__
+#define __RTC_H__
+
+#include "defs.h"
+
+struct rtc
+{
+ int batt;
+ int sel;
+ int latch;
+ int d, h, m, s, t;
+ int stop, carry;
+ byte regs[8];
+};
+
+extern struct rtc rtc;
+
+void rtc_latch(byte b);
+void rtc_write(byte b);
+void rtc_tick();
+void rtc_check();
+
+#endif
diff --git a/games/retrogo/src/icon.png b/games/retrogo/src/icon.png
new file mode 100644
index 00000000..295f89bc
Binary files /dev/null and b/games/retrogo/src/icon.png differ
diff --git a/games/retrogo/src/main.c b/games/retrogo/src/main.c
new file mode 100644
index 00000000..f526a00c
--- /dev/null
+++ b/games/retrogo/src/main.c
@@ -0,0 +1,1377 @@
+/* Retro-Go: Game Boy, Game Boy Color and NES games on the calculator.
+ *
+ * Retro-Go (ducalex) is a launcher and a set of emulators for ESP32 handhelds whose 320 x 240
+ * screen is the calculator's. This is its look and its ways, made again for the keypad: the
+ * launcher's system tabs and game lists, its menus (Save & Continue, Save & Quit, Load game,
+ * Reset, Options...), its scaling (1x, Fit, Full), its frame skipping (a frame drawn, then at
+ * least one skipped, more when the calculator can't keep up), save states in 4 slots and the
+ * cartridges' battery saves. The emulators are gnuboy (Game Boy, Game Boy Color) and nofrendo
+ * (NES), the ones Retro-Go started from; Retro-Go's own code is GPL-2.0 only, so none of it is
+ * here (see README.md).
+ *
+ * The games come in a table in flash, np_roms (tools/romtable.py, or the customizer website),
+ * read in place. Inside NumPlay the app draws with the launcher's strips and fonts and saves
+ * through its file functions; on its own (RetroGo.nwa) it brings them along. */
+#include <eadk.h>
+#include <string.h>
+#include "../../../launcher/src/gfx.h"
+#include "../../common/np_text.h"
+#include "rg.h"
+#include "romtable.h"
+#include "pack.h"
+#include "gb/gb.h"
+#include "nes/nes_core.h"
+
+#if NP_MODULE /* (np_file_read, np_file_write, np_storage_delete: NumPlay's, launcher/src/np.h) */
+#define np_app_begin()
+#define np_app_end() 0
+#define file_delete np_storage_delete
+#else
+#include "../../common/epsilon_app.h"
+#include "../../common/epsilon_files.h"
+#define np_file_read ef_read
+#define np_file_write ef_write
+#define file_delete ef_remove
+const char eadk_app_name[] __attribute__((section(".rodata.eadk_app_name"))) = "Retro-Go";
+const uint32_t eadk_api_level __attribute__((section(".rodata.eadk_api_level"))) = 0;
+void np_push(int x, int y, int w, int h, const color_t *px) {
+ eadk_display_push_rect((eadk_rect_t){(uint16_t)x, (uint16_t)y, (uint16_t)w, (uint16_t)h}, px);
+}
+#endif
+
+/* The games: np_roms, up to the end of Retro-Go's block of flash (np_retrogo_end: NumPlay's
+ linker script, or the one of RetroGo.nwa on its own). */
+#if PLATFORM_DEVICE
+extern const uint8_t np_roms[], np_retrogo_end[];
+#define TABLE_LIMIT ((uintptr_t)np_retrogo_end > (uintptr_t)np_roms ? (uint32_t)((uintptr_t)np_retrogo_end - (uintptr_t)np_roms) : 0)
+#else
+extern const uint8_t np_roms[];
+extern const uint32_t np_roms_size;
+#define TABLE_LIMIT np_roms_size
+#endif
+
+#define KEY(k) (1ull << (k))
+#define WHITE 0xFFFF
+#define BLACK 0x0000
+
+/* ------------------------------------------------------------ memory */
+static uint8_t heap[RG_HEAP_SIZE] __attribute__((aligned(8)));
+static uint32_t heap_used;
+bool rg_drawing = true;
+
+void *rg_alloc(uint32_t size) {
+ size = (size + 7) & ~7u;
+ if (size > sizeof heap - heap_used) return NULL;
+ void *p = heap + heap_used;
+ heap_used += size;
+ memset(p, 0, size);
+ return p;
+}
+void rg_alloc_reset(void) { heap_used = 0; }
+
+/* one strip of the screen: the launcher's drawing functions draw there, and the emulators'
+ pictures go through it */
+static color_t strip[SCREEN_W * STRIP_H] __attribute__((aligned(4)));
+
+static uint32_t millis(void) { return (uint32_t)eadk_timing_millis(); }
+
+/* ------------------------------------------------------------ settings (retrogo.cfg) */
+enum { SCALE_OFF, SCALE_FIT, SCALE_FULL, SCALE_COUNT };
+static struct {
+ uint8_t magic, version;
+ uint8_t scaling, speed; /* speed: 0.5x a step, from 0.5x */
+ uint8_t gb_palette, nes_palette;
+ uint8_t overscan, crop_sides, sprite_limit;
+ uint8_t autosave; /* the battery save, so many seconds after the game wrote it; 0 off */
+ uint8_t flags; /* 1: the controls were shown */
+ uint8_t tab, browse;
+ uint8_t cursor[RG_SYS_COUNT];
+} cfg;
+#define CFG_NAME "retrogo.cfg"
+
+static void cfg_defaults(void) {
+ memset(&cfg, 0, sizeof cfg);
+ cfg.magic = 'R', cfg.version = 1;
+ cfg.scaling = SCALE_FIT, cfg.speed = 1;
+ cfg.gb_palette = GB_PAL_DMG, cfg.nes_palette = NES_PAL_NTSC;
+ cfg.overscan = 1, cfg.crop_sides = 0, cfg.sprite_limit = 1, cfg.autosave = 10;
+}
+
+static void cfg_load(void) {
+ uint32_t len = 0;
+ const uint8_t *d = np_file_read(CFG_NAME, &len);
+ cfg_defaults();
+ if (!d || len != sizeof cfg || d[0] != 'R' || d[1] != 1) return;
+ memcpy(&cfg, d, sizeof cfg);
+ /* whatever it holds, settings Retro-Go has */
+ if (cfg.scaling >= SCALE_COUNT) cfg.scaling = SCALE_FIT;
+ if (cfg.speed > 4) cfg.speed = 1;
+ if (cfg.gb_palette >= GB_PAL_COUNT) cfg.gb_palette = 0;
+ if (cfg.nes_palette >= NES_PAL_COUNT) cfg.nes_palette = 0;
+ cfg.overscan &= 1, cfg.sprite_limit &= 1, cfg.browse &= 1;
+ if (cfg.crop_sides > 2) cfg.crop_sides = 0;
+ if (cfg.autosave > 99) cfg.autosave = 10;
+}
+
+static void cfg_save(void) { np_file_write(CFG_NAME, &cfg, sizeof cfg); }
+
+/* ------------------------------------------------------------ the games */
+static rg_rom_t roms[RG_MAX_ROMS];
+static int nroms;
+/* Retro-Go's tabs, in its order */
+static const uint8_t tab_order[] = {RG_SYS_NES, RG_SYS_GB, RG_SYS_GBC, RG_SYS_SMS, RG_SYS_GG};
+static uint8_t tabs[5], ntabs;
+static const char *const sys_name[RG_SYS_COUNT] = {
+ "Retro-Go", "Nintendo Gameboy", "Nintendo Gameboy Color", "Nintendo Entertainment System", "Sega Master System",
+ "Sega Game Gear"};
+static const char *const sys_short[RG_SYS_COUNT] = {"", "GB", "GBC", "NES", "SMS", "GG"};
+/* the tab's banner: the maker, then the system, as Retro-Go's banners show them */
+static const char *const sys_maker[RG_SYS_COUNT] = {"", "Nintendo", "Nintendo", "Nintendo", "SEGA", "SEGA"};
+static const char *const sys_model[RG_SYS_COUNT] = {"Retro-Go", "Game Boy", "Game Boy Color", "Entertainment System",
+ "Master System", "Game Gear"};
+static bool sys_supported(int s) { return s == RG_SYS_GB || s == RG_SYS_GBC || s == RG_SYS_NES; }
+
+static int tab_first(int sys) {
+ for (int i = 0; i < nroms; i++)
+ if (roms[i].system == sys) return i;
+ return 0;
+}
+static int tab_count(int sys) {
+ int n = 0;
+ for (int i = 0; i < nroms; i++) n += roms[i].system == sys;
+ return n;
+}
+
+/* CRC32 of a game (its save files are named after it, and Properties shows it) */
+static uint32_t crc32(const uint8_t *p, uint32_t n) {
+ static const uint32_t nib[16] = {0x00000000, 0x1DB71064, 0x3B6E20C8, 0x26D930AC, 0x76DC4190, 0x6B6B51F4,
+ 0x4DB26158, 0x5005713C, 0xEDB88320, 0xF00F9344, 0xD6D6A3E8, 0xCB61B38C,
+ 0x9B64C2B0, 0x86D3D2D4, 0xA00AE278, 0xBDBDF21C};
+ uint32_t c = 0xFFFFFFFF;
+ for (uint32_t i = 0; i < n; i++) {
+ c ^= p[i];
+ c = (c >> 4) ^ nib[c & 15];
+ c = (c >> 4) ^ nib[c & 15];
+ }
+ return ~c;
+}
+static const rg_rom_t *crc_rom;
+static uint32_t crc_value;
+static uint32_t rom_crc(const rg_rom_t *r) {
+ if (crc_rom != r) crc_rom = r, crc_value = crc32(r->data, r->size);
+ return crc_value;
+}
+
+static char *hex8(char *o, uint32_t v) {
+ for (int i = 7; i >= 0; i--, v >>= 4) o[i] = "0123456789ABCDEF"[v & 15];
+ o[8] = 0;
+ return o + 8;
+}
+static char *num(char *o, uint32_t v) {
+ char t[10];
+ int n = 0;
+ do t[n++] = (char)('0' + v % 10); while (v /= 10);
+ while (n) *o++ = t[--n];
+ *o = 0;
+ return o;
+}
+static char *cat(char *o, const char *s) {
+ while (*s) *o++ = *s++;
+ *o = 0;
+ return o;
+}
+
+/* "rg_XXXXXXXX.srm" (the battery save) and ".st0" to ".st3" (the states) */
+static void save_name(char *o, const rg_rom_t *r, int slot) {
+ o = cat(o, "rg_");
+ o = hex8(o, rom_crc(r));
+ if (slot < 0) cat(o, ".srm");
+ else o = cat(o, ".st"), o[0] = (char)('0' + slot), o[1] = 0;
+}
+
+/* ------------------------------------------------------------ drawing in a rectangle */
+/* The scene for rows [y0, y1), pushed for columns [x0, x1) only (what is around stays). */
+static void render_rect(gfx_scene_t scene, void *ctx, int x0, int y0, int x1, int y1) {
+ color_t *their = gfx_buf;
+ gfx_buf = strip;
+ x0 = NP_CLAMP(x0, 0, SCREEN_W), x1 = NP_CLAMP(x1, x0, SCREEN_W);
+ y0 = NP_CLAMP(y0, 0, SCREEN_H), y1 = NP_CLAMP(y1, y0, SCREEN_H);
+ int w = x1 - x0;
+ for (int y = y0; y < y1 && w > 0; y += STRIP_H) {
+ gfx_y0 = y;
+ gfx_y1 = NP_MIN(y + STRIP_H, y1);
+ scene(ctx);
+ int h = gfx_y1 - y;
+ if (w < SCREEN_W)
+ for (int j = 0; j < h; j++) memmove(strip + j * w, strip + j * SCREEN_W + x0, (size_t)w * sizeof(color_t));
+ np_push(x0, y, w, h, strip);
+ }
+ gfx_buf = their;
+}
+
+static void fill_screen(int x, int y, int w, int h, color_t c) {
+ if (w > 0 && h > 0)
+ eadk_display_push_rect_uniform((eadk_rect_t){(uint16_t)x, (uint16_t)y, (uint16_t)w, (uint16_t)h}, c);
+}
+
+/* ------------------------------------------------------------ the emulators' picture */
+static struct {
+ int src_x, src_y, src_w, src_h; /* the part of the core's picture shown */
+ int x, y, w, h; /* where, on the screen */
+} view;
+static uint8_t xmap[SCREEN_W]; /* screen column -> picture column */
+static uint8_t row_first[241]; /* picture row -> its first screen row */
+static uint32_t line_sum[240]; /* each picture row as it was last pushed (Retro-Go's partial updates) */
+static bool redraw_all;
+static int pend_y, pend_n, covered_y = SCREEN_H; /* rows waiting in the strip; rows from covered_y down are left alone */
+
+static void flush(void) {
+ int n = NP_MIN(pend_n, covered_y - pend_y);
+ if (n > 0) np_push(view.x, pend_y, view.w, n, strip);
+ pend_n = 0;
+}
+
+static uint32_t checksum(const uint16_t *p, int n) {
+ uint32_t h = 2166136261u;
+ for (int i = 0; i + 1 < n; i += 2) h = (h ^ (p[i] | (uint32_t)p[i + 1] << 16)) * 16777619u;
+ return h;
+}
+
+void rg_line(int y, const uint16_t *px) {
+ int sy = y - view.src_y;
+ if (sy < 0 || sy >= view.src_h) return;
+ int d0 = row_first[sy], d1 = row_first[sy + 1];
+ if (d0 >= d1) return;
+ const uint16_t *src = px + view.src_x;
+ uint32_t sum = checksum(src, view.src_w);
+ if (!redraw_all && sum == line_sum[sy]) { /* (unchanged since it was pushed) */
+ flush();
+ return;
+ }
+ line_sum[sy] = sum;
+ for (int d = d0; d < d1; d++) {
+ if (pend_n && (pend_y + pend_n != view.y + d || pend_n == STRIP_H)) flush();
+ if (!pend_n) pend_y = view.y + d;
+ color_t *row = strip + pend_n * view.w;
+ if (d > d0 && pend_n) memcpy(row, row - view.w, (size_t)view.w * 2);
+ else if (view.w == view.src_w) memcpy(row, src, (size_t)view.w * 2);
+ else
+ for (int x = 0; x < view.w; x++) row[x] = src[xmap[x]];
+ pend_n++;
+ }
+}
+
+/* the picture's place for the game running (Retro-Go's update_viewport_scaling) */
+static int sys_now;
+static void set_view(void) {
+ int sw = 160, sh = 144, cx = 0, cy = 0;
+ if (sys_now == RG_SYS_NES) {
+ sw = NES_WIDTH, sh = NES_HEIGHT;
+ cy = cfg.overscan ? 8 : 0;
+ cx = cfg.crop_sides ? 8 : 0;
+ }
+ view.src_x = cx, view.src_y = cy, view.src_w = sw - 2 * cx, view.src_h = sh - 2 * cy;
+ sw = view.src_w, sh = view.src_h;
+ int w = sw, h = sh;
+ if (cfg.scaling == SCALE_FULL) {
+ w = SCREEN_W, h = SCREEN_H;
+ } else if (cfg.scaling == SCALE_FIT) {
+ w = (int)(SCREEN_H * ((float)sw / sh) + 0.1f), h = SCREEN_H;
+ if (w > SCREEN_W) w = SCREEN_W, h = (int)(SCREEN_W * ((float)sh / sw) + 0.1f);
+ }
+ w &= ~1, h &= ~1;
+ view.w = NP_MIN(w, SCREEN_W), view.h = NP_MIN(h, SCREEN_H);
+ view.x = (SCREEN_W - view.w) / 2, view.y = (SCREEN_H - view.h) / 2;
+ for (int x = 0; x < view.w; x++) xmap[x] = (uint8_t)(x * sw / view.w);
+ for (int y = 0; y <= sh; y++) row_first[y] = (uint8_t)((y * view.h + sh - 1) / sh);
+ redraw_all = true;
+}
+
+static void core_redraw(void);
+
+/* ------------------------------------------------------------ the systems' looks */
+/* Each system's colours (Retro-Go's theme) and a shape of the console, tilted, behind its tab:
+ rounded boxes and discs in the console's own frame, the first one its body. */
+typedef struct { int16_t u0, v0, u1, v1; uint8_t r, hole; } shape_t;
+typedef struct { uint32_t bg, ink; const char *year; const shape_t *shapes; uint8_t n; } look_t;
+static const shape_t gb_shape[] = {
+ {-62, -100, 62, 100, 12, 0}, {-48, -84, 48, -6, 6, 1}, {-40, 22, -12, 34, 2, 1}, {-32, 14, -20, 42, 2, 1},
+ {16, 26, 32, 42, 8, 1}, {34, 14, 50, 30, 8, 1}, {-14, 64, 2, 70, 3, 1}, {6, 64, 22, 70, 3, 1}};
+static const shape_t gbc_shape[] = {
+ {-58, -96, 58, 100, 22, 0}, {-44, -80, 44, -10, 6, 1}, {-38, 22, -10, 34, 2, 1}, {-30, 14, -18, 42, 2, 1},
+ {14, 24, 30, 40, 8, 1}, {32, 12, 48, 28, 8, 1}, {-14, 66, 0, 72, 3, 1}, {6, 66, 20, 72, 3, 1}};
+static const shape_t nes_shape[] = {
+ {-150, -62, 150, 62, 6, 0}, {-120, -16, -60, 4, 2, 1}, {-100, -36, -80, 24, 2, 1}, {-34, -2, -8, 8, 4, 1},
+ {6, -2, 32, 8, 4, 1}, {58, -14, 86, 14, 14, 1}, {98, -14, 126, 14, 14, 1}};
+static const shape_t sms_shape[] = {
+ {-150, -50, 150, 50, 4, 0}, {-120, -30, -20, 30, 6, 1}, {30, -20, 60, 10, 15, 1}, {75, -20, 105, 10, 15, 1}};
+static const shape_t gg_shape[] = {
+ {-140, -62, 140, 62, 40, 0}, {-56, -46, 56, 40, 6, 1}, {-112, -12, -84, 0, 2, 1}, {-104, -20, -92, 8, 2, 1},
+ {84, -8, 100, 8, 8, 1}, {106, -18, 122, -2, 8, 1}};
+static const look_t looks[RG_SYS_COUNT] = {
+ {0x202020, 0x303030, "", gb_shape, 0},
+ {0xE8811F, 0xDF6C10, "1989", gb_shape, sizeof gb_shape / sizeof gb_shape[0]},
+ {0x3199DC, 0x2481BA, "1998", gbc_shape, sizeof gbc_shape / sizeof gbc_shape[0]},
+ {0xE84B39, 0xC23627, "1985", nes_shape, sizeof nes_shape / sizeof nes_shape[0]},
+ {0x3199DB, 0x2481BA, "1986", sms_shape, sizeof sms_shape / sizeof sms_shape[0]},
+ {0x0EA186, 0x13BC9D, "1990", gg_shape, sizeof gg_shape / sizeof gg_shape[0]},
+};
+
+static bool in_shape(const shape_t *s, int u, int v) {
+ if (u < s->u0 || u >= s->u1 || v < s->v0 || v >= s->v1) return false;
+ int r = s->r, du = u < s->u0 + r ? s->u0 + r - u : u >= s->u1 - r ? u - (s->u1 - r) + 1 : 0;
+ int dv = v < s->v0 + r ? s->v0 + r - v : v >= s->v1 - r ? v - (s->v1 - r) + 1 : 0;
+ return du * du + dv * dv <= r * r;
+}
+
+/* the tab's background: its colour, the console tilted 30 degrees, darker by `shade` (Retro-Go
+ divides the colours by 4 behind a list) */
+static void background(int sys, int shade) {
+ const look_t *l = &looks[sys];
+ color_t bg = gfx_rgb(l->bg), ink = gfx_rgb(l->ink);
+ if (shade) {
+ bg = (color_t)(((bg >> 11) / shade) << 11 | (((bg >> 5) & 63) / shade) << 5 | (bg & 31) / shade);
+ ink = (color_t)(((ink >> 11) / shade) << 11 | (((ink >> 5) & 63) / shade) << 5 | (ink & 31) / shade);
+ }
+ enum { COS = 887, SIN = 512 }; /* (30 degrees, in 1024ths) */
+ int cx = 196, cy = 150;
+ for (int y = gfx_y0; y < gfx_y1; y++) {
+ color_t *p = gfx_buf + (y - gfx_y0) * SCREEN_W;
+ int dy = y - cy;
+ for (int x = 0; x < SCREEN_W; x++) {
+ int dx = x - cx, u = (dx * COS + dy * SIN) >> 10, v = (dy * COS - dx * SIN) >> 10;
+ color_t c = bg;
+ if (l->n && in_shape(&l->shapes[0], u, v)) {
+ c = ink;
+ for (int k = 1; k < l->n; k++)
+ if (in_shape(&l->shapes[k], u, v)) { c = bg; break; }
+ }
+ p[x] = c;
+ }
+ }
+}
+
+/* Retro-Go's tab header: the console's card on the left, its name and a line on the right */
+#define HEADER_H 50
+#define LOGO_W 46
+static void header(int sys, int y) {
+ const look_t *l = &looks[sys];
+ gfx_rrect(1, y + 1, LOGO_W - 2, HEADER_H - 2, 4, WHITE, 256);
+ gfx_rrect_outline(1, y + 1, LOGO_W - 2, HEADER_H - 2, 4, 1, HEX(0x9AA0A6), 256);
+ /* a little console: the body, its screen or its pad */
+ if (sys == RG_SYS_NES || sys == RG_SYS_SMS) {
+ gfx_fill(7, y + 11, 32, 15, HEX(0x8C8C8C));
+ gfx_fill(7, y + 22, 32, 4, HEX(0x3C3C3C));
+ gfx_fill(10, y + 14, 12, 4, HEX(0xD8D8D8));
+ } else {
+ gfx_rrect(14, y + 4, 18, 25, 3, gfx_rgb(sys == RG_SYS_GB || !sys ? 0xB8B8B0 : l->bg), 256);
+ gfx_fill(17, y + 7, 12, 9, HEX(0x6E8A3A));
+ gfx_fill(17, y + 21, 5, 2, HEX(0x303030));
+ gfx_fill(18, y + 20, 2, 4, HEX(0x303030));
+ gfx_circle(27, y + 22, 2, HEX(0xA0204A), 256);
+ }
+ gfx_text_center(&np_font_small, LOGO_W / 2, y + 39, sys_short[sys], HEX(0x303030), 256);
+ if (*l->year) { /* the year it came out, on a blue label */
+ gfx_rrect(LOGO_W / 2 - 12, y + 40, 24, 9, 3, HEX(0x2F6FD0), 256);
+ gfx_text_center(&np_font_small, LOGO_W / 2, y + 48, l->year, WHITE, 256);
+ }
+ /* the maker, small, then the name, big, and its line to the edge */
+ gfx_text(&np_font_small, LOGO_W + 9, y + 11, sys_maker[sys], WHITE, 256);
+ int w = gfx_text(&np_font_title, LOGO_W + 8, y + 30, sys_model[sys], WHITE, 256);
+ if (w < SCREEN_W - 4) gfx_fill(w + 4, y + 23, SCREEN_W - w - 4, 2, WHITE);
+}
+
+/* ------------------------------------------------------------ Retro-Go's dialogs */
+/* A box in the middle, its title, then its items: a label, and a value after ": " for an
+ option; the selected item in reverse. Up/Down choose, Left/Right change a value, OK takes, Back
+ goes back. */
+#define DLG_BG 0x0010 /* Retro-Go's theme: dark blue, */
+#define DLG_BORDER 0x6B4D /* a grey border, */
+#define DLG_DIM 0x8410 /* grey for what can't be taken, */
+#define DLG_MSG 0xBDF7 /* light grey for messages */
+#define ROW_H 16
+#define PAD 6
+#define ROW_PAD 8
+enum { IT_NORMAL, IT_DISABLED, IT_MESSAGE, IT_HIDDEN };
+enum { EV_SHOW, EV_PREV, EV_NEXT, EV_ENTER };
+enum { CB_NONE, CB_SELECT, CB_REDRAW };
+enum { DLG_BACK = -1, DLG_HOME = -2 };
+typedef struct item_s item_t;
+typedef int (*item_cb)(item_t *it, int event);
+struct item_s {
+ int id;
+ const char *label;
+ char value[42];
+ uint8_t flags, has_value;
+ item_cb cb;
+ intptr_t arg;
+};
+
+typedef struct {
+ const char *title;
+ item_t *items;
+ int n, sel, top, rows;
+ int x, y, w, h, col1, col2;
+} dialog_t;
+
+static void (*restore_behind)(void); /* the picture behind the dialogs, drawn again */
+
+static void dialog_layout(dialog_t *d) {
+ int sep = gfx_text_width(&np_font_body, ": "), maxw = SCREEN_W * 82 / 100;
+ int inner = d->title ? gfx_text_width(&np_font_body, d->title) : 0, rows = 0;
+ d->col1 = 0, d->col2 = 0;
+ for (int i = 0; i < d->n; i++) {
+ item_t *it = &d->items[i];
+ if (it->flags == IT_HIDDEN) continue;
+ rows++;
+ int lw = gfx_text_width(&np_font_body, it->label);
+ if (it->has_value) {
+ d->col1 = NP_MAX(d->col1, lw);
+ d->col2 = NP_MAX(d->col2, gfx_text_width(&np_font_body, it->value));
+ } else {
+ inner = NP_MAX(inner, lw);
+ }
+ }
+ if (d->col2) inner = NP_MAX(inner, d->col1 + sep + d->col2);
+ inner = NP_MIN(inner, maxw - 2 * (PAD + ROW_PAD));
+ int maxrows = (SCREEN_H * 82 / 100 - 2 * PAD - (d->title ? ROW_H + 6 : 0)) / ROW_H;
+ d->rows = NP_MIN(rows, maxrows);
+ d->w = inner + 2 * (PAD + ROW_PAD);
+ d->h = 2 * PAD + (d->title ? ROW_H + 6 : 0) + d->rows * ROW_H;
+ d->x = (SCREEN_W - d->w) / 2, d->y = (SCREEN_H - d->h) / 2;
+}
+
+/* text cut with "..." to fit maxw pixels */
+static void text_fit(const np_font_t *f, int x, int base, const char *s, int maxw, color_t c) {
+ if (gfx_text_width(f, s) <= maxw) {
+ gfx_text(f, x, base, s, c, 256);
+ return;
+ }
+ char b[48];
+ int n = 0;
+ while (s[n] && n < 44) n++;
+ for (; n > 0; n--) {
+ memcpy(b, s, (size_t)n);
+ strcpy(b + n, "...");
+ if (gfx_text_width(f, b) <= maxw) break;
+ }
+ if (!n) strcpy(b, "...");
+ gfx_text(f, x, base, b, c, 256);
+}
+
+static void dialog_scene(void *ctx) {
+ dialog_t *d = ctx;
+ gfx_fill(d->x - 1, d->y - 1, d->w + 2, d->h + 2, DLG_BORDER);
+ gfx_fill(d->x, d->y, d->w, d->h, DLG_BG);
+ int y = d->y + PAD, sep = gfx_text_width(&np_font_body, ": ");
+ if (d->title) {
+ gfx_text_center(&np_font_body, d->x + d->w / 2, y + 12, d->title, WHITE, 256);
+ y += ROW_H + 6;
+ }
+ int shown = 0;
+ for (int i = d->top; i < d->n && shown < d->rows; i++) {
+ item_t *it = &d->items[i];
+ if (it->flags == IT_HIDDEN) continue;
+ color_t c = it->flags == IT_NORMAL ? WHITE : it->flags == IT_MESSAGE ? DLG_MSG : DLG_DIM;
+ bool hl = i == d->sel && it->flags == IT_NORMAL;
+ color_t fg = hl ? DLG_BG : c;
+ if (hl) gfx_fill(d->x + PAD, y, d->w - 2 * PAD, ROW_H, c);
+ int x = d->x + PAD + ROW_PAD, inner = d->w - 2 * (PAD + ROW_PAD);
+ if (it->has_value) {
+ gfx_text(&np_font_body, x, y + 12, it->label, fg, 256);
+ gfx_text(&np_font_body, x + d->col1, y + 12, ": ", fg, 256);
+ text_fit(&np_font_body, x + d->col1 + sep, y + 12, it->value, inner - d->col1 - sep, fg);
+ } else {
+ text_fit(&np_font_body, x, y + 12, it->label, inner, fg);
+ }
+ y += ROW_H;
+ shown++;
+ }
+ /* (more above or below: Retro-Go's little arrows) */
+ int ax = d->x + d->w - 10, ay = d->y + PAD + 6;
+ if (d->top > 0)
+ for (int k = 0; k < 3; k++) gfx_fill(ax + k, ay - 2 * k, 6 - 2 * k, 2, WHITE);
+ ay = d->y + d->h - 6;
+ int last = d->top, shown2 = 0;
+ for (; last < d->n && shown2 < d->rows; last++) shown2 += d->items[last].flags != IT_HIDDEN;
+ if (last < d->n)
+ for (int k = 0; k < 3; k++) gfx_fill(ax + k, ay - 4 + 2 * k, 6 - 2 * k, 2, WHITE);
+}
+
+static void dialog_draw(dialog_t *d) {
+ dialog_layout(d);
+ /* keep the selection on screen */
+ if (d->sel < d->top) d->top = d->sel;
+ int vis = 0;
+ for (int i = d->top; i <= d->sel && i < d->n; i++) vis += d->items[i].flags != IT_HIDDEN;
+ while (vis > d->rows && d->top < d->sel) vis -= d->items[d->top++].flags != IT_HIDDEN;
+ render_rect(dialog_scene, d, d->x - 1, d->y - 1, d->x + d->w + 1, d->y + d->h + 1);
+}
+
+static bool takeable(const item_t *it) { return it->flags == IT_NORMAL; }
+
+/* keys as they are pressed, the arrows repeating while held */
+static uint64_t held_keys;
+static uint32_t repeat_at;
+static uint64_t key_hits(void) {
+ uint64_t k = eadk_keyboard_scan(), hit = k & ~held_keys;
+ const uint64_t arrows = KEY(eadk_key_left) | KEY(eadk_key_right) | KEY(eadk_key_up) | KEY(eadk_key_down);
+ uint32_t now = millis();
+ if (hit & arrows) repeat_at = now + 300;
+ else if ((k & arrows) && (int32_t)(now - repeat_at) >= 0) hit |= k & arrows, repeat_at = now + 90;
+ held_keys = k;
+ return hit | (k & (KEY(eadk_key_home) | KEY(eadk_key_on_off)));
+}
+static void wait_release(void) {
+ while (eadk_keyboard_scan() & ~(KEY(eadk_key_home) | KEY(eadk_key_on_off))) eadk_timing_msleep(10);
+ held_keys = eadk_keyboard_scan();
+}
+
+/* Runs a dialog; the item's id, DLG_BACK or DLG_HOME. */
+static int dialog_run(const char *title, item_t *items, int n, int sel) {
+ dialog_t d = {title, items, n, 0, 0, 0, 0, 0, 0, 0, 0, 0};
+ for (int i = 0; i < n; i++)
+ if (items[i].cb) items[i].cb(&items[i], EV_SHOW);
+ if (sel < 0 || sel >= n || !takeable(&items[sel]))
+ for (sel = 0; sel < n && !takeable(&items[sel]); sel++) {}
+ d.sel = sel < n ? sel : 0;
+ dialog_draw(&d);
+ int result = DLG_BACK;
+ for (;;) {
+ eadk_timing_msleep(16);
+ uint64_t hit = key_hits();
+ if (hit & (KEY(eadk_key_home) | KEY(eadk_key_on_off))) { result = DLG_HOME; break; }
+ if (hit & KEY(eadk_key_back)) break;
+ int dy = !!(hit & KEY(eadk_key_down)) - !!(hit & KEY(eadk_key_up));
+ if (dy) {
+ int s = d.sel;
+ for (int k = 0; k < n; k++) {
+ s = (s + dy + n) % n;
+ if (takeable(&items[s])) break;
+ }
+ if (takeable(&items[s]) && s != d.sel) d.sel = s, dialog_draw(&d);
+ continue;
+ }
+ item_t *it = &items[d.sel];
+ if (!takeable(it)) continue;
+ int ev = hit & KEY(eadk_key_left) ? EV_PREV : hit & KEY(eadk_key_right) ? EV_NEXT : 0;
+ if (ev && it->cb) {
+ int r = it->cb(it, ev);
+ it->cb(it, EV_SHOW);
+ if (r == CB_REDRAW && restore_behind) {
+ dialog_layout(&d);
+ restore_behind();
+ }
+ dialog_draw(&d);
+ continue;
+ }
+ if (hit & (KEY(eadk_key_ok) | KEY(eadk_key_exe))) {
+ if (!it->cb) { result = it->id; break; }
+ int r = it->cb(it, EV_ENTER);
+ if (r == CB_SELECT) { result = it->id; break; }
+ if (restore_behind) restore_behind();
+ for (int i = 0; i < n; i++)
+ if (items[i].cb) items[i].cb(&items[i], EV_SHOW);
+ dialog_draw(&d);
+ }
+ }
+ wait_release();
+ if (restore_behind) restore_behind();
+ return result;
+}
+
+#define ITEM(id, label) {(id), (label), "", IT_NORMAL, 0, NULL, 0}
+#define OPTION(label, cb, arg) {0, (label), "", IT_NORMAL, 1, (cb), (arg)}
+#define MESSAGE(label) {0, (label), "", IT_MESSAGE, 0, NULL, 0}
+
+static void message_box(const char *title, const char *text) { /* drawn, not waited on */
+ item_t it[1] = {MESSAGE(text)};
+ dialog_t d = {title, it, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0};
+ dialog_draw(&d);
+}
+
+static int alert(const char *title, const char *text) {
+ item_t it[] = {MESSAGE(text), ITEM(1, T("OK"))};
+ return dialog_run(title, it, 2, 1);
+}
+
+/* Retro-Go's yes or no: 1 yes, 0 no (DLG_BACK too), DLG_HOME */
+static int confirm(const char *title, const char *text) {
+ item_t it[] = {MESSAGE(text ? text : ""), ITEM(1, T("Yes")), ITEM(0, T("No"))};
+ int r = text ? dialog_run(title, it, 3, 2) : dialog_run(title, it + 1, 2, 1);
+ return r == DLG_BACK ? 0 : r;
+}
+
+/* ------------------------------------------------------------ saves */
+/* A save file: a header, the size of each part as it is and packed, a checksum of the packed
+ data, then the parts packed. */
+#define SAVE_MAGIC_STATE 0x54534752u /* "RGST" */
+#define SAVE_MAGIC_SRAM 0x52534752u /* "RGSR" */
+#define SAVE_VERSION 1
+typedef struct {
+ uint32_t magic;
+ uint8_t version, system;
+ uint16_t parts;
+ uint32_t rom;
+ uint32_t seq; /* states: the higher, the more recent (Retro-Go's "last used") */
+ uint32_t check;
+} save_head_t;
+static uint32_t save_seq;
+
+static uint32_t fnv(const uint8_t *p, uint32_t n) {
+ uint32_t h = 2166136261u;
+ for (uint32_t i = 0; i < n; i++) h = (h ^ p[i]) * 16777619u;
+ return h;
+}
+static void wr32(uint8_t *p, uint32_t v) { p[0] = (uint8_t)v, p[1] = (uint8_t)(v >> 8), p[2] = (uint8_t)(v >> 16), p[3] = (uint8_t)(v >> 24); }
+static uint32_t rd32(const uint8_t *p) { return p[0] | p[1] << 8 | p[2] << 16 | (uint32_t)p[3] << 24; }
+
+/* (the packer's table is the strip: nothing is drawn while a save is made) */
+static bool save_parts(const char *name, uint32_t magic, uint32_t rom, const rg_chunk_t *parts, int n) {
+ uint16_t *table = (uint16_t *)(void *)strip;
+ uint32_t packed[RG_MAX_CHUNKS], total = sizeof(save_head_t) + 8u * (uint32_t)n;
+ for (int i = 0; i < n; i++) {
+ packed[i] = rg_pack(parts[i].at, parts[i].size, NULL, table);
+ total += packed[i];
+ }
+ if (total > 0xFF00 || !np_file_write(name, NULL, total)) return false;
+ uint32_t len = 0;
+ uint8_t *f = (uint8_t *)(uintptr_t)np_file_read(name, &len);
+ if (!f || len != total) return false;
+ uint8_t *o = f + sizeof(save_head_t) + 8 * n, *body = o;
+ for (int i = 0; i < n; i++) {
+ wr32(f + sizeof(save_head_t) + 8 * i, parts[i].size);
+ wr32(f + sizeof(save_head_t) + 8 * i + 4, packed[i]);
+ o += rg_pack(parts[i].at, parts[i].size, o, table);
+ }
+ save_head_t h = {magic, SAVE_VERSION, (uint8_t)sys_now, (uint16_t)n, rom, save_seq, fnv(body, (uint32_t)(o - body))};
+ memcpy(f, &h, sizeof h);
+ return true;
+}
+
+/* a state's header, if it is one of this game's: its sequence number, 0 if none */
+static uint32_t state_seq(const char *name, uint32_t rom, int system) {
+ uint32_t len = 0;
+ const uint8_t *f = np_file_read(name, &len);
+ save_head_t h;
+ if (!f || len < sizeof h) return 0;
+ memcpy(&h, f, sizeof h);
+ if (h.magic != SAVE_MAGIC_STATE || h.version != SAVE_VERSION || h.rom != rom || h.system != system) return 0;
+ return h.seq ? h.seq : 1;
+}
+
+/* 1: read; 0: no such file, or one for something else (nothing changed); -1: damaged half way
+ (the parts are not to be trusted) */
+static int load_parts(const char *name, uint32_t magic, uint32_t rom, const rg_chunk_t *parts, int n) {
+ uint32_t len = 0;
+ const uint8_t *f = np_file_read(name, &len);
+ save_head_t h;
+ if (!f || len < sizeof h) return 0;
+ memcpy(&h, f, sizeof h);
+ if (h.magic != magic || h.version != SAVE_VERSION || h.system != sys_now || h.rom != rom || h.parts != n) return 0;
+ uint32_t at = sizeof h + 8u * (uint32_t)n, sum = 0;
+ if (len < at) return 0;
+ for (int i = 0; i < n; i++) {
+ uint32_t raw = rd32(f + sizeof h + 8 * i), size = rd32(f + sizeof h + 8 * i + 4);
+ if (raw != parts[i].size || size > len - at - sum) return 0;
+ sum += size;
+ }
+ if (at + sum != len || fnv(f + at, sum) != h.check) return 0;
+ for (int i = 0; i < n; i++) {
+ uint32_t size = rd32(f + sizeof h + 8 * i + 4);
+ if (!rg_unpack(f + at, size, parts[i].at, parts[i].size)) return -1;
+ at += size;
+ }
+ return 1;
+}
+
+/* ------------------------------------------------------------ the game running */
+static const rg_rom_t *game;
+static uint32_t game_crc;
+static int last_slot = -1; /* the slot saved last (Retro-Go's "last used") */
+static int session_slot = -1; /* the slot this game was loaded from or saved to since it started */
+static int frameskip = 1, skip; /* Retro-Go's frame skipping */
+static uint32_t autosave_at; /* when the battery save is due, 0 none */
+
+static bool is_gb(void) { return sys_now == RG_SYS_GB || sys_now == RG_SYS_GBC; }
+
+static int core_chunks(rg_chunk_t *c) { return is_gb() ? gb_state_chunks(c) : nes_state_chunks(c); }
+
+static uint8_t *core_sram(uint32_t *size) { return is_gb() ? gb_sram(size) : nes_sram(size); }
+static bool core_sram_dirty(void) { return is_gb() ? gb_sram_dirty() : nes_sram_dirty(); }
+
+static void core_redraw(void) {
+ redraw_all = true;
+ pend_n = 0;
+ if (is_gb()) gb_redraw();
+ else nes_redraw();
+ flush();
+ redraw_all = false;
+}
+
+static bool sram_save(void) {
+ uint32_t size = 0;
+ uint8_t *ram = core_sram(&size);
+ if (!ram) return true;
+ char name[20];
+ save_name(name, game, -1);
+ rg_chunk_t parts[2] = {{ram, size}, {NULL, 0}};
+ int n = 1;
+ if (is_gb() && gb_has_rtc()) parts[n].at = gb_rtc_state(&parts[n].size), n++;
+ bool ok = !size && n == 1 ? true : save_parts(name, SAVE_MAGIC_SRAM, game_crc, parts, n);
+ if (ok) {
+ if (is_gb()) gb_sram_saved();
+ else nes_sram_saved();
+ }
+ autosave_at = 0;
+ return ok;
+}
+
+static void sram_load(void) {
+ uint32_t size = 0;
+ uint8_t *ram = core_sram(&size);
+ if (!ram) return;
+ char name[20];
+ save_name(name, game, -1);
+ rg_chunk_t parts[2] = {{ram, size}, {NULL, 0}};
+ int n = 1;
+ if (is_gb() && gb_has_rtc()) parts[n].at = gb_rtc_state(&parts[n].size), n++;
+ if (load_parts(name, SAVE_MAGIC_SRAM, game_crc, parts, n) < 0) memset(ram, 0xFF, size);
+ if (is_gb()) {
+ if (gb_has_rtc()) gb_rtc_loaded();
+ gb_sram_saved();
+ } else {
+ nes_sram_saved();
+ }
+}
+
+static uint32_t slot_seq(const rg_rom_t *r, int slot) {
+ char name[20];
+ save_name(name, r, slot);
+ return state_seq(name, rom_crc(r), r->system);
+}
+static bool state_exists(const rg_rom_t *r, int slot) { return slot_seq(r, slot) != 0; }
+
+/* the slot saved last, -1 if none */
+static int newest_slot(const rg_rom_t *r) {
+ int best = -1;
+ uint32_t top = 0;
+ for (int i = 0; i < 4; i++) {
+ uint32_t s = slot_seq(r, i);
+ if (s > top) top = s, best = i;
+ }
+ return best;
+}
+
+static bool state_save(int slot) {
+ rg_chunk_t parts[RG_MAX_CHUNKS];
+ int n = core_chunks(parts);
+ char name[20];
+ save_seq = 1;
+ for (int i = 0; i < 4; i++) save_seq = NP_MAX(save_seq, slot_seq(game, i) + 1);
+ save_name(name, game, slot);
+ bool ok = save_parts(name, SAVE_MAGIC_STATE, game_crc, parts, n);
+ if (ok) last_slot = session_slot = slot;
+ return ok;
+}
+
+static void core_reset(bool hard);
+/* false when it couldn't (the game as it was, or, if the state broke half way, started again) */
+static bool state_load(int slot) {
+ rg_chunk_t parts[RG_MAX_CHUNKS];
+ int n = core_chunks(parts);
+ char name[20];
+ save_name(name, game, slot);
+ int r = load_parts(name, SAVE_MAGIC_STATE, game_crc, parts, n);
+ if (r > 0) {
+ if (is_gb()) gb_state_loaded();
+ else nes_state_loaded();
+ last_slot = session_slot = slot, skip = 0;
+ return true;
+ }
+ if (r < 0) { /* (as Retro-Go: a hard reset, and the battery save) */
+ core_reset(true);
+ sram_load();
+ }
+ return false;
+}
+
+static void core_reset(bool hard) {
+ if (is_gb()) gb_reset(hard);
+ else nes_reset_machine(hard);
+ skip = 0;
+}
+
+static void apply_settings(void) {
+ if (is_gb()) gb_set_palette(cfg.gb_palette);
+ else nes_set_palette(cfg.nes_palette), nes_set_sprite_limit(cfg.sprite_limit);
+}
+
+/* the game's picture again, with what is around it */
+static void borders_scene(void *ctx) {
+ (void)ctx;
+ gfx_fill(0, gfx_y0, SCREEN_W, gfx_y1 - gfx_y0, BLACK);
+ if (view.x < 72) return;
+ /* (room on the sides: the keys) */
+ static const char *const keys[][2] = {{T("arrows"), T("D-pad")}, {T("OK"), "A"}, {T("Back"), "B"},
+ {T("shift"), T("Select")}, {T("EXE"), T("Start")},
+ {T("Backspace"), T("menu")}, {T("Home"), T("quit")}};
+ for (int i = 0; i < 7; i++) {
+ int y = view.y + 10 + i * 20;
+ gfx_text_right(&np_font_small, view.x - 6, y, keys[i][0], HEX(0x9AA0A6), 256);
+ gfx_text_right(&np_font_small, view.x - 6, y + 9, keys[i][1], WHITE, 256);
+ }
+}
+static void game_screen(void) {
+ if (view.y > 0) fill_screen(0, 0, SCREEN_W, view.y, BLACK), fill_screen(0, view.y + view.h, SCREEN_W, SCREEN_H - view.y - view.h, BLACK);
+ if (view.x > 0) {
+ render_rect(borders_scene, NULL, 0, view.y, view.x, view.y + view.h);
+ fill_screen(view.x + view.w, view.y, SCREEN_W - view.x - view.w, view.h, BLACK);
+ }
+ core_redraw();
+}
+
+/* ---- the options (Retro-Go's, those the calculator has) */
+static const char *const scale_names[] = {"1x", T("Fit"), T("Full")};
+static int scaling_cb(item_t *it, int ev) {
+ if (ev == EV_PREV) cfg.scaling = (uint8_t)((cfg.scaling + SCALE_COUNT - 1) % SCALE_COUNT);
+ if (ev == EV_NEXT) cfg.scaling = (uint8_t)((cfg.scaling + 1) % SCALE_COUNT);
+ strcpy(it->value, scale_names[cfg.scaling]);
+ if (ev == EV_PREV || ev == EV_NEXT) {
+ if (game) set_view();
+ return CB_REDRAW;
+ }
+ return CB_NONE;
+}
+static int speed_cb(item_t *it, int ev) {
+ if (ev == EV_PREV && cfg.speed > 0) cfg.speed--;
+ if (ev == EV_NEXT && cfg.speed < 4) cfg.speed++;
+ if (ev == EV_PREV || ev == EV_NEXT) frameskip = NP_MAX(1, cfg.speed * 3 / 2); /* (Retro-Go: (speed - 0.5) x 3) */
+ char *o = num(it->value, (cfg.speed + 1) / 2);
+ cat(o, cfg.speed & 1 ? ".0x" : ".5x");
+ return CB_NONE;
+}
+static const char *const gb_pal_names[GB_PAL_COUNT] = {"DMG", T("Pocket"), T("Light"), "GBC", "SGB"};
+static int gb_palette_cb(item_t *it, int ev) {
+ if (gb_is_cgb()) {
+ strcpy(it->value, "GBC");
+ return CB_NONE;
+ }
+ int p = cfg.gb_palette;
+ if (ev == EV_PREV) p = (p + GB_PAL_COUNT - 1) % GB_PAL_COUNT;
+ if (ev == EV_NEXT) p = (p + 1) % GB_PAL_COUNT;
+ strcpy(it->value, gb_pal_names[p]);
+ if (p != cfg.gb_palette) {
+ cfg.gb_palette = (uint8_t)p;
+ gb_set_palette(p);
+ return CB_REDRAW;
+ }
+ return CB_NONE;
+}
+static int rtc_field_cb(item_t *it, int ev) {
+ int t[4];
+ gb_get_time(&t[0], &t[1], &t[2], &t[3]);
+ static const int top[4] = {512, 24, 60, 60};
+ int k = (int)it->arg;
+ if (ev == EV_PREV) t[k] = (t[k] + top[k] - 1) % top[k];
+ if (ev == EV_NEXT) t[k] = (t[k] + 1) % top[k];
+ gb_set_time(t[0], t[1], t[2], t[3]);
+ char *o = it->value;
+ if (t[k] < 10) *o++ = '0';
+ num(o, (uint32_t)t[k]);
+ return CB_NONE;
+}
+static int rtc_cb(item_t *it, int ev) {
+ if (ev == EV_ENTER) {
+ item_t items[] = {OPTION(T("Day"), rtc_field_cb, 0), OPTION(T("Hour"), rtc_field_cb, 1),
+ OPTION(T("Min"), rtc_field_cb, 2), OPTION(T("Sec"), rtc_field_cb, 3)};
+ if (dialog_run(it->label, items, 4, 0) == DLG_HOME) return CB_SELECT;
+ }
+ int h, m;
+ gb_get_time(NULL, &h, &m, NULL);
+ char *o = it->value;
+ *o++ = (char)('0' + h / 10), *o++ = (char)('0' + h % 10), *o++ = ':';
+ *o++ = (char)('0' + m / 10), *o++ = (char)('0' + m % 10), *o = 0;
+ return CB_NONE;
+}
+static int autosave_cb(item_t *it, int ev) {
+ static const uint8_t steps[] = {0, 5, 10, 30, 60};
+ int k = 0;
+ while (k < 4 && steps[k] < cfg.autosave) k++;
+ if (ev == EV_PREV && k > 0) k--;
+ if (ev == EV_NEXT && k < 4) k++;
+ cfg.autosave = steps[k];
+ if (!cfg.autosave) strcpy(it->value, T("Off"));
+ else cat(num(it->value, cfg.autosave), "s");
+ return CB_NONE;
+}
+static const char *const nes_pal_names[NES_PAL_COUNT] = {"Nofrendo", "NTSC"};
+static int nes_palette_cb(item_t *it, int ev) {
+ int p = cfg.nes_palette;
+ if (ev == EV_PREV) p = (p + NES_PAL_COUNT - 1) % NES_PAL_COUNT;
+ if (ev == EV_NEXT) p = (p + 1) % NES_PAL_COUNT;
+ strcpy(it->value, nes_pal_names[p]);
+ if (p != cfg.nes_palette) {
+ cfg.nes_palette = (uint8_t)p;
+ nes_set_palette(p);
+ return CB_REDRAW;
+ }
+ return CB_NONE;
+}
+static int overscan_cb(item_t *it, int ev) {
+ if (ev == EV_PREV || ev == EV_NEXT) cfg.overscan ^= 1;
+ strcpy(it->value, cfg.overscan ? T("Auto") : T("Off"));
+ if (ev == EV_PREV || ev == EV_NEXT) {
+ set_view();
+ return CB_REDRAW;
+ }
+ return CB_NONE;
+}
+static int crop_cb(item_t *it, int ev) {
+ static const char *const names[] = {T("Never"), T("Auto"), T("Always")};
+ int v = cfg.crop_sides;
+ if (ev == EV_PREV) v = (v + 2) % 3;
+ if (ev == EV_NEXT) v = (v + 1) % 3;
+ strcpy(it->value, names[v]);
+ if (v != cfg.crop_sides) {
+ cfg.crop_sides = (uint8_t)v;
+ set_view();
+ return CB_REDRAW;
+ }
+ return CB_NONE;
+}
+static int sprite_limit_cb(item_t *it, int ev) {
+ if (ev == EV_PREV || ev == EV_NEXT) cfg.sprite_limit ^= 1, nes_set_sprite_limit(cfg.sprite_limit);
+ strcpy(it->value, cfg.sprite_limit ? T("On") : T("Off"));
+ return CB_NONE;
+}
+static int emulator_options_cb(item_t *it, int ev) {
+ if (ev != EV_ENTER) return CB_NONE;
+ int r;
+ if (is_gb()) {
+ item_t items[] = {OPTION(T("Palette"), gb_palette_cb, 0), OPTION(T("RTC config"), rtc_cb, 0),
+ OPTION(T("SRAM autosave"), autosave_cb, 0)};
+ if (!gb_has_rtc()) items[1].flags = IT_DISABLED;
+ r = dialog_run(it->label, items, 3, 0);
+ } else {
+ item_t items[] = {OPTION(T("Palette"), nes_palette_cb, 0), OPTION(T("Overscan"), overscan_cb, 0),
+ OPTION(T("Crop sides"), crop_cb, 0), OPTION(T("Sprite limit"), sprite_limit_cb, 0),
+ OPTION(T("SRAM autosave"), autosave_cb, 0)};
+ r = dialog_run(it->label, items, 5, 0);
+ }
+ return r == DLG_HOME ? CB_SELECT : CB_NONE;
+}
+static int options_menu(void) {
+ item_t items[] = {OPTION(T("Scaling"), scaling_cb, 0), OPTION(T("Speed"), speed_cb, 0),
+ {1, T("Emulator options"), "", IT_NORMAL, 0, emulator_options_cb, 0}};
+ int r = dialog_run(T("Options"), items, game ? 3 : 1, 0);
+ cfg_save();
+ return r;
+}
+
+static int controls(void) {
+ item_t items[] = {
+ {0, T("D-pad"), "", IT_MESSAGE, 1, NULL, 0}, {0, "A", "", IT_MESSAGE, 1, NULL, 0},
+ {0, "B", "", IT_MESSAGE, 1, NULL, 0}, {0, T("Select"), "", IT_MESSAGE, 1, NULL, 0},
+ {0, T("Start"), "", IT_MESSAGE, 1, NULL, 0}, {0, T("Menu"), "", IT_MESSAGE, 1, NULL, 0},
+ {0, T("Quit"), "", IT_MESSAGE, 1, NULL, 0}, ITEM(1, T("OK"))};
+ static const char *const keys[] = {T("arrows"), "OK", T("Back"), T("shift"), "EXE", T("Backspace"),
+ T("Home (saves)")};
+ for (int i = 0; i < 7; i++) strcpy(items[i].value, keys[i]);
+ return dialog_run(T("Controls"), items, 8, 7);
+}
+
+static int about(void) {
+ item_t items[] = {
+ {0, T("Retro-Go"), "ducalex", IT_MESSAGE, 1, NULL, 0}, {0, "Game Boy", "gnuboy", IT_MESSAGE, 1, NULL, 0},
+ {0, "NES", "nofrendo", IT_MESSAGE, 1, NULL, 0}, {0, T("Port"), "NumPlay", IT_MESSAGE, 1, NULL, 0},
+ MESSAGE(T("Not affiliated with Retro-Go")), ITEM(1, T("OK"))};
+ return dialog_run(T("About Retro-Go"), items, 6, 5);
+}
+
+/* Retro-Go's save slots: 0 to 3; the slot, DLG_BACK or DLG_HOME */
+static int slot_menu(const char *title, const rg_rom_t *r, bool used_only) {
+ item_t items[4];
+ int sel = last_slot >= 0 ? last_slot : 0;
+ for (int i = 0; i < 4; i++) {
+ static const char *const labels[] = {T("Slot 0"), T("Slot 1"), T("Slot 2"), T("Slot 3")};
+ bool used = state_exists(r, i);
+ items[i] = (item_t){i, labels[i], "", IT_NORMAL, 1, NULL, 0};
+ strcpy(items[i].value, !used ? T("empty") : i == last_slot ? T("last used") : T("saved"));
+ if (used_only && !used) items[i].flags = IT_DISABLED;
+ }
+ if (used_only && !state_exists(r, sel))
+ for (sel = 0; sel < 4 && items[sel].flags != IT_NORMAL; sel++) {}
+ return dialog_run(title, items, 4, sel);
+}
+
+enum { GAME_ON, GAME_PICKER, GAME_EXIT };
+
+static void saving(void) { message_box(NULL, T("Saving...")); }
+
+/* Home: the battery save, and a state in the slot this game came from or went to (a new game:
+ the first empty slot; none, no state rather than over another game), then out */
+static void save_and_exit(void) {
+ sram_save();
+ int slot = session_slot;
+ for (int i = 0; i < 4 && slot < 0; i++)
+ if (!state_exists(game, i)) slot = i;
+ if (slot >= 0) state_save(slot);
+ cfg_save();
+}
+
+static int game_menu(void) {
+ if (core_sram_dirty()) sram_save(); /* (in case the game ends here) */
+ enum { M_SAVE = 1000, M_SAVE_QUIT = 2000, M_LOAD = 3001, M_RESET = 3000, M_OPTIONS = 5500, M_CONTROLS = 5600,
+ M_ABOUT = 6000, M_QUIT = 7000 };
+ item_t items[] = {ITEM(M_SAVE, T("Save & Continue")), ITEM(M_SAVE_QUIT, T("Save & Quit")),
+ ITEM(M_LOAD, T("Load game")), ITEM(M_RESET, T("Reset")),
+ ITEM(M_OPTIONS, T("Options")), ITEM(M_CONTROLS, T("Controls")),
+ ITEM(M_ABOUT, T("About")), ITEM(M_QUIT, T("Quit"))};
+ int sel = dialog_run("Retro-Go", items, 8, 0), slot;
+ switch (sel) {
+ case DLG_HOME:
+ save_and_exit();
+ return GAME_EXIT;
+ case M_SAVE:
+ case M_SAVE_QUIT:
+ slot = slot_menu(T("Save"), game, false);
+ if (slot == DLG_HOME) return save_and_exit(), GAME_EXIT;
+ if (slot < 0) break;
+ saving();
+ if (!state_save(slot) || !sram_save()) {
+ if (alert(T("Not enough room"), T("Delete other saves to make room.")) == DLG_HOME) return save_and_exit(), GAME_EXIT;
+ break;
+ }
+ if (sel == M_SAVE_QUIT) return GAME_PICKER;
+ break;
+ case M_LOAD:
+ slot = slot_menu(T("Load"), game, true);
+ if (slot == DLG_HOME) return save_and_exit(), GAME_EXIT;
+ if (slot >= 0 && !state_load(slot) && alert(T("Load game"), T("This save can't be read.")) == DLG_HOME)
+ return save_and_exit(), GAME_EXIT;
+ break;
+ case M_RESET: {
+ item_t r[] = {ITEM(1, T("Soft reset")), ITEM(2, T("Hard reset"))};
+ int k = dialog_run(T("Reset Emulation?"), r, 2, 0);
+ if (k == DLG_HOME) return save_and_exit(), GAME_EXIT;
+ if (k > 0) core_reset(k == 2);
+ break;
+ }
+ case M_OPTIONS:
+ if (options_menu() == DLG_HOME) return save_and_exit(), GAME_EXIT;
+ break;
+ case M_CONTROLS:
+ if (controls() == DLG_HOME) return save_and_exit(), GAME_EXIT;
+ break;
+ case M_ABOUT:
+ if (about() == DLG_HOME) return save_and_exit(), GAME_EXIT;
+ break;
+ case M_QUIT: {
+ int k = confirm(T("Quit game?"), T("The battery save is kept."));
+ if (k == DLG_HOME) return save_and_exit(), GAME_EXIT;
+ if (k == 1) return sram_save(), GAME_PICKER;
+ break;
+ }
+ default:
+ break;
+ }
+ return GAME_ON;
+}
+
+/* the frame counters (perf_frames: tools/emu.py prints the frame rate from it) */
+uint32_t perf_frames, perf_drawn;
+
+static int play(const rg_rom_t *r, int slot) {
+ sys_now = r->system;
+ game = r;
+ game_crc = rom_crc(r);
+ int err = is_gb() ? gb_load(r->data, r->size) : nes_load(r->data, r->size);
+ if (err != RG_OK) {
+ game = NULL;
+ const char *why = err == RG_ERR_MAPPER ? T("This cartridge type isn't supported.")
+ : err == RG_ERR_MEMORY ? T("This game needs more memory than the calculator has.")
+ : T("This file isn't a game Retro-Go can read.");
+ return alert(T("Can't start the game"), why) == DLG_HOME ? GAME_EXIT : GAME_PICKER;
+ }
+ apply_settings();
+ sram_load();
+ last_slot = newest_slot(r), session_slot = -1;
+ if (slot >= 0 && !state_load(slot)) {
+ if (alert(T("Load game"), T("This save can't be read.")) == DLG_HOME) return GAME_EXIT;
+ }
+ set_view();
+ restore_behind = game_screen;
+ fill_screen(0, 0, SCREEN_W, SCREEN_H, BLACK);
+ if (!(cfg.flags & 1)) {
+ cfg.flags |= 1;
+ cfg_save();
+ if (controls() == DLG_HOME) return save_and_exit(), GAME_EXIT;
+ }
+ game_screen();
+ wait_release();
+
+ const bool gb = is_gb();
+ /* a frame: the Game Boy's 70224 clocks at 4.194304 MHz, the NES's 29780.5 at 1.789773 MHz */
+ const uint32_t frame_us = gb ? 16742 : 16639;
+ uint32_t next_us = millis() * 1000u, second = millis(), frames = 0, busy = 0;
+ int result = GAME_ON;
+ frameskip = NP_MAX(1, cfg.speed * 3 / 2), skip = 0, autosave_at = 0;
+ while (result == GAME_ON) {
+ uint64_t k = eadk_keyboard_scan();
+ if (k & (KEY(eadk_key_home) | KEY(eadk_key_on_off))) {
+ saving();
+ save_and_exit();
+ result = GAME_EXIT;
+ break;
+ }
+ if (k & KEY(eadk_key_backspace)) {
+ wait_release();
+ result = game_menu();
+ if (result != GAME_ON) break;
+ game_screen();
+ wait_release();
+ next_us = millis() * 1000u;
+ continue;
+ }
+ int pad = 0;
+ if (k & KEY(eadk_key_up)) pad |= RG_PAD_UP;
+ if (k & KEY(eadk_key_down)) pad |= RG_PAD_DOWN;
+ if (k & KEY(eadk_key_left)) pad |= RG_PAD_LEFT;
+ if (k & KEY(eadk_key_right)) pad |= RG_PAD_RIGHT;
+ if (k & KEY(eadk_key_ok)) pad |= RG_PAD_A;
+ if (k & KEY(eadk_key_back)) pad |= RG_PAD_B;
+ if (k & KEY(eadk_key_shift)) pad |= RG_PAD_SELECT;
+ if (k & KEY(eadk_key_exe)) pad |= RG_PAD_START;
+
+ uint32_t t0 = millis();
+ bool draw = skip == 0;
+ if (gb) gb_set_pad(pad), gb_run_frame(draw);
+ else nes_set_pad(pad), nes_run_frame(draw);
+ if (draw) flush(), redraw_all = false, perf_drawn++;
+ perf_frames++, frames++;
+ uint32_t elapsed = millis() - t0;
+ busy += elapsed;
+
+ /* the battery save, a while after the game wrote it */
+ if (cfg.autosave && core_sram_dirty()) {
+ if (!autosave_at) autosave_at = t0 + cfg.autosave * 1000u + 1;
+ else if ((int32_t)(t0 - autosave_at) >= 0) sram_save();
+ }
+
+ /* Retro-Go's frame skipping: after a frame drawn, `frameskip` frames not drawn (one at least) */
+ if (skip == 0) skip = frameskip;
+ else skip--;
+
+ /* the game's own speed (times Retro-Go's Speed), whatever the frames cost */
+ next_us += frame_us * 2 / (cfg.speed + 1);
+ uint32_t now_us = millis() * 1000u;
+ if ((int32_t)(next_us - now_us) > 0) eadk_timing_usleep(next_us - now_us);
+ else if ((int32_t)(now_us - next_us) > 100000) next_us = now_us; /* (too far behind: start again from now) */
+
+ /* once a second, Retro-Go's monitor: more frames skipped when the speed falls, fewer when it's back */
+ uint32_t now = millis();
+ if (now - second >= 1000) {
+ uint32_t span = now - second, target = (uint32_t)(span * 1000u / frame_us * (cfg.speed + 1) / 2);
+ uint32_t speed = target ? frames * 100 / target : 100, busy_pc = busy * 100 / span;
+ if (speed > 99 && busy_pc < 85 && frameskip > 1) frameskip--;
+ else if (speed < 96 && busy_pc > 85 && frameskip < 5) frameskip++;
+ second = now, frames = 0, busy = 0;
+ }
+ }
+ restore_behind = NULL;
+ game = NULL;
+ return result;
+}
+
+/* ------------------------------------------------------------ the launcher */
+static int tab, cursor; /* the tab shown (in tabs[]), the game chosen (in roms[]) */
+static bool browse;
+
+static void picker_scene(void *ctx) {
+ (void)ctx;
+ int sys = ntabs ? tabs[tab] : 0;
+ background(sys, browse ? 4 : 0);
+ if (!ntabs) { /* (no games: Retro-Go's welcome, and where they come from) */
+ header(0, 0);
+ static const char *const lines[] = {T("Welcome to Retro-Go!"), "", T("Add games on NumPlay's"),
+ T("customizer website:"), T("Game Boy, Game Boy Color"), T("and NES games."),
+ "", T("Home: quit")};
+ for (int i = 0; i < 8; i++) gfx_text(&np_font_body, 8, 80 + 18 * i, lines[i], i ? 0xAD55 : WHITE, 256);
+ return;
+ }
+ if (!browse) {
+ header(sys, (SCREEN_H - HEADER_H) / 2);
+ gfx_text_center(&np_font_small, SCREEN_W / 2, SCREEN_H - 6, T("Left/Right: system OK: games Home: quit"),
+ WHITE, 220);
+ return;
+ }
+ header(sys, 0);
+ int first = tab_first(sys), count = tab_count(sys), at = cursor - first;
+ char s[24], *o = num(s, (uint32_t)at + 1);
+ o = cat(o, " / ");
+ num(o, (uint32_t)count);
+ gfx_text(&np_font_small, LOGO_W + 12, HEADER_H - 5, s, 0xFFDE, 256);
+ /* the list, the game chosen in the middle line (Retro-Go's center scrolling) */
+ int top = HEADER_H + 6, bottom = SCREEN_H - 14, lines = (bottom - top) / ROW_H;
+ top += (bottom - top - lines * ROW_H) / 2;
+ for (int i = 0; i < lines; i++) {
+ int idx = at - lines / 2 + i, y = top + i * ROW_H;
+ if (idx < 0 || idx >= count) continue;
+ char name[41];
+ rg_rom_name(&roms[first + idx], name, sizeof name);
+ bool sel = idx == at;
+ if (sel) gfx_fill(0, y, SCREEN_W, ROW_H, WHITE);
+ gfx_text(&np_font_body, 4, y + 12, name, sel ? BLACK : 0xAD55, 256);
+ }
+ gfx_text_center(&np_font_small, SCREEN_W / 2, SCREEN_H - 4,
+ T("OK: play Back: systems Left/Right: system"), WHITE, 200);
+}
+
+static void picker_draw(void) { render_rect(picker_scene, NULL, 0, 0, SCREEN_W, SCREEN_H); }
+
+static int properties(const rg_rom_t *r) {
+ char name[41], size[16], crc[12];
+ rg_rom_name(r, name, sizeof name);
+ cat(num(size, r->size / 1024), " KB");
+ message_box(NULL, T("Reading..."));
+ hex8(crc, rom_crc(r));
+ item_t items[] = {{0, T("Name"), "", IT_MESSAGE, 1, NULL, 0}, {0, T("System"), "", IT_MESSAGE, 1, NULL, 0},
+ {0, T("Size"), "", IT_MESSAGE, 1, NULL, 0}, {0, "CRC32", "", IT_MESSAGE, 1, NULL, 0},
+ ITEM(1, T("Close"))};
+ memcpy(items[0].value, name, sizeof items[0].value - 1);
+ items[0].value[sizeof items[0].value - 1] = 0;
+ strcpy(items[1].value, sys_short[r->system]);
+ strcpy(items[2].value, size);
+ strcpy(items[3].value, crc);
+ return dialog_run(T("File properties"), items, 5, 4);
+}
+
+/* Retro-Go's menu for a game: Resume game, New game, Delete save, Properties */
+static int file_menu(const rg_rom_t *r) {
+ if (!sys_supported(r->system)) {
+ return alert(sys_name[r->system], T("Retro-Go on the calculator plays Game Boy, Game Boy Color and NES games."));
+ }
+ message_box(NULL, T("Reading..."));
+ bool has_save = false, has_sram = false;
+ for (int i = 0; i < 4; i++) has_save |= state_exists(r, i);
+ char name[20];
+ uint32_t len;
+ save_name(name, r, -1);
+ has_sram = np_file_read(name, &len) != NULL;
+ item_t items[] = {ITEM(0, T("Resume game")), ITEM(1, T("New game")), ITEM(2, T("Delete save")),
+ ITEM(4, T("Properties"))};
+ if (!has_save) items[0].flags = IT_DISABLED;
+ if (!has_save && !has_sram) items[2].flags = IT_DISABLED;
+ int sel = dialog_run(NULL, items, 4, has_save ? 0 : 1), slot = -1;
+ switch (sel) {
+ case 0:
+ last_slot = newest_slot(r);
+ slot = slot_menu(T("Resume"), r, true);
+ if (slot == DLG_HOME) return GAME_EXIT;
+ if (slot < 0) return GAME_PICKER;
+ /* fall through */
+ case 1:
+ cfg_save();
+ return play(r, slot);
+ case 2:
+ for (;;) {
+ last_slot = newest_slot(r);
+ slot = slot_menu(T("Delete save?"), r, true);
+ if (slot == DLG_HOME) return GAME_EXIT;
+ if (slot < 0) break;
+ save_name(name, r, slot);
+ file_delete(name);
+ }
+ if (has_sram) {
+ int k = confirm(T("Delete sram file?"), NULL);
+ if (k == DLG_HOME) return GAME_EXIT;
+ if (k == 1) save_name(name, r, -1), file_delete(name);
+ }
+ return GAME_PICKER;
+ case 4:
+ return properties(r) == DLG_HOME ? GAME_EXIT : GAME_PICKER;
+ case DLG_HOME:
+ return GAME_EXIT;
+ default:
+ return GAME_PICKER;
+ }
+}
+
+static void launcher_menu_redraw(void) { picker_draw(); }
+
+int main(void) {
+ np_app_begin();
+ color_t *their_strip = gfx_buf;
+ gfx_buf = strip;
+ cfg_load();
+ int n = rg_romtable_read(np_roms, TABLE_LIMIT, roms, RG_MAX_ROMS);
+ nroms = n > 0 ? n : 0;
+ ntabs = 0;
+ for (unsigned i = 0; i < sizeof tab_order; i++)
+ if (tab_count(tab_order[i])) tabs[ntabs++] = tab_order[i];
+ tab = cfg.tab < ntabs ? cfg.tab : 0;
+ browse = cfg.browse;
+ cursor = ntabs ? tab_first(tabs[tab]) + NP_MIN(cfg.cursor[tabs[tab]], tab_count(tabs[tab]) - 1) : 0;
+ restore_behind = launcher_menu_redraw;
+ picker_draw();
+ wait_release();
+ bool quit = false;
+ while (!quit) {
+ eadk_timing_msleep(16);
+ uint64_t hit = key_hits();
+ if (hit & (KEY(eadk_key_home) | KEY(eadk_key_on_off))) break;
+ if (hit & KEY(eadk_key_backspace)) { /* Retro-Go's launcher menu */
+ item_t items[] = {ITEM(1, T("Options")), ITEM(2, T("Controls")), ITEM(3, T("About")), ITEM(4, T("Quit"))};
+ int k = dialog_run("Retro-Go", items, 4, 0);
+ if (k == DLG_HOME || k == 4) break;
+ if (k == 1 && options_menu() == DLG_HOME) break;
+ if (k == 2 && controls() == DLG_HOME) break;
+ if (k == 3 && about() == DLG_HOME) break;
+ continue;
+ }
+ if (!ntabs) {
+ if (hit & KEY(eadk_key_back)) break;
+ continue;
+ }
+ int sys = tabs[tab], first = tab_first(sys), count = tab_count(sys), change = 0;
+ bool redraw = false;
+ if (!browse) {
+ if (hit & (KEY(eadk_key_left) | KEY(eadk_key_up))) change = -1;
+ if (hit & (KEY(eadk_key_right) | KEY(eadk_key_down))) change = 1;
+ if (hit & (KEY(eadk_key_ok) | KEY(eadk_key_exe))) browse = true, redraw = true;
+ if (hit & KEY(eadk_key_back)) break;
+ } else {
+ if (hit & KEY(eadk_key_up)) cursor = first + (cursor - first + count - 1) % count, redraw = true;
+ if (hit & KEY(eadk_key_down)) cursor = first + (cursor - first + 1) % count, redraw = true;
+ if (hit & KEY(eadk_key_left)) change = -1;
+ if (hit & KEY(eadk_key_right)) change = 1;
+ if (hit & KEY(eadk_key_back)) browse = false, redraw = true;
+ if (hit & (KEY(eadk_key_ok) | KEY(eadk_key_exe))) {
+ cfg.tab = (uint8_t)tab, cfg.browse = browse, cfg.cursor[sys] = (uint8_t)(cursor - first);
+ wait_release();
+ int r = file_menu(&roms[cursor]);
+ restore_behind = launcher_menu_redraw;
+ if (r == GAME_EXIT) quit = true;
+ else picker_draw();
+ wait_release();
+ continue;
+ }
+ }
+ if (change && ntabs > 1) {
+ cfg.cursor[sys] = (uint8_t)(cursor - first);
+ tab = (tab + change + ntabs) % ntabs;
+ sys = tabs[tab];
+ cursor = tab_first(sys) + NP_MIN(cfg.cursor[sys], tab_count(sys) - 1);
+ redraw = true;
+ }
+ if (redraw) picker_draw();
+ }
+ if (ntabs) {
+ int sys = tabs[tab];
+ cfg.tab = (uint8_t)tab, cfg.browse = browse, cfg.cursor[sys] = (uint8_t)(cursor - tab_first(sys));
+ }
+ cfg_save();
+ gfx_buf = their_strip;
+ return np_app_end();
+}
diff --git a/games/retrogo/src/nes/COPYING.LGPL b/games/retrogo/src/nes/COPYING.LGPL
new file mode 100644
index 00000000..a5dee30e
--- /dev/null
+++ b/games/retrogo/src/nes/COPYING.LGPL
@@ -0,0 +1,491 @@
+ GNU LIBRARY GENERAL PUBLIC LICENSE
+ Version 2, June 1991
+
+ Copyright (C) 1991 Free Software Foundation, Inc.
+ 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
+ Everyone is permitted to copy and distribute verbatim copies
+ of this license document, but changing it is not allowed.
+
+[This is the first released version of the library GPL. It is
+ numbered 2 because it goes with version 2 of the ordinary GPL.]
+
+ Preamble
+
+ The licenses for most software are designed to take away your
+freedom to share and change it. By contrast, the GNU General Public
+Licenses are intended to guarantee your freedom to share and change
+free software--to make sure the software is free for all its users.
+
+ This license, the Library General Public License, applies to some
+specially designated Free Software Foundation software, and to any
+other libraries whose authors decide to use it. You can use it for
+your libraries, too.
+
+ When we speak of free software, we are referring to freedom, not
+price. Our General Public Licenses are designed to make sure that you
+have the freedom to distribute copies of free software (and charge for
+this service if you wish), that you receive source code or can get it
+if you want it, that you can change the software or use pieces of it
+in new free programs; and that you know you can do these things.
+
+ To protect your rights, we need to make restrictions that forbid
+anyone to deny you these rights or to ask you to surrender the rights.
+These restrictions translate to certain responsibilities for you if
+you distribute copies of the library, or if you modify it.
+
+ For example, if you distribute copies of the library, whether gratis
+or for a fee, you must give the recipients all the rights that we gave
+you. You must make sure that they, too, receive or can get the source
+code. If you link a program with the library, you must provide
+complete object files to the recipients so that they can relink them
+with the library, after making changes to the library and recompiling
+it. And you must show them these terms so they know their rights.
+
+ Our method of protecting your rights has two steps: (1) copyright
+the library, and (2) offer you this license which gives you legal
+permission to copy, distribute and/or modify the library.
+
+ Also, for each distributor's protection, we want to make certain
+that everyone understands that there is no warranty for this free
+library. If the library is modified by someone else and passed on, we
+want its recipients to know that what they have is not the original
+version, so that any problems introduced by others will not reflect on
+the original authors' reputations.
+
+
+ Finally, any free program is threatened constantly by software
+patents. We wish to avoid the danger that companies distributing free
+software will individually obtain patent licenses, thus in effect
+transforming the program into proprietary software. To prevent this,
+we have made it clear that any patent must be licensed for everyone's
+free use or not licensed at all.
+
+ Most GNU software, including some libraries, is covered by the ordinary
+GNU General Public License, which was designed for utility programs. This
+license, the GNU Library General Public License, applies to certain
+designated libraries. This license is quite different from the ordinary
+one; be sure to read it in full, and don't assume that anything in it is
+the same as in the ordinary license.
+
+ The reason we have a separate public license for some libraries is that
+they blur the distinction we usually make between modifying or adding to a
+program and simply using it. Linking a program with a library, without
+changing the library, is in some sense simply using the library, and is
+analogous to running a utility program or application program. However, in
+a textual and legal sense, the linked executable is a combined work, a
+derivative of the original library, and the ordinary General Public License
+treats it as such.
+
+ Because of this blurred distinction, using the ordinary General
+Public License for libraries did not effectively promote software
+sharing, because most developers did not use the libraries. We
+concluded that weaker conditions might promote sharing better.
+
+ However, unrestricted linking of non-free programs would deprive the
+users of those programs of all benefit from the free status of the
+libraries themselves. This Library General Public License is intended to
+permit developers of non-free programs to use free libraries, while
+preserving your freedom as a user of such programs to change the free
+libraries that are incorporated in them. (We have not seen how to achieve
+this as regards changes in header files, but we have achieved it as regards
+changes in the actual functions of the Library.) The hope is that this
+will lead to faster development of free libraries.
+
+ The precise terms and conditions for copying, distribution and
+modification follow. Pay close attention to the difference between a
+"work based on the library" and a "work that uses the library". The
+former contains code derived from the library, while the latter only
+works together with the library.
+
+ Note that it is possible for a library to be covered by the ordinary
+General Public License rather than by this special one.
+
+
+ GNU LIBRARY GENERAL PUBLIC LICENSE
+ TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION
+
+ 0. This License Agreement applies to any software library which
+contains a notice placed by the copyright holder or other authorized
+party saying it may be distributed under the terms of this Library
+General Public License (also called "this License"). Each licensee is
+addressed as "you".
+
+ A "library" means a collection of software functions and/or data
+prepared so as to be conveniently linked with application programs
+(which use some of those functions and data) to form executables.
+
+ The "Library", below, refers to any such software library or work
+which has been distributed under these terms. A "work based on the
+Library" means either the Library or any derivative work under
+copyright law: that is to say, a work containing the Library or a
+portion of it, either verbatim or with modifications and/or translated
+straightforwardly into another language. (Hereinafter, translation is
+included without limitation in the term "modification".)
+
+ "Source code" for a work means the preferred form of the work for
+making modifications to it. For a library, complete source code means
+all the source code for all modules it contains, plus any associated
+interface definition files, plus the scripts used to control compilation
+and installation of the library.
+
+ Activities other than copying, distribution and modification are not
+covered by this License; they are outside its scope. The act of
+running a program using the Library is not restricted, and output from
+such a program is covered only if its contents constitute a work based
+on the Library (independent of the use of the Library in a tool for
+writing it). Whether that is true depends on what the Library does
+and what the program that uses the Library does.
+
+ 1. You may copy and distribute verbatim copies of the Library's
+complete source code as you receive it, in any medium, provided that
+you conspicuously and appropriately publish on each copy an
+appropriate copyright notice and disclaimer of warranty; keep intact
+all the notices that refer to this License and to the absence of any
+warranty; and distribute a copy of this License along with the
+Library.
+
+ You may charge a fee for the physical act of transferring a copy,
+and you may at your option offer warranty protection in exchange for a
+fee.
+
+
+ 2. You may modify your copy or copies of the Library or any portion
+of it, thus forming a work based on the Library, and copy and
+distribute such modifications or work under the terms of Section 1
+above, provided that you also meet all of these conditions:
+
+ a) The modified work must itself be a software library.
+
+ b) You must cause the files modified to carry prominent notices
+ stating that you changed the files and the date of any change.
+
+ c) You must cause the whole of the work to be licensed at no
+ charge to all third parties under the terms of this License.
+
+ d) If a facility in the modified Library refers to a function or a
+ table of data to be supplied by an application program that uses
+ the facility, other than as an argument passed when the facility
+ is invoked, then you must make a good faith effort to ensure that,
+ in the event an application does not supply such function or
+ table, the facility still operates, and performs whatever part of
+ its purpose remains meaningful.
+
+ (For example, a function in a library to compute square roots has
+ a purpose that is entirely well-defined independent of the
+ application. Therefore, Subsection 2d requires that any
+ application-supplied function or table used by this function must
+ be optional: if the application does not supply it, the square
+ root function must still compute square roots.)
+
+These requirements apply to the modified work as a whole. If
+identifiable sections of that work are not derived from the Library,
+and can be reasonably considered independent and separate works in
+themselves, then this License, and its terms, do not apply to those
+sections when you distribute them as separate works. But when you
+distribute the same sections as part of a whole which is a work based
+on the Library, the distribution of the whole must be on the terms of
+this License, whose permissions for other licensees extend to the
+entire whole, and thus to each and every part regardless of who wrote
+it.
+
+Thus, it is not the intent of this section to claim rights or contest
+your rights to work written entirely by you; rather, the intent is to
+exercise the right to control the distribution of derivative or
+collective works based on the Library.
+
+In addition, mere aggregation of another work not based on the Library
+with the Library (or with a work based on the Library) on a volume of
+a storage or distribution medium does not bring the other work under
+the scope of this License.
+
+ 3. You may opt to apply the terms of the ordinary GNU General Public
+License instead of this License to a given copy of the Library. To do
+this, you must alter all the notices that refer to this License, so
+that they refer to the ordinary GNU General Public License, version 2,
+instead of to this License. (If a newer version than version 2 of the
+ordinary GNU General Public License has appeared, then you can specify
+that version instead if you wish.) Do not make any other change in
+these notices.
+
+
+ Once this change is made in a given copy, it is irreversible for
+that copy, so the ordinary GNU General Public License applies to all
+subsequent copies and derivative works made from that copy.
+
+ This option is useful when you wish to copy part of the code of
+the Library into a program that is not a library.
+
+ 4. You may copy and distribute the Library (or a portion or
+derivative of it, under Section 2) in object code or executable form
+under the terms of Sections 1 and 2 above provided that you accompany
+it with the complete corresponding machine-readable source code, which
+must be distributed under the terms of Sections 1 and 2 above on a
+medium customarily used for software interchange.
+
+ If distribution of object code is made by offering access to copy
+from a designated place, then offering equivalent access to copy the
+source code from the same place satisfies the requirement to
+distribute the source code, even though third parties are not
+compelled to copy the source along with the object code.
+
+ 5. A program that contains no derivative of any portion of the
+Library, but is designed to work with the Library by being compiled or
+linked with it, is called a "work that uses the Library". Such a
+work, in isolation, is not a derivative work of the Library, and
+therefore falls outside the scope of this License.
+
+ However, linking a "work that uses the Library" with the Library
+creates an executable that is a derivative of the Library (because it
+contains portions of the Library), rather than a "work that uses the
+library". The executable is therefore covered by this License.
+Section 6 states terms for distribution of such executables.
+
+ When a "work that uses the Library" uses material from a header file
+that is part of the Library, the object code for the work may be a
+derivative work of the Library even though the source code is not.
+Whether this is true is especially significant if the work can be
+linked without the Library, or if the work is itself a library. The
+threshold for this to be true is not precisely defined by law.
+
+ If such an object file uses only numerical parameters, data
+structure layouts and accessors, and small macros and small inline
+functions (ten lines or less in length), then the use of the object
+file is unrestricted, regardless of whether it is legally a derivative
+work. (Executables containing this object code plus portions of the
+Library will still fall under Section 6.)
+
+ Otherwise, if the work is a derivative of the Library, you may
+distribute the object code for the work under the terms of Section 6.
+Any executables containing that work also fall under Section 6,
+whether or not they are linked directly with the Library itself.
+
+
+ 6. As an exception to the Sections above, you may also compile or
+link a "work that uses the Library" with the Library to produce a
+work containing portions of the Library, and distribute that work
+under terms of your choice, provided that the terms permit
+modification of the work for the customer's own use and reverse
+engineering for debugging such modifications.
+
+ You must give prominent notice with each copy of the work that the
+Library is used in it and that the Library and its use are covered by
+this License. You must supply a copy of this License. If the work
+during execution displays copyright notices, you must include the
+copyright notice for the Library among them, as well as a reference
+directing the user to the copy of this License. Also, you must do one
+of these things:
+
+ a) Accompany the work with the complete corresponding
+ machine-readable source code for the Library including whatever
+ changes were used in the work (which must be distributed under
+ Sections 1 and 2 above); and, if the work is an executable linked
+ with the Library, with the complete machine-readable "work that
+ uses the Library", as object code and/or source code, so that the
+ user can modify the Library and then relink to produce a modified
+ executable containing the modified Library. (It is understood
+ that the user who changes the contents of definitions files in the
+ Library will not necessarily be able to recompile the application
+ to use the modified definitions.)
+
+ b) Accompany the work with a written offer, valid for at
+ least three years, to give the same user the materials
+ specified in Subsection 6a, above, for a charge no more
+ than the cost of performing this distribution.
+
+ c) If distribution of the work is made by offering access to copy
+ from a designated place, offer equivalent access to copy the above
+ specified materials from the same place.
+
+ d) Verify that the user has already received a copy of these
+ materials or that you have already sent this user a copy.
+
+ For an executable, the required form of the "work that uses the
+Library" must include any data and utility programs needed for
+reproducing the executable from it. However, as a special exception,
+the source code distributed need not include anything that is normally
+distributed (in either source or binary form) with the major
+components (compiler, kernel, and so on) of the operating system on
+which the executable runs, unless that component itself accompanies
+the executable.
+
+ It may happen that this requirement contradicts the license
+restrictions of other proprietary libraries that do not normally
+accompany the operating system. Such a contradiction means you cannot
+use both them and the Library together in an executable that you
+distribute.
+
+
+ 7. You may place library facilities that are a work based on the
+Library side-by-side in a single library together with other library
+facilities not covered by this License, and distribute such a combined
+library, provided that the separate distribution of the work based on
+the Library and of the other library facilities is otherwise
+permitted, and provided that you do these two things:
+
+ a) Accompany the combined library with a copy of the same work
+ based on the Library, uncombined with any other library
+ facilities. This must be distributed under the terms of the
+ Sections above.
+
+ b) Give prominent notice with the combined library of the fact
+ that part of it is a work based on the Library, and explaining
+ where to find the accompanying uncombined form of the same work.
+
+ 8. You may not copy, modify, sublicense, link with, or distribute
+the Library except as expressly provided under this License. Any
+attempt otherwise to copy, modify, sublicense, link with, or
+distribute the Library is void, and will automatically terminate your
+rights under this License. However, parties who have received copies,
+or rights, from you under this License will not have their licenses
+terminated so long as such parties remain in full compliance.
+
+ 9. You are not required to accept this License, since you have not
+signed it. However, nothing else grants you permission to modify or
+distribute the Library or its derivative works. These actions are
+prohibited by law if you do not accept this License. Therefore, by
+modifying or distributing the Library (or any work based on the
+Library), you indicate your acceptance of this License to do so, and
+all its terms and conditions for copying, distributing or modifying
+the Library or works based on it.
+
+ 10. Each time you redistribute the Library (or any work based on the
+Library), the recipient automatically receives a license from the
+original licensor to copy, distribute, link with or modify the Library
+subject to these terms and conditions. You may not impose any further
+restrictions on the recipients' exercise of the rights granted herein.
+You are not responsible for enforcing compliance by third parties to
+this License.
+
+
+ 11. If, as a consequence of a court judgment or allegation of patent
+infringement or for any other reason (not limited to patent issues),
+conditions are imposed on you (whether by court order, agreement or
+otherwise) that contradict the conditions of this License, they do not
+excuse you from the conditions of this License. If you cannot
+distribute so as to satisfy simultaneously your obligations under this
+License and any other pertinent obligations, then as a consequence you
+may not distribute the Library at all. For example, if a patent
+license would not permit royalty-free redistribution of the Library by
+all those who receive copies directly or indirectly through you, then
+the only way you could satisfy both it and this License would be to
+refrain entirely from distribution of the Library.
+
+If any portion of this section is held invalid or unenforceable under any
+particular circumstance, the balance of the section is intended to apply,
+and the section as a whole is intended to apply in other circumstances.
+
+It is not the purpose of this section to induce you to infringe any
+patents or other property right claims or to contest validity of any
+such claims; this section has the sole purpose of protecting the
+integrity of the free software distribution system which is
+implemented by public license practices. Many people have made
+generous contributions to the wide range of software distributed
+through that system in reliance on consistent application of that
+system; it is up to the author/donor to decide if he or she is willing
+to distribute software through any other system and a licensee cannot
+impose that choice.
+
+This section is intended to make thoroughly clear what is believed to
+be a consequence of the rest of this License.
+
+ 12. If the distribution and/or use of the Library is restricted in
+certain countries either by patents or by copyrighted interfaces, the
+original copyright holder who places the Library under this License may add
+an explicit geographical distribution limitation excluding those countries,
+so that distribution is permitted only in or among countries not thus
+excluded. In such case, this License incorporates the limitation as if
+written in the body of this License.
+
+ 13. The Free Software Foundation may publish revised and/or new
+versions of the Library General Public License from time to time.
+Such new versions will be similar in spirit to the present version,
+but may differ in detail to address new problems or concerns.
+
+Each version is given a distinguishing version number. If the Library
+specifies a version number of this License which applies to it and
+"any later version", you have the option of following the terms and
+conditions either of that version or of any later version published by
+the Free Software Foundation. If the Library does not specify a
+license version number, you may choose any version ever published by
+the Free Software Foundation.
+
+
+ 14. If you wish to incorporate parts of the Library into other free
+programs whose distribution conditions are incompatible with these,
+write to the author to ask for permission. For software which is
+copyrighted by the Free Software Foundation, write to the Free
+Software Foundation; we sometimes make exceptions for this. Our
+decision will be guided by the two goals of preserving the free status
+of all derivatives of our free software and of promoting the sharing
+and reuse of software generally.
+
+ NO WARRANTY
+
+ 15. BECAUSE THE LIBRARY IS LICENSED FREE OF CHARGE, THERE IS NO
+WARRANTY FOR THE LIBRARY, TO THE EXTENT PERMITTED BY APPLICABLE LAW.
+EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR
+OTHER PARTIES PROVIDE THE LIBRARY "AS IS" WITHOUT WARRANTY OF ANY
+KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE
+IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
+PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE
+LIBRARY IS WITH YOU. SHOULD THE LIBRARY PROVE DEFECTIVE, YOU ASSUME
+THE COST OF ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
+
+ 16. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN
+WRITING WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY
+AND/OR REDISTRIBUTE THE LIBRARY AS PERMITTED ABOVE, BE LIABLE TO YOU
+FOR DAMAGES, INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR
+CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OR INABILITY TO USE THE
+LIBRARY (INCLUDING BUT NOT LIMITED TO LOSS OF DATA OR DATA BEING
+RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD PARTIES OR A
+FAILURE OF THE LIBRARY TO OPERATE WITH ANY OTHER SOFTWARE), EVEN IF
+SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH
+DAMAGES.
+
+ END OF TERMS AND CONDITIONS
+
+
+ How to Apply These Terms to Your New Libraries
+
+ If you develop a new library, and you want it to be of the greatest
+possible use to the public, we recommend making it free software that
+everyone can redistribute and change. You can do so by permitting
+redistribution under these terms (or, alternatively, under the terms of the
+ordinary General Public License).
+
+ To apply these terms, attach the following notices to the library. It is
+safest to attach them to the start of each source file to most effectively
+convey the exclusion of warranty; and each file should have at least the
+"copyright" line and a pointer to where the full notice is found.
+
+ <one line to give the library's name and a brief idea of what it does.>
+ Copyright (C) <year> <name of author>
+
+ This library is free software; you can redistribute it and/or
+ modify it under the terms of the GNU Library General Public
+ License as published by the Free Software Foundation; either
+ version 2 of the License, or (at your option) any later version.
+
+ This library is distributed in the hope that it will be useful,
+ but WITHOUT ANY WARRANTY; without even the implied warranty of
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ Library General Public License for more details.
+
+ You should have received a copy of the GNU Library General Public
+ License along with this library; if not, write to the
+ Free Software Foundation, Inc., 59 Temple Place - Suite 330,
+ Boston, MA 02111-1307 USA.
+
+Also add information on how to contact you by electronic and paper mail.
+
+You should also get your employer (if you work as a programmer) or your
+school, if any, to sign a "copyright disclaimer" for the library, if
+necessary. Here is a sample; alter the names:
+
+ Yoyodyne, Inc., hereby disclaims all copyright interest in the
+ library `Frob' (a library for tweaking knobs) written by James Random Hacker.
+
+ <signature of Ty Coon>, 1 April 1990
+ Ty Coon, President of Vice
+
+That's all there is to it!
diff --git a/games/retrogo/src/nes/libsnss.h b/games/retrogo/src/nes/libsnss.h
new file mode 100644
index 00000000..03962c4b
--- /dev/null
+++ b/games/retrogo/src/nes/libsnss.h
@@ -0,0 +1,25 @@
+/* The part of a mapper a save state keeps besides its banks: what nofrendo's mappers read and
+ * write in their get_state and set_state (written for Retro-Go on NumPlay with the names those
+ * mappers use; GPL-3.0-or-later). */
+#ifndef _LIBSNSS_H_
+#define _LIBSNSS_H_
+
+typedef struct
+{
+ union
+ {
+ struct { unsigned char registers[4], latch, numberOfBits; } mapper1;
+ struct { unsigned char irqCounter, irqLatchCounter, irqCounterEnabled, last8000Write; } mapper4;
+ struct { unsigned char dummy; } mapper5;
+ struct { unsigned char latch[2], lastB000Write, lastC000Write, lastD000Write, lastE000Write; } mapper9;
+ struct { unsigned char irqCounterLowByte, irqCounterHighByte, irqCounterEnabled; } mapper16;
+ struct { unsigned char irqCounterLowByte, irqCounterHighByte, irqCounterEnabled; } mapper18;
+ struct { unsigned char irqCounterLowByte, irqCounterHighByte, irqCounterEnabled; } mapper19;
+ struct { unsigned char irqCounter, irqCounterEnabled; } mapper21;
+ struct { unsigned char irqCounter, irqCounterEnabled; } mapper24;
+ struct { unsigned char irqCounter, irqCounterEnabled; } mapper40;
+ unsigned char bytes[32];
+ } extraData;
+} SnssMapperBlock;
+
+#endif
diff --git a/games/retrogo/src/nes/mappers/map000.c b/games/retrogo/src/nes/mappers/map000.c
new file mode 100644
index 00000000..bc50d038
--- /dev/null
+++ b/games/retrogo/src/nes/mappers/map000.c
@@ -0,0 +1,41 @@
+/*
+** Nofrendo (c) 1998-2000 Matthew Conte ([email protected])
+**
+**
+** This program is free software; you can redistribute it and/or modify it under the terms of
+** the GNU General Public License as published by the Free Software Foundation; either version 3
+** of the License, or (at your option) any later version. (Nofrendo was released under version
+** 2 of the GNU Library General Public License; as its section 3 allows, this copy, changed for
+** Retro-Go on NumPlay, is under the GNU General Public License instead.)
+**
+** This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY;
+** without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
+** See the GNU General Public License for more details.
+**
+** Any permitted reproduction of these routines, in whole or in part,
+** must bear this legend.
+**
+**
+** map0.c
+**
+** mapper 0 interface
+** $Id: map000.c,v 1.2 2001/04/27 14:37:11 neil Exp $
+*/
+
+#include "noftypes.h"
+#include "nes_mmc.h"
+
+mapintf_t map0_intf =
+{
+ 0, /* mapper number */
+ "None", /* mapper name */
+ NULL, /* init routine */
+ NULL, /* vblank callback */
+ NULL, /* hblank callback */
+ NULL, /* get state (snss) */
+ NULL, /* set state (snss) */
+ NULL, /* memory read structure */
+ NULL, /* memory write structure */
+ NULL /* external sound device */
+};
+
diff --git a/games/retrogo/src/nes/mappers/map001.c b/games/retrogo/src/nes/mappers/map001.c
new file mode 100644
index 00000000..173635b2
--- /dev/null
+++ b/games/retrogo/src/nes/mappers/map001.c
@@ -0,0 +1,202 @@
+/*
+** Nofrendo (c) 1998-2000 Matthew Conte ([email protected])
+**
+**
+** This program is free software; you can redistribute it and/or modify it under the terms of
+** the GNU General Public License as published by the Free Software Foundation; either version 3
+** of the License, or (at your option) any later version. (Nofrendo was released under version
+** 2 of the GNU Library General Public License; as its section 3 allows, this copy, changed for
+** Retro-Go on NumPlay, is under the GNU General Public License instead.)
+**
+** This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY;
+** without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
+** See the GNU General Public License for more details.
+**
+** Any permitted reproduction of these routines, in whole or in part,
+** must bear this legend.
+**
+**
+** map1.c
+**
+** mapper 1 interface
+** $Id: map001.c,v 1.2 2001/04/27 14:37:11 neil Exp $
+*/
+
+#include <string.h>
+#include "noftypes.h"
+#include "nes_mmc.h"
+#include "nes_ppu.h"
+
+/* TODO: WRAM enable ala Mark Knibbs:
+ ==================================
+The SNROM board uses 8K CHR-RAM. The CHR-RAM is paged (i.e. it can be split
+into two 4Kbyte pages).
+
+The CRA16 line of the MMC1 is connected to the /CS1 pin of the WRAM. THIS MEANS
+THAT THE WRAM CAN BE ENABLED OR DISABLED ACCORDING TO THE STATE OF THE CRA16
+LINE. The CRA16 line corresponds to bit 4 of MMC1 registers 1 & 2.
+
+The WRAM is enabled when the CRA16 line is low, and disabled when CRA16 is
+high. This has implications when CHR page size is 4K, if the two page numbers
+set have different CRA16 states (e.g. reg 1 bit 4 = 0, reg 2 bit 4 = 1). Then
+the WRAM will be enabled and disabled depending on what CHR address is being
+accessed.
+
+When CHR page size is 8K, bit 4 of MMC1 register 1 (and not register 2, because
+page size is 8K) controls whether the WRAM is enabled or not. It must be low
+to be enabled. When the WRAM is disabled, reading from and writing to it will
+not be possible.
+*/
+
+/* TODO: roll this into something... */
+static int bitcount = 0;
+static uint8 latch = 0;
+static uint8 regs[4];
+static int bank_select;
+static uint8 lastreg;
+
+static void map1_write(uint32 address, uint8 value)
+{
+ int regnum = (address >> 13) - 4;
+
+ if (value & 0x80)
+ {
+ regs[0] |= 0x0C;
+ bitcount = 0;
+ latch = 0;
+ return;
+ }
+
+ if (lastreg != regnum)
+ {
+ bitcount = 0;
+ latch = 0;
+ lastreg = regnum;
+ }
+ //lastreg = regnum;
+
+ latch |= ((value & 1) << bitcount++);
+
+ /* 5 bit registers */
+ if (5 != bitcount)
+ return;
+
+ regs[regnum] = latch;
+ value = latch;
+ bitcount = 0;
+ latch = 0;
+
+ switch (regnum)
+ {
+ case 0:
+ {
+ if (0 == (value & 2))
+ {
+ int mirror = value & 1;
+ ppu_mirror(mirror, mirror, mirror, mirror);
+ }
+ else
+ {
+ if (value & 1)
+ ppu_mirror(0, 0, 1, 1);
+ else
+ ppu_mirror(0, 1, 0, 1);
+ }
+ }
+ break;
+
+ case 1:
+ if (regs[0] & 0x10)
+ mmc_bankvrom(4, 0x0000, value);
+ else
+ mmc_bankvrom(8, 0x0000, value >> 1);
+ break;
+
+ case 2:
+ if (regs[0] & 0x10)
+ mmc_bankvrom(4, 0x1000, value);
+ break;
+
+ case 3:
+ if (mmc_getinfo()->rom_banks == 0x20)
+ {
+ bank_select = (regs[1] & 0x10) ? 0 : 0x10;
+ }
+ else if (mmc_getinfo()->rom_banks == 0x40)
+ {
+ if (regs[0] & 0x10)
+ bank_select = (regs[1] & 0x10) | ((regs[2] & 0x10) << 1);
+ else
+ bank_select = (regs[1] & 0x10) << 1;
+ }
+ else
+ {
+ bank_select = 0;
+ }
+
+ if (0 == (regs[0] & 0x08))
+ mmc_bankrom(32, 0x8000, ((regs[3] >> 1) + (bank_select >> 1)));
+ else if (regs[0] & 0x04)
+ mmc_bankrom(16, 0x8000, ((regs[3] & 0xF) + bank_select));
+ else
+ mmc_bankrom(16, 0xC000, ((regs[3] & 0xF) + bank_select));
+
+ default:
+ break;
+ }
+}
+
+static void map1_init(void)
+{
+ bitcount = 0;
+ latch = 0;
+
+ memset(regs, 0, sizeof(regs));
+
+ if (mmc_getinfo()->rom_banks == 0x20)
+ mmc_bankrom(16, 0xC000, 0x0F);
+
+ map1_write(0x8000, 0x80);
+}
+
+static void map1_getstate(SnssMapperBlock *state)
+{
+ state->extraData.mapper1.registers[0] = regs[0];
+ state->extraData.mapper1.registers[1] = regs[1];
+ state->extraData.mapper1.registers[2] = regs[2];
+ state->extraData.mapper1.registers[3] = regs[3];
+ state->extraData.mapper1.latch = latch;
+ state->extraData.mapper1.numberOfBits = bitcount;
+}
+
+
+static void map1_setstate(SnssMapperBlock *state)
+{
+ regs[1] = state->extraData.mapper1.registers[0];
+ regs[1] = state->extraData.mapper1.registers[1];
+ regs[2] = state->extraData.mapper1.registers[2];
+ regs[3] = state->extraData.mapper1.registers[3];
+ latch = state->extraData.mapper1.latch;
+ bitcount = state->extraData.mapper1.numberOfBits;
+}
+
+static map_memwrite map1_memwrite[] =
+{
+ { 0x8000, 0xFFFF, map1_write },
+ { -1, -1, NULL }
+};
+
+mapintf_t map1_intf =
+{
+ 1, /* mapper number */
+ "MMC1", /* mapper name */
+ map1_init, /* init routine */
+ NULL, /* vblank callback */
+ NULL, /* hblank callback */
+ map1_getstate, /* get state (snss) */
+ map1_setstate, /* set state (snss) */
+ NULL, /* memory read structure */
+ map1_memwrite, /* memory write structure */
+ NULL /* external sound device */
+};
+
diff --git a/games/retrogo/src/nes/mappers/map002.c b/games/retrogo/src/nes/mappers/map002.c
new file mode 100644
index 00000000..aebe5d70
--- /dev/null
+++ b/games/retrogo/src/nes/mappers/map002.c
@@ -0,0 +1,55 @@
+/*
+** Nofrendo (c) 1998-2000 Matthew Conte ([email protected])
+**
+**
+** This program is free software; you can redistribute it and/or modify it under the terms of
+** the GNU General Public License as published by the Free Software Foundation; either version 3
+** of the License, or (at your option) any later version. (Nofrendo was released under version
+** 2 of the GNU Library General Public License; as its section 3 allows, this copy, changed for
+** Retro-Go on NumPlay, is under the GNU General Public License instead.)
+**
+** This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY;
+** without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
+** See the GNU General Public License for more details.
+**
+** Any permitted reproduction of these routines, in whole or in part,
+** must bear this legend.
+**
+**
+** map2.c
+**
+** mapper 2 interface
+** $Id: map002.c,v 1.2 2001/04/27 14:37:11 neil Exp $
+*/
+
+#include "noftypes.h"
+#include "nes_mmc.h"
+
+/* mapper 2: UNROM */
+static void map2_write(uint32 address, uint8 value)
+{
+ UNUSED(address);
+
+ mmc_bankrom(16, 0x8000, value);
+}
+
+static map_memwrite map2_memwrite[] =
+{
+ { 0x8000, 0xFFFF, map2_write },
+ { -1, -1, NULL }
+};
+
+mapintf_t map2_intf =
+{
+ 2, /* mapper number */
+ "UNROM", /* mapper name */
+ NULL, /* init routine */
+ NULL, /* vblank callback */
+ NULL, /* hblank callback */
+ NULL, /* get state (snss) */
+ NULL, /* set state (snss) */
+ NULL, /* memory read structure */
+ map2_memwrite, /* memory write structure */
+ NULL /* external sound device */
+};
+
diff --git a/games/retrogo/src/nes/mappers/map003.c b/games/retrogo/src/nes/mappers/map003.c
new file mode 100644
index 00000000..07b9f8c6
--- /dev/null
+++ b/games/retrogo/src/nes/mappers/map003.c
@@ -0,0 +1,55 @@
+/*
+** Nofrendo (c) 1998-2000 Matthew Conte ([email protected])
+**
+**
+** This program is free software; you can redistribute it and/or modify it under the terms of
+** the GNU General Public License as published by the Free Software Foundation; either version 3
+** of the License, or (at your option) any later version. (Nofrendo was released under version
+** 2 of the GNU Library General Public License; as its section 3 allows, this copy, changed for
+** Retro-Go on NumPlay, is under the GNU General Public License instead.)
+**
+** This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY;
+** without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
+** See the GNU General Public License for more details.
+**
+** Any permitted reproduction of these routines, in whole or in part,
+** must bear this legend.
+**
+**
+** map3.c
+**
+** mapper 3 interface
+** $Id: map003.c,v 1.2 2001/04/27 14:37:11 neil Exp $
+*/
+
+#include "noftypes.h"
+#include "nes_mmc.h"
+
+/* mapper 3: CNROM */
+static void map3_write(uint32 address, uint8 value)
+{
+ UNUSED(address);
+
+ mmc_bankvrom(8, 0x0000, value);
+}
+
+static map_memwrite map3_memwrite[] =
+{
+ { 0x8000, 0xFFFF, map3_write },
+ { -1, -1, NULL }
+};
+
+mapintf_t map3_intf =
+{
+ 3, /* mapper number */
+ "CNROM", /* mapper name */
+ NULL, /* init routine */
+ NULL, /* vblank callback */
+ NULL, /* hblank callback */
+ NULL, /* get state (snss) */
+ NULL, /* set state (snss) */
+ NULL, /* memory read structure */
+ map3_memwrite, /* memory write structure */
+ NULL /* external sound device */
+};
+
diff --git a/games/retrogo/src/nes/mappers/map004.c b/games/retrogo/src/nes/mappers/map004.c
new file mode 100644
index 00000000..26e5e668
--- /dev/null
+++ b/games/retrogo/src/nes/mappers/map004.c
@@ -0,0 +1,214 @@
+/*
+** Nofrendo (c) 1998-2000 Matthew Conte ([email protected])
+**
+**
+** This program is free software; you can redistribute it and/or modify it under the terms of
+** the GNU General Public License as published by the Free Software Foundation; either version 3
+** of the License, or (at your option) any later version. (Nofrendo was released under version
+** 2 of the GNU Library General Public License; as its section 3 allows, this copy, changed for
+** Retro-Go on NumPlay, is under the GNU General Public License instead.)
+**
+** This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY;
+** without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
+** See the GNU General Public License for more details.
+**
+** Any permitted reproduction of these routines, in whole or in part,
+** must bear this legend.
+**
+**
+** map4.c
+**
+** mapper 4 interface
+** $Id: map004.c,v 1.2 2001/04/27 14:37:11 neil Exp $
+*/
+
+#include "noftypes.h"
+#include "nes_mmc.h"
+#include "nes.h"
+#include "libsnss.h"
+
+static struct
+{
+ int counter, latch;
+ bool enabled, reset;
+} irq;
+
+static uint8 reg;
+static uint8 command;
+static uint16 vrombase;
+
+/* mapper 4: MMC3 */
+static void map4_write(uint32 address, uint8 value)
+{
+ switch (address & 0xE001)
+ {
+ case 0x8000:
+ command = value;
+ vrombase = (command & 0x80) ? 0x1000 : 0x0000;
+
+ if (reg != (value & 0x40))
+ {
+ if (value & 0x40)
+ mmc_bankrom(8, 0x8000, (mmc_getinfo()->rom_banks * 2) - 2);
+ else
+ mmc_bankrom(8, 0xC000, (mmc_getinfo()->rom_banks * 2) - 2);
+ }
+ reg = value & 0x40;
+ break;
+
+ case 0x8001:
+ switch (command & 0x07)
+ {
+ case 0:
+ value &= 0xFE;
+ mmc_bankvrom(1, vrombase ^ 0x0000, value);
+ mmc_bankvrom(1, vrombase ^ 0x0400, value + 1);
+ break;
+
+ case 1:
+ value &= 0xFE;
+ mmc_bankvrom(1, vrombase ^ 0x0800, value);
+ mmc_bankvrom(1, vrombase ^ 0x0C00, value + 1);
+ break;
+
+ case 2:
+ mmc_bankvrom(1, vrombase ^ 0x1000, value);
+ break;
+
+ case 3:
+ mmc_bankvrom(1, vrombase ^ 0x1400, value);
+ break;
+
+ case 4:
+ mmc_bankvrom(1, vrombase ^ 0x1800, value);
+ break;
+
+ case 5:
+ mmc_bankvrom(1, vrombase ^ 0x1C00, value);
+ break;
+
+ case 6:
+ mmc_bankrom(8, (command & 0x40) ? 0xC000 : 0x8000, value);
+ break;
+
+ case 7:
+ mmc_bankrom(8, 0xA000, value);
+ break;
+ }
+ break;
+
+ case 0xA000:
+ /* four screen mirroring crap */
+ if (0 == (mmc_getinfo()->flags & ROM_FLAG_FOURSCREEN))
+ {
+ if (value & 1)
+ ppu_mirror(0, 0, 1, 1); /* horizontal */
+ else
+ ppu_mirror(0, 1, 0, 1); /* vertical */
+ }
+ break;
+
+ case 0xA001:
+ /* Save RAM enable / disable */
+ /* Messes up Startropics I/II if implemented -- bah */
+ break;
+
+ case 0xC000:
+ irq.latch = value;
+// if (irq.reset)
+// irq.counter = irq.latch;
+ break;
+
+ case 0xC001:
+ irq.reset = true;
+ irq.counter = irq.latch;
+ break;
+
+ case 0xE000:
+ irq.enabled = false;
+// if (irq.reset)
+// irq.counter = irq.latch;
+ break;
+
+ case 0xE001:
+ irq.enabled = true;
+// if (irq.reset)
+// irq.counter = irq.latch;
+ break;
+
+ default:
+ break;
+ }
+
+ if (true == irq.reset)
+ irq.counter = irq.latch;
+}
+
+static void map4_hblank(int vblank)
+{
+ if (vblank)
+ return;
+
+ if (ppu_enabled())
+ {
+ if (irq.counter >= 0)
+ {
+ irq.reset = false;
+ irq.counter--;
+
+ if (irq.counter < 0)
+ {
+ if (irq.enabled)
+ {
+ irq.reset = true;
+ nes_irq();
+ }
+ }
+ }
+ }
+}
+
+static void map4_getstate(SnssMapperBlock *state)
+{
+ state->extraData.mapper4.irqCounter = irq.counter;
+ state->extraData.mapper4.irqLatchCounter = irq.latch;
+ state->extraData.mapper4.irqCounterEnabled = irq.enabled;
+ state->extraData.mapper4.last8000Write = command;
+}
+
+static void map4_setstate(SnssMapperBlock *state)
+{
+ irq.counter = state->extraData.mapper4.irqCounter;
+ irq.latch = state->extraData.mapper4.irqLatchCounter;
+ irq.enabled = state->extraData.mapper4.irqCounterEnabled;
+ command = state->extraData.mapper4.last8000Write;
+}
+
+static void map4_init(void)
+{
+ irq.counter = irq.latch = 0;
+ irq.enabled = irq.reset = false;
+ reg = command = 0;
+ vrombase = 0x0000;
+}
+
+static map_memwrite map4_memwrite[] =
+{
+ { 0x8000, 0xFFFF, map4_write },
+ { -1, -1, NULL }
+};
+
+mapintf_t map4_intf =
+{
+ 4, /* mapper number */
+ "MMC3", /* mapper name */
+ map4_init, /* init routine */
+ NULL, /* vblank callback */
+ map4_hblank, /* hblank callback */
+ map4_getstate, /* get state (snss) */
+ map4_setstate, /* set state (snss) */
+ NULL, /* memory read structure */
+ map4_memwrite, /* memory write structure */
+ NULL /* external sound device */
+};
+
diff --git a/games/retrogo/src/nes/mappers/map005.c b/games/retrogo/src/nes/mappers/map005.c
new file mode 100644
index 00000000..ca71368a
--- /dev/null
+++ b/games/retrogo/src/nes/mappers/map005.c
@@ -0,0 +1,272 @@
+/*
+** Nofrendo (c) 1998-2000 Matthew Conte ([email protected])
+**
+**
+** This program is free software; you can redistribute it and/or modify it under the terms of
+** the GNU General Public License as published by the Free Software Foundation; either version 3
+** of the License, or (at your option) any later version. (Nofrendo was released under version
+** 2 of the GNU Library General Public License; as its section 3 allows, this copy, changed for
+** Retro-Go on NumPlay, is under the GNU General Public License instead.)
+**
+** This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY;
+** without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
+** See the GNU General Public License for more details.
+**
+** Any permitted reproduction of these routines, in whole or in part,
+** must bear this legend.
+**
+**
+** map5.c
+**
+** mapper 5 interface
+** $Id: map005.c,v 1.2 2001/04/27 14:37:11 neil Exp $
+*/
+
+#include "noftypes.h"
+#include "nes_mmc.h"
+#include "nes.h"
+
+/* TODO: there's lots of info about this mapper now;
+** let's implement it correctly/completely
+*/
+
+static struct
+{
+ int counter, enabled;
+ int reset, latch;
+} irq;
+
+/* MMC5 - Castlevania III, etc */
+static void map5_hblank(int vblank)
+{
+ UNUSED(vblank);
+
+ if (irq.counter == nes_getcontextptr()->scanline)
+ {
+ if (true == irq.enabled)
+ {
+ nes_irq();
+ irq.reset = true;
+ }
+ //else
+ // irq.reset = false;
+ irq.counter = irq.latch;
+ }
+}
+
+static void map5_write(uint32 address, uint8 value)
+{
+ static int page_size = 8;
+
+ /* ex-ram memory-- bleh! */
+ if (address >= 0x5C00 && address <= 0x5FFF)
+ return;
+
+ switch (address)
+ {
+ case 0x5100:
+ /* PRG page size setting */
+ /* 0:32k 1:16k 2,3:8k */
+ switch (value & 3)
+ {
+ case 0:
+ page_size = 32;
+ break;
+
+ case 1:
+ page_size = 16;
+ break;
+
+ case 2:
+ case 3:
+ page_size = 8;
+ break;
+ }
+ break;
+
+ case 0x5101:
+ /* CHR page size setting */
+ /* 0:8k 1:4k 2:2k 3:1k */
+ break;
+
+ case 0x5104:
+ /* GFX mode setting */
+ /*
+ 00:split mode
+ 01:split & exgraffix
+ 10:ex-ram
+ 11:exram + write protect
+ */
+ break;
+
+ case 0x5105:
+ /* TODO: exram needs to fill in nametables 2-3 */
+ ppu_mirror(value & 3, (value >> 2) & 3, (value >> 4) & 3, value >> 6);
+ break;
+
+ case 0x5106:
+ case 0x5107:
+ /* ex-ram fill mode stuff */
+ break;
+
+ case 0x5113:
+ /* ram page for $6000-7FFF? bit 2*/
+ break;
+
+ case 0x5114:
+ mmc_bankrom(8, 0x8000, value);
+ //if (page_size == 8)
+ // mmc_bankrom(8, 0x8000, value);
+ break;
+
+ case 0x5115:
+ mmc_bankrom(8, 0x8000, value);
+ mmc_bankrom(8, 0xA000, value + 1);
+ //if (page_size == 8)
+ // mmc_bankrom(8, 0xA000, value);
+ //else if (page_size == 16)
+ // mmc_bankrom(16, 0x8000, value >> 1);
+ //mmc_bankrom(16, 0x8000, value & 0xFE);
+ break;
+
+ case 0x5116:
+ mmc_bankrom(8, 0xC000, value);
+ //if (page_size == 8)
+ // mmc_bankrom(8, 0xC000, value);
+ break;
+
+ case 0x5117:
+ //if (page_size == 8)
+ // mmc_bankrom(8, 0xE000, value);
+ //else if (page_size == 16)
+ // mmc_bankrom(16, 0xC000, value >> 1);
+ //mmc_bankrom(16, 0xC000, value & 0xFE);
+ //else if (page_size == 32)
+ // mmc_bankrom(32, 0x8000, value >> 2);
+ //mmc_bankrom(32, 0x8000, value & 0xFC);
+ break;
+
+ case 0x5120:
+ mmc_bankvrom(1, 0x0000, value);
+ break;
+
+ case 0x5121:
+ mmc_bankvrom(1, 0x0400, value);
+ break;
+
+ case 0x5122:
+ mmc_bankvrom(1, 0x0800, value);
+ break;
+
+ case 0x5123:
+ mmc_bankvrom(1, 0x0C00, value);
+ break;
+
+ case 0x5124:
+ case 0x5125:
+ case 0x5126:
+ case 0x5127:
+ /* more VROM shit? */
+ break;
+
+ case 0x5128:
+ mmc_bankvrom(1, 0x1000, value);
+ break;
+
+ case 0x5129:
+ mmc_bankvrom(1, 0x1400, value);
+ break;
+
+ case 0x512A:
+ mmc_bankvrom(1, 0x1800, value);
+ break;
+
+ case 0x512B:
+ mmc_bankvrom(1, 0x1C00, value);
+ break;
+
+ case 0x5203:
+ irq.counter = value;
+ irq.latch = value;
+// irq.reset = false;
+ break;
+
+ case 0x5204:
+ irq.enabled = (value & 0x80) ? true : false;
+// irq.reset = false;
+ break;
+
+ default:
+#ifdef NOFRENDO_DEBUG
+ log_printf("unknown mmc5 write: $%02X to $%04X\n", value, address);
+#endif /* NOFRENDO_DEBUG */
+ break;
+ }
+}
+
+static uint8 map5_read(uint32 address)
+{
+ /* Castlevania 3 IRQ counter */
+ if (address == 0x5204)
+ {
+ /* if reset == 1, we've hit scanline */
+ return (irq.reset ? 0x40 : 0x00);
+ }
+ else
+ {
+#ifdef NOFRENDO_DEBUG
+ log_printf("invalid MMC5 read: $%04X", address);
+#endif
+ return 0xFF;
+ }
+}
+
+static void map5_init(void)
+{
+ mmc_bankrom(8, 0x8000, MMC_LASTBANK);
+ mmc_bankrom(8, 0xA000, MMC_LASTBANK);
+ mmc_bankrom(8, 0xC000, MMC_LASTBANK);
+ mmc_bankrom(8, 0xE000, MMC_LASTBANK);
+
+ irq.counter = irq.enabled = 0;
+ irq.reset = irq.latch = 0;
+}
+
+/* incomplete SNSS definition */
+static void map5_getstate(SnssMapperBlock *state)
+{
+ state->extraData.mapper5.dummy = 0;
+}
+
+static void map5_setstate(SnssMapperBlock *state)
+{
+ UNUSED(state);
+}
+
+static map_memwrite map5_memwrite[] =
+{
+ /* $5000 - $5015 handled by sound */
+ { 0x5016, 0x5FFF, map5_write },
+ { 0x8000, 0xFFFF, map5_write },
+ { -1, -1, NULL }
+};
+
+static map_memread map5_memread[] =
+{
+ { 0x5204, 0x5204, map5_read },
+ { -1, -1, NULL }
+};
+
+mapintf_t map5_intf =
+{
+ 5, /* mapper number */
+ "MMC5", /* mapper name */
+ map5_init, /* init routine */
+ NULL, /* vblank callback */
+ map5_hblank, /* hblank callback */
+ map5_getstate, /* get state (snss) */
+ map5_setstate, /* set state (snss) */
+ map5_memread, /* memory read structure */
+ map5_memwrite, /* memory write structure */
+ NULL /* external sound device (no sound: the calculator has no speaker) */
+};
diff --git a/games/retrogo/src/nes/mappers/map007.c b/games/retrogo/src/nes/mappers/map007.c
new file mode 100644
index 00000000..c9255554
--- /dev/null
+++ b/games/retrogo/src/nes/mappers/map007.c
@@ -0,0 +1,64 @@
+/*
+** Nofrendo (c) 1998-2000 Matthew Conte ([email protected])
+**
+**
+** This program is free software; you can redistribute it and/or modify it under the terms of
+** the GNU General Public License as published by the Free Software Foundation; either version 3
+** of the License, or (at your option) any later version. (Nofrendo was released under version
+** 2 of the GNU Library General Public License; as its section 3 allows, this copy, changed for
+** Retro-Go on NumPlay, is under the GNU General Public License instead.)
+**
+** This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY;
+** without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
+** See the GNU General Public License for more details.
+**
+** Any permitted reproduction of these routines, in whole or in part,
+** must bear this legend.
+**
+**
+** map7.c
+**
+** mapper 7 interface
+** $Id: map007.c,v 1.2 2001/04/27 14:37:11 neil Exp $
+*/
+
+#include "noftypes.h"
+#include "nes_mmc.h"
+#include "nes_ppu.h"
+
+/* mapper 7: AOROM */
+static void map7_write(uint32 address, uint8 value)
+{
+ int mirror;
+ UNUSED(address);
+
+ mmc_bankrom(32, 0x8000, value);
+ mirror = (value & 0x10) >> 4;
+ ppu_mirror(mirror, mirror, mirror, mirror);
+}
+
+static void map7_init(void)
+{
+ mmc_bankrom(32, 0x8000, 0);
+}
+
+static map_memwrite map7_memwrite[] =
+{
+ { 0x8000, 0xFFFF, map7_write },
+ { -1, -1, NULL }
+};
+
+mapintf_t map7_intf =
+{
+ 7, /* mapper number */
+ "AOROM", /* mapper name */
+ map7_init, /* init routine */
+ NULL, /* vblank callback */
+ NULL, /* hblank callback */
+ NULL, /* get state (snss) */
+ NULL, /* set state (snss) */
+ NULL, /* memory read structure */
+ map7_memwrite, /* memory write structure */
+ NULL /* external sound device */
+};
+
diff --git a/games/retrogo/src/nes/mappers/map008.c b/games/retrogo/src/nes/mappers/map008.c
new file mode 100644
index 00000000..aed61da9
--- /dev/null
+++ b/games/retrogo/src/nes/mappers/map008.c
@@ -0,0 +1,63 @@
+/*
+** Nofrendo (c) 1998-2000 Matthew Conte ([email protected])
+**
+**
+** This program is free software; you can redistribute it and/or modify it under the terms of
+** the GNU General Public License as published by the Free Software Foundation; either version 3
+** of the License, or (at your option) any later version. (Nofrendo was released under version
+** 2 of the GNU Library General Public License; as its section 3 allows, this copy, changed for
+** Retro-Go on NumPlay, is under the GNU General Public License instead.)
+**
+** This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY;
+** without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
+** See the GNU General Public License for more details.
+**
+** Any permitted reproduction of these routines, in whole or in part,
+** must bear this legend.
+**
+**
+** map8.c
+**
+** mapper 8 interface
+** $Id: map008.c,v 1.2 2001/04/27 14:37:11 neil Exp $
+*/
+
+#include "noftypes.h"
+#include "nes_mmc.h"
+
+/* mapper 8: FFE F3xxx -- what the hell uses this? */
+static void map8_write(uint32 address, uint8 value)
+{
+ UNUSED(address);
+
+ mmc_bankrom(16, 0x8000, value >> 3);
+ mmc_bankvrom(8, 0x0000, value & 7);
+}
+
+static void map8_init(void)
+{
+ mmc_bankrom(16, 0x8000, 0);
+ mmc_bankrom(16, 0xC000, 1);
+ mmc_bankvrom(8, 0x0000, 0);
+}
+
+static map_memwrite map8_memwrite[] =
+{
+ { 0x8000, 0xFFFF, map8_write },
+ { -1, -1, NULL }
+};
+
+mapintf_t map8_intf =
+{
+ 8, /* mapper number */
+ "FFE F3xxx", /* mapper name */
+ map8_init, /* init routine */
+ NULL, /* vblank callback */
+ NULL, /* hblank callback */
+ NULL, /* get state (snss) */
+ NULL, /* set state (snss) */
+ NULL, /* memory read structure */
+ map8_memwrite, /* memory write structure */
+ NULL /* external sound device */
+};
+
diff --git a/games/retrogo/src/nes/mappers/map009.c b/games/retrogo/src/nes/mappers/map009.c
new file mode 100644
index 00000000..89c9c36e
--- /dev/null
+++ b/games/retrogo/src/nes/mappers/map009.c
@@ -0,0 +1,156 @@
+/*
+** Nofrendo (c) 1998-2000 Matthew Conte ([email protected])
+**
+**
+** This program is free software; you can redistribute it and/or modify it under the terms of
+** the GNU General Public License as published by the Free Software Foundation; either version 3
+** of the License, or (at your option) any later version. (Nofrendo was released under version
+** 2 of the GNU Library General Public License; as its section 3 allows, this copy, changed for
+** Retro-Go on NumPlay, is under the GNU General Public License instead.)
+**
+** This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY;
+** without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
+** See the GNU General Public License for more details.
+**
+** Any permitted reproduction of these routines, in whole or in part,
+** must bear this legend.
+**
+**
+** map9.c
+**
+** mapper 9 interface
+** $Id: map009.c,v 1.2 2001/04/27 14:37:11 neil Exp $
+*/
+
+#include <string.h>
+#include "noftypes.h"
+#include "nes_mmc.h"
+#include "nes_ppu.h"
+#include "libsnss.h"
+
+static uint8 latch[2];
+static uint8 regs[4];
+
+/* Used when tile $FD/$FE is accessed */
+static void mmc9_latchfunc(uint32 address, uint8 value)
+{
+ if (0xFD == value || 0xFE == value)
+ {
+ int reg;
+
+ if (address)
+ {
+ latch[1] = value;
+ reg = 2 + (value - 0xFD);
+ }
+ else
+ {
+ latch[0] = value;
+ reg = value - 0xFD;
+ }
+
+ mmc_bankvrom(4, address, regs[reg]);
+ }
+}
+
+/* mapper 9: MMC2 */
+/* MMC2: Punch-Out! */
+static void map9_write(uint32 address, uint8 value)
+{
+ switch ((address & 0xF000) >> 12)
+ {
+ case 0xA:
+ mmc_bankrom(8, 0x8000, value);
+ break;
+
+ case 0xB:
+ regs[0] = value;
+ if (0xFD == latch[0])
+ mmc_bankvrom(4, 0x0000, value);
+ break;
+
+ case 0xC:
+ regs[1] = value;
+ if (0xFE == latch[0])
+ mmc_bankvrom(4, 0x0000, value);
+ break;
+
+ case 0xD:
+ regs[2] = value;
+ if (0xFD == latch[1])
+ mmc_bankvrom(4, 0x1000, value);
+ break;
+
+ case 0xE:
+ regs[3] = value;
+ if (0xFE == latch[1])
+ mmc_bankvrom(4, 0x1000, value);
+ break;
+
+ case 0xF:
+ if (value & 1)
+ ppu_mirror(0, 0, 1, 1); /* horizontal */
+ else
+ ppu_mirror(0, 1, 0, 1); /* vertical */
+ break;
+
+ default:
+ break;
+ }
+}
+
+static void map9_init(void)
+{
+ memset(regs, 0, sizeof(regs));
+
+ mmc_bankrom(8, 0x8000, 0);
+ mmc_bankrom(8, 0xA000, (mmc_getinfo()->rom_banks * 2) - 3);
+ mmc_bankrom(8, 0xC000, (mmc_getinfo()->rom_banks * 2) - 2);
+ mmc_bankrom(8, 0xE000, (mmc_getinfo()->rom_banks * 2) - 1);
+
+ latch[0] = 0xFE;
+ latch[1] = 0xFE;
+
+ ppu_setlatchfunc(mmc9_latchfunc);
+}
+
+static void map9_getstate(SnssMapperBlock *state)
+{
+ state->extraData.mapper9.latch[0] = latch[0];
+ state->extraData.mapper9.latch[1] = latch[1];
+ state->extraData.mapper9.lastB000Write = regs[0];
+ state->extraData.mapper9.lastC000Write = regs[1];
+ state->extraData.mapper9.lastD000Write = regs[2];
+ state->extraData.mapper9.lastE000Write = regs[3];
+}
+
+static void map9_setstate(SnssMapperBlock *state)
+{
+ latch[0] = state->extraData.mapper9.latch[0];
+ latch[1] = state->extraData.mapper9.latch[1];
+ regs[0] = state->extraData.mapper9.lastB000Write;
+ regs[1] = state->extraData.mapper9.lastC000Write;
+ regs[2] = state->extraData.mapper9.lastD000Write;
+ regs[3] = state->extraData.mapper9.lastE000Write;
+}
+
+static map_memwrite map9_memwrite[] =
+{
+ { 0x8000, 0xFFFF, map9_write },
+ { -1, -1, NULL }
+};
+
+mapintf_t map9_intf =
+{
+ 9, /* mapper number */
+ "MMC2", /* mapper name */
+ map9_init, /* init routine */
+ NULL, /* vblank callback */
+ NULL, /* hblank callback */
+ map9_getstate, /* get state (snss) */
+ map9_setstate, /* set state (snss) */
+ NULL, /* memory read structure */
+ map9_memwrite, /* memory write structure */
+ NULL /* external sound device */
+};
+
diff --git a/games/retrogo/src/nes/mappers/map011.c b/games/retrogo/src/nes/mappers/map011.c
new file mode 100644
index 00000000..312d36ab
--- /dev/null
+++ b/games/retrogo/src/nes/mappers/map011.c
@@ -0,0 +1,62 @@
+/*
+** Nofrendo (c) 1998-2000 Matthew Conte ([email protected])
+**
+**
+** This program is free software; you can redistribute it and/or modify it under the terms of
+** the GNU General Public License as published by the Free Software Foundation; either version 3
+** of the License, or (at your option) any later version. (Nofrendo was released under version
+** 2 of the GNU Library General Public License; as its section 3 allows, this copy, changed for
+** Retro-Go on NumPlay, is under the GNU General Public License instead.)
+**
+** This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY;
+** without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
+** See the GNU General Public License for more details.
+**
+** Any permitted reproduction of these routines, in whole or in part,
+** must bear this legend.
+**
+**
+** map11.c
+**
+** mapper 11 interface
+** $Id: map011.c,v 1.2 2001/04/27 14:37:11 neil Exp $
+*/
+
+#include "noftypes.h"
+#include "nes_mmc.h"
+
+/* mapper 11: Color Dreams, Wisdom Tree */
+static void map11_write(uint32 address, uint8 value)
+{
+ UNUSED(address);
+
+ mmc_bankrom(32, 0x8000, value & 0x0F);
+ mmc_bankvrom(8, 0x0000, value >> 4);
+}
+
+static void map11_init(void)
+{
+ mmc_bankrom(32, 0x8000, 0);
+ mmc_bankvrom(8, 0x0000, 0);
+}
+
+static map_memwrite map11_memwrite[] =
+{
+ { 0x8000, 0xFFFF, map11_write },
+ { -1, -1, NULL }
+};
+
+mapintf_t map11_intf =
+{
+ 11, /* mapper number */
+ "Color Dreams", /* mapper name */
+ map11_init, /* init routine */
+ NULL, /* vblank callback */
+ NULL, /* hblank callback */
+ NULL, /* get state (snss) */
+ NULL, /* set state (snss) */
+ NULL, /* memory read structure */
+ map11_memwrite, /* memory write structure */
+ NULL /* external sound device */
+};
+
diff --git a/games/retrogo/src/nes/mappers/map015.c b/games/retrogo/src/nes/mappers/map015.c
new file mode 100644
index 00000000..b91fc952
--- /dev/null
+++ b/games/retrogo/src/nes/mappers/map015.c
@@ -0,0 +1,110 @@
+/*
+** Nofrendo (c) 1998-2000 Matthew Conte ([email protected])
+**
+**
+** This program is free software; you can redistribute it and/or modify it under the terms of
+** the GNU General Public License as published by the Free Software Foundation; either version 3
+** of the License, or (at your option) any later version. (Nofrendo was released under version
+** 2 of the GNU Library General Public License; as its section 3 allows, this copy, changed for
+** Retro-Go on NumPlay, is under the GNU General Public License instead.)
+**
+** This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY;
+** without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
+** See the GNU General Public License for more details.
+**
+** Any permitted reproduction of these routines, in whole or in part,
+** must bear this legend.
+**
+**
+** map15.c
+**
+** mapper 15 interface
+** $Id: map015.c,v 1.2 2001/04/27 14:37:11 neil Exp $
+*/
+
+#include "noftypes.h"
+#include "nes_mmc.h"
+#include "nes_ppu.h"
+
+/* mapper 15: Contra 100-in-1 */
+static void map15_write(uint32 address, uint8 value)
+{
+ int bank = value & 0x3F;
+ uint8 swap = (value & 0x80) >> 7;
+
+ switch (address & 0x3)
+ {
+ case 0:
+ mmc_bankrom(8, 0x8000, (bank << 1) + swap);
+ mmc_bankrom(8, 0xA000, (bank << 1) + (swap ^ 1));
+ mmc_bankrom(8, 0xC000, ((bank + 1) << 1) + swap);
+ mmc_bankrom(8, 0xE000, ((bank + 1) << 1) + (swap ^ 1));
+
+ if (value & 0x40)
+ ppu_mirror(0, 0, 1, 1); /* horizontal */
+ else
+ ppu_mirror(0, 1, 0, 1); /* vertical */
+ break;
+
+ case 1:
+ mmc_bankrom(8, 0xC000, (bank << 1) + swap);
+ mmc_bankrom(8, 0xE000, (bank << 1) + (swap ^ 1));
+ break;
+
+ case 2:
+ if (swap)
+ {
+ mmc_bankrom(8, 0x8000, (bank << 1) + 1);
+ mmc_bankrom(8, 0xA000, (bank << 1) + 1);
+ mmc_bankrom(8, 0xC000, (bank << 1) + 1);
+ mmc_bankrom(8, 0xE000, (bank << 1) + 1);
+ }
+ else
+ {
+ mmc_bankrom(8, 0x8000, (bank << 1));
+ mmc_bankrom(8, 0xA000, (bank << 1));
+ mmc_bankrom(8, 0xC000, (bank << 1));
+ mmc_bankrom(8, 0xE000, (bank << 1));
+ }
+ break;
+
+ case 3:
+ mmc_bankrom(8, 0xC000, (bank << 1) + swap);
+ mmc_bankrom(8, 0xE000, (bank << 1) + (swap ^ 1));
+
+ if (value & 0x40)
+ ppu_mirror(0, 0, 1, 1); /* horizontal */
+ else
+ ppu_mirror(0, 1, 0, 1); /* vertical */
+ break;
+
+ default:
+ break;
+ }
+}
+
+static void map15_init(void)
+{
+ mmc_bankrom(32, 0x8000, 0);
+}
+
+static map_memwrite map15_memwrite[] =
+{
+ { 0x8000, 0xFFFF, map15_write },
+ { -1, -1, NULL }
+};
+
+mapintf_t map15_intf =
+{
+ 15, /* mapper number */
+ "Contra 100-in-1", /* mapper name */
+ map15_init, /* init routine */
+ NULL, /* vblank callback */
+ NULL, /* hblank callback */
+ NULL, /* get state (snss) */
+ NULL, /* set state (snss) */
+ NULL, /* memory read structure */
+ map15_memwrite, /* memory write structure */
+ NULL /* external sound device */
+};
+
diff --git a/games/retrogo/src/nes/mappers/map016.c b/games/retrogo/src/nes/mappers/map016.c
new file mode 100644
index 00000000..19cd04a3
--- /dev/null
+++ b/games/retrogo/src/nes/mappers/map016.c
@@ -0,0 +1,151 @@
+/*
+** Nofrendo (c) 1998-2000 Matthew Conte ([email protected])
+**
+**
+** This program is free software; you can redistribute it and/or modify it under the terms of
+** the GNU General Public License as published by the Free Software Foundation; either version 3
+** of the License, or (at your option) any later version. (Nofrendo was released under version
+** 2 of the GNU Library General Public License; as its section 3 allows, this copy, changed for
+** Retro-Go on NumPlay, is under the GNU General Public License instead.)
+**
+** This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY;
+** without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
+** See the GNU General Public License for more details.
+**
+** Any permitted reproduction of these routines, in whole or in part,
+** must bear this legend.
+**
+**
+** map16.c
+**
+** mapper 16 interface
+** $Id: map016.c,v 1.2 2001/04/27 14:37:11 neil Exp $
+*/
+
+#include "noftypes.h"
+#include "nes_mmc.h"
+#include "nes_ppu.h"
+#include "nes.h"
+
+static struct
+{
+ int counter;
+ bool enabled;
+} irq;
+
+/* mapper 16: Bandai */
+
+static void map16_init(void)
+{
+ mmc_bankrom(16, 0x8000, 0);
+ mmc_bankrom(16, 0xC000, MMC_LASTBANK);
+ irq.counter = 0;
+ irq.enabled = false;
+}
+
+static void map16_write(uint32 address, uint8 value)
+{
+ int reg = address & 0xF;
+
+ if (reg < 8)
+ {
+ mmc_bankvrom(1, reg << 10, value);
+ }
+ else
+ {
+ switch (address & 0x000F)
+ {
+ case 0x8:
+ mmc_bankrom(16, 0x8000, value);
+ break;
+
+ case 0x9:
+ switch (value & 3)
+ {
+ case 0:
+ ppu_mirror(0, 0, 1, 1); /* horizontal */
+ break;
+
+ case 1:
+ ppu_mirror(0, 1, 0, 1); /* vertical */
+ break;
+
+ case 2:
+ ppu_mirror(0, 0, 0, 0);
+ break;
+
+ case 3:
+ ppu_mirror(1, 1, 1, 1);
+ break;
+ }
+ break;
+
+ case 0xA:
+ irq.enabled = (value & 1) ? true : false;
+ break;
+
+ case 0xB:
+ irq.counter = (irq.counter & 0xFF00) | value;
+ break;
+
+ case 0xC:
+ irq.counter = (value << 8) | (irq.counter & 0xFF);
+ break;
+
+ case 0xD:
+ /* eeprom I/O port? */
+ break;
+ }
+ }
+}
+
+static void map16_hblank(int vblank)
+{
+ UNUSED(vblank);
+
+ if (irq.enabled)
+ {
+ if (irq.counter)
+ {
+ if (0 == --irq.counter)
+ nes_irq();
+ }
+ }
+}
+
+static void map16_getstate(SnssMapperBlock *state)
+{
+ state->extraData.mapper16.irqCounterLowByte = irq.counter & 0xFF;
+ state->extraData.mapper16.irqCounterHighByte = irq.counter >> 8;
+ state->extraData.mapper16.irqCounterEnabled = irq.enabled;
+}
+
+static void map16_setstate(SnssMapperBlock *state)
+{
+ irq.counter = (state->extraData.mapper16.irqCounterHighByte << 8)
+ | state->extraData.mapper16.irqCounterLowByte;
+ irq.enabled = state->extraData.mapper16.irqCounterEnabled;
+}
+
+static map_memwrite map16_memwrite[] =
+{
+ { 0x6000, 0x600D, map16_write },
+ { 0x7FF0, 0x7FFD, map16_write },
+ { 0x8000, 0x800D, map16_write },
+ { -1, -1, NULL }
+};
+
+mapintf_t map16_intf =
+{
+ 16, /* mapper number */
+ "Bandai", /* mapper name */
+ map16_init, /* init routine */
+ NULL, /* vblank callback */
+ map16_hblank, /* hblank callback */
+ map16_getstate, /* get state (snss) */
+ map16_setstate, /* set state (snss) */
+ NULL, /* memory read structure */
+ map16_memwrite, /* memory write structure */
+ NULL /* external sound device */
+};
+
diff --git a/games/retrogo/src/nes/mappers/map018.c b/games/retrogo/src/nes/mappers/map018.c
new file mode 100644
index 00000000..ff0fee9c
--- /dev/null
+++ b/games/retrogo/src/nes/mappers/map018.c
@@ -0,0 +1,175 @@
+/*
+** Nofrendo (c) 1998-2000 Matthew Conte ([email protected])
+**
+**
+** This program is free software; you can redistribute it and/or modify it under the terms of
+** the GNU General Public License as published by the Free Software Foundation; either version 3
+** of the License, or (at your option) any later version. (Nofrendo was released under version
+** 2 of the GNU Library General Public License; as its section 3 allows, this copy, changed for
+** Retro-Go on NumPlay, is under the GNU General Public License instead.)
+**
+** This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY;
+** without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
+** See the GNU General Public License for more details.
+**
+** Any permitted reproduction of these routines, in whole or in part,
+** must bear this legend.
+**
+**
+** map18.c
+**
+** mapper 18 interface
+** $Id: map018.c,v 1.2 2001/04/27 14:37:11 neil Exp $
+*/
+
+#include "noftypes.h"
+#include "nes_mmc.h"
+#include "nes_ppu.h"
+
+/* mapper 18: Jaleco SS8806 */
+#define VRC_PBANK(bank, value, high) \
+do { \
+ if ((high)) \
+ highprgnybbles[(bank)] = (value) & 0x0F; \
+ else \
+ lowprgnybbles[(bank)] = (value) & 0x0F; \
+ mmc_bankrom(8, 0x8000 + ((bank) << 13), (highprgnybbles[(bank)] << 4)+lowprgnybbles[(bank)]); \
+} while (0)
+
+#define VRC_VBANK(bank, value, high) \
+{ \
+ if ((high)) \
+ highnybbles[(bank)] = (value) & 0x0F; \
+ else \
+ lownybbles[(bank)] = (value) & 0x0F; \
+ mmc_bankvrom(1, (bank) << 10, (highnybbles[(bank)] << 4)+lownybbles[(bank)]); \
+}
+
+static struct
+{
+ int counter, enabled;
+ uint8 nybbles[4];
+ int clockticks;
+} irq;
+
+static void map18_init(void)
+{
+ irq.counter = irq.enabled = 0;
+}
+
+static uint8 lownybbles[8];
+static uint8 highnybbles[8];
+static uint8 lowprgnybbles[3];
+static uint8 highprgnybbles[3];
+
+
+static void map18_write(uint32 address, uint8 value)
+{
+ switch (address)
+ {
+ case 0x8000: VRC_PBANK(0, value, 0); break;
+ case 0x8001: VRC_PBANK(0, value, 1); break;
+ case 0x8002: VRC_PBANK(1, value, 0); break;
+ case 0x8003: VRC_PBANK(1, value, 1); break;
+ case 0x9000: VRC_PBANK(2, value, 0); break;
+ case 0x9001: VRC_PBANK(2, value, 1); break;
+ case 0xA000: VRC_VBANK(0, value, 0); break;
+ case 0xA001: VRC_VBANK(0, value, 1); break;
+ case 0xA002: VRC_VBANK(1, value, 0); break;
+ case 0xA003: VRC_VBANK(1, value, 1); break;
+ case 0xB000: VRC_VBANK(2, value, 0); break;
+ case 0xB001: VRC_VBANK(2, value, 1); break;
+ case 0xB002: VRC_VBANK(3, value, 0); break;
+ case 0xB003: VRC_VBANK(3, value, 1); break;
+ case 0xC000: VRC_VBANK(4, value, 0); break;
+ case 0xC001: VRC_VBANK(4, value, 1); break;
+ case 0xC002: VRC_VBANK(5, value, 0); break;
+ case 0xC003: VRC_VBANK(5, value, 1); break;
+ case 0xD000: VRC_VBANK(6, value, 0); break;
+ case 0xD001: VRC_VBANK(6, value, 1); break;
+ case 0xD002: VRC_VBANK(7, value, 0); break;
+ case 0xD003: VRC_VBANK(7, value, 1); break;
+ case 0xE000:
+ irq.nybbles[0]=value&0x0F;
+ irq.clockticks= (irq.nybbles[0]) | (irq.nybbles[1]<<4) |
+ (irq.nybbles[2]<<8) | (irq.nybbles[3]<<12);
+ irq.counter=(uint8)(irq.clockticks/114);
+ if(irq.counter>15) irq.counter-=16;
+ break;
+ case 0xE001:
+ irq.nybbles[1]=value&0x0F;
+ irq.clockticks= (irq.nybbles[0]) | (irq.nybbles[1]<<4) |
+ (irq.nybbles[2]<<8) | (irq.nybbles[3]<<12);
+ irq.counter=(uint8)(irq.clockticks/114);
+ if(irq.counter>15) irq.counter-=16;
+ break;
+ case 0xE002:
+ irq.nybbles[2]=value&0x0F;
+ irq.clockticks= (irq.nybbles[0]) | (irq.nybbles[1]<<4) |
+ (irq.nybbles[2]<<8) | (irq.nybbles[3]<<12);
+ irq.counter=(uint8)(irq.clockticks/114);
+ if(irq.counter>15) irq.counter-=16;
+ break;
+ case 0xE003:
+ irq.nybbles[3]=value&0x0F;
+ irq.clockticks= (irq.nybbles[0]) | (irq.nybbles[1]<<4) |
+ (irq.nybbles[2]<<8) | (irq.nybbles[3]<<12);
+ irq.counter=(uint8)(irq.clockticks/114);
+ if(irq.counter>15) irq.counter-=16;
+ break;
+ case 0xF000:
+ if(value&0x01) irq.enabled=true;
+ break;
+ case 0xF001:
+ irq.enabled=value&0x01;
+ break;
+ case 0xF002:
+ switch(value&0x03)
+ {
+ case 0: ppu_mirror(0, 0, 1, 1); break;
+ case 1: ppu_mirror(0, 1, 0, 1); break;
+ case 2: ppu_mirror(1,1,1,1);break;
+ case 3: ppu_mirror(1,1,1,1);break; // should this be zero?
+ default: break;
+ }
+ break;
+ default:
+ break;
+ }
+}
+
+
+static map_memwrite map18_memwrite[] =
+{
+ { 0x8000, 0xFFFF, map18_write },
+ { -1, -1, NULL }
+};
+
+static void map18_getstate(SnssMapperBlock *state)
+{
+ state->extraData.mapper18.irqCounterLowByte = irq.counter & 0xFF;
+ state->extraData.mapper18.irqCounterHighByte = irq.counter >> 8;
+ state->extraData.mapper18.irqCounterEnabled = irq.enabled;
+}
+
+static void map18_setstate(SnssMapperBlock *state)
+{
+ irq.counter = (state->extraData.mapper18.irqCounterHighByte << 8)
+ | state->extraData.mapper18.irqCounterLowByte;
+ irq.enabled = state->extraData.mapper18.irqCounterEnabled;
+}
+
+mapintf_t map18_intf =
+{
+ 18, /* mapper number */
+ "Jaleco SS8806", /* mapper name */
+ map18_init, /* init routine */
+ NULL, /* vblank callback */
+ NULL, /* hblank callback */
+ map18_getstate, /* get state (snss) */
+ map18_setstate, /* set state (snss) */
+ NULL, /* memory read structure */
+ map18_memwrite, /* memory write structure */
+ NULL /* external sound device */
+};
+
diff --git a/games/retrogo/src/nes/mappers/map019.c b/games/retrogo/src/nes/mappers/map019.c
new file mode 100644
index 00000000..e784d7ec
--- /dev/null
+++ b/games/retrogo/src/nes/mappers/map019.c
@@ -0,0 +1,141 @@
+/*
+** Nofrendo (c) 1998-2000 Matthew Conte ([email protected])
+**
+**
+** This program is free software; you can redistribute it and/or modify it under the terms of
+** the GNU General Public License as published by the Free Software Foundation; either version 3
+** of the License, or (at your option) any later version. (Nofrendo was released under version
+** 2 of the GNU Library General Public License; as its section 3 allows, this copy, changed for
+** Retro-Go on NumPlay, is under the GNU General Public License instead.)
+**
+** This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY;
+** without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
+** See the GNU General Public License for more details.
+**
+** Any permitted reproduction of these routines, in whole or in part,
+** must bear this legend.
+**
+**
+** map19.c
+**
+** mapper 19 interface
+** $Id: map019.c,v 1.2 2001/04/27 14:37:11 neil Exp $
+*/
+
+#include "noftypes.h"
+#include "nes_mmc.h"
+#include "nes_ppu.h"
+
+/* TODO: shouldn't there be an h-blank IRQ handler??? */
+
+/* Special mirroring macro for mapper 19 */
+/* (values from $E0 pick the console's own nametable RAM; Retro-Go on NumPlay: a cartridge
+ without CHR ROM keeps its nametables) */
+#define N_BANK1(table, value) \
+{ \
+ if ((value) < 0xE0) \
+ { \
+ if (mmc_getinfo()->vrom_banks) \
+ ppu_setpage(1, (table) + 8, &mmc_getinfo()->vrom[((value) % (mmc_getinfo()->vrom_banks * 8)) << 10] - (0x2000 + ((table) << 10))); \
+ } \
+ else \
+ ppu_setpage(1, (table) + 8, &ppu.nametab[((value) & 1) << 10] - (0x2000 + ((table) << 10))); \
+ ppu_mirrorhipages(); \
+}
+
+static struct
+{
+ int counter, enabled;
+} irq;
+
+static void map19_init(void)
+{
+ irq.counter = irq.enabled = 0;
+}
+
+/* mapper 19: Namcot 106 */
+static void map19_write(uint32 address, uint8 value)
+{
+ int reg = address >> 11;
+ switch (reg)
+ {
+ case 0xA:
+ irq.counter &= ~0xFF;
+ irq.counter |= value;
+ break;
+
+ case 0xB:
+ irq.counter = ((value & 0x7F) << 8) | (irq.counter & 0xFF);
+ irq.enabled = (value & 0x80) ? true : false;
+ break;
+
+ case 0x10:
+ case 0x11:
+ case 0x12:
+ case 0x13:
+ case 0x14:
+ case 0x15:
+ case 0x16:
+ case 0x17:
+ mmc_bankvrom(1, (reg & 7) << 10, value);
+ break;
+
+ case 0x18:
+ case 0x19:
+ case 0x1A:
+ case 0x1B:
+ N_BANK1(reg & 3, value);
+ break;
+
+ case 0x1C:
+ mmc_bankrom(8, 0x8000, value);
+ break;
+
+ case 0x1D:
+ mmc_bankrom(8, 0xA000, value);
+ break;
+
+ case 0x1E:
+ mmc_bankrom(8, 0xC000, value);
+ break;
+
+ default:
+ break;
+ }
+}
+
+static void map19_getstate(SnssMapperBlock *state)
+{
+ state->extraData.mapper19.irqCounterLowByte = irq.counter & 0xFF;
+ state->extraData.mapper19.irqCounterHighByte = irq.counter >> 8;
+ state->extraData.mapper19.irqCounterEnabled = irq.enabled;
+}
+
+static void map19_setstate(SnssMapperBlock *state)
+{
+ irq.counter = (state->extraData.mapper19.irqCounterHighByte << 8)
+ | state->extraData.mapper19.irqCounterLowByte;
+ irq.enabled = state->extraData.mapper19.irqCounterEnabled;
+}
+
+static map_memwrite map19_memwrite[] =
+{
+ { 0x5000, 0x5FFF, map19_write },
+ { 0x8000, 0xFFFF, map19_write },
+ { -1, -1, NULL }
+};
+
+mapintf_t map19_intf =
+{
+ 19, /* mapper number */
+ "Namcot 106", /* mapper name */
+ map19_init, /* init routine */
+ NULL, /* vblank callback */
+ NULL, /* hblank callback */
+ map19_getstate, /* get state (snss) */
+ map19_setstate, /* set state (snss) */
+ NULL, /* memory read structure */
+ map19_memwrite, /* memory write structure */
+ NULL /* external sound device */
+};
+
diff --git a/games/retrogo/src/nes/mappers/map024.c b/games/retrogo/src/nes/mappers/map024.c
new file mode 100644
index 00000000..0f5feb95
--- /dev/null
+++ b/games/retrogo/src/nes/mappers/map024.c
@@ -0,0 +1,184 @@
+/*
+** Nofrendo (c) 1998-2000 Matthew Conte ([email protected])
+**
+**
+** This program is free software; you can redistribute it and/or modify it under the terms of
+** the GNU General Public License as published by the Free Software Foundation; either version 3
+** of the License, or (at your option) any later version. (Nofrendo was released under version
+** 2 of the GNU Library General Public License; as its section 3 allows, this copy, changed for
+** Retro-Go on NumPlay, is under the GNU General Public License instead.)
+**
+** This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY;
+** without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
+** See the GNU General Public License for more details.
+**
+** Any permitted reproduction of these routines, in whole or in part,
+** must bear this legend.
+**
+**
+** map24.c
+**
+** mapper 24 interface
+** $Id: map024.c,v 1.2 2001/04/27 14:37:11 neil Exp $
+*/
+
+#include "noftypes.h"
+#include "nes_mmc.h"
+#include "nes.h"
+
+static struct
+{
+ int counter, enabled;
+ int latch, wait_state;
+} irq;
+
+static void map24_init(void)
+{
+ irq.counter = irq.enabled = 0;
+ irq.latch = irq.wait_state = 0;
+}
+
+static void map24_hblank(int vblank)
+{
+ UNUSED(vblank);
+
+ if (irq.enabled)
+ {
+ if (256 == ++irq.counter)
+ {
+ irq.counter = irq.latch;
+ nes_irq();
+ //irq.enabled = false;
+ irq.enabled = irq.wait_state;
+ }
+ }
+}
+
+static void map24_write(uint32 address, uint8 value)
+{
+ switch (address & 0xF003)
+ {
+ case 0x8000:
+ mmc_bankrom(16, 0x8000, value);
+ break;
+
+ case 0x9003:
+ /* ??? */
+ break;
+
+ case 0xB003:
+ switch (value & 0x0C)
+ {
+ case 0x00:
+ ppu_mirror(0, 1, 0, 1); /* vertical */
+ break;
+
+ case 0x04:
+ ppu_mirror(0, 0, 1, 1); /* horizontal */
+ break;
+
+ case 0x08:
+ ppu_mirror(0, 0, 0, 0);
+ break;
+
+ case 0x0C:
+ ppu_mirror(1, 1, 1, 1);
+ break;
+
+ default:
+ break;
+ }
+ break;
+
+
+ case 0xC000:
+ mmc_bankrom(8, 0xC000, value);
+ break;
+
+ case 0xD000:
+ mmc_bankvrom(1, 0x0000, value);
+ break;
+
+ case 0xD001:
+ mmc_bankvrom(1, 0x0400, value);
+ break;
+
+ case 0xD002:
+ mmc_bankvrom(1, 0x0800, value);
+ break;
+
+ case 0xD003:
+ mmc_bankvrom(1, 0x0C00, value);
+ break;
+
+ case 0xE000:
+ mmc_bankvrom(1, 0x1000, value);
+ break;
+
+ case 0xE001:
+ mmc_bankvrom(1, 0x1400, value);
+ break;
+
+ case 0xE002:
+ mmc_bankvrom(1, 0x1800, value);
+ break;
+
+ case 0xE003:
+ mmc_bankvrom(1, 0x1C00, value);
+ break;
+
+ case 0xF000:
+ irq.latch = value;
+ break;
+
+ case 0xF001:
+ irq.enabled = (value >> 1) & 0x01;
+ irq.wait_state = value & 0x01;
+ if (irq.enabled)
+ irq.counter = irq.latch;
+ break;
+
+ case 0xF002:
+ irq.enabled = irq.wait_state;
+ break;
+
+ default:
+#ifdef NOFRENDO_DEBUG
+ log_printf("invalid VRC6 write: $%02X to $%04X", value, address);
+#endif
+ break;
+ }
+}
+
+static void map24_getstate(SnssMapperBlock *state)
+{
+ state->extraData.mapper24.irqCounter = irq.counter;
+ state->extraData.mapper24.irqCounterEnabled = irq.enabled;
+}
+
+static void map24_setstate(SnssMapperBlock *state)
+{
+ irq.counter = state->extraData.mapper24.irqCounter;
+ irq.enabled = state->extraData.mapper24.irqCounterEnabled;
+}
+
+static map_memwrite map24_memwrite[] =
+{
+ { 0x8000, 0xF002, map24_write },
+ { -1, -1, NULL }
+};
+
+mapintf_t map24_intf =
+{
+ 24, /* mapper number */
+ "Konami VRC6", /* mapper name */
+ map24_init, /* init routine */
+ NULL, /* vblank callback */
+ map24_hblank, /* hblank callback */
+ map24_getstate, /* get state (snss) */
+ map24_setstate, /* set state (snss) */
+ NULL, /* memory read structure */
+ map24_memwrite, /* memory write structure */
+ NULL /* external sound device (no sound: the calculator has no speaker) */
+};
+
diff --git a/games/retrogo/src/nes/mappers/map032.c b/games/retrogo/src/nes/mappers/map032.c
new file mode 100644
index 00000000..affd91b5
--- /dev/null
+++ b/games/retrogo/src/nes/mappers/map032.c
@@ -0,0 +1,87 @@
+/*
+** Nofrendo (c) 1998-2000 Matthew Conte ([email protected])
+**
+**
+** This program is free software; you can redistribute it and/or modify it under the terms of
+** the GNU General Public License as published by the Free Software Foundation; either version 3
+** of the License, or (at your option) any later version. (Nofrendo was released under version
+** 2 of the GNU Library General Public License; as its section 3 allows, this copy, changed for
+** Retro-Go on NumPlay, is under the GNU General Public License instead.)
+**
+** This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY;
+** without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
+** See the GNU General Public License for more details.
+**
+** Any permitted reproduction of these routines, in whole or in part,
+** must bear this legend.
+**
+**
+** map32.c
+**
+** mapper 32 interface
+** $Id: map032.c,v 1.2 2001/04/27 14:37:11 neil Exp $
+*/
+
+#include "noftypes.h"
+#include "nes_mmc.h"
+#include "nes_ppu.h"
+
+static int select_c000 = 0;
+
+/* mapper 32: Irem G-101 */
+static void map32_write(uint32 address, uint8 value)
+{
+ switch (address >> 12)
+ {
+ case 0x08:
+ if (select_c000)
+ mmc_bankrom(8, 0xC000, value);
+ else
+ mmc_bankrom(8, 0x8000, value);
+ break;
+
+ case 0x09:
+ if (value & 1)
+ ppu_mirror(0, 0, 1, 1); /* horizontal */
+ else
+ ppu_mirror(0, 1, 0, 1); /* vertical */
+
+ select_c000 = (value & 0x02);
+ break;
+
+ case 0x0A:
+ mmc_bankrom(8, 0xA000, value);
+ break;
+
+ case 0x0B:
+ {
+ int loc = (address & 0x07) << 10;
+ mmc_bankvrom(1, loc, value);
+ }
+ break;
+
+ default:
+ break;
+ }
+}
+
+static map_memwrite map32_memwrite[] =
+{
+ { 0x8000, 0xFFFF, map32_write },
+ { -1, -1, NULL }
+};
+
+mapintf_t map32_intf =
+{
+ 32, /* mapper number */
+ "Irem G-101", /* mapper name */
+ NULL, /* init routine */
+ NULL, /* vblank callback */
+ NULL, /* hblank callback */
+ NULL, /* get state (snss) */
+ NULL, /* set state (snss) */
+ NULL, /* memory read structure */
+ map32_memwrite, /* memory write structure */
+ NULL /* external sound device */
+};
+
diff --git a/games/retrogo/src/nes/mappers/map033.c b/games/retrogo/src/nes/mappers/map033.c
new file mode 100644
index 00000000..2000cc95
--- /dev/null
+++ b/games/retrogo/src/nes/mappers/map033.c
@@ -0,0 +1,108 @@
+/*
+** Nofrendo (c) 1998-2000 Matthew Conte ([email protected])
+**
+**
+** This program is free software; you can redistribute it and/or modify it under the terms of
+** the GNU General Public License as published by the Free Software Foundation; either version 3
+** of the License, or (at your option) any later version. (Nofrendo was released under version
+** 2 of the GNU Library General Public License; as its section 3 allows, this copy, changed for
+** Retro-Go on NumPlay, is under the GNU General Public License instead.)
+**
+** This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY;
+** without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
+** See the GNU General Public License for more details.
+**
+** Any permitted reproduction of these routines, in whole or in part,
+** must bear this legend.
+**
+**
+** map33.c
+**
+** mapper 33 interface
+** $Id: map033.c,v 1.2 2001/04/27 14:37:11 neil Exp $
+*/
+
+#include "noftypes.h"
+#include "nes_mmc.h"
+#include "nes_ppu.h"
+
+/* mapper 33: Taito TC0190*/
+static void map33_write(uint32 address, uint8 value)
+{
+ int page = (address >> 13) & 3;
+ int reg = address & 3;
+
+ switch (page)
+ {
+ case 0: /* $800X */
+ switch (reg)
+ {
+ case 0:
+ mmc_bankrom(8, 0x8000, value);
+ break;
+
+ case 1:
+ mmc_bankrom(8, 0xA000, value);
+ break;
+
+ case 2:
+ mmc_bankvrom(2, 0x0000, value);
+ break;
+
+ case 3:
+ mmc_bankvrom(2, 0x0800, value);
+ break;
+ }
+ break;
+
+ case 1: /* $A00X */
+ {
+ int loc = 0x1000 + (reg << 10);
+ mmc_bankvrom(1, loc, value);
+ }
+ break;
+
+ case 2: /* $C00X */
+ case 3: /* $E00X */
+ switch (reg)
+ {
+ case 0:
+ /* irqs maybe ? */
+ //break;
+
+ case 1:
+ /* this doesn't seem to work just right */
+ if (value & 1)
+ ppu_mirror(0, 0, 1, 1); /* horizontal */
+ else
+ ppu_mirror(0, 1, 0, 1);
+ break;
+
+ default:
+ break;
+ }
+ break;
+ }
+}
+
+
+static map_memwrite map33_memwrite[] =
+{
+ { 0x8000, 0xFFFF, map33_write },
+ { -1, -1, NULL }
+};
+
+mapintf_t map33_intf =
+{
+ 33, /* mapper number */
+ "Taito TC0190", /* mapper name */
+ NULL, /* init routine */
+ NULL, /* vblank callback */
+ NULL, /* hblank callback */
+ NULL, /* get state (snss) */
+ NULL, /* set state (snss) */
+ NULL, /* memory read structure */
+ map33_memwrite, /* memory write structure */
+ NULL /* external sound device */
+};
+
diff --git a/games/retrogo/src/nes/mappers/map034.c b/games/retrogo/src/nes/mappers/map034.c
new file mode 100644
index 00000000..a9afd55c
--- /dev/null
+++ b/games/retrogo/src/nes/mappers/map034.c
@@ -0,0 +1,68 @@
+/*
+** Nofrendo (c) 1998-2000 Matthew Conte ([email protected])
+**
+**
+** This program is free software; you can redistribute it and/or modify it under the terms of
+** the GNU General Public License as published by the Free Software Foundation; either version 3
+** of the License, or (at your option) any later version. (Nofrendo was released under version
+** 2 of the GNU Library General Public License; as its section 3 allows, this copy, changed for
+** Retro-Go on NumPlay, is under the GNU General Public License instead.)
+**
+** This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY;
+** without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
+** See the GNU General Public License for more details.
+**
+** Any permitted reproduction of these routines, in whole or in part,
+** must bear this legend.
+**
+**
+** map34.c
+**
+** mapper 34 interface
+** $Id: map034.c,v 1.2 2001/04/27 14:37:11 neil Exp $
+*/
+
+#include "noftypes.h"
+#include "nes_mmc.h"
+
+static void map34_init(void)
+{
+ mmc_bankrom(32, 0x8000, MMC_LASTBANK);
+}
+
+static void map34_write(uint32 address, uint8 value)
+{
+ if ((address & 0x8000) || (0x7FFD == address))
+ {
+ mmc_bankrom(32, 0x8000, value);
+ }
+ else if (0x7FFE == address)
+ {
+ mmc_bankvrom(4, 0x0000, value);
+ }
+ else if (0x7FFF == address)
+ {
+ mmc_bankvrom(4, 0x1000, value);
+ }
+}
+
+static map_memwrite map34_memwrite[] =
+{
+ { 0x7FFD, 0xFFFF, map34_write },
+ { -1, -1, NULL }
+};
+
+mapintf_t map34_intf =
+{
+ 34, /* mapper number */
+ "Nina-1", /* mapper name */
+ map34_init, /* init routine */
+ NULL, /* vblank callback */
+ NULL, /* hblank callback */
+ NULL, /* get state (snss) */
+ NULL, /* set state (snss) */
+ NULL, /* memory read structure */
+ map34_memwrite, /* memory write structure */
+ NULL /* external sound device */
+};
+
diff --git a/games/retrogo/src/nes/mappers/map040.c b/games/retrogo/src/nes/mappers/map040.c
new file mode 100644
index 00000000..ac2cfac1
--- /dev/null
+++ b/games/retrogo/src/nes/mappers/map040.c
@@ -0,0 +1,119 @@
+/*
+** Nofrendo (c) 1998-2000 Matthew Conte ([email protected])
+**
+**
+** This program is free software; you can redistribute it and/or modify it under the terms of
+** the GNU General Public License as published by the Free Software Foundation; either version 3
+** of the License, or (at your option) any later version. (Nofrendo was released under version
+** 2 of the GNU Library General Public License; as its section 3 allows, this copy, changed for
+** Retro-Go on NumPlay, is under the GNU General Public License instead.)
+**
+** This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY;
+** without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
+** See the GNU General Public License for more details.
+**
+** Any permitted reproduction of these routines, in whole or in part,
+** must bear this legend.
+**
+**
+** map40.c
+**
+** mapper 40 interface
+** $Id: map040.c,v 1.2 2001/04/27 14:37:11 neil Exp $
+*/
+
+#include "noftypes.h"
+#include "nes_mmc.h"
+#include "nes.h"
+#include "libsnss.h"
+
+#define MAP40_IRQ_PERIOD (4096 / 113.666666)
+
+static struct
+{
+ int enabled, counter;
+} irq;
+
+/* mapper 40: SMB 2j (hack) */
+static void map40_init(void)
+{
+ mmc_bankrom(8, 0x6000, 6);
+ mmc_bankrom(8, 0x8000, 4);
+ mmc_bankrom(8, 0xA000, 5);
+ mmc_bankrom(8, 0xE000, 7);
+
+ irq.enabled = false;
+ irq.counter = (int) MAP40_IRQ_PERIOD;
+}
+
+static void map40_hblank(int vblank)
+{
+ UNUSED(vblank);
+
+ if (irq.enabled && irq.counter)
+ {
+ irq.counter--;
+ if (0 == irq.counter)
+ {
+ nes_irq();
+ irq.enabled = false;
+ }
+ }
+}
+
+static void map40_write(uint32 address, uint8 value)
+{
+ int range = (address >> 13) - 4;
+
+ switch (range)
+ {
+ case 0: /* 0x8000-0x9FFF */
+ irq.enabled = false;
+ irq.counter = (int) MAP40_IRQ_PERIOD;
+ break;
+
+ case 1: /* 0xA000-0xBFFF */
+ irq.enabled = true;
+ break;
+
+ case 3: /* 0xE000-0xFFFF */
+ mmc_bankrom(8, 0xC000, value & 7);
+ break;
+
+ default:
+ break;
+ }
+}
+
+static void map40_getstate(SnssMapperBlock *state)
+{
+ state->extraData.mapper40.irqCounter = irq.counter;
+ state->extraData.mapper40.irqCounterEnabled = irq.enabled;
+}
+
+static void map40_setstate(SnssMapperBlock *state)
+{
+ irq.counter = state->extraData.mapper40.irqCounter;
+ irq.enabled = state->extraData.mapper40.irqCounterEnabled;
+}
+
+static map_memwrite map40_memwrite[] =
+{
+ { 0x8000, 0xFFFF, map40_write },
+ { -1, -1, NULL }
+};
+
+mapintf_t map40_intf =
+{
+ 40, /* mapper number */
+ "SMB 2j (pirate)", /* mapper name */
+ map40_init, /* init routine */
+ NULL, /* vblank callback */
+ map40_hblank, /* hblank callback */
+ map40_getstate, /* get state (snss) */
+ map40_setstate, /* set state (snss) */
+ NULL, /* memory read structure */
+ map40_memwrite, /* memory write structure */
+ NULL /* external sound device */
+};
+
diff --git a/games/retrogo/src/nes/mappers/map064.c b/games/retrogo/src/nes/mappers/map064.c
new file mode 100644
index 00000000..bf4ff877
--- /dev/null
+++ b/games/retrogo/src/nes/mappers/map064.c
@@ -0,0 +1,193 @@
+/*
+** Nofrendo (c) 1998-2000 Matthew Conte ([email protected])
+**
+**
+** This program is free software; you can redistribute it and/or modify it under the terms of
+** the GNU General Public License as published by the Free Software Foundation; either version 3
+** of the License, or (at your option) any later version. (Nofrendo was released under version
+** 2 of the GNU Library General Public License; as its section 3 allows, this copy, changed for
+** Retro-Go on NumPlay, is under the GNU General Public License instead.)
+**
+** This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY;
+** without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
+** See the GNU General Public License for more details.
+**
+** Any permitted reproduction of these routines, in whole or in part,
+** must bear this legend.
+**
+**
+** map64.c
+**
+** mapper 64 interface
+** $Id: map064.c,v 1.2 2001/04/27 14:37:11 neil Exp $
+*/
+
+#include "noftypes.h"
+#include "nes_mmc.h"
+#include "nes.h"
+
+static struct
+{
+ int counter, latch;
+ bool enabled, reset;
+} irq;
+
+static uint8 command = 0;
+static uint16 vrombase = 0x0000;
+
+static void map64_hblank(int vblank)
+{
+ if (vblank)
+ return;
+
+ irq.reset = false;
+
+ if (ppu_enabled())
+ {
+ if (0 == irq.counter--)
+ {
+ irq.counter = irq.latch;
+
+ if (true == irq.enabled)
+ nes_irq();
+
+ irq.reset = true;
+ }
+ }
+}
+
+/* mapper 64: Tengen RAMBO-1 */
+static void map64_write(uint32 address, uint8 value)
+{
+ switch (address & 0xE001)
+ {
+ case 0x8000:
+ command = value;
+ vrombase = (value & 0x80) ? 0x1000 : 0x0000;
+ break;
+
+ case 0x8001:
+ switch (command & 0xF)
+ {
+ case 0:
+ mmc_bankvrom(1, 0x0000 ^ vrombase, value);
+ mmc_bankvrom(1, 0x0400 ^ vrombase, value);
+ break;
+
+ case 1:
+ mmc_bankvrom(1, 0x0800 ^ vrombase, value);
+ mmc_bankvrom(1, 0x0C00 ^ vrombase, value);
+ break;
+
+ case 2:
+ mmc_bankvrom(1, 0x1000 ^ vrombase, value);
+ break;
+
+ case 3:
+ mmc_bankvrom(1, 0x1400 ^ vrombase, value);
+ break;
+
+ case 4:
+ mmc_bankvrom(1, 0x1800 ^ vrombase, value);
+ break;
+
+ case 5:
+ mmc_bankvrom(1, 0x1C00 ^ vrombase, value);
+ break;
+
+ case 6:
+ mmc_bankrom(8, (command & 0x40) ? 0xA000 : 0x8000, value);
+ break;
+
+ case 7:
+ mmc_bankrom(8, (command & 0x40) ? 0xC000 : 0xA000, value);
+ break;
+
+ case 8:
+ mmc_bankvrom(1, 0x0400, value);
+ break;
+
+ case 9:
+ mmc_bankvrom(1, 0x0C00, value);
+ break;
+
+ case 15:
+ mmc_bankrom(8, (command & 0x40) ? 0x8000 : 0xC000, value);
+ break;
+
+ default:
+#ifdef NOFRENDO_DEBUG
+ log_printf("mapper 64: unknown command #%d", command & 0xF);
+#endif
+ break;
+ }
+ break;
+
+ case 0xA000:
+ if (value & 1)
+ ppu_mirror(0, 0, 1, 1);
+ else
+ ppu_mirror(0, 1, 0, 1);
+ break;
+
+ case 0xC000:
+ //irq.counter = value;
+ irq.latch = value;
+ break;
+
+ case 0xC001:
+ //irq.latch = value;
+ irq.reset = true;
+ break;
+
+ case 0xE000:
+ //irq.counter = irq.latch;
+ irq.enabled = false;
+ break;
+
+ case 0xE001:
+ irq.enabled = true;
+ break;
+
+ default:
+#ifdef NOFRENDO_DEBUG
+ log_printf("mapper 64: Wrote $%02X to $%04X", value, address);
+#endif
+ break;
+ }
+
+ if (true == irq.reset)
+ irq.counter = irq.latch;
+}
+
+static void map64_init(void)
+{
+ mmc_bankrom(8, 0x8000, MMC_LASTBANK);
+ mmc_bankrom(8, 0xA000, MMC_LASTBANK);
+ mmc_bankrom(8, 0xC000, MMC_LASTBANK);
+ mmc_bankrom(8, 0xE000, MMC_LASTBANK);
+
+ irq.counter = irq.latch = 0;
+ irq.reset = irq.enabled = false;
+}
+
+static map_memwrite map64_memwrite[] =
+{
+ { 0x8000, 0xFFFF, map64_write },
+ { -1, -1, NULL }
+};
+
+mapintf_t map64_intf =
+{
+ 64, /* mapper number */
+ "Tengen RAMBO-1", /* mapper name */
+ map64_init, /* init routine */
+ NULL, /* vblank callback */
+ map64_hblank, /* hblank callback */
+ NULL, /* get state (snss) */
+ NULL, /* set state (snss) */
+ NULL, /* memory read structure */
+ map64_memwrite, /* memory write structure */
+ NULL /* external sound device */
+};
+
diff --git a/games/retrogo/src/nes/mappers/map065.c b/games/retrogo/src/nes/mappers/map065.c
new file mode 100644
index 00000000..9881c798
--- /dev/null
+++ b/games/retrogo/src/nes/mappers/map065.c
@@ -0,0 +1,113 @@
+/*
+** Nofrendo (c) 1998-2000 Matthew Conte ([email protected])
+**
+**
+** This program is free software; you can redistribute it and/or modify it under the terms of
+** the GNU General Public License as published by the Free Software Foundation; either version 3
+** of the License, or (at your option) any later version. (Nofrendo was released under version
+** 2 of the GNU Library General Public License; as its section 3 allows, this copy, changed for
+** Retro-Go on NumPlay, is under the GNU General Public License instead.)
+**
+** This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY;
+** without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
+** See the GNU General Public License for more details.
+**
+** Any permitted reproduction of these routines, in whole or in part,
+** must bear this legend.
+**
+**
+** map65.c
+**
+** mapper 65 interface
+** $Id: map065.c,v 1.2 2001/04/27 14:37:11 neil Exp $
+*/
+
+#include "noftypes.h"
+#include "nes_mmc.h"
+#include "nes_ppu.h"
+
+static struct
+{
+ int counter;
+ bool enabled;
+ int cycles;
+ uint8 low, high;
+} irq;
+
+static void map65_init(void)
+{
+ irq.counter = 0;
+ irq.enabled = false;
+ irq.low = irq.high = 0;
+ irq.cycles = 0;
+}
+
+/* TODO: shouldn't there be some kind of HBlank callback??? */
+
+/* mapper 65: Irem H-3001*/
+static void map65_write(uint32 address, uint8 value)
+{
+ int range = address & 0xF000;
+ int reg = address & 7;
+
+ switch (range)
+ {
+ case 0x8000:
+ case 0xA000:
+ case 0xC000:
+ mmc_bankrom(8, range, value);
+ break;
+
+ case 0xB000:
+ mmc_bankvrom(1, reg << 10, value);
+ break;
+
+ case 0x9000:
+ switch (reg)
+ {
+ case 4:
+ irq.enabled = (value & 0x01) ? false : true;
+ break;
+
+ case 5:
+ irq.high = value;
+ irq.cycles = (irq.high << 8) | irq.low;
+ irq.counter = (uint8)(irq.cycles / 128);
+ break;
+
+ case 6:
+ irq.low = value;
+ irq.cycles = (irq.high << 8) | irq.low;
+ irq.counter = (uint8)(irq.cycles / 128);
+ break;
+
+ default:
+ break;
+ }
+ break;
+
+ default:
+ break;
+ }
+}
+
+static map_memwrite map65_memwrite[] =
+{
+ { 0x8000, 0xFFFF, map65_write },
+ { -1, -1, NULL }
+};
+
+mapintf_t map65_intf =
+{
+ 65, /* mapper number */
+ "Irem H-3001", /* mapper name */
+ map65_init, /* init routine */
+ NULL, /* vblank callback */
+ NULL, /* hblank callback */
+ NULL, /* get state (snss) */
+ NULL, /* set state (snss) */
+ NULL, /* memory read structure */
+ map65_memwrite, /* memory write structure */
+ NULL /* external sound device */
+};
+
diff --git a/games/retrogo/src/nes/mappers/map066.c b/games/retrogo/src/nes/mappers/map066.c
new file mode 100644
index 00000000..b944e694
--- /dev/null
+++ b/games/retrogo/src/nes/mappers/map066.c
@@ -0,0 +1,63 @@
+/*
+** Nofrendo (c) 1998-2000 Matthew Conte ([email protected])
+**
+**
+** This program is free software; you can redistribute it and/or modify it under the terms of
+** the GNU General Public License as published by the Free Software Foundation; either version 3
+** of the License, or (at your option) any later version. (Nofrendo was released under version
+** 2 of the GNU Library General Public License; as its section 3 allows, this copy, changed for
+** Retro-Go on NumPlay, is under the GNU General Public License instead.)
+**
+** This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY;
+** without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
+** See the GNU General Public License for more details.
+**
+** Any permitted reproduction of these routines, in whole or in part,
+** must bear this legend.
+**
+**
+** map66.c
+**
+** mapper 66 interface
+** $Id: map066.c,v 1.2 2001/04/27 14:37:11 neil Exp $
+*/
+
+#include "noftypes.h"
+#include "nes_mmc.h"
+
+/* mapper 66: GNROM */
+static void map66_write(uint32 address, uint8 value)
+{
+ UNUSED(address);
+
+ mmc_bankrom(32, 0x8000, (value >> 4) & 3);
+ mmc_bankvrom(8, 0x0000, value & 3);
+}
+
+static void map66_init(void)
+{
+ mmc_bankrom(32, 0x8000, 0);
+ mmc_bankvrom(8, 0x0000, 0);
+}
+
+
+static map_memwrite map66_memwrite[] =
+{
+ { 0x8000, 0xFFFF, map66_write },
+ { -1, -1, NULL }
+};
+
+mapintf_t map66_intf =
+{
+ 66, /* mapper number */
+ "GNROM", /* mapper name */
+ map66_init, /* init routine */
+ NULL, /* vblank callback */
+ NULL, /* hblank callback */
+ NULL, /* get state (snss) */
+ NULL, /* set state (snss) */
+ NULL, /* memory read structure */
+ map66_memwrite, /* memory write structure */
+ NULL /* external sound device */
+};
+
diff --git a/games/retrogo/src/nes/mappers/map070.c b/games/retrogo/src/nes/mappers/map070.c
new file mode 100644
index 00000000..4b06ccad
--- /dev/null
+++ b/games/retrogo/src/nes/mappers/map070.c
@@ -0,0 +1,78 @@
+/*
+** Nofrendo (c) 1998-2000 Matthew Conte ([email protected])
+**
+**
+** This program is free software; you can redistribute it and/or modify it under the terms of
+** the GNU General Public License as published by the Free Software Foundation; either version 3
+** of the License, or (at your option) any later version. (Nofrendo was released under version
+** 2 of the GNU Library General Public License; as its section 3 allows, this copy, changed for
+** Retro-Go on NumPlay, is under the GNU General Public License instead.)
+**
+** This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY;
+** without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
+** See the GNU General Public License for more details.
+**
+** Any permitted reproduction of these routines, in whole or in part,
+** must bear this legend.
+**
+**
+** map70.c
+**
+** mapper 70 interface
+** $Id: map070.c,v 1.2 2001/04/27 14:37:11 neil Exp $
+*/
+
+#include "noftypes.h"
+#include "nes_mmc.h"
+#include "nes_ppu.h"
+
+/* mapper 70: Arkanoid II, Kamen Rider Club, etc. */
+/* ($8000-$FFFF) D6-D4 = switch $8000-$BFFF */
+/* ($8000-$FFFF) D3-D0 = switch PPU $0000-$1FFF */
+/* ($8000-$FFFF) D7 = switch mirroring */
+static void map70_write(uint32 address, uint8 value)
+{
+ UNUSED(address);
+
+ mmc_bankrom(16, 0x8000, (value >> 4) & 0x07);
+ mmc_bankvrom(8, 0x0000, value & 0x0F);
+
+ /* Argh! FanWen used the 4-screen bit to determine
+ ** whether the game uses D7 to switch between
+ ** horizontal and vertical mirroring, or between
+ ** one-screen mirroring from $2000 or $2400.
+ */
+ if (mmc_getinfo()->flags & ROM_FLAG_FOURSCREEN)
+ {
+ if (value & 0x80)
+ ppu_mirror(0, 0, 1, 1); /* horiz */
+ else
+ ppu_mirror(0, 1, 0, 1); /* vert */
+ }
+ else
+ {
+ int mirror = (value & 0x80) >> 7;
+ ppu_mirror(mirror, mirror, mirror, mirror);
+ }
+}
+
+static map_memwrite map70_memwrite[] =
+{
+ { 0x8000, 0xFFFF, map70_write },
+ { -1, -1, NULL }
+};
+
+mapintf_t map70_intf =
+{
+ 70, /* mapper number */
+ "Mapper 70", /* mapper name */
+ NULL, /* init routine */
+ NULL, /* vblank callback */
+ NULL, /* hblank callback */
+ NULL, /* get state (snss) */
+ NULL, /* set state (snss) */
+ NULL, /* memory read structure */
+ map70_memwrite, /* memory write structure */
+ NULL /* external sound device */
+};
+
diff --git a/games/retrogo/src/nes/mappers/map075.c b/games/retrogo/src/nes/mappers/map075.c
new file mode 100644
index 00000000..b0a9b40c
--- /dev/null
+++ b/games/retrogo/src/nes/mappers/map075.c
@@ -0,0 +1,97 @@
+/*
+** Nofrendo (c) 1998-2000 Matthew Conte ([email protected])
+**
+**
+** This program is free software; you can redistribute it and/or modify it under the terms of
+** the GNU General Public License as published by the Free Software Foundation; either version 3
+** of the License, or (at your option) any later version. (Nofrendo was released under version
+** 2 of the GNU Library General Public License; as its section 3 allows, this copy, changed for
+** Retro-Go on NumPlay, is under the GNU General Public License instead.)
+**
+** This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY;
+** without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
+** See the GNU General Public License for more details.
+**
+** Any permitted reproduction of these routines, in whole or in part,
+** must bear this legend.
+**
+**
+** map75.c
+**
+** mapper 75 interface
+** $Id: map075.c,v 1.2 2001/04/27 14:37:11 neil Exp $
+*/
+
+#include "noftypes.h"
+#include "nes_mmc.h"
+#include "nes_ppu.h"
+
+
+static uint8 latch[2];
+static uint8 hibits;
+
+/* mapper 75: Konami VRC1 */
+static void map75_write(uint32 address, uint8 value)
+{
+ switch ((address & 0xF000) >> 12)
+ {
+ case 0x8:
+ mmc_bankrom(8, 0x8000, value);
+ break;
+
+ case 0x9:
+ hibits = (value & 0x06);
+
+ mmc_bankvrom(4, 0x0000, ((hibits & 0x02) << 3) | latch[0]);
+ mmc_bankvrom(4, 0x1000, ((hibits & 0x04) << 2) | latch[1]);
+
+ if (value & 1)
+ ppu_mirror(0, 1, 0, 1); /* vert */
+ else
+ ppu_mirror(0, 0, 1, 1); /* horiz */
+
+ break;
+
+ case 0xA:
+ mmc_bankrom(8, 0xA000, value);
+ break;
+
+ case 0xC:
+ mmc_bankrom(8, 0xC000, value);
+ break;
+
+ case 0xE:
+ latch[0] = (value & 0x0F);
+ mmc_bankvrom(4, 0x0000, ((hibits & 0x02) << 3) | latch[0]);
+ break;
+
+ case 0xF:
+ latch[1] = (value & 0x0F);
+ mmc_bankvrom(4, 0x1000, ((hibits & 0x04) << 2) | latch[1]);
+ break;
+
+ default:
+ break;
+ }
+}
+
+static map_memwrite map75_memwrite[] =
+{
+ { 0x8000, 0xFFFF, map75_write },
+ { -1, -1, NULL }
+};
+
+mapintf_t map75_intf =
+{
+ 75, /* mapper number */
+ "Konami VRC1", /* mapper name */
+ NULL, /* init routine */
+ NULL, /* vblank callback */
+ NULL, /* hblank callback */
+ NULL, /* get state (snss) */
+ NULL, /* set state (snss) */
+ NULL, /* memory read structure */
+ map75_memwrite, /* memory write structure */
+ NULL /* external sound device */
+};
+
diff --git a/games/retrogo/src/nes/mappers/map078.c b/games/retrogo/src/nes/mappers/map078.c
new file mode 100644
index 00000000..2fe7234b
--- /dev/null
+++ b/games/retrogo/src/nes/mappers/map078.c
@@ -0,0 +1,74 @@
+/*
+** Nofrendo (c) 1998-2000 Matthew Conte ([email protected])
+**
+**
+** This program is free software; you can redistribute it and/or modify it under the terms of
+** the GNU General Public License as published by the Free Software Foundation; either version 3
+** of the License, or (at your option) any later version. (Nofrendo was released under version
+** 2 of the GNU Library General Public License; as its section 3 allows, this copy, changed for
+** Retro-Go on NumPlay, is under the GNU General Public License instead.)
+**
+** This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY;
+** without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
+** See the GNU General Public License for more details.
+**
+** Any permitted reproduction of these routines, in whole or in part,
+** must bear this legend.
+**
+**
+** map78.c
+**
+** mapper 78 interface
+** $Id: map078.c,v 1.2 2001/04/27 14:37:11 neil Exp $
+*/
+
+#include "noftypes.h"
+#include "nes_mmc.h"
+#include "nes_ppu.h"
+
+/* mapper 78: Holy Diver, Cosmo Carrier */
+/* ($8000-$FFFF) D2-D0 = switch $8000-$BFFF */
+/* ($8000-$FFFF) D7-D4 = switch PPU $0000-$1FFF */
+/* ($8000-$FFFF) D3 = switch mirroring */
+static void map78_write(uint32 address, uint8 value)
+{
+ UNUSED(address);
+
+ mmc_bankrom(16, 0x8000, value & 7);
+ mmc_bankvrom(8, 0x0000, (value >> 4) & 0x0F);
+
+ /* Ugh! Same abuse of the 4-screen bit as with Mapper #70 */
+ if (mmc_getinfo()->flags & ROM_FLAG_FOURSCREEN)
+ {
+ if (value & 0x08)
+ ppu_mirror(0, 1, 0, 1); /* vert */
+ else
+ ppu_mirror(0, 0, 1, 1); /* horiz */
+ }
+ else
+ {
+ int mirror = (value >> 3) & 1;
+ ppu_mirror(mirror, mirror, mirror, mirror);
+ }
+}
+
+static map_memwrite map78_memwrite[] =
+{
+ { 0x8000, 0xFFFF, map78_write },
+ { -1, -1, NULL }
+};
+
+mapintf_t map78_intf =
+{
+ 78, /* mapper number */
+ "Mapper 78", /* mapper name */
+ NULL, /* init routine */
+ NULL, /* vblank callback */
+ NULL, /* hblank callback */
+ NULL, /* get state (snss) */
+ NULL, /* set state (snss) */
+ NULL, /* memory read structure */
+ map78_memwrite, /* memory write structure */
+ NULL /* external sound device */
+};
+
diff --git a/games/retrogo/src/nes/mappers/map079.c b/games/retrogo/src/nes/mappers/map079.c
new file mode 100644
index 00000000..3a6085b4
--- /dev/null
+++ b/games/retrogo/src/nes/mappers/map079.c
@@ -0,0 +1,63 @@
+/*
+** Nofrendo (c) 1998-2000 Matthew Conte ([email protected])
+**
+**
+** This program is free software; you can redistribute it and/or modify it under the terms of
+** the GNU General Public License as published by the Free Software Foundation; either version 3
+** of the License, or (at your option) any later version. (Nofrendo was released under version
+** 2 of the GNU Library General Public License; as its section 3 allows, this copy, changed for
+** Retro-Go on NumPlay, is under the GNU General Public License instead.)
+**
+** This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY;
+** without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
+** See the GNU General Public License for more details.
+**
+** Any permitted reproduction of these routines, in whole or in part,
+** must bear this legend.
+**
+**
+** map78.c
+**
+** mapper 78 interface
+** $Id: map079.c,v 1.2 2001/04/27 14:37:11 neil Exp $
+*/
+
+#include "noftypes.h"
+#include "nes_mmc.h"
+
+/* mapper 79: NINA-03/06 */
+static void map79_write(uint32 address, uint8 value)
+{
+ if ((address & 0x5100) == 0x4100)
+ {
+ mmc_bankrom(32, 0x8000, (value >> 3) & 1);
+ mmc_bankvrom(8, 0x0000, value & 7);
+ }
+}
+
+static void map79_init(void)
+{
+ mmc_bankrom(32, 0x8000, 0);
+ mmc_bankvrom(8, 0x0000, 0);
+}
+
+static map_memwrite map79_memwrite[] =
+{
+ { 0x4100, 0x5FFF, map79_write }, /* ????? incorrect range ??? */
+ { -1, -1, NULL }
+};
+
+mapintf_t map79_intf =
+{
+ 79, /* mapper number */
+ "NINA-03/06", /* mapper name */
+ map79_init, /* init routine */
+ NULL, /* vblank callback */
+ NULL, /* hblank callback */
+ NULL, /* get state (snss) */
+ NULL, /* set state (snss) */
+ NULL, /* memory read structure */
+ map79_memwrite, /* memory write structure */
+ NULL /* external sound device */
+};
+
diff --git a/games/retrogo/src/nes/mappers/map085.c b/games/retrogo/src/nes/mappers/map085.c
new file mode 100644
index 00000000..d7c9681b
--- /dev/null
+++ b/games/retrogo/src/nes/mappers/map085.c
@@ -0,0 +1,182 @@
+/*
+** Nofrendo (c) 1998-2000 Matthew Conte ([email protected])
+**
+**
+** This program is free software; you can redistribute it and/or modify it under the terms of
+** the GNU General Public License as published by the Free Software Foundation; either version 3
+** of the License, or (at your option) any later version. (Nofrendo was released under version
+** 2 of the GNU Library General Public License; as its section 3 allows, this copy, changed for
+** Retro-Go on NumPlay, is under the GNU General Public License instead.)
+**
+** This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY;
+** without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
+** See the GNU General Public License for more details.
+**
+** Any permitted reproduction of these routines, in whole or in part,
+** must bear this legend.
+**
+**
+** map85.c
+**
+** mapper 85 interface
+** $Id: map085.c,v 1.3 2001/05/06 01:42:03 neil Exp $
+*/
+
+#include "noftypes.h"
+#include "nes_mmc.h"
+#include "nes.h"
+
+static struct
+{
+ int counter, latch;
+ int wait_state;
+ bool enabled;
+} irq;
+
+/* mapper 85: Konami VRC7 */
+static void map85_write(uint32 address, uint8 value)
+{
+ uint8 bank = address >> 12;
+ uint8 reg = (address & 0x10) | ((address & 0x08) << 1);
+
+ switch (bank)
+ {
+ case 0x08:
+ if (0x10 == reg)
+ mmc_bankrom(8, 0xA000, value);
+ else
+ mmc_bankrom(8, 0x8000, value);
+ break;
+
+ case 0x09:
+ /* 0x10 & 0x30 should be trapped by sound emulation */
+ mmc_bankrom(8, 0xC000, value);
+ break;
+
+ case 0x0A:
+ if (0x10 == reg)
+ mmc_bankvrom(1, 0x0400, value);
+ else
+ mmc_bankvrom(1, 0x0000, value);
+ break;
+
+ case 0x0B:
+ if (0x10 == reg)
+ mmc_bankvrom(1, 0x0C00, value);
+ else
+ mmc_bankvrom(1, 0x0800, value);
+ break;
+
+ case 0x0C:
+ if (0x10 == reg)
+ mmc_bankvrom(1, 0x1400, value);
+ else
+ mmc_bankvrom(1, 0x1000, value);
+ break;
+
+ case 0x0D:
+ if (0x10 == reg)
+ mmc_bankvrom(1, 0x1C00, value);
+ else
+ mmc_bankvrom(1, 0x1800, value);
+ break;
+
+ case 0x0E:
+ if (0x10 == reg)
+ {
+ irq.latch = value;
+ }
+ else
+ {
+ switch (value & 3)
+ {
+ case 0:
+ ppu_mirror(0, 1, 0, 1); /* vertical */
+ break;
+
+ case 1:
+ ppu_mirror(0, 0, 1, 1); /* horizontal */
+ break;
+
+ case 2:
+ ppu_mirror(0, 0, 0, 0);
+ break;
+
+ case 3:
+ ppu_mirror(1, 1, 1, 1);
+ break;
+ }
+ }
+ break;
+
+ case 0x0F:
+ if (0x10 == reg)
+ {
+ irq.enabled = irq.wait_state;
+ }
+ else
+ {
+ irq.wait_state = value & 0x01;
+ irq.enabled = (value & 0x02) ? true : false;
+ if (true == irq.enabled)
+ irq.counter = irq.latch;
+ }
+ break;
+
+ default:
+#ifdef NOFRENDO_DEBUG
+ log_printf("unhandled vrc7 write: $%02X to $%04X\n", value, address);
+#endif /* NOFRENDO_DEBUG */
+ break;
+ }
+}
+
+static void map85_hblank(int vblank)
+{
+ UNUSED(vblank);
+
+ if (irq.enabled)
+ {
+ if (++irq.counter > 0xFF)
+ {
+ irq.counter = irq.latch;
+ nes_irq();
+
+ //return;
+ }
+ //irq.counter++;
+ }
+}
+
+static map_memwrite map85_memwrite[] =
+{
+ { 0x8000, 0xFFFF, map85_write },
+ { -1, -1, NULL }
+};
+
+static void map85_init(void)
+{
+ mmc_bankrom(16, 0x8000, 0);
+ mmc_bankrom(16, 0xC000, MMC_LASTBANK);
+
+ mmc_bankvrom(8, 0x0000, 0);
+
+ irq.counter = irq.latch = 0;
+ irq.wait_state = 0;
+ irq.enabled = false;
+}
+
+mapintf_t map85_intf =
+{
+ 85, /* mapper number */
+ "Konami VRC7", /* mapper name */
+ map85_init, /* init routine */
+ NULL, /* vblank callback */
+ map85_hblank, /* hblank callback */
+ NULL, /* get state (snss) */
+ NULL, /* set state (snss) */
+ NULL, /* memory read structure */
+ map85_memwrite, /* memory write structure */
+ NULL
+};
+
diff --git a/games/retrogo/src/nes/mappers/map094.c b/games/retrogo/src/nes/mappers/map094.c
new file mode 100644
index 00000000..6a49ce44
--- /dev/null
+++ b/games/retrogo/src/nes/mappers/map094.c
@@ -0,0 +1,56 @@
+/*
+** Nofrendo (c) 1998-2000 Matthew Conte ([email protected])
+**
+**
+** This program is free software; you can redistribute it and/or modify it under the terms of
+** the GNU General Public License as published by the Free Software Foundation; either version 3
+** of the License, or (at your option) any later version. (Nofrendo was released under version
+** 2 of the GNU Library General Public License; as its section 3 allows, this copy, changed for
+** Retro-Go on NumPlay, is under the GNU General Public License instead.)
+**
+** This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY;
+** without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
+** See the GNU General Public License for more details.
+**
+** Any permitted reproduction of these routines, in whole or in part,
+** must bear this legend.
+**
+**
+** map94.c
+**
+** mapper 94 interface
+** $Id: map094.c,v 1.2 2001/04/27 14:37:11 neil Exp $
+*/
+
+#include "noftypes.h"
+#include "nes_mmc.h"
+
+/* mapper 94: Senjou no Ookami */
+static void map94_write(uint32 address, uint8 value)
+{
+ UNUSED(address);
+
+ /* ($8000-$FFFF) D7-D2 = switch $8000-$BFFF */
+ mmc_bankrom(16, 0x8000, value >> 2);
+}
+
+static map_memwrite map94_memwrite[] =
+{
+ { 0x8000, 0xFFFF, map94_write },
+ { -1, -1, NULL }
+};
+
+mapintf_t map94_intf =
+{
+ 94, /* mapper number */
+ "Mapper 94", /* mapper name */
+ NULL, /* init routine */
+ NULL, /* vblank callback */
+ NULL, /* hblank callback */
+ NULL, /* get state (snss) */
+ NULL, /* set state (snss) */
+ NULL, /* memory read structure */
+ map94_memwrite, /* memory write structure */
+ NULL /* external sound device */
+};
+
diff --git a/games/retrogo/src/nes/mappers/map099.c b/games/retrogo/src/nes/mappers/map099.c
new file mode 100644
index 00000000..2083d631
--- /dev/null
+++ b/games/retrogo/src/nes/mappers/map099.c
@@ -0,0 +1,56 @@
+/*
+** Nofrendo (c) 1998-2000 Matthew Conte ([email protected])
+**
+**
+** This program is free software; you can redistribute it and/or modify it under the terms of
+** the GNU General Public License as published by the Free Software Foundation; either version 3
+** of the License, or (at your option) any later version. (Nofrendo was released under version
+** 2 of the GNU Library General Public License; as its section 3 allows, this copy, changed for
+** Retro-Go on NumPlay, is under the GNU General Public License instead.)
+**
+** This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY;
+** without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
+** See the GNU General Public License for more details.
+**
+** Any permitted reproduction of these routines, in whole or in part,
+** must bear this legend.
+**
+**
+** map99.c
+**
+** mapper 99 interface
+** $Id: map099.c,v 1.2 2001/04/27 14:37:11 neil Exp $
+*/
+
+#include "noftypes.h"
+#include "nes_mmc.h"
+#include "nes_ppu.h"
+
+/* Switch VROM for VS games */
+static void map99_vromswitch(uint8 value)
+{
+ int bank = (value & 0x04) >> 2;
+ mmc_bankvrom(8, 0x0000, bank);
+}
+
+/* mapper 99: VS. System */
+static void map99_init(void)
+{
+ ppu_mirror(0, 1, 2, 3);
+ ppu_setvromswitch(map99_vromswitch);
+}
+
+mapintf_t map99_intf =
+{
+ 99, /* mapper number */
+ "VS. System", /* mapper name */
+ map99_init, /* init routine */
+ NULL, /* vblank callback */
+ NULL, /* hblank callback */
+ NULL, /* get state (snss) */
+ NULL, /* set state (snss) */
+ NULL, /* memory read structure */
+ NULL, /* memory write structure */
+ NULL /* external sound device */
+};
+
diff --git a/games/retrogo/src/nes/mappers/map231.c b/games/retrogo/src/nes/mappers/map231.c
new file mode 100644
index 00000000..9707f9c0
--- /dev/null
+++ b/games/retrogo/src/nes/mappers/map231.c
@@ -0,0 +1,66 @@
+/*
+** Nofrendo (c) 1998-2000 Matthew Conte ([email protected])
+**
+**
+** This program is free software; you can redistribute it and/or modify it under the terms of
+** the GNU General Public License as published by the Free Software Foundation; either version 3
+** of the License, or (at your option) any later version. (Nofrendo was released under version
+** 2 of the GNU Library General Public License; as its section 3 allows, this copy, changed for
+** Retro-Go on NumPlay, is under the GNU General Public License instead.)
+**
+** This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY;
+** without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
+** See the GNU General Public License for more details.
+**
+** Any permitted reproduction of these routines, in whole or in part,
+** must bear this legend.
+**
+**
+** map231.c
+**
+** mapper 231 interface
+** $Id: map231.c,v 1.2 2001/04/27 14:37:11 neil Exp $
+*/
+
+#include "noftypes.h"
+#include "nes_mmc.h"
+
+/* mapper 231: NINA-07, used in Wally Bear and the NO! Gang */
+
+static void map231_init(void)
+{
+ mmc_bankrom(32, 0x8000, MMC_LASTBANK);
+}
+
+static void map231_write(uint32 address, uint8 value)
+{
+ int bank, vbank;
+ UNUSED(address);
+
+ bank = ((value & 0x80) >> 5) | (value & 0x03);
+ vbank = (value >> 4) & 0x07;
+
+ mmc_bankrom(32, 0x8000, bank);
+ mmc_bankvrom(8, 0x0000, vbank);
+}
+
+static map_memwrite map231_memwrite[] =
+{
+ { 0x8000, 0xFFFF, map231_write },
+ { -1, -1, NULL }
+};
+
+mapintf_t map231_intf =
+{
+ 231, /* mapper number */
+ "NINA-07", /* mapper name */
+ map231_init, /* init routine */
+ NULL, /* vblank callback */
+ NULL, /* hblank callback */
+ NULL, /* get state (snss) */
+ NULL, /* set state (snss) */
+ NULL, /* memory read structure */
+ map231_memwrite, /* memory write structure */
+ NULL /* external sound device */
+};
+
diff --git a/games/retrogo/src/nes/mappers/mapvrc.c b/games/retrogo/src/nes/mappers/mapvrc.c
new file mode 100644
index 00000000..e30bd854
--- /dev/null
+++ b/games/retrogo/src/nes/mappers/mapvrc.c
@@ -0,0 +1,405 @@
+/*
+** Nofrendo (c) 1998-2000 Matthew Conte ([email protected])
+**
+**
+** This program is free software; you can redistribute it and/or modify it under the terms of
+** the GNU General Public License as published by the Free Software Foundation; either version 3
+** of the License, or (at your option) any later version. (Nofrendo was released under version
+** 2 of the GNU Library General Public License; as its section 3 allows, this copy, changed for
+** Retro-Go on NumPlay, is under the GNU General Public License instead.)
+**
+** This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY;
+** without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
+** See the GNU General Public License for more details.
+**
+** Any permitted reproduction of these routines, in whole or in part,
+** must bear this legend.
+**
+**
+** map_vrc.c
+**
+** VRC mapper interface
+** $Id: mapvrc.c,v 1.2 2001/04/27 14:37:11 neil Exp $
+*/
+
+#include "noftypes.h"
+#include "nes_mmc.h"
+#include "nes.h"
+
+#define VRC_VBANK(bank, value, high) \
+{ \
+ if ((high)) \
+ highnybbles[(bank)] = (value) & 0x0F; \
+ else \
+ lownybbles[(bank)] = (value) & 0x0F; \
+ mmc_bankvrom(1, (bank) << 10, (highnybbles[(bank)] << 4)+lownybbles[(bank)]); \
+}
+
+static struct
+{
+ int counter, enabled;
+ int latch, wait_state;
+} irq;
+
+static int select_c000 = 0;
+static uint8 lownybbles[8];
+static uint8 highnybbles[8];
+
+static void vrc_init(void)
+{
+ irq.counter = irq.enabled = 0;
+ irq.latch = irq.wait_state = 0;
+}
+
+static void map21_write(uint32 address, uint8 value)
+{
+ switch (address)
+ {
+ case 0x8000:
+ if (select_c000)
+ mmc_bankrom(8, 0xC000,value);
+ else
+ mmc_bankrom(8, 0x8000,value);
+ break;
+
+ case 0x9000:
+ switch (value & 3)
+ {
+ case 0:
+ ppu_mirror(0, 1, 0, 1); /* vertical */
+ break;
+
+ case 1:
+ ppu_mirror(0, 0, 1, 1); /* horizontal */
+ break;
+
+ case 2:
+ ppu_mirror(0, 0, 0, 0);
+ break;
+
+ case 3:
+ ppu_mirror(1, 1, 1, 1);
+ break;
+
+ default:
+ break;
+ }
+ break;
+ case 0x9002: select_c000=(value&0x02)>>1; break;
+ case 0xA000: mmc_bankrom(8, 0xA000,value); break;
+
+ case 0xB000: VRC_VBANK(0,value,0); break;
+ case 0xB002:
+ case 0xB040: VRC_VBANK(0,value,1); break;
+ case 0xB001:
+ case 0xB004:
+ case 0xB080: VRC_VBANK(1,value,0); break;
+ case 0xB003:
+ case 0xB006:
+ case 0xB0C0: VRC_VBANK(1,value,1); break;
+ case 0xC000: VRC_VBANK(2,value,0); break;
+ case 0xC002:
+ case 0xC040: VRC_VBANK(2,value,1); break;
+ case 0xC001:
+ case 0xC004:
+ case 0xC080: VRC_VBANK(3,value,0); break;
+ case 0xC003:
+ case 0xC006:
+ case 0xC0C0: VRC_VBANK(3,value,1); break;
+ case 0xD000: VRC_VBANK(4,value,0); break;
+ case 0xD002:
+ case 0xD040: VRC_VBANK(4,value,1); break;
+ case 0xD001:
+ case 0xD004:
+ case 0xD080: VRC_VBANK(5,value,0); break;
+ case 0xD003:
+ case 0xD006:
+ case 0xD0C0: VRC_VBANK(5,value,1); break;
+ case 0xE000: VRC_VBANK(6,value,0); break;
+ case 0xE002:
+ case 0xE040: VRC_VBANK(6,value,1); break;
+ case 0xE001:
+ case 0xE004:
+ case 0xE080: VRC_VBANK(7,value,0); break;
+ case 0xE003:
+ case 0xE006:
+ case 0xE0C0: VRC_VBANK(7,value,1); break;
+
+ case 0xF000:
+ irq.latch &= 0xF0;
+ irq.latch |= (value & 0x0F);
+ break;
+ case 0xF002:
+ case 0xF040:
+ irq.latch &= 0x0F;
+ irq.latch |= ((value & 0x0F) << 4);
+ break;
+ case 0xF004:
+ case 0xF001:
+ case 0xF080:
+ irq.enabled = (value >> 1) & 0x01;
+ irq.wait_state = value & 0x01;
+ irq.counter = irq.latch;
+ break;
+ case 0xF006:
+ case 0xF003:
+ case 0xF0C0:
+ irq.enabled = irq.wait_state;
+ break;
+
+ default:
+#ifdef NOFRENDO_DEBUG
+ log_printf("wrote $%02X to $%04X", value, address);
+#endif
+ break;
+ }
+}
+
+static void map22_write(uint32 address, uint8 value)
+{
+ int reg = address >> 12;
+
+ switch (reg)
+ {
+ case 0x8:
+ mmc_bankrom(8, 0x8000, value);
+ break;
+
+ case 0xA:
+ mmc_bankrom(8, 0xA000, value);
+ break;
+
+ case 0x9:
+ switch (value & 3)
+ {
+ case 0:
+ ppu_mirror(0, 1, 0, 1); /* vertical */
+ break;
+
+ case 1:
+ ppu_mirror(0, 0, 1, 1); /* horizontal */
+ break;
+
+ case 2:
+ ppu_mirror(1, 1, 1, 1);
+ break;
+
+ case 3:
+ ppu_mirror(0, 0, 0, 0);
+ break;
+ }
+ break;
+
+ case 0xB:
+ case 0xC:
+ case 0xD:
+ case 0xE:
+ {
+ int loc = (((reg - 0xB) << 1) + (address & 1)) << 10;
+ mmc_bankvrom(1, loc, value >> 1);
+ }
+ break;
+
+ default:
+ break;
+ }
+}
+
+static void map23_write(uint32 address, uint8 value)
+{
+ switch (address)
+ {
+ case 0x8000:
+ case 0x8FFF:
+ mmc_bankrom(8, 0x8000, value);
+ break;
+
+ case 0xA000:
+ case 0xAFFF:
+ mmc_bankrom(8, 0xA000, value);
+ break;
+
+ case 0x9000:
+ case 0x9004:
+ case 0x9008:
+ switch(value & 3)
+ {
+ case 0:
+ ppu_mirror(0, 1, 0, 1); /* vertical */
+ break;
+
+ case 1:
+ ppu_mirror(0, 0, 1, 1); /* horizontal */
+ break;
+
+ case 2:
+ ppu_mirror(0, 0, 0, 0);
+ break;
+
+ case 3:
+ ppu_mirror(1, 1, 1, 1);
+ break;
+ }
+ break;
+
+ case 0xB000: VRC_VBANK(0,value,0); break;
+ case 0xB001:
+ case 0xB004: VRC_VBANK(0,value,1); break;
+ case 0xB002:
+ case 0xB008: VRC_VBANK(1,value,0); break;
+ case 0xB003:
+ case 0xB00C: VRC_VBANK(1,value,1); break;
+ case 0xC000: VRC_VBANK(2,value,0); break;
+ case 0xC001:
+ case 0xC004: VRC_VBANK(2,value,1); break;
+ case 0xC002:
+ case 0xC008: VRC_VBANK(3,value,0); break;
+ case 0xC003:
+ case 0xC00C: VRC_VBANK(3,value,1); break;
+ case 0xD000: VRC_VBANK(4,value,0); break;
+ case 0xD001:
+ case 0xD004: VRC_VBANK(4,value,1); break;
+ case 0xD002:
+ case 0xD008: VRC_VBANK(5,value,0); break;
+ case 0xD003:
+ case 0xD00C: VRC_VBANK(5,value,1); break;
+ case 0xE000: VRC_VBANK(6,value,0); break;
+ case 0xE001:
+ case 0xE004: VRC_VBANK(6,value,1); break;
+ case 0xE002:
+ case 0xE008: VRC_VBANK(7,value,0); break;
+ case 0xE003:
+ case 0xE00C: VRC_VBANK(7,value,1); break;
+
+ case 0xF000:
+ irq.latch &= 0xF0;
+ irq.latch |= (value & 0x0F);
+ break;
+
+ case 0xF004:
+ irq.latch &= 0x0F;
+ irq.latch |= ((value & 0x0F) << 4);
+ break;
+
+ case 0xF008:
+ irq.enabled = (value >> 1) & 0x01;
+ irq.wait_state = value & 0x01;
+ irq.counter = irq.latch;
+ break;
+
+ case 0xF00C:
+ irq.enabled = irq.wait_state;
+ break;
+
+ default:
+#ifdef NOFRENDO_DEBUG
+ log_printf("wrote $%02X to $%04X",value,address);
+#endif
+ break;
+ }
+}
+
+static void vrc_hblank(int vblank)
+{
+ UNUSED(vblank);
+
+ if (irq.enabled)
+ {
+ if (256 == ++irq.counter)
+ {
+ irq.counter = irq.latch;
+ nes_irq();
+ //irq.enabled = false;
+ irq.enabled = irq.wait_state;
+ }
+ }
+}
+
+
+
+static map_memwrite map21_memwrite[] =
+{
+ { 0x8000, 0xFFFF, map21_write },
+ { -1, -1, NULL }
+};
+
+static map_memwrite map22_memwrite[] =
+{
+ { 0x8000, 0xFFFF, map22_write },
+ { -1, -1, NULL }
+};
+
+static map_memwrite map23_memwrite[] =
+{
+ { 0x8000, 0xFFFF, map23_write },
+ { -1, -1, NULL }
+};
+
+static void map21_getstate(SnssMapperBlock *state)
+{
+ state->extraData.mapper21.irqCounter = irq.counter;
+ state->extraData.mapper21.irqCounterEnabled = irq.enabled;
+}
+
+static void map21_setstate(SnssMapperBlock *state)
+{
+ irq.counter = state->extraData.mapper21.irqCounter;
+ irq.enabled = state->extraData.mapper21.irqCounterEnabled;
+}
+
+mapintf_t map21_intf =
+{
+ 21, /* mapper number */
+ "Konami VRC4 A", /* mapper name */
+ vrc_init, /* init routine */
+ NULL, /* vblank callback */
+ vrc_hblank, /* hblank callback */
+ map21_getstate, /* get state (snss) */
+ map21_setstate, /* set state (snss) */
+ NULL, /* memory read structure */
+ map21_memwrite, /* memory write structure */
+ NULL /* external sound device */
+};
+
+mapintf_t map22_intf =
+{
+ 22, /* mapper number */
+ "Konami VRC2 A", /* mapper name */
+ vrc_init, /* init routine */
+ NULL, /* vblank callback */
+ NULL, /* hblank callback */
+ NULL, /* get state (snss) */
+ NULL, /* set state (snss) */
+ NULL, /* memory read structure */
+ map22_memwrite, /* memory write structure */
+ NULL /* external sound device */
+};
+
+mapintf_t map23_intf =
+{
+ 23, /* mapper number */
+ "Konami VRC2 B", /* mapper name */
+ vrc_init, /* init routine */
+ NULL, /* vblank callback */
+ vrc_hblank, /* hblank callback */
+ NULL, /* get state (snss) */
+ NULL, /* set state (snss) */
+ NULL, /* memory read structure */
+ map23_memwrite, /* memory write structure */
+ NULL /* external sound device */
+};
+
+mapintf_t map25_intf =
+{
+ 25, /* mapper number */
+ "Konami VRC4 B", /* mapper name */
+ NULL, /* init routine */
+ NULL, /* vblank callback */
+ vrc_hblank, /* hblank callback */
+ NULL, /* get state (snss) */
+ NULL, /* set state (snss) */
+ NULL, /* memory read structure */
+ map21_memwrite, /* memory write structure */
+ NULL /* external sound device */
+};
+
diff --git a/games/retrogo/src/nes/mmclist.c b/games/retrogo/src/nes/mmclist.c
new file mode 100644
index 00000000..1c017589
--- /dev/null
+++ b/games/retrogo/src/nes/mmclist.c
@@ -0,0 +1,103 @@
+/*
+** Nofrendo (c) 1998-2000 Matthew Conte ([email protected])
+**
+**
+** This program is free software; you can redistribute it and/or modify it under the terms of
+** the GNU General Public License as published by the Free Software Foundation; either version 3
+** of the License, or (at your option) any later version. (Nofrendo was released under version
+** 2 of the GNU Library General Public License; as its section 3 allows, this copy, changed for
+** Retro-Go on NumPlay, is under the GNU General Public License instead.)
+**
+** This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY;
+** without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
+** See the GNU General Public License for more details.
+**
+** Any permitted reproduction of these routines, in whole or in part,
+** must bear this legend.
+**
+**
+** mmclist.c
+**
+** list of all mapper interfaces
+** $Id: mmclist.c,v 1.2 2001/04/27 14:37:11 neil Exp $
+*/
+
+#include "noftypes.h"
+#include "nes_mmc.h"
+
+/* mapper interfaces */
+extern mapintf_t map0_intf;
+extern mapintf_t map1_intf;
+extern mapintf_t map2_intf;
+extern mapintf_t map3_intf;
+extern mapintf_t map4_intf;
+extern mapintf_t map5_intf;
+extern mapintf_t map7_intf;
+extern mapintf_t map8_intf;
+extern mapintf_t map9_intf;
+extern mapintf_t map11_intf;
+extern mapintf_t map15_intf;
+extern mapintf_t map16_intf;
+extern mapintf_t map18_intf;
+extern mapintf_t map19_intf;
+extern mapintf_t map21_intf;
+extern mapintf_t map22_intf;
+extern mapintf_t map23_intf;
+extern mapintf_t map24_intf;
+extern mapintf_t map25_intf;
+extern mapintf_t map32_intf;
+extern mapintf_t map33_intf;
+extern mapintf_t map34_intf;
+extern mapintf_t map40_intf;
+extern mapintf_t map64_intf;
+extern mapintf_t map65_intf;
+extern mapintf_t map66_intf;
+extern mapintf_t map70_intf;
+extern mapintf_t map75_intf;
+extern mapintf_t map78_intf;
+extern mapintf_t map79_intf;
+extern mapintf_t map85_intf;
+extern mapintf_t map94_intf;
+extern mapintf_t map99_intf;
+extern mapintf_t map231_intf;
+
+/* implemented mapper interfaces */
+mapintf_t *mappers[] =
+{
+ &map0_intf,
+ &map1_intf,
+ &map2_intf,
+ &map3_intf,
+ &map4_intf,
+ &map5_intf,
+ &map7_intf,
+ &map8_intf,
+ &map9_intf,
+ &map11_intf,
+ &map15_intf,
+ &map16_intf,
+ &map18_intf,
+ &map19_intf,
+ &map21_intf,
+ &map22_intf,
+ &map23_intf,
+ &map24_intf,
+ &map25_intf,
+ &map32_intf,
+ &map33_intf,
+ &map34_intf,
+ &map40_intf,
+ &map64_intf,
+ &map65_intf,
+ &map66_intf,
+ &map70_intf,
+ &map75_intf,
+ &map78_intf,
+ &map79_intf,
+ &map85_intf,
+ &map94_intf,
+ &map99_intf,
+ &map231_intf,
+ NULL
+};
+
diff --git a/games/retrogo/src/nes/mmclist.h b/games/retrogo/src/nes/mmclist.h
new file mode 100644
index 00000000..c22d0484
--- /dev/null
+++ b/games/retrogo/src/nes/mmclist.h
@@ -0,0 +1,33 @@
+/*
+** Nofrendo (c) 1998-2000 Matthew Conte ([email protected])
+**
+**
+** This program is free software; you can redistribute it and/or modify it under the terms of
+** the GNU General Public License as published by the Free Software Foundation; either version 3
+** of the License, or (at your option) any later version. (Nofrendo was released under version
+** 2 of the GNU Library General Public License; as its section 3 allows, this copy, changed for
+** Retro-Go on NumPlay, is under the GNU General Public License instead.)
+**
+** This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY;
+** without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
+** See the GNU General Public License for more details.
+**
+** Any permitted reproduction of these routines, in whole or in part,
+** must bear this legend.
+**
+**
+** mmclist.h
+**
+** list of all mapper interfaces
+** $Id: mmclist.h,v 1.2 2001/04/27 14:37:11 neil Exp $
+*/
+
+#ifndef _MMCLIST_H_
+#define _MMCLIST_H_
+
+#include "nes_mmc.h"
+
+extern mapintf_t *mappers[];
+
+#endif /* !_MMCLIST_H_ */
+
diff --git a/games/retrogo/src/nes/nes.c b/games/retrogo/src/nes/nes.c
new file mode 100644
index 00000000..76868d85
--- /dev/null
+++ b/games/retrogo/src/nes/nes.c
@@ -0,0 +1,572 @@
+/*
+** Nofrendo (c) 1998-2000 Matthew Conte ([email protected])
+**
+** This program is free software; you can redistribute it and/or modify it under the terms of
+** the GNU General Public License as published by the Free Software Foundation; either version 3
+** of the License, or (at your option) any later version. (Nofrendo was released under version
+** 2 of the GNU Library General Public License; as its section 3 allows, this copy, changed for
+** Retro-Go on NumPlay, is under the GNU General Public License instead.)
+**
+** This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY;
+** without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
+** See the GNU General Public License for more details.
+**
+** Any permitted reproduction of these routines, in whole or in part, must bear this legend.
+**
+** nes.c: the NES machine, from nofrendo's nes.c (its address handlers, frame IRQ and frame of
+** 262 scanlines) and nes_rom.c (the iNES header). Changed for Retro-Go on NumPlay: one static
+** machine, the cartridge read in place from the calculator's flash, RAM from Retro-Go's block,
+** the pads, the palettes, the battery RAM and save states.
+*/
+
+#include "noftypes.h"
+#include "nes.h"
+#include "mmclist.h"
+#include "nes_core.h"
+
+#define NES_CLOCK_DIVIDER 12
+#define NES_MASTER_CLOCK (236250000 / 11)
+#define NES_SCANLINE_CYCLES (1364.0f / NES_CLOCK_DIVIDER)
+#define NES_FIQ_PERIOD (NES_MASTER_CLOCK / NES_CLOCK_DIVIDER / 60)
+
+#define NES_RAMSIZE 0x800
+
+nes_t nes;
+uint8 *nes_rom_lo, *nes_rom_hi;
+static uint8 *ram;
+static bool sram_dirty;
+
+nes_t *nes_getcontextptr(void)
+{
+ return &nes;
+}
+
+static uint8 ram_read(uint32 address)
+{
+ return ram[address & (NES_RAMSIZE - 1)];
+}
+
+static void ram_write(uint32 address, uint8 value)
+{
+ ram[address & (NES_RAMSIZE - 1)] = value;
+}
+
+/* $6000-$7FFF: the cartridge's RAM, unless its mapper put ROM there */
+static void wram_write(uint32 address, uint8 value)
+{
+ uint8 *p = nes6502_pages()[(address >> 12) & 15] + (address & 0xFFF);
+ if (p >= nes_rom_lo && p < nes_rom_hi)
+ return;
+ if (*p != value)
+ {
+ *p = value;
+ if (p >= nes.rominfo.sram && p < nes.rominfo.sram + 0x2000)
+ sram_dirty = true;
+ }
+}
+
+static void write_protect(uint32 address, uint8 value)
+{
+ /* don't allow write to go through */
+ UNUSED(address);
+ UNUSED(value);
+}
+
+static uint8 read_protect(uint32 address)
+{
+ /* don't allow read to go through */
+ UNUSED(address);
+
+ return 0xFF;
+}
+
+#define LAST_MEMORY_HANDLER { -1, -1, NULL }
+/* read/write handlers for standard NES */
+static const nes6502_memread default_readhandler[] =
+{
+ { 0x0800, 0x1FFF, ram_read },
+ { 0x2000, 0x3FFF, ppu_read },
+ { 0x4000, 0x4015, apu_read },
+ { 0x4016, 0x4017, ppu_readhigh },
+ LAST_MEMORY_HANDLER
+};
+
+static const nes6502_memwrite default_writehandler[] =
+{
+ { 0x0800, 0x1FFF, ram_write },
+ { 0x2000, 0x3FFF, ppu_write },
+ { 0x4000, 0x4013, apu_write },
+ { 0x4015, 0x4015, apu_write },
+ { 0x4014, 0x4017, ppu_writehigh },
+ LAST_MEMORY_HANDLER
+};
+
+/* this big nasty boy sets up the address handlers that the CPU uses */
+static void build_address_handlers(void)
+{
+ int count, num_handlers = 0;
+ mapintf_t *intf = mmc.intf;
+
+ memset(nes.readhandler, 0, sizeof(nes.readhandler));
+ memset(nes.writehandler, 0, sizeof(nes.writehandler));
+
+ for (count = 0; default_readhandler[count].read_func; count++)
+ nes.readhandler[num_handlers++] = default_readhandler[count];
+ if (intf->mem_read)
+ for (count = 0; intf->mem_read[count].read_func && num_handlers < MAX_MEM_HANDLERS - 2; count++)
+ {
+ nes.readhandler[num_handlers].min_range = intf->mem_read[count].min_range;
+ nes.readhandler[num_handlers].max_range = intf->mem_read[count].max_range;
+ nes.readhandler[num_handlers++].read_func = intf->mem_read[count].read_func;
+ }
+ nes.readhandler[num_handlers++] = (nes6502_memread){ 0x4018, 0x5FFF, read_protect };
+ nes.readhandler[num_handlers++] = (nes6502_memread)LAST_MEMORY_HANDLER;
+
+ num_handlers = 0;
+ for (count = 0; default_writehandler[count].write_func; count++)
+ nes.writehandler[num_handlers++] = default_writehandler[count];
+ if (intf->mem_write)
+ for (count = 0; intf->mem_write[count].write_func && num_handlers < MAX_MEM_HANDLERS - 4; count++)
+ {
+ nes.writehandler[num_handlers].min_range = intf->mem_write[count].min_range;
+ nes.writehandler[num_handlers].max_range = intf->mem_write[count].max_range;
+ nes.writehandler[num_handlers++].write_func = intf->mem_write[count].write_func;
+ }
+ /* catch-all for bad writes */
+ nes.writehandler[num_handlers++] = (nes6502_memwrite){ 0x4018, 0x5FFF, write_protect };
+ nes.writehandler[num_handlers++] = (nes6502_memwrite){ 0x6000, 0x7FFF, wram_write };
+ nes.writehandler[num_handlers++] = (nes6502_memwrite){ 0x8000, 0xFFFF, write_protect };
+ nes.writehandler[num_handlers++] = (nes6502_memwrite)LAST_MEMORY_HANDLER;
+}
+
+/* raise an IRQ */
+void nes_irq(void)
+{
+ nes6502_irq();
+}
+
+uint8 nes_clearfiq(void)
+{
+ if (nes.fiq_occurred)
+ {
+ nes.fiq_occurred = false;
+ return 0x40;
+ }
+
+ return 0;
+}
+
+void nes_setfiq(uint8 value)
+{
+ nes.fiq_state = value;
+ nes.fiq_cycles = (int) NES_FIQ_PERIOD;
+}
+
+static void nes_checkfiq(int cycles)
+{
+ nes.fiq_cycles -= cycles;
+ if (nes.fiq_cycles <= 0)
+ {
+ nes.fiq_cycles += (int) NES_FIQ_PERIOD;
+ if (0 == (nes.fiq_state & 0xC0))
+ {
+ nes.fiq_occurred = true;
+ nes6502_irq();
+ }
+ }
+}
+
+void nes_nmi(void)
+{
+ nes6502_nmi();
+}
+
+static void nes_renderframe(bool draw_flag)
+{
+ int elapsed_cycles;
+ mapintf_t *mapintf = mmc.intf;
+ int in_vblank = 0;
+
+ while (262 != nes.scanline)
+ {
+ ppu_scanline(nes.scanline, draw_flag);
+
+ if (241 == nes.scanline)
+ {
+ /* 7-9 cycle delay between when VINT flag goes up and NMI is taken */
+ elapsed_cycles = nes6502_execute(7);
+ nes.scanline_cycles -= elapsed_cycles;
+ nes_checkfiq(elapsed_cycles);
+
+ ppu_checknmi();
+
+ if (mapintf->vblank)
+ mapintf->vblank();
+ in_vblank = 1;
+ }
+
+ if (mapintf->hblank)
+ mapintf->hblank(in_vblank);
+
+ nes.scanline_cycles += (float) NES_SCANLINE_CYCLES;
+ elapsed_cycles = nes6502_execute((int) nes.scanline_cycles);
+ nes.scanline_cycles -= (float) elapsed_cycles;
+ nes_checkfiq(elapsed_cycles);
+
+ ppu_endscanline(nes.scanline);
+ nes.scanline++;
+ }
+
+ nes.scanline = 0;
+}
+
+/* Reset NES hardware */
+void nes_reset(int reset_type)
+{
+ if (HARD_RESET == reset_type)
+ {
+ memset(ram, 0, NES_RAMSIZE);
+ if (nes.rominfo.vram)
+ memset(nes.rominfo.vram, 0, 0x2000);
+ }
+
+ apu_reset();
+ ppu_reset(reset_type);
+ mmc_reset();
+ nes6502_reset();
+
+ nes.scanline = 241;
+ nes.scanline_cycles = 0;
+ nes.fiq_cycles = (int) NES_FIQ_PERIOD;
+}
+
+/* ------------------------------------------------------------ the pads */
+static uint8 pad_now, pad_shift[2];
+
+void input_strobe(void)
+{
+ pad_shift[0] = pad_now;
+ pad_shift[1] = 0;
+}
+
+uint8 input_get(int port)
+{
+ int p = (port & INP_JOYPAD1) ? 1 : 0;
+ uint8 bit = pad_shift[p] & 1;
+ pad_shift[p] = (uint8) (pad_shift[p] >> 1 | 0x80); /* (1s once the 8 buttons are read) */
+ return 0x40 | bit;
+}
+
+void nes_set_pad(int rg_pad)
+{
+ /* the order the NES reads them in is Retro-Go's: A B Select Start Up Down Left Right */
+ pad_now = (uint8) rg_pad;
+}
+
+/* ------------------------------------------------------------ the palettes */
+/* nofrendo's own (its nes_pal.c generator: hue 334, tint 0.4), and the 2C02's composite signal
+ decoded (games/retrogo/tools/nespal.py makes both) */
+static const uint16 palettes[NES_PAL_COUNT][64] = {
+ {
+ 0x8410, 0x12B3, 0x41D6, 0x7114, 0x98B0, 0xB0AA, 0xA103, 0x81E0,
+ 0x52C0, 0x1B80, 0x0402, 0x03E8, 0x038E, 0x0000, 0x0020, 0x0020,
+ 0xC618, 0x3C19, 0x6B1B, 0xA259, 0xC9F5, 0xD9EF, 0xCA68, 0xAB23,
+ 0x7C01, 0x44C2, 0x1D47, 0x0D4D, 0x14D4, 0x39E7, 0x0841, 0x0841,
+ 0xFFFF, 0x865F, 0xB55F, 0xE49F, 0xFC3E, 0xFC38, 0xFCB1, 0xF56C,
+ 0xC64A, 0x8F0B, 0x6790, 0x5796, 0x5F1C, 0x7BCF, 0x0861, 0x0861,
+ 0xFFFF, 0xAF9F, 0xDEBF, 0xFDFF, 0xFD9F, 0xFD9D, 0xFDF7, 0xFED2,
+ 0xEFB0, 0xBFF1, 0x97F5, 0x87FB, 0x8FFF, 0xC638, 0x1082, 0x1082
+ },
+ {
+ 0x630C, 0x00F1, 0x2073, 0x4010, 0x580B, 0x6004, 0x5880, 0x4140,
+ 0x21C0, 0x0240, 0x0260, 0x0225, 0x01AC, 0x0000, 0x0000, 0x0000,
+ 0xAD55, 0x2A7C, 0x59BE, 0x811B, 0xA0F4, 0xA94A, 0xA1E0, 0x7AC0,
+ 0x53A0, 0x2440, 0x0461, 0x040B, 0x0B75, 0x0000, 0x0000, 0x0000,
+ 0xFFFF, 0x7D1F, 0xAC3F, 0xD39F, 0xFB7E, 0xFBD4, 0xF469, 0xD562,
+ 0xA640, 0x76C3, 0x56EB, 0x4EB5, 0x5DFF, 0x4A69, 0x0000, 0x0000,
+ 0xFFFF, 0xCEDF, 0xDE7F, 0xEE3F, 0xFE3F, 0xFE5B, 0xFE97, 0xEEF4,
+ 0xDF53, 0xCF94, 0xBF97, 0xB77B, 0xBF3F, 0xBDD7, 0x0000, 0x0000
+ },
+};
+
+void nes_set_palette(int pal)
+{
+ nes_palette565 = palettes[pal >= 0 && pal < NES_PAL_COUNT ? pal : 0];
+}
+
+void nes_set_sprite_limit(bool on)
+{
+ ppu_limit_sprites = on;
+}
+
+/* ------------------------------------------------------------ the cartridge */
+#define ROM_INES_MAGIC "NES\x1A"
+
+int nes_load(const uint8_t *data, uint32_t size)
+{
+ rominfo_t *r = &nes.rominfo;
+
+ if (!data || size < 16 + 0x4000 || memcmp(data, ROM_INES_MAGIC, 4))
+ return RG_ERR_ROM;
+ memset(&nes, 0, sizeof nes);
+ if (!nes_palette565)
+ nes_set_palette(NES_PAL_NTSC);
+
+ /* the iNES header (nofrendo's rom_getheader) */
+ uint8 flags6 = data[6], flags7 = data[7];
+ r->rom_banks = data[4];
+ r->vrom_banks = data[5];
+ r->sram_banks = 8; /* 1kB banks, so 8KB */
+ r->vram_banks = 1; /* 8kB banks, so 8KB */
+ r->mirror = (flags6 & 0x01) ? MIRROR_VERT : MIRROR_HORIZ;
+ r->flags = 0;
+ if (flags6 & 0x02)
+ r->flags |= ROM_FLAG_BATTERY;
+ if (flags6 & 0x04)
+ r->flags |= ROM_FLAG_TRAINER;
+ if (flags6 & 0x08)
+ r->flags |= ROM_FLAG_FOURSCREEN;
+ r->mapper_number = flags6 >> 4;
+ /* the high nybble only from a clean header (or NES 2.0's); `DiskDude!' and other tags wrote
+ over it */
+ static const uint8 zero[8];
+ if (!memcmp(data + 8, zero, 8) || (flags7 & 0x0C) == 0x08)
+ r->mapper_number |= (flags7 & 0xF0);
+ if (99 == r->mapper_number)
+ r->flags |= ROM_FLAG_VERSUS;
+
+ uint32 at = 16 + ((r->flags & ROM_FLAG_TRAINER) ? 512 : 0);
+ if (!r->rom_banks || at + (uint32) r->rom_banks * 0x4000 > size)
+ return RG_ERR_ROM;
+ if (!mmc_init(r))
+ return RG_ERR_MAPPER;
+ /* (a ROM file cut short keeps the CHR banks it has) */
+ uint32 chr_at = at + (uint32) r->rom_banks * 0x4000;
+ if (chr_at + (uint32) r->vrom_banks * 0x2000 > size)
+ r->vrom_banks = (int) ((size - chr_at) / 0x2000);
+ r->rom = (uint8 *) data + at;
+ r->vrom = r->vrom_banks ? (uint8 *) data + chr_at : NULL;
+ nes_rom_lo = (uint8 *) data;
+ nes_rom_hi = (uint8 *) data + size;
+
+ rg_alloc_reset();
+ ram = rg_alloc(NES_RAMSIZE);
+ r->sram = rg_alloc(0x2000);
+ r->vram = r->vrom_banks ? NULL : rg_alloc(0x2000);
+ nes6502_null_page = rg_alloc(NES6502_BANKSIZE);
+ if (!ram || !r->sram || (!r->vrom_banks && !r->vram) || !nes6502_null_page)
+ return RG_ERR_MEMORY;
+ if (r->flags & ROM_FLAG_TRAINER)
+ memcpy(r->sram + 0x1000, data + 16, 512);
+
+ /* the CPU's memory: RAM, the cartridge's RAM at $6000-$7FFF, the rest unmapped */
+ nes6502_context cpu;
+ memset(&cpu, 0, sizeof cpu);
+ cpu.mem_page[0] = ram;
+ cpu.mem_page[6] = r->sram;
+ cpu.mem_page[7] = r->sram + 0x1000;
+ cpu.read_handler = nes.readhandler;
+ cpu.write_handler = nes.writehandler;
+ build_address_handlers();
+ nes6502_setcontext(&cpu);
+ memset(&ppu, 0, sizeof ppu);
+ ppu.vram_present = r->vram != NULL;
+ nes_reset(HARD_RESET);
+ sram_dirty = false;
+ return RG_OK;
+}
+
+void nes_reset_machine(bool hard)
+{
+ nes_reset(hard ? HARD_RESET : SOFT_RESET);
+}
+
+void nes_run_frame(bool draw)
+{
+ rg_drawing = draw;
+ nes_renderframe(draw);
+ apu_halfframe();
+ apu_halfframe();
+}
+
+void nes_redraw(void)
+{
+ ppu_redraw();
+}
+
+int nes_mapper(void)
+{
+ return nes.rominfo.mapper_number;
+}
+
+/* ------------------------------------------------------------ battery RAM */
+uint8_t *nes_sram(uint32_t *size)
+{
+ *size = 0x2000;
+ return (nes.rominfo.flags & ROM_FLAG_BATTERY) ? nes.rominfo.sram : NULL;
+}
+
+bool nes_sram_dirty(void)
+{
+ return (nes.rominfo.flags & ROM_FLAG_BATTERY) && sram_dirty;
+}
+
+void nes_sram_saved(void)
+{
+ sram_dirty = false;
+}
+
+/* ------------------------------------------------------------ save states */
+/* A memory page as a save state keeps it: which memory, and where in it (the pointers
+ themselves change from one build to the next). */
+enum { AREA_NULL, AREA_PRG, AREA_CHR, AREA_SRAM, AREA_VRAM, AREA_RAM, AREA_NAMETAB, AREA_COUNT };
+typedef struct { uint8 area; uint32 offset; } page_ref_t;
+
+static struct
+{
+ uint32 pc;
+ uint8 a, p, x, y, s, jammed, int_pending, int_latency;
+ int32 total_cycles, burn_cycles;
+ page_ref_t cpu_pages[NES6502_NUMBANKS], ppu_pages[16];
+ uint8 fiq_occurred;
+ uint8 fiq_state, pad_shift[2];
+ int fiq_cycles, scanline;
+ float scanline_cycles;
+ SnssMapperBlock mapper;
+} snap;
+
+static uint8 *area_base(int area, uint32 *size)
+{
+ rominfo_t *r = &nes.rominfo;
+ switch (area)
+ {
+ case AREA_PRG: *size = (uint32) r->rom_banks * 0x4000; return r->rom;
+ case AREA_CHR: *size = (uint32) r->vrom_banks * 0x2000; return r->vrom;
+ case AREA_SRAM: *size = 0x2000; return r->sram;
+ case AREA_VRAM: *size = r->vram ? 0x2000 : 0; return r->vram;
+ case AREA_RAM: *size = NES_RAMSIZE; return ram;
+ case AREA_NAMETAB: *size = sizeof ppu.nametab; return ppu.nametab;
+ default: *size = 0; return NULL;
+ }
+}
+
+static page_ref_t ref_of(const uint8 *p)
+{
+ for (int a = AREA_PRG; a < AREA_COUNT; a++)
+ {
+ uint32 size;
+ uint8 *base = area_base(a, &size);
+ if (base && p >= base && p < base + size)
+ return (page_ref_t){ (uint8) a, (uint32) (p - base) };
+ }
+ return (page_ref_t){ AREA_NULL, 0 };
+}
+
+/* the memory a page refers to, if that much of it is there (NULL otherwise) */
+static uint8 *page_of(page_ref_t r, uint32 length)
+{
+ uint32 size;
+ uint8 *base = area_base(r.area, &size);
+ if (!base || r.offset > size || size - r.offset < length)
+ return NULL;
+ return base + r.offset;
+}
+
+int nes_state_chunks(rg_chunk_t *out)
+{
+ nes6502_context cpu;
+ nes6502_getcontext(&cpu);
+ snap.pc = cpu.pc_reg, snap.a = cpu.a_reg, snap.p = cpu.p_reg, snap.x = cpu.x_reg;
+ snap.y = cpu.y_reg, snap.s = cpu.s_reg, snap.jammed = cpu.jammed;
+ snap.int_pending = cpu.int_pending, snap.int_latency = cpu.int_latency;
+ snap.total_cycles = cpu.total_cycles, snap.burn_cycles = cpu.burn_cycles;
+ for (int i = 0; i < NES6502_NUMBANKS; i++)
+ snap.cpu_pages[i] = cpu.mem_page[i] ? ref_of(cpu.mem_page[i]) : (page_ref_t){ AREA_NULL, 0 };
+ for (int i = 0; i < 16; i++)
+ snap.ppu_pages[i] = ref_of(ppu.page[i] + (i << 10));
+ snap.fiq_occurred = nes.fiq_occurred, snap.fiq_state = nes.fiq_state;
+ snap.fiq_cycles = nes.fiq_cycles, snap.scanline = nes.scanline;
+ snap.scanline_cycles = nes.scanline_cycles;
+ snap.pad_shift[0] = pad_shift[0], snap.pad_shift[1] = pad_shift[1];
+ memset(&snap.mapper, 0, sizeof snap.mapper);
+ if (mmc.intf->get_state)
+ mmc.intf->get_state(&snap.mapper);
+
+ int n = 0;
+ out[n++] = (rg_chunk_t){ &snap, sizeof snap };
+ out[n++] = (rg_chunk_t){ &ppu, sizeof ppu };
+ out[n++] = (rg_chunk_t){ &apu, sizeof apu };
+ out[n++] = (rg_chunk_t){ ram, NES_RAMSIZE };
+ out[n++] = (rg_chunk_t){ nes.rominfo.sram, 0x2000 };
+ if (nes.rominfo.vram)
+ out[n++] = (rg_chunk_t){ nes.rominfo.vram, 0x2000 };
+ return n;
+}
+
+/* whatever the state held, a machine this cartridge can be */
+void nes_state_loaded(void)
+{
+ ppulatchfunc_t latch = NULL;
+ ppuvromswitch_t vrom = NULL;
+ /* (the mapper's callbacks are its own, not the state's) */
+ mmc_reset();
+ latch = ppu.latchfunc;
+ vrom = ppu.vromswitch;
+
+ nes6502_context cpu;
+ nes6502_getcontext(&cpu);
+ cpu.pc_reg = snap.pc & 0xFFFF, cpu.a_reg = snap.a, cpu.p_reg = snap.p, cpu.x_reg = snap.x;
+ cpu.y_reg = snap.y, cpu.s_reg = snap.s, cpu.jammed = snap.jammed != 0;
+ cpu.int_pending = snap.int_pending & 1, cpu.int_latency = snap.int_latency;
+ cpu.total_cycles = snap.total_cycles;
+ cpu.burn_cycles = snap.burn_cycles >= 0 && snap.burn_cycles < 1000 ? snap.burn_cycles : 0;
+ cpu.mem_page[0] = ram;
+ for (int i = 6; i < NES6502_NUMBANKS; i++)
+ {
+ uint8 *p = page_of(snap.cpu_pages[i], NES6502_BANKSIZE);
+ cpu.mem_page[i] = p ? p : (i < 8 ? nes.rominfo.sram + (i - 6) * 0x1000 : NULL);
+ }
+ if (!cpu.mem_page[8]) /* (never left without code) */
+ for (int i = 8; i < 16; i++)
+ cpu.mem_page[i] = nes.rominfo.rom + ((i - 8) * 0x1000) % ((uint32) nes.rominfo.rom_banks * 0x4000);
+ cpu.read_handler = nes.readhandler;
+ cpu.write_handler = nes.writehandler;
+ nes6502_setcontext(&cpu);
+
+ for (int i = 0; i < 16; i++)
+ {
+ uint8 *p = page_of(snap.ppu_pages[i], 0x400);
+ if (!p)
+ p = i < 8 ? (nes.rominfo.vrom ? nes.rominfo.vrom : nes.rominfo.vram) + (i << 10)
+ : ppu.nametab + ((i & 3) << 10);
+ ppu.page[i] = p - (i << 10);
+ }
+ ppu.latchfunc = latch;
+ ppu_pages_changed = true;
+ ppu.vromswitch = vrom;
+ ppu.vram_present = nes.rominfo.vram != NULL;
+ /* the registers' derived values, from the registers */
+ /* (flags read back as bytes: any byte a true or false) */
+ bool *flags[] = { &ppu.bg_on, &ppu.obj_on, &ppu.obj_mask, &ppu.bg_mask, &ppu.strikeflag, &ppu.vram_accessible };
+ for (unsigned k = 0; k < sizeof flags / sizeof flags[0]; k++)
+ {
+ uint8 v;
+ memcpy(&v, flags[k], 1);
+ *flags[k] = v != 0;
+ }
+ ppu_write(PPU_CTRL0, ppu.ctrl0);
+ ppu_write(PPU_CTRL1, ppu.ctrl1);
+ ppu.vaddr &= 0x3FFF;
+ ppu.vaddr_latch &= 0x7FFF;
+ ppu.tile_xofs &= 7;
+ ppu.flipflop &= 1;
+
+ nes.fiq_occurred = snap.fiq_occurred != 0, nes.fiq_state = snap.fiq_state;
+ nes.fiq_cycles = snap.fiq_cycles > 0 && snap.fiq_cycles <= (int) NES_FIQ_PERIOD ? snap.fiq_cycles : (int) NES_FIQ_PERIOD;
+ nes.scanline = snap.scanline >= 0 && snap.scanline < 262 ? snap.scanline : 0;
+ nes.scanline_cycles = snap.scanline_cycles > -1000.0f && snap.scanline_cycles < 1000.0f ? snap.scanline_cycles : 0;
+ pad_shift[0] = snap.pad_shift[0], pad_shift[1] = snap.pad_shift[1];
+ if (mmc.intf->set_state)
+ mmc.intf->set_state(&snap.mapper);
+ sram_dirty = true;
+}
diff --git a/games/retrogo/src/nes/nes.h b/games/retrogo/src/nes/nes.h
new file mode 100644
index 00000000..7d60a502
--- /dev/null
+++ b/games/retrogo/src/nes/nes.h
@@ -0,0 +1,77 @@
+/*
+** Nofrendo (c) 1998-2000 Matthew Conte ([email protected])
+**
+** This program is free software; you can redistribute it and/or modify it under the terms of
+** the GNU General Public License as published by the Free Software Foundation; either version 3
+** of the License, or (at your option) any later version. (Nofrendo was released under version
+** 2 of the GNU Library General Public License; as its section 3 allows, this copy, changed for
+** Retro-Go on NumPlay, is under the GNU General Public License instead.)
+**
+** This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY;
+** without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
+** See the GNU General Public License for more details.
+**
+** Any permitted reproduction of these routines, in whole or in part, must bear this legend.
+**
+** nes.h: the NES machine. Retro-Go on NumPlay keeps one, static, with its cartridge read in
+** place.
+*/
+
+#ifndef _NES_H_
+#define _NES_H_
+
+#include "noftypes.h"
+#include "nes_apu.h"
+#include "nes_mmc.h"
+#include "nes_ppu.h"
+#include "nes_rom.h"
+#include "nes6502.h"
+
+#define NES_SCREEN_WIDTH 256
+#define NES_SCREEN_HEIGHT 240
+#define NES_REFRESH_RATE 60
+
+#define MAX_MEM_HANDLERS 32
+
+enum
+{
+ SOFT_RESET,
+ HARD_RESET
+};
+
+typedef struct nes_s
+{
+ nes6502_memread readhandler[MAX_MEM_HANDLERS];
+ nes6502_memwrite writehandler[MAX_MEM_HANDLERS];
+ rominfo_t rominfo;
+
+ bool fiq_occurred;
+ uint8 fiq_state;
+ int fiq_cycles;
+
+ int scanline;
+
+ /* Timing stuff */
+ float scanline_cycles;
+} nes_t;
+
+extern nes_t nes;
+/* the cartridge's bytes: nothing writes there */
+extern uint8 *nes_rom_lo, *nes_rom_hi;
+extern uint8 *nes6502_null_page;
+
+extern nes_t *nes_getcontextptr(void);
+extern void nes_setfiq(uint8 state);
+extern uint8 nes_clearfiq(void);
+extern void nes_nmi(void);
+extern void nes_irq(void);
+extern void nes_reset(int reset_type);
+
+/* the pads */
+#define INP_JOYPAD0 0x0001
+#define INP_JOYPAD1 0x0002
+#define INP_ZAPPER 0x0004
+extern void input_strobe(void);
+extern uint8 input_get(int port);
+
+#endif /* _NES_H_ */
diff --git a/games/retrogo/src/nes/nes6502.c b/games/retrogo/src/nes/nes6502.c
new file mode 100644
index 00000000..18a89d36
--- /dev/null
+++ b/games/retrogo/src/nes/nes6502.c
@@ -0,0 +1,2478 @@
+/*
+** Nofrendo (c) 1998-2000 Matthew Conte ([email protected])
+**
+**
+** This program is free software; you can redistribute it and/or modify it under the terms of
+** the GNU General Public License as published by the Free Software Foundation; either version 3
+** of the License, or (at your option) any later version. (Nofrendo was released under version
+** 2 of the GNU Library General Public License; as its section 3 allows, this copy, changed for
+** Retro-Go on NumPlay, is under the GNU General Public License instead.)
+**
+** This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY;
+** without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
+** See the GNU General Public License for more details.
+**
+** Any permitted reproduction of these routines, in whole or in part,
+** must bear this legend.
+**
+**
+** nes6502.c
+**
+** NES custom 6502 (2A03) CPU implementation
+** $Id: nes6502.c,v 1.2 2001/04/27 14:37:11 neil Exp $
+*/
+
+
+#include "noftypes.h"
+#include "nes6502.h"
+#include "nes.h"
+
+
+//#define NES6502_DISASM
+
+#ifdef __GNUC__
+#define NES6502_JUMPTABLE
+#endif /* __GNUC__ */
+
+
+#define ADD_CYCLES(x) \
+{ \
+ remaining_cycles -= (x); \
+ cpu.total_cycles += (x); \
+}
+
+/*
+** Check to see if an index reg addition overflowed to next page
+*/
+#define PAGE_CROSS_CHECK(addr, reg) \
+{ \
+ if ((reg) > (uint8) (addr)) \
+ ADD_CYCLES(1); \
+}
+
+#define EMPTY_READ(value) /* empty */
+
+/*
+** Addressing mode macros
+*/
+
+/* Immediate */
+#define IMMEDIATE_BYTE(value) \
+{ \
+ value = bank_readbyte(PC++); \
+}
+
+/* Absolute */
+#define ABSOLUTE_ADDR(address) \
+{ \
+ address = bank_readword(PC); \
+ PC += 2; \
+}
+
+#define ABSOLUTE(address, value) \
+{ \
+ ABSOLUTE_ADDR(address); \
+ value = mem_readbyte(address); \
+}
+
+#define ABSOLUTE_BYTE(value) \
+{ \
+ ABSOLUTE(temp, value); \
+}
+
+/* Absolute indexed X */
+#define ABS_IND_X_ADDR(address) \
+{ \
+ ABSOLUTE_ADDR(address); \
+ address = (address + X) & 0xFFFF; \
+}
+
+#define ABS_IND_X(address, value) \
+{ \
+ ABS_IND_X_ADDR(address); \
+ value = mem_readbyte(address); \
+}
+
+#define ABS_IND_X_BYTE(value) \
+{ \
+ ABS_IND_X(temp, value); \
+}
+
+/* special page-cross check version for read instructions */
+#define ABS_IND_X_BYTE_READ(value) \
+{ \
+ ABS_IND_X_ADDR(temp); \
+ PAGE_CROSS_CHECK(temp, X); \
+ value = mem_readbyte(temp); \
+}
+
+/* Absolute indexed Y */
+#define ABS_IND_Y_ADDR(address) \
+{ \
+ ABSOLUTE_ADDR(address); \
+ address = (address + Y) & 0xFFFF; \
+}
+
+#define ABS_IND_Y(address, value) \
+{ \
+ ABS_IND_Y_ADDR(address); \
+ value = mem_readbyte(address); \
+}
+
+#define ABS_IND_Y_BYTE(value) \
+{ \
+ ABS_IND_Y(temp, value); \
+}
+
+/* special page-cross check version for read instructions */
+#define ABS_IND_Y_BYTE_READ(value) \
+{ \
+ ABS_IND_Y_ADDR(temp); \
+ PAGE_CROSS_CHECK(temp, Y); \
+ value = mem_readbyte(temp); \
+}
+
+/* Zero-page */
+#define ZERO_PAGE_ADDR(address) \
+{ \
+ IMMEDIATE_BYTE(address); \
+}
+
+#define ZERO_PAGE(address, value) \
+{ \
+ ZERO_PAGE_ADDR(address); \
+ value = ZP_READBYTE(address); \
+}
+
+#define ZERO_PAGE_BYTE(value) \
+{ \
+ ZERO_PAGE(btemp, value); \
+}
+
+/* Zero-page indexed X */
+#define ZP_IND_X_ADDR(address) \
+{ \
+ ZERO_PAGE_ADDR(address); \
+ address += X; \
+}
+
+#define ZP_IND_X(address, value) \
+{ \
+ ZP_IND_X_ADDR(address); \
+ value = ZP_READBYTE(address); \
+}
+
+#define ZP_IND_X_BYTE(value) \
+{ \
+ ZP_IND_X(btemp, value); \
+}
+
+/* Zero-page indexed Y */
+/* Not really an adressing mode, just for LDx/STx */
+#define ZP_IND_Y_ADDR(address) \
+{ \
+ ZERO_PAGE_ADDR(address); \
+ address += Y; \
+}
+
+#define ZP_IND_Y_BYTE(value) \
+{ \
+ ZP_IND_Y_ADDR(btemp); \
+ value = ZP_READBYTE(btemp); \
+}
+
+/* Indexed indirect */
+#define INDIR_X_ADDR(address) \
+{ \
+ ZERO_PAGE_ADDR(btemp); \
+ btemp += X; \
+ address = zp_readword(btemp); \
+}
+
+#define INDIR_X(address, value) \
+{ \
+ INDIR_X_ADDR(address); \
+ value = mem_readbyte(address); \
+}
+
+#define INDIR_X_BYTE(value) \
+{ \
+ INDIR_X(temp, value); \
+}
+
+/* Indirect indexed */
+#define INDIR_Y_ADDR(address) \
+{ \
+ ZERO_PAGE_ADDR(btemp); \
+ address = (zp_readword(btemp) + Y) & 0xFFFF; \
+}
+
+#define INDIR_Y(address, value) \
+{ \
+ INDIR_Y_ADDR(address); \
+ value = mem_readbyte(address); \
+}
+
+#define INDIR_Y_BYTE(value) \
+{ \
+ INDIR_Y(temp, value); \
+}
+
+/* special page-cross check version for read instructions */
+#define INDIR_Y_BYTE_READ(value) \
+{ \
+ INDIR_Y_ADDR(temp); \
+ PAGE_CROSS_CHECK(temp, Y); \
+ value = mem_readbyte(temp); \
+}
+
+
+
+/* Stack push/pull */
+#define PUSH(value) stack[S--] = (uint8) (value)
+#define PULL() stack[++S]
+
+
+/*
+** flag register helper macros
+*/
+
+/* Theory: Z and N flags are set in just about every
+** instruction, so we will just store the value in those
+** flag variables, and mask out the irrelevant data when
+** we need to check them (branches, etc). This makes the
+** zero flag only really be 'set' when z_flag == 0.
+** The rest of the flags are stored as true booleans.
+*/
+
+/* Scatter flags to separate variables */
+#define SCATTER_FLAGS(value) \
+{ \
+ n_flag = (value) & N_FLAG; \
+ v_flag = (value) & V_FLAG; \
+ b_flag = (value) & B_FLAG; \
+ d_flag = (value) & D_FLAG; \
+ i_flag = (value) & I_FLAG; \
+ z_flag = (0 == ((value) & Z_FLAG)); \
+ c_flag = (value) & C_FLAG; \
+}
+
+/* Combine flags into flag register */
+#define COMBINE_FLAGS() \
+( \
+ (n_flag & N_FLAG) \
+ | (v_flag ? V_FLAG : 0) \
+ | R_FLAG \
+ | (b_flag ? B_FLAG : 0) \
+ | (d_flag ? D_FLAG : 0) \
+ | (i_flag ? I_FLAG : 0) \
+ | (z_flag ? 0 : Z_FLAG) \
+ | c_flag \
+)
+
+/* Set N and Z flags based on given value */
+#define SET_NZ_FLAGS(value) n_flag = z_flag = (value);
+
+/* For BCC, BCS, BEQ, BMI, BNE, BPL, BVC, BVS */
+#define RELATIVE_BRANCH(condition) \
+{ \
+ if (condition) \
+ { \
+ IMMEDIATE_BYTE(btemp); \
+ if (((int8) btemp + (PC & 0x00FF)) & 0x100) \
+ ADD_CYCLES(1); \
+ ADD_CYCLES(3); \
+ PC += (int8) btemp; \
+ } \
+ else \
+ { \
+ PC++; \
+ ADD_CYCLES(2); \
+ } \
+}
+
+#define JUMP(address) \
+{ \
+ PC = bank_readword((address)); \
+}
+
+/*
+** Interrupt macros
+*/
+#define NMI_PROC() \
+{ \
+ PUSH(PC >> 8); \
+ PUSH(PC & 0xFF); \
+ b_flag = 0; \
+ PUSH(COMBINE_FLAGS()); \
+ i_flag = 1; \
+ JUMP(NMI_VECTOR); \
+}
+
+#define IRQ_PROC() \
+{ \
+ PUSH(PC >> 8); \
+ PUSH(PC & 0xFF); \
+ b_flag = 0; \
+ PUSH(COMBINE_FLAGS()); \
+ i_flag = 1; \
+ JUMP(IRQ_VECTOR); \
+}
+
+/*
+** Instruction macros
+*/
+
+/* Warning! NES CPU has no decimal mode, so by default this does no BCD! */
+#ifdef NES6502_DECIMAL
+#define ADC(cycles, read_func) \
+{ \
+ read_func(data); \
+ if (d_flag) \
+ { \
+ temp = (A & 0x0F) + (data & 0x0F) + c_flag; \
+ if (temp >= 10) \
+ temp = (temp - 10) | 0x10; \
+ temp += (A & 0xF0) + (data & 0xF0); \
+ z_flag = (A + data + c_flag) & 0xFF; \
+ n_flag = temp; \
+ v_flag = ((~(A ^ data)) & (A ^ temp) & 0x80); \
+ if (temp > 0x90) \
+ { \
+ temp += 0x60; \
+ c_flag = 1; \
+ } \
+ else \
+ { \
+ c_flag = 0; \
+ } \
+ A = (uint8) temp; \
+ } \
+ else \
+ { \
+ temp = A + data + c_flag; \
+ c_flag = (temp >> 8) & 1; \
+ v_flag = ((~(A ^ data)) & (A ^ temp) & 0x80); \
+ A = (uint8) temp; \
+ SET_NZ_FLAGS(A); \
+ }\
+ ADD_CYCLES(cycles); \
+}
+#else
+#define ADC(cycles, read_func) \
+{ \
+ read_func(data); \
+ temp = A + data + c_flag; \
+ c_flag = (temp >> 8) & 1; \
+ v_flag = ((~(A ^ data)) & (A ^ temp) & 0x80); \
+ A = (uint8) temp; \
+ SET_NZ_FLAGS(A); \
+ ADD_CYCLES(cycles); \
+}
+#endif /* NES6502_DECIMAL */
+
+/* undocumented */
+#define ANC(cycles, read_func) \
+{ \
+ read_func(data); \
+ A &= data; \
+ c_flag = (n_flag & N_FLAG) >> 7; \
+ SET_NZ_FLAGS(A); \
+ ADD_CYCLES(cycles); \
+}
+
+#define AND(cycles, read_func) \
+{ \
+ read_func(data); \
+ A &= data; \
+ SET_NZ_FLAGS(A); \
+ ADD_CYCLES(cycles); \
+}
+
+/* undocumented */
+#define ANE(cycles, read_func) \
+{ \
+ read_func(data); \
+ A = (A | 0xEE) & X & data; \
+ SET_NZ_FLAGS(A); \
+ ADD_CYCLES(cycles); \
+}
+
+/* undocumented */
+#ifdef NES6502_DECIMAL
+#define ARR(cycles, read_func) \
+{ \
+ read_func(data); \
+ data &= A; \
+ if (d_flag) \
+ { \
+ temp = (data >> 1) | (c_flag << 7); \
+ SET_NZ_FLAGS(temp); \
+ v_flag = (temp ^ data) & 0x40; \
+ if (((data & 0x0F) + (data & 0x01)) > 5) \
+ temp = (temp & 0xF0) | ((temp + 0x6) & 0x0F); \
+ if (((data & 0xF0) + (data & 0x10)) > 0x50) \
+ { \
+ temp = (temp & 0x0F) | ((temp + 0x60) & 0xF0); \
+ c_flag = 1; \
+ } \
+ else \
+ { \
+ c_flag = 0; \
+ } \
+ A = (uint8) temp; \
+ } \
+ else \
+ { \
+ A = (data >> 1) | (c_flag << 7); \
+ SET_NZ_FLAGS(A); \
+ c_flag = (A & 0x40) >> 6; \
+ v_flag = ((A >> 6) ^ (A >> 5)) & 1; \
+ }\
+ ADD_CYCLES(cycles); \
+}
+#else
+#define ARR(cycles, read_func) \
+{ \
+ read_func(data); \
+ data &= A; \
+ A = (data >> 1) | (c_flag << 7); \
+ SET_NZ_FLAGS(A); \
+ c_flag = (A & 0x40) >> 6; \
+ v_flag = ((A >> 6) ^ (A >> 5)) & 1; \
+ ADD_CYCLES(cycles); \
+}
+#endif /* NES6502_DECIMAL */
+
+#define ASL(cycles, read_func, write_func, addr) \
+{ \
+ read_func(addr, data); \
+ c_flag = data >> 7; \
+ data <<= 1; \
+ write_func(addr, data); \
+ SET_NZ_FLAGS(data); \
+ ADD_CYCLES(cycles); \
+}
+
+#define ASL_A() \
+{ \
+ c_flag = A >> 7; \
+ A <<= 1; \
+ SET_NZ_FLAGS(A); \
+ ADD_CYCLES(2); \
+}
+
+/* undocumented */
+#define ASR(cycles, read_func) \
+{ \
+ read_func(data); \
+ data &= A; \
+ c_flag = data & 1; \
+ A = data >> 1; \
+ SET_NZ_FLAGS(A); \
+ ADD_CYCLES(cycles); \
+}
+
+#define BCC() \
+{ \
+ RELATIVE_BRANCH(0 == c_flag); \
+}
+
+#define BCS() \
+{ \
+ RELATIVE_BRANCH(0 != c_flag); \
+}
+
+#define BEQ() \
+{ \
+ RELATIVE_BRANCH(0 == z_flag); \
+}
+
+/* bit 7/6 of data move into N/V flags */
+#define BIT(cycles, read_func) \
+{ \
+ read_func(data); \
+ n_flag = data; \
+ v_flag = data & V_FLAG; \
+ z_flag = data & A; \
+ ADD_CYCLES(cycles); \
+}
+
+#define BMI() \
+{ \
+ RELATIVE_BRANCH(n_flag & N_FLAG); \
+}
+
+#define BNE() \
+{ \
+ RELATIVE_BRANCH(0 != z_flag); \
+}
+
+#define BPL() \
+{ \
+ RELATIVE_BRANCH(0 == (n_flag & N_FLAG)); \
+}
+
+/* Software interrupt type thang */
+#define BRK() \
+{ \
+ PC++; \
+ PUSH(PC >> 8); \
+ PUSH(PC & 0xFF); \
+ b_flag = 1; \
+ PUSH(COMBINE_FLAGS()); \
+ i_flag = 1; \
+ JUMP(IRQ_VECTOR); \
+ ADD_CYCLES(7); \
+}
+
+#define BVC() \
+{ \
+ RELATIVE_BRANCH(0 == v_flag); \
+}
+
+#define BVS() \
+{ \
+ RELATIVE_BRANCH(0 != v_flag); \
+}
+
+#define CLC() \
+{ \
+ c_flag = 0; \
+ ADD_CYCLES(2); \
+}
+
+#define CLD() \
+{ \
+ d_flag = 0; \
+ ADD_CYCLES(2); \
+}
+
+#define CLI() \
+{ \
+ i_flag = 0; \
+ ADD_CYCLES(2); \
+ if (cpu.int_pending && remaining_cycles > 0) \
+ { \
+ cpu.int_pending = 0; \
+ IRQ_PROC(); \
+ ADD_CYCLES(INT_CYCLES); \
+ } \
+}
+
+#define CLV() \
+{ \
+ v_flag = 0; \
+ ADD_CYCLES(2); \
+}
+
+/* C is clear when data > A */
+#define _COMPARE(reg, value) \
+{ \
+ temp = (reg) - (value); \
+ c_flag = ((temp & 0x100) >> 8) ^ 1; \
+ SET_NZ_FLAGS((uint8) temp); \
+}
+
+#define CMP(cycles, read_func) \
+{ \
+ read_func(data); \
+ _COMPARE(A, data); \
+ ADD_CYCLES(cycles); \
+}
+
+#define CPX(cycles, read_func) \
+{ \
+ read_func(data); \
+ _COMPARE(X, data); \
+ ADD_CYCLES(cycles); \
+}
+
+#define CPY(cycles, read_func) \
+{ \
+ read_func(data); \
+ _COMPARE(Y, data); \
+ ADD_CYCLES(cycles); \
+}
+
+/* undocumented */
+#define DCP(cycles, read_func, write_func, addr) \
+{ \
+ read_func(addr, data); \
+ data--; \
+ write_func(addr, data); \
+ CMP(cycles, EMPTY_READ); \
+}
+
+#define DEC(cycles, read_func, write_func, addr) \
+{ \
+ read_func(addr, data); \
+ data--; \
+ write_func(addr, data); \
+ SET_NZ_FLAGS(data); \
+ ADD_CYCLES(cycles); \
+}
+
+#define DEX() \
+{ \
+ X--; \
+ SET_NZ_FLAGS(X); \
+ ADD_CYCLES(2); \
+}
+
+#define DEY() \
+{ \
+ Y--; \
+ SET_NZ_FLAGS(Y); \
+ ADD_CYCLES(2); \
+}
+
+/* undocumented (double-NOP) */
+#define DOP(cycles) \
+{ \
+ PC++; \
+ ADD_CYCLES(cycles); \
+}
+
+#define EOR(cycles, read_func) \
+{ \
+ read_func(data); \
+ A ^= data; \
+ SET_NZ_FLAGS(A); \
+ ADD_CYCLES(cycles); \
+}
+
+#define INC(cycles, read_func, write_func, addr) \
+{ \
+ read_func(addr, data); \
+ data++; \
+ write_func(addr, data); \
+ SET_NZ_FLAGS(data); \
+ ADD_CYCLES(cycles); \
+}
+
+#define INX() \
+{ \
+ X++; \
+ SET_NZ_FLAGS(X); \
+ ADD_CYCLES(2); \
+}
+
+#define INY() \
+{ \
+ Y++; \
+ SET_NZ_FLAGS(Y); \
+ ADD_CYCLES(2); \
+}
+
+/* undocumented */
+#define ISB(cycles, read_func, write_func, addr) \
+{ \
+ read_func(addr, data); \
+ data++; \
+ write_func(addr, data); \
+ SBC(cycles, EMPTY_READ); \
+}
+
+/* TODO: make this a function callback */
+#ifdef NES6502_TESTOPS
+#define JAM() \
+{ \
+ cpu_Jam(); \
+}
+#else /* !NES6502_TESTOPS */
+#define JAM() \
+{ \
+ PC--; \
+ cpu.jammed = true; \
+ cpu.int_pending = 0; \
+ ADD_CYCLES(2); \
+}
+#endif /* !NES6502_TESTOPS */
+
+#define JMP_INDIRECT() \
+{ \
+ temp = bank_readword(PC); \
+ /* bug in crossing page boundaries */ \
+ if (0xFF == (temp & 0xFF)) \
+ PC = (bank_readbyte(temp & 0xFF00) << 8) | bank_readbyte(temp); \
+ else \
+ JUMP(temp); \
+ ADD_CYCLES(5); \
+}
+
+#define JMP_ABSOLUTE() \
+{ \
+ JUMP(PC); \
+ ADD_CYCLES(3); \
+}
+
+#define JSR() \
+{ \
+ PC++; \
+ PUSH(PC >> 8); \
+ PUSH(PC & 0xFF); \
+ JUMP(PC - 1); \
+ ADD_CYCLES(6); \
+}
+
+/* undocumented */
+#define LAS(cycles, read_func) \
+{ \
+ read_func(data); \
+ A = X = S = (S & data); \
+ SET_NZ_FLAGS(A); \
+ ADD_CYCLES(cycles); \
+}
+
+/* undocumented */
+#define LAX(cycles, read_func) \
+{ \
+ read_func(A); \
+ X = A; \
+ SET_NZ_FLAGS(A); \
+ ADD_CYCLES(cycles); \
+}
+
+#define LDA(cycles, read_func) \
+{ \
+ read_func(A); \
+ SET_NZ_FLAGS(A); \
+ ADD_CYCLES(cycles); \
+}
+
+#define LDX(cycles, read_func) \
+{ \
+ read_func(X); \
+ SET_NZ_FLAGS(X);\
+ ADD_CYCLES(cycles); \
+}
+
+#define LDY(cycles, read_func) \
+{ \
+ read_func(Y); \
+ SET_NZ_FLAGS(Y);\
+ ADD_CYCLES(cycles); \
+}
+
+#define LSR(cycles, read_func, write_func, addr) \
+{ \
+ read_func(addr, data); \
+ c_flag = data & 1; \
+ data >>= 1; \
+ write_func(addr, data); \
+ SET_NZ_FLAGS(data); \
+ ADD_CYCLES(cycles); \
+}
+
+#define LSR_A() \
+{ \
+ c_flag = A & 1; \
+ A >>= 1; \
+ SET_NZ_FLAGS(A); \
+ ADD_CYCLES(2); \
+}
+
+/* undocumented */
+#define LXA(cycles, read_func) \
+{ \
+ read_func(data); \
+ A = X = ((A | 0xEE) & data); \
+ SET_NZ_FLAGS(A); \
+ ADD_CYCLES(cycles); \
+}
+
+#define NOP() \
+{ \
+ ADD_CYCLES(2); \
+}
+
+#define ORA(cycles, read_func) \
+{ \
+ read_func(data); \
+ A |= data; \
+ SET_NZ_FLAGS(A);\
+ ADD_CYCLES(cycles); \
+}
+
+#define PHA() \
+{ \
+ PUSH(A); \
+ ADD_CYCLES(3); \
+}
+
+#define PHP() \
+{ \
+ /* B flag is pushed on stack as well */ \
+ PUSH(COMBINE_FLAGS() | B_FLAG); \
+ ADD_CYCLES(3); \
+}
+
+#define PLA() \
+{ \
+ A = PULL(); \
+ SET_NZ_FLAGS(A); \
+ ADD_CYCLES(4); \
+}
+
+#define PLP() \
+{ \
+ btemp = PULL(); \
+ SCATTER_FLAGS(btemp); \
+ ADD_CYCLES(4); \
+}
+
+/* undocumented */
+#define RLA(cycles, read_func, write_func, addr) \
+{ \
+ read_func(addr, data); \
+ btemp = c_flag; \
+ c_flag = data >> 7; \
+ data = (data << 1) | btemp; \
+ write_func(addr, data); \
+ A &= data; \
+ SET_NZ_FLAGS(A); \
+ ADD_CYCLES(cycles); \
+}
+
+/* 9-bit rotation (carry flag used for rollover) */
+#define ROL(cycles, read_func, write_func, addr) \
+{ \
+ read_func(addr, data); \
+ btemp = c_flag; \
+ c_flag = data >> 7; \
+ data = (data << 1) | btemp; \
+ write_func(addr, data); \
+ SET_NZ_FLAGS(data); \
+ ADD_CYCLES(cycles); \
+}
+
+#define ROL_A() \
+{ \
+ btemp = c_flag; \
+ c_flag = A >> 7; \
+ A = (A << 1) | btemp; \
+ SET_NZ_FLAGS(A); \
+ ADD_CYCLES(2); \
+}
+
+#define ROR(cycles, read_func, write_func, addr) \
+{ \
+ read_func(addr, data); \
+ btemp = c_flag << 7; \
+ c_flag = data & 1; \
+ data = (data >> 1) | btemp; \
+ write_func(addr, data); \
+ SET_NZ_FLAGS(data); \
+ ADD_CYCLES(cycles); \
+}
+
+#define ROR_A() \
+{ \
+ btemp = c_flag << 7; \
+ c_flag = A & 1; \
+ A = (A >> 1) | btemp; \
+ SET_NZ_FLAGS(A); \
+ ADD_CYCLES(2); \
+}
+
+/* undocumented */
+#define RRA(cycles, read_func, write_func, addr) \
+{ \
+ read_func(addr, data); \
+ btemp = c_flag << 7; \
+ c_flag = data & 1; \
+ data = (data >> 1) | btemp; \
+ write_func(addr, data); \
+ ADC(cycles, EMPTY_READ); \
+}
+
+#define RTI() \
+{ \
+ btemp = PULL(); \
+ SCATTER_FLAGS(btemp); \
+ PC = PULL(); \
+ PC |= PULL() << 8; \
+ ADD_CYCLES(6); \
+ if (0 == i_flag && cpu.int_pending && remaining_cycles > 0) \
+ { \
+ cpu.int_pending = 0; \
+ IRQ_PROC(); \
+ ADD_CYCLES(INT_CYCLES); \
+ } \
+}
+
+#define RTS() \
+{ \
+ PC = PULL(); \
+ PC = (PC | (PULL() << 8)) + 1; \
+ ADD_CYCLES(6); \
+}
+
+/* undocumented */
+#define SAX(cycles, read_func, write_func, addr) \
+{ \
+ read_func(addr); \
+ data = A & X; \
+ write_func(addr, data); \
+ ADD_CYCLES(cycles); \
+}
+
+/* Warning! NES CPU has no decimal mode, so by default this does no BCD! */
+#ifdef NES6502_DECIMAL
+#define SBC(cycles, read_func) \
+{ \
+ read_func(data); \
+ temp = A - data - (c_flag ^ 1); \
+ if (d_flag) \
+ { \
+ uint8 al, ah; \
+ al = (A & 0x0F) - (data & 0x0F) - (c_flag ^ 1); \
+ ah = (A >> 4) - (data >> 4); \
+ if (al & 0x10) \
+ { \
+ al -= 6; \
+ ah--; \
+ } \
+ if (ah & 0x10) \
+ { \
+ ah -= 6; \
+ c_flag = 0; \
+ } \
+ else \
+ { \
+ c_flag = 1; \
+ } \
+ v_flag = (A ^ temp) & (A ^ data) & 0x80; \
+ SET_NZ_FLAGS(temp & 0xFF); \
+ A = (ah << 4) | (al & 0x0F); \
+ } \
+ else \
+ { \
+ v_flag = (A ^ temp) & (A ^ data) & 0x80; \
+ c_flag = ((temp & 0x100) >> 8) ^ 1; \
+ A = (uint8) temp; \
+ SET_NZ_FLAGS(A & 0xFF); \
+ } \
+ ADD_CYCLES(cycles); \
+}
+#else
+#define SBC(cycles, read_func) \
+{ \
+ read_func(data); \
+ temp = A - data - (c_flag ^ 1); \
+ v_flag = (A ^ data) & (A ^ temp) & 0x80; \
+ c_flag = ((temp >> 8) & 1) ^ 1; \
+ A = (uint8) temp; \
+ SET_NZ_FLAGS(A); \
+ ADD_CYCLES(cycles); \
+}
+#endif /* NES6502_DECIMAL */
+
+/* undocumented */
+#define SBX(cycles, read_func) \
+{ \
+ read_func(data); \
+ temp = (A & X) - data; \
+ c_flag = ((temp >> 8) & 1) ^ 1; \
+ X = temp & 0xFF; \
+ SET_NZ_FLAGS(X); \
+ ADD_CYCLES(cycles); \
+}
+
+#define SEC() \
+{ \
+ c_flag = 1; \
+ ADD_CYCLES(2); \
+}
+
+#define SED() \
+{ \
+ d_flag = 1; \
+ ADD_CYCLES(2); \
+}
+
+#define SEI() \
+{ \
+ i_flag = 1; \
+ ADD_CYCLES(2); \
+}
+
+/* undocumented */
+#define SHA(cycles, read_func, write_func, addr) \
+{ \
+ read_func(addr); \
+ data = A & X & ((uint8) ((addr >> 8) + 1)); \
+ write_func(addr, data); \
+ ADD_CYCLES(cycles); \
+}
+
+/* undocumented */
+#define SHS(cycles, read_func, write_func, addr) \
+{ \
+ read_func(addr); \
+ S = A & X; \
+ data = S & ((uint8) ((addr >> 8) + 1)); \
+ write_func(addr, data); \
+ ADD_CYCLES(cycles); \
+}
+
+/* undocumented */
+#define SHX(cycles, read_func, write_func, addr) \
+{ \
+ read_func(addr); \
+ data = X & ((uint8) ((addr >> 8) + 1)); \
+ write_func(addr, data); \
+ ADD_CYCLES(cycles); \
+}
+
+/* undocumented */
+#define SHY(cycles, read_func, write_func, addr) \
+{ \
+ read_func(addr); \
+ data = Y & ((uint8) ((addr >> 8 ) + 1)); \
+ write_func(addr, data); \
+ ADD_CYCLES(cycles); \
+}
+
+/* undocumented */
+#define SLO(cycles, read_func, write_func, addr) \
+{ \
+ read_func(addr, data); \
+ c_flag = data >> 7; \
+ data <<= 1; \
+ write_func(addr, data); \
+ A |= data; \
+ SET_NZ_FLAGS(A); \
+ ADD_CYCLES(cycles); \
+}
+
+/* undocumented */
+#define SRE(cycles, read_func, write_func, addr) \
+{ \
+ read_func(addr, data); \
+ c_flag = data & 1; \
+ data >>= 1; \
+ write_func(addr, data); \
+ A ^= data; \
+ SET_NZ_FLAGS(A); \
+ ADD_CYCLES(cycles); \
+}
+
+#define STA(cycles, read_func, write_func, addr) \
+{ \
+ read_func(addr); \
+ write_func(addr, A); \
+ ADD_CYCLES(cycles); \
+}
+
+#define STX(cycles, read_func, write_func, addr) \
+{ \
+ read_func(addr); \
+ write_func(addr, X); \
+ ADD_CYCLES(cycles); \
+}
+
+#define STY(cycles, read_func, write_func, addr) \
+{ \
+ read_func(addr); \
+ write_func(addr, Y); \
+ ADD_CYCLES(cycles); \
+}
+
+#define TAX() \
+{ \
+ X = A; \
+ SET_NZ_FLAGS(X);\
+ ADD_CYCLES(2); \
+}
+
+#define TAY() \
+{ \
+ Y = A; \
+ SET_NZ_FLAGS(Y);\
+ ADD_CYCLES(2); \
+}
+
+/* undocumented (triple-NOP) */
+#define TOP() \
+{ \
+ PC += 2; \
+ ADD_CYCLES(4); \
+}
+
+#define TSX() \
+{ \
+ X = S; \
+ SET_NZ_FLAGS(X);\
+ ADD_CYCLES(2); \
+}
+
+#define TXA() \
+{ \
+ A = X; \
+ SET_NZ_FLAGS(A);\
+ ADD_CYCLES(2); \
+}
+
+#define TXS() \
+{ \
+ S = X; \
+ ADD_CYCLES(2); \
+}
+
+#define TYA() \
+{ \
+ A = Y; \
+ SET_NZ_FLAGS(A); \
+ ADD_CYCLES(2); \
+}
+
+
+
+/* internal CPU context */
+static nes6502_context cpu;
+static int remaining_cycles = 0; /* so we can release timeslice */
+/* memory region pointers */
+static uint8 *ram = NULL, *stack = NULL;
+/* (the dead page: what reads of unmapped memory find; Retro-Go gives it from its block) */
+uint8 *nes6502_null_page;
+#define null_page nes6502_null_page
+
+
+/*
+** Zero-page helper macros
+*/
+
+#define ZP_READBYTE(addr) ram[(addr)]
+#define ZP_WRITEBYTE(addr, value) ram[(addr)] = (uint8) (value)
+
+#ifdef HOST_LITTLE_ENDIAN
+
+/* NOTE: following two functions will fail on architectures
+** which do not support byte alignment
+*/
+/* (byte by byte: the cartridge is read in place, and a word may cross from one bank to the
+ next; the zero page wraps) */
+INLINE uint32 zp_readword(register uint8 address)
+{
+ return (uint32) ram[address] | (uint32) ram[(uint8) (address + 1)] << 8;
+}
+
+INLINE uint32 bank_readword(register uint32 address)
+{
+ return (uint32) cpu.mem_page[(address >> NES6502_BANKSHIFT) & 15][address & NES6502_BANKMASK]
+ | (uint32) cpu.mem_page[((address + 1) >> NES6502_BANKSHIFT) & 15][(address + 1) & NES6502_BANKMASK] << 8;
+}
+
+#else /* !HOST_LITTLE_ENDIAN */
+
+INLINE uint32 zp_readword(register uint8 address)
+{
+#ifdef TARGET_CPU_PPC
+ return __lhbrx(ram, address);
+#else /* !TARGET_CPU_PPC */
+ uint32 x = (uint32) *(uint16 *)(ram + address);
+ return (x << 8) | (x >> 8);
+#endif /* !TARGET_CPU_PPC */
+}
+
+INLINE uint32 bank_readword(register uint32 address)
+{
+#ifdef TARGET_CPU_PPC
+ return __lhbrx(cpu.mem_page[address >> NES6502_BANKSHIFT], address & NES6502_BANKMASK);
+#else /* !TARGET_CPU_PPC */
+ uint32 x = (uint32) *(uint16 *)(cpu.mem_page[address >> NES6502_BANKSHIFT] + (address & NES6502_BANKMASK));
+ return (x << 8) | (x >> 8);
+#endif /* !TARGET_CPU_PPC */
+}
+
+#endif /* !HOST_LITTLE_ENDIAN */
+
+INLINE uint8 bank_readbyte(register uint32 address)
+{
+ return cpu.mem_page[(address >> NES6502_BANKSHIFT) & 15][address & NES6502_BANKMASK]; /* (the PC may have run past $FFFF) */
+}
+
+INLINE void bank_writebyte(register uint32 address, register uint8 value)
+{
+ uint8 *p = &cpu.mem_page[(address >> NES6502_BANKSHIFT) & 15][address & NES6502_BANKMASK];
+ /* the cartridge is read in place, from the calculator's flash: a write there goes nowhere */
+ if (p >= nes_rom_lo && p < nes_rom_hi)
+ return;
+ *p = value;
+}
+
+/* read a byte of 6502 memory */
+static uint8 mem_readbyte(uint32 address)
+{
+ nes6502_memread *mr;
+
+ /* TODO: following 2 cases are N2A03-specific */
+ if (address < 0x800)
+ {
+ /* RAM */
+ return ram[address];
+ }
+ else if (address >= 0x8000)
+ {
+ /* always paged memory */
+ return bank_readbyte(address);
+ }
+ /* check memory range handlers */
+ else
+ {
+ for (mr = cpu.read_handler; mr->min_range != 0xFFFFFFFF; mr++)
+ {
+ if (address >= mr->min_range && address <= mr->max_range)
+ return mr->read_func(address);
+ }
+ }
+
+ /* return paged memory */
+ return bank_readbyte(address);
+}
+
+/* write a byte of data to 6502 memory */
+static void mem_writebyte(uint32 address, uint8 value)
+{
+ nes6502_memwrite *mw;
+
+ /* RAM */
+ if (address < 0x800)
+ {
+ ram[address] = value;
+ return;
+ }
+ /* check memory range handlers */
+ else
+ {
+ for (mw = cpu.write_handler; mw->min_range != 0xFFFFFFFF; mw++)
+ {
+ if (address >= mw->min_range && address <= mw->max_range)
+ {
+ mw->write_func(address, value);
+ return;
+ }
+ }
+ }
+
+ /* write to paged memory */
+ bank_writebyte(address, value);
+}
+
+/* set the current context */
+void nes6502_setcontext(nes6502_context *context)
+{
+ int loop;
+
+ ASSERT(context);
+
+ cpu = *context;
+
+ /* set dead page for all pages not pointed at anything */
+ for (loop = 0; loop < NES6502_NUMBANKS; loop++)
+ {
+ if (NULL == cpu.mem_page[loop])
+ cpu.mem_page[loop] = null_page;
+ }
+
+ ram = cpu.mem_page[0]; /* quick zero-page/RAM references */
+ stack = ram + STACK_OFFSET;
+}
+
+/* get the current context */
+void nes6502_getcontext(nes6502_context *context)
+{
+ int loop;
+
+ ASSERT(context);
+
+ *context = cpu;
+
+ /* reset dead pages to null */
+ for (loop = 0; loop < NES6502_NUMBANKS; loop++)
+ {
+ if (null_page == context->mem_page[loop])
+ context->mem_page[loop] = NULL;
+ }
+}
+
+/* DMA a byte of data from ROM */
+uint8 nes6502_getbyte(uint32 address)
+{
+ return bank_readbyte(address);
+}
+
+/* get number of elapsed cycles */
+uint32 nes6502_getcycles(bool reset_flag)
+{
+ uint32 cycles = cpu.total_cycles;
+
+ if (reset_flag)
+ cpu.total_cycles = 0;
+
+ return cycles;
+}
+
+#define GET_GLOBAL_REGS() \
+{ \
+ PC = cpu.pc_reg; \
+ A = cpu.a_reg; \
+ X = cpu.x_reg; \
+ Y = cpu.y_reg; \
+ SCATTER_FLAGS(cpu.p_reg); \
+ S = cpu.s_reg; \
+}
+
+#define STORE_LOCAL_REGS() \
+{ \
+ cpu.pc_reg = PC; \
+ cpu.a_reg = A; \
+ cpu.x_reg = X; \
+ cpu.y_reg = Y; \
+ cpu.p_reg = COMBINE_FLAGS(); \
+ cpu.s_reg = S; \
+}
+
+#define MIN(a,b) (((a) < (b)) ? (a) : (b))
+
+#ifdef NES6502_JUMPTABLE
+
+#define OPCODE_BEGIN(xx) op##xx:
+#ifdef NES6502_DISASM
+
+#define OPCODE_END \
+ if (remaining_cycles <= 0) \
+ goto end_execute; \
+ log_printf(nes6502_disasm(PC, COMBINE_FLAGS(), A, X, Y, S)); \
+ goto *opcode_table[bank_readbyte(PC++)];
+
+#else /* !NES6520_DISASM */
+
+#define OPCODE_END \
+ if (remaining_cycles <= 0) \
+ goto end_execute; \
+ goto *opcode_table[bank_readbyte(PC++)];
+
+#endif /* !NES6502_DISASM */
+
+#else /* !NES6502_JUMPTABLE */
+#define OPCODE_BEGIN(xx) case 0x##xx:
+#define OPCODE_END break;
+#endif /* !NES6502_JUMPTABLE */
+
+
+/* Execute instructions until count expires
+**
+** Returns the number of cycles *actually* executed, which will be
+** anywhere from zero to timeslice_cycles + 6
+*/
+int nes6502_execute(int timeslice_cycles)
+{
+ int old_cycles = cpu.total_cycles;
+
+ uint32 temp, addr; /* for macros */
+ uint8 btemp, baddr; /* for macros */
+ uint8 data;
+
+ /* flags */
+ uint8 n_flag, v_flag, b_flag;
+ uint8 d_flag, i_flag, z_flag, c_flag;
+
+ /* local copies of regs */
+ uint32 PC;
+ uint8 A, X, Y, S;
+
+#ifdef NES6502_JUMPTABLE
+
+ static const void *const opcode_table[256] =
+ {
+ &&op00, &&op01, &&op02, &&op03, &&op04, &&op05, &&op06, &&op07,
+ &&op08, &&op09, &&op0A, &&op0B, &&op0C, &&op0D, &&op0E, &&op0F,
+ &&op10, &&op11, &&op12, &&op13, &&op14, &&op15, &&op16, &&op17,
+ &&op18, &&op19, &&op1A, &&op1B, &&op1C, &&op1D, &&op1E, &&op1F,
+ &&op20, &&op21, &&op22, &&op23, &&op24, &&op25, &&op26, &&op27,
+ &&op28, &&op29, &&op2A, &&op2B, &&op2C, &&op2D, &&op2E, &&op2F,
+ &&op30, &&op31, &&op32, &&op33, &&op34, &&op35, &&op36, &&op37,
+ &&op38, &&op39, &&op3A, &&op3B, &&op3C, &&op3D, &&op3E, &&op3F,
+ &&op40, &&op41, &&op42, &&op43, &&op44, &&op45, &&op46, &&op47,
+ &&op48, &&op49, &&op4A, &&op4B, &&op4C, &&op4D, &&op4E, &&op4F,
+ &&op50, &&op51, &&op52, &&op53, &&op54, &&op55, &&op56, &&op57,
+ &&op58, &&op59, &&op5A, &&op5B, &&op5C, &&op5D, &&op5E, &&op5F,
+ &&op60, &&op61, &&op62, &&op63, &&op64, &&op65, &&op66, &&op67,
+ &&op68, &&op69, &&op6A, &&op6B, &&op6C, &&op6D, &&op6E, &&op6F,
+ &&op70, &&op71, &&op72, &&op73, &&op74, &&op75, &&op76, &&op77,
+ &&op78, &&op79, &&op7A, &&op7B, &&op7C, &&op7D, &&op7E, &&op7F,
+ &&op80, &&op81, &&op82, &&op83, &&op84, &&op85, &&op86, &&op87,
+ &&op88, &&op89, &&op8A, &&op8B, &&op8C, &&op8D, &&op8E, &&op8F,
+ &&op90, &&op91, &&op92, &&op93, &&op94, &&op95, &&op96, &&op97,
+ &&op98, &&op99, &&op9A, &&op9B, &&op9C, &&op9D, &&op9E, &&op9F,
+ &&opA0, &&opA1, &&opA2, &&opA3, &&opA4, &&opA5, &&opA6, &&opA7,
+ &&opA8, &&opA9, &&opAA, &&opAB, &&opAC, &&opAD, &&opAE, &&opAF,
+ &&opB0, &&opB1, &&opB2, &&opB3, &&opB4, &&opB5, &&opB6, &&opB7,
+ &&opB8, &&opB9, &&opBA, &&opBB, &&opBC, &&opBD, &&opBE, &&opBF,
+ &&opC0, &&opC1, &&opC2, &&opC3, &&opC4, &&opC5, &&opC6, &&opC7,
+ &&opC8, &&opC9, &&opCA, &&opCB, &&opCC, &&opCD, &&opCE, &&opCF,
+ &&opD0, &&opD1, &&opD2, &&opD3, &&opD4, &&opD5, &&opD6, &&opD7,
+ &&opD8, &&opD9, &&opDA, &&opDB, &&opDC, &&opDD, &&opDE, &&opDF,
+ &&opE0, &&opE1, &&opE2, &&opE3, &&opE4, &&opE5, &&opE6, &&opE7,
+ &&opE8, &&opE9, &&opEA, &&opEB, &&opEC, &&opED, &&opEE, &&opEF,
+ &&opF0, &&opF1, &&opF2, &&opF3, &&opF4, &&opF5, &&opF6, &&opF7,
+ &&opF8, &&opF9, &&opFA, &&opFB, &&opFC, &&opFD, &&opFE, &&opFF
+ };
+
+#endif /* NES6502_JUMPTABLE */
+
+ remaining_cycles = timeslice_cycles;
+
+ GET_GLOBAL_REGS();
+
+ /* check for DMA cycle burning */
+ if (cpu.burn_cycles && remaining_cycles > 0)
+ {
+ int burn_for;
+
+ burn_for = MIN(remaining_cycles, cpu.burn_cycles);
+ ADD_CYCLES(burn_for);
+ cpu.burn_cycles -= burn_for;
+ }
+
+ if (0 == i_flag && cpu.int_pending && remaining_cycles > 0)
+ {
+ cpu.int_pending = 0;
+ IRQ_PROC();
+ ADD_CYCLES(INT_CYCLES);
+ }
+
+#ifdef NES6502_JUMPTABLE
+ /* fetch first instruction */
+ OPCODE_END
+
+#else /* !NES6502_JUMPTABLE */
+
+ /* Continue until we run out of cycles */
+ while (remaining_cycles > 0)
+ {
+#ifdef NES6502_DISASM
+ log_printf(nes6502_disasm(PC, COMBINE_FLAGS(), A, X, Y, S));
+#endif /* NES6502_DISASM */
+
+ /* Fetch and execute instruction */
+ switch (bank_readbyte(PC++))
+ {
+#endif /* !NES6502_JUMPTABLE */
+
+ OPCODE_BEGIN(00) /* BRK */
+ BRK();
+ OPCODE_END
+
+ OPCODE_BEGIN(01) /* ORA ($nn,X) */
+ ORA(6, INDIR_X_BYTE);
+ OPCODE_END
+
+ OPCODE_BEGIN(02) /* JAM */
+ OPCODE_BEGIN(12) /* JAM */
+ OPCODE_BEGIN(22) /* JAM */
+ OPCODE_BEGIN(32) /* JAM */
+ OPCODE_BEGIN(42) /* JAM */
+ OPCODE_BEGIN(52) /* JAM */
+ OPCODE_BEGIN(62) /* JAM */
+ OPCODE_BEGIN(72) /* JAM */
+ OPCODE_BEGIN(92) /* JAM */
+ OPCODE_BEGIN(B2) /* JAM */
+ OPCODE_BEGIN(D2) /* JAM */
+ OPCODE_BEGIN(F2) /* JAM */
+ JAM();
+ /* kill the CPU */
+ remaining_cycles = 0;
+ OPCODE_END
+
+ OPCODE_BEGIN(03) /* SLO ($nn,X) */
+ SLO(8, INDIR_X, mem_writebyte, addr);
+ OPCODE_END
+
+ OPCODE_BEGIN(04) /* NOP $nn */
+ OPCODE_BEGIN(44) /* NOP $nn */
+ OPCODE_BEGIN(64) /* NOP $nn */
+ DOP(3);
+ OPCODE_END
+
+ OPCODE_BEGIN(05) /* ORA $nn */
+ ORA(3, ZERO_PAGE_BYTE);
+ OPCODE_END
+
+ OPCODE_BEGIN(06) /* ASL $nn */
+ ASL(5, ZERO_PAGE, ZP_WRITEBYTE, baddr);
+ OPCODE_END
+
+ OPCODE_BEGIN(07) /* SLO $nn */
+ SLO(5, ZERO_PAGE, ZP_WRITEBYTE, baddr);
+ OPCODE_END
+
+ OPCODE_BEGIN(08) /* PHP */
+ PHP();
+ OPCODE_END
+
+ OPCODE_BEGIN(09) /* ORA #$nn */
+ ORA(2, IMMEDIATE_BYTE);
+ OPCODE_END
+
+ OPCODE_BEGIN(0A) /* ASL A */
+ ASL_A();
+ OPCODE_END
+
+ OPCODE_BEGIN(0B) /* ANC #$nn */
+ ANC(2, IMMEDIATE_BYTE);
+ OPCODE_END
+
+ OPCODE_BEGIN(0C) /* NOP $nnnn */
+ TOP();
+ OPCODE_END
+
+ OPCODE_BEGIN(0D) /* ORA $nnnn */
+ ORA(4, ABSOLUTE_BYTE);
+ OPCODE_END
+
+ OPCODE_BEGIN(0E) /* ASL $nnnn */
+ ASL(6, ABSOLUTE, mem_writebyte, addr);
+ OPCODE_END
+
+ OPCODE_BEGIN(0F) /* SLO $nnnn */
+ SLO(6, ABSOLUTE, mem_writebyte, addr);
+ OPCODE_END
+
+ OPCODE_BEGIN(10) /* BPL $nnnn */
+ BPL();
+ OPCODE_END
+
+ OPCODE_BEGIN(11) /* ORA ($nn),Y */
+ ORA(5, INDIR_Y_BYTE_READ);
+ OPCODE_END
+
+ OPCODE_BEGIN(13) /* SLO ($nn),Y */
+ SLO(8, INDIR_Y, mem_writebyte, addr);
+ OPCODE_END
+
+ OPCODE_BEGIN(14) /* NOP $nn,X */
+ OPCODE_BEGIN(34) /* NOP */
+ OPCODE_BEGIN(54) /* NOP $nn,X */
+ OPCODE_BEGIN(74) /* NOP $nn,X */
+ OPCODE_BEGIN(D4) /* NOP $nn,X */
+ OPCODE_BEGIN(F4) /* NOP ($nn,X) */
+ DOP(4);
+ OPCODE_END
+
+ OPCODE_BEGIN(15) /* ORA $nn,X */
+ ORA(4, ZP_IND_X_BYTE);
+ OPCODE_END
+
+ OPCODE_BEGIN(16) /* ASL $nn,X */
+ ASL(6, ZP_IND_X, ZP_WRITEBYTE, baddr);
+ OPCODE_END
+
+ OPCODE_BEGIN(17) /* SLO $nn,X */
+ SLO(6, ZP_IND_X, ZP_WRITEBYTE, baddr);
+ OPCODE_END
+
+ OPCODE_BEGIN(18) /* CLC */
+ CLC();
+ OPCODE_END
+
+ OPCODE_BEGIN(19) /* ORA $nnnn,Y */
+ ORA(4, ABS_IND_Y_BYTE_READ);
+ OPCODE_END
+
+ OPCODE_BEGIN(1A) /* NOP */
+ OPCODE_BEGIN(3A) /* NOP */
+ OPCODE_BEGIN(5A) /* NOP */
+ OPCODE_BEGIN(7A) /* NOP */
+ OPCODE_BEGIN(DA) /* NOP */
+ OPCODE_BEGIN(FA) /* NOP */
+ NOP();
+ OPCODE_END
+
+ OPCODE_BEGIN(1B) /* SLO $nnnn,Y */
+ SLO(7, ABS_IND_Y, mem_writebyte, addr);
+ OPCODE_END
+
+ OPCODE_BEGIN(1C) /* NOP $nnnn,X */
+ OPCODE_BEGIN(3C) /* NOP $nnnn,X */
+ OPCODE_BEGIN(5C) /* NOP $nnnn,X */
+ OPCODE_BEGIN(7C) /* NOP $nnnn,X */
+ OPCODE_BEGIN(DC) /* NOP $nnnn,X */
+ OPCODE_BEGIN(FC) /* NOP $nnnn,X */
+ TOP();
+ OPCODE_END
+
+ OPCODE_BEGIN(1D) /* ORA $nnnn,X */
+ ORA(4, ABS_IND_X_BYTE_READ);
+ OPCODE_END
+
+ OPCODE_BEGIN(1E) /* ASL $nnnn,X */
+ ASL(7, ABS_IND_X, mem_writebyte, addr);
+ OPCODE_END
+
+ OPCODE_BEGIN(1F) /* SLO $nnnn,X */
+ SLO(7, ABS_IND_X, mem_writebyte, addr);
+ OPCODE_END
+
+ OPCODE_BEGIN(20) /* JSR $nnnn */
+ JSR();
+ OPCODE_END
+
+ OPCODE_BEGIN(21) /* AND ($nn,X) */
+ AND(6, INDIR_X_BYTE);
+ OPCODE_END
+
+ OPCODE_BEGIN(23) /* RLA ($nn,X) */
+ RLA(8, INDIR_X, mem_writebyte, addr);
+ OPCODE_END
+
+ OPCODE_BEGIN(24) /* BIT $nn */
+ BIT(3, ZERO_PAGE_BYTE);
+ OPCODE_END
+
+ OPCODE_BEGIN(25) /* AND $nn */
+ AND(3, ZERO_PAGE_BYTE);
+ OPCODE_END
+
+ OPCODE_BEGIN(26) /* ROL $nn */
+ ROL(5, ZERO_PAGE, ZP_WRITEBYTE, baddr);
+ OPCODE_END
+
+ OPCODE_BEGIN(27) /* RLA $nn */
+ RLA(5, ZERO_PAGE, ZP_WRITEBYTE, baddr);
+ OPCODE_END
+
+ OPCODE_BEGIN(28) /* PLP */
+ PLP();
+ OPCODE_END
+
+ OPCODE_BEGIN(29) /* AND #$nn */
+ AND(2, IMMEDIATE_BYTE);
+ OPCODE_END
+
+ OPCODE_BEGIN(2A) /* ROL A */
+ ROL_A();
+ OPCODE_END
+
+ OPCODE_BEGIN(2B) /* ANC #$nn */
+ ANC(2, IMMEDIATE_BYTE);
+ OPCODE_END
+
+ OPCODE_BEGIN(2C) /* BIT $nnnn */
+ BIT(4, ABSOLUTE_BYTE);
+ OPCODE_END
+
+ OPCODE_BEGIN(2D) /* AND $nnnn */
+ AND(4, ABSOLUTE_BYTE);
+ OPCODE_END
+
+ OPCODE_BEGIN(2E) /* ROL $nnnn */
+ ROL(6, ABSOLUTE, mem_writebyte, addr);
+ OPCODE_END
+
+ OPCODE_BEGIN(2F) /* RLA $nnnn */
+ RLA(6, ABSOLUTE, mem_writebyte, addr);
+ OPCODE_END
+
+ OPCODE_BEGIN(30) /* BMI $nnnn */
+ BMI();
+ OPCODE_END
+
+ OPCODE_BEGIN(31) /* AND ($nn),Y */
+ AND(5, INDIR_Y_BYTE_READ);
+ OPCODE_END
+
+ OPCODE_BEGIN(33) /* RLA ($nn),Y */
+ RLA(8, INDIR_Y, mem_writebyte, addr);
+ OPCODE_END
+
+ OPCODE_BEGIN(35) /* AND $nn,X */
+ AND(4, ZP_IND_X_BYTE);
+ OPCODE_END
+
+ OPCODE_BEGIN(36) /* ROL $nn,X */
+ ROL(6, ZP_IND_X, ZP_WRITEBYTE, baddr);
+ OPCODE_END
+
+ OPCODE_BEGIN(37) /* RLA $nn,X */
+ RLA(6, ZP_IND_X, ZP_WRITEBYTE, baddr);
+ OPCODE_END
+
+ OPCODE_BEGIN(38) /* SEC */
+ SEC();
+ OPCODE_END
+
+ OPCODE_BEGIN(39) /* AND $nnnn,Y */
+ AND(4, ABS_IND_Y_BYTE_READ);
+ OPCODE_END
+
+ OPCODE_BEGIN(3B) /* RLA $nnnn,Y */
+ RLA(7, ABS_IND_Y, mem_writebyte, addr);
+ OPCODE_END
+
+ OPCODE_BEGIN(3D) /* AND $nnnn,X */
+ AND(4, ABS_IND_X_BYTE_READ);
+ OPCODE_END
+
+ OPCODE_BEGIN(3E) /* ROL $nnnn,X */
+ ROL(7, ABS_IND_X, mem_writebyte, addr);
+ OPCODE_END
+
+ OPCODE_BEGIN(3F) /* RLA $nnnn,X */
+ RLA(7, ABS_IND_X, mem_writebyte, addr);
+ OPCODE_END
+
+ OPCODE_BEGIN(40) /* RTI */
+ RTI();
+ OPCODE_END
+
+ OPCODE_BEGIN(41) /* EOR ($nn,X) */
+ EOR(6, INDIR_X_BYTE);
+ OPCODE_END
+
+ OPCODE_BEGIN(43) /* SRE ($nn,X) */
+ SRE(8, INDIR_X, mem_writebyte, addr);
+ OPCODE_END
+
+ OPCODE_BEGIN(45) /* EOR $nn */
+ EOR(3, ZERO_PAGE_BYTE);
+ OPCODE_END
+
+ OPCODE_BEGIN(46) /* LSR $nn */
+ LSR(5, ZERO_PAGE, ZP_WRITEBYTE, baddr);
+ OPCODE_END
+
+ OPCODE_BEGIN(47) /* SRE $nn */
+ SRE(5, ZERO_PAGE, ZP_WRITEBYTE, baddr);
+ OPCODE_END
+
+ OPCODE_BEGIN(48) /* PHA */
+ PHA();
+ OPCODE_END
+
+ OPCODE_BEGIN(49) /* EOR #$nn */
+ EOR(2, IMMEDIATE_BYTE);
+ OPCODE_END
+
+ OPCODE_BEGIN(4A) /* LSR A */
+ LSR_A();
+ OPCODE_END
+
+ OPCODE_BEGIN(4B) /* ASR #$nn */
+ ASR(2, IMMEDIATE_BYTE);
+ OPCODE_END
+
+ OPCODE_BEGIN(4C) /* JMP $nnnn */
+ JMP_ABSOLUTE();
+ OPCODE_END
+
+ OPCODE_BEGIN(4D) /* EOR $nnnn */
+ EOR(4, ABSOLUTE_BYTE);
+ OPCODE_END
+
+ OPCODE_BEGIN(4E) /* LSR $nnnn */
+ LSR(6, ABSOLUTE, mem_writebyte, addr);
+ OPCODE_END
+
+ OPCODE_BEGIN(4F) /* SRE $nnnn */
+ SRE(6, ABSOLUTE, mem_writebyte, addr);
+ OPCODE_END
+
+ OPCODE_BEGIN(50) /* BVC $nnnn */
+ BVC();
+ OPCODE_END
+
+ OPCODE_BEGIN(51) /* EOR ($nn),Y */
+ EOR(5, INDIR_Y_BYTE_READ);
+ OPCODE_END
+
+ OPCODE_BEGIN(53) /* SRE ($nn),Y */
+ SRE(8, INDIR_Y, mem_writebyte, addr);
+ OPCODE_END
+
+ OPCODE_BEGIN(55) /* EOR $nn,X */
+ EOR(4, ZP_IND_X_BYTE);
+ OPCODE_END
+
+ OPCODE_BEGIN(56) /* LSR $nn,X */
+ LSR(6, ZP_IND_X, ZP_WRITEBYTE, baddr);
+ OPCODE_END
+
+ OPCODE_BEGIN(57) /* SRE $nn,X */
+ SRE(6, ZP_IND_X, ZP_WRITEBYTE, baddr);
+ OPCODE_END
+
+ OPCODE_BEGIN(58) /* CLI */
+ CLI();
+ OPCODE_END
+
+ OPCODE_BEGIN(59) /* EOR $nnnn,Y */
+ EOR(4, ABS_IND_Y_BYTE_READ);
+ OPCODE_END
+
+ OPCODE_BEGIN(5B) /* SRE $nnnn,Y */
+ SRE(7, ABS_IND_Y, mem_writebyte, addr);
+ OPCODE_END
+
+ OPCODE_BEGIN(5D) /* EOR $nnnn,X */
+ EOR(4, ABS_IND_X_BYTE_READ);
+ OPCODE_END
+
+ OPCODE_BEGIN(5E) /* LSR $nnnn,X */
+ LSR(7, ABS_IND_X, mem_writebyte, addr);
+ OPCODE_END
+
+ OPCODE_BEGIN(5F) /* SRE $nnnn,X */
+ SRE(7, ABS_IND_X, mem_writebyte, addr);
+ OPCODE_END
+
+ OPCODE_BEGIN(60) /* RTS */
+ RTS();
+ OPCODE_END
+
+ OPCODE_BEGIN(61) /* ADC ($nn,X) */
+ ADC(6, INDIR_X_BYTE);
+ OPCODE_END
+
+ OPCODE_BEGIN(63) /* RRA ($nn,X) */
+ RRA(8, INDIR_X, mem_writebyte, addr);
+ OPCODE_END
+
+ OPCODE_BEGIN(65) /* ADC $nn */
+ ADC(3, ZERO_PAGE_BYTE);
+ OPCODE_END
+
+ OPCODE_BEGIN(66) /* ROR $nn */
+ ROR(5, ZERO_PAGE, ZP_WRITEBYTE, baddr);
+ OPCODE_END
+
+ OPCODE_BEGIN(67) /* RRA $nn */
+ RRA(5, ZERO_PAGE, ZP_WRITEBYTE, baddr);
+ OPCODE_END
+
+ OPCODE_BEGIN(68) /* PLA */
+ PLA();
+ OPCODE_END
+
+ OPCODE_BEGIN(69) /* ADC #$nn */
+ ADC(2, IMMEDIATE_BYTE);
+ OPCODE_END
+
+ OPCODE_BEGIN(6A) /* ROR A */
+ ROR_A();
+ OPCODE_END
+
+ OPCODE_BEGIN(6B) /* ARR #$nn */
+ ARR(2, IMMEDIATE_BYTE);
+ OPCODE_END
+
+ OPCODE_BEGIN(6C) /* JMP ($nnnn) */
+ JMP_INDIRECT();
+ OPCODE_END
+
+ OPCODE_BEGIN(6D) /* ADC $nnnn */
+ ADC(4, ABSOLUTE_BYTE);
+ OPCODE_END
+
+ OPCODE_BEGIN(6E) /* ROR $nnnn */
+ ROR(6, ABSOLUTE, mem_writebyte, addr);
+ OPCODE_END
+
+ OPCODE_BEGIN(6F) /* RRA $nnnn */
+ RRA(6, ABSOLUTE, mem_writebyte, addr);
+ OPCODE_END
+
+ OPCODE_BEGIN(70) /* BVS $nnnn */
+ BVS();
+ OPCODE_END
+
+ OPCODE_BEGIN(71) /* ADC ($nn),Y */
+ ADC(5, INDIR_Y_BYTE_READ);
+ OPCODE_END
+
+ OPCODE_BEGIN(73) /* RRA ($nn),Y */
+ RRA(8, INDIR_Y, mem_writebyte, addr);
+ OPCODE_END
+
+ OPCODE_BEGIN(75) /* ADC $nn,X */
+ ADC(4, ZP_IND_X_BYTE);
+ OPCODE_END
+
+ OPCODE_BEGIN(76) /* ROR $nn,X */
+ ROR(6, ZP_IND_X, ZP_WRITEBYTE, baddr);
+ OPCODE_END
+
+ OPCODE_BEGIN(77) /* RRA $nn,X */
+ RRA(6, ZP_IND_X, ZP_WRITEBYTE, baddr);
+ OPCODE_END
+
+ OPCODE_BEGIN(78) /* SEI */
+ SEI();
+ OPCODE_END
+
+ OPCODE_BEGIN(79) /* ADC $nnnn,Y */
+ ADC(4, ABS_IND_Y_BYTE_READ);
+ OPCODE_END
+
+ OPCODE_BEGIN(7B) /* RRA $nnnn,Y */
+ RRA(7, ABS_IND_Y, mem_writebyte, addr);
+ OPCODE_END
+
+ OPCODE_BEGIN(7D) /* ADC $nnnn,X */
+ ADC(4, ABS_IND_X_BYTE_READ);
+ OPCODE_END
+
+ OPCODE_BEGIN(7E) /* ROR $nnnn,X */
+ ROR(7, ABS_IND_X, mem_writebyte, addr);
+ OPCODE_END
+
+ OPCODE_BEGIN(7F) /* RRA $nnnn,X */
+ RRA(7, ABS_IND_X, mem_writebyte, addr);
+ OPCODE_END
+
+ OPCODE_BEGIN(80) /* NOP #$nn */
+ OPCODE_BEGIN(82) /* NOP #$nn */
+ OPCODE_BEGIN(89) /* NOP #$nn */
+ OPCODE_BEGIN(C2) /* NOP #$nn */
+ OPCODE_BEGIN(E2) /* NOP #$nn */
+ DOP(2);
+ OPCODE_END
+
+ OPCODE_BEGIN(81) /* STA ($nn,X) */
+ STA(6, INDIR_X_ADDR, mem_writebyte, addr);
+ OPCODE_END
+
+ OPCODE_BEGIN(83) /* SAX ($nn,X) */
+ SAX(6, INDIR_X_ADDR, mem_writebyte, addr);
+ OPCODE_END
+
+ OPCODE_BEGIN(84) /* STY $nn */
+ STY(3, ZERO_PAGE_ADDR, ZP_WRITEBYTE, baddr);
+ OPCODE_END
+
+ OPCODE_BEGIN(85) /* STA $nn */
+ STA(3, ZERO_PAGE_ADDR, ZP_WRITEBYTE, baddr);
+ OPCODE_END
+
+ OPCODE_BEGIN(86) /* STX $nn */
+ STX(3, ZERO_PAGE_ADDR, ZP_WRITEBYTE, baddr);
+ OPCODE_END
+
+ OPCODE_BEGIN(87) /* SAX $nn */
+ SAX(3, ZERO_PAGE_ADDR, ZP_WRITEBYTE, baddr);
+ OPCODE_END
+
+ OPCODE_BEGIN(88) /* DEY */
+ DEY();
+ OPCODE_END
+
+ OPCODE_BEGIN(8A) /* TXA */
+ TXA();
+ OPCODE_END
+
+ OPCODE_BEGIN(8B) /* ANE #$nn */
+ ANE(2, IMMEDIATE_BYTE);
+ OPCODE_END
+
+ OPCODE_BEGIN(8C) /* STY $nnnn */
+ STY(4, ABSOLUTE_ADDR, mem_writebyte, addr);
+ OPCODE_END
+
+ OPCODE_BEGIN(8D) /* STA $nnnn */
+ STA(4, ABSOLUTE_ADDR, mem_writebyte, addr);
+ OPCODE_END
+
+ OPCODE_BEGIN(8E) /* STX $nnnn */
+ STX(4, ABSOLUTE_ADDR, mem_writebyte, addr);
+ OPCODE_END
+
+ OPCODE_BEGIN(8F) /* SAX $nnnn */
+ SAX(4, ABSOLUTE_ADDR, mem_writebyte, addr);
+ OPCODE_END
+
+ OPCODE_BEGIN(90) /* BCC $nnnn */
+ BCC();
+ OPCODE_END
+
+ OPCODE_BEGIN(91) /* STA ($nn),Y */
+ STA(6, INDIR_Y_ADDR, mem_writebyte, addr);
+ OPCODE_END
+
+ OPCODE_BEGIN(93) /* SHA ($nn),Y */
+ SHA(6, INDIR_Y_ADDR, mem_writebyte, addr);
+ OPCODE_END
+
+ OPCODE_BEGIN(94) /* STY $nn,X */
+ STY(4, ZP_IND_X_ADDR, ZP_WRITEBYTE, baddr);
+ OPCODE_END
+
+ OPCODE_BEGIN(95) /* STA $nn,X */
+ STA(4, ZP_IND_X_ADDR, ZP_WRITEBYTE, baddr);
+ OPCODE_END
+
+ OPCODE_BEGIN(96) /* STX $nn,Y */
+ STX(4, ZP_IND_Y_ADDR, ZP_WRITEBYTE, baddr);
+ OPCODE_END
+
+ OPCODE_BEGIN(97) /* SAX $nn,Y */
+ SAX(4, ZP_IND_Y_ADDR, ZP_WRITEBYTE, baddr);
+ OPCODE_END
+
+ OPCODE_BEGIN(98) /* TYA */
+ TYA();
+ OPCODE_END
+
+ OPCODE_BEGIN(99) /* STA $nnnn,Y */
+ STA(5, ABS_IND_Y_ADDR, mem_writebyte, addr);
+ OPCODE_END
+
+ OPCODE_BEGIN(9A) /* TXS */
+ TXS();
+ OPCODE_END
+
+ OPCODE_BEGIN(9B) /* SHS $nnnn,Y */
+ SHS(5, ABS_IND_Y_ADDR, mem_writebyte, addr);
+ OPCODE_END
+
+ OPCODE_BEGIN(9C) /* SHY $nnnn,X */
+ SHY(5, ABS_IND_X_ADDR, mem_writebyte, addr);
+ OPCODE_END
+
+ OPCODE_BEGIN(9D) /* STA $nnnn,X */
+ STA(5, ABS_IND_X_ADDR, mem_writebyte, addr);
+ OPCODE_END
+
+ OPCODE_BEGIN(9E) /* SHX $nnnn,Y */
+ SHX(5, ABS_IND_Y_ADDR, mem_writebyte, addr);
+ OPCODE_END
+
+ OPCODE_BEGIN(9F) /* SHA $nnnn,Y */
+ SHA(5, ABS_IND_Y_ADDR, mem_writebyte, addr);
+ OPCODE_END
+
+ OPCODE_BEGIN(A0) /* LDY #$nn */
+ LDY(2, IMMEDIATE_BYTE);
+ OPCODE_END
+
+ OPCODE_BEGIN(A1) /* LDA ($nn,X) */
+ LDA(6, INDIR_X_BYTE);
+ OPCODE_END
+
+ OPCODE_BEGIN(A2) /* LDX #$nn */
+ LDX(2, IMMEDIATE_BYTE);
+ OPCODE_END
+
+ OPCODE_BEGIN(A3) /* LAX ($nn,X) */
+ LAX(6, INDIR_X_BYTE);
+ OPCODE_END
+
+ OPCODE_BEGIN(A4) /* LDY $nn */
+ LDY(3, ZERO_PAGE_BYTE);
+ OPCODE_END
+
+ OPCODE_BEGIN(A5) /* LDA $nn */
+ LDA(3, ZERO_PAGE_BYTE);
+ OPCODE_END
+
+ OPCODE_BEGIN(A6) /* LDX $nn */
+ LDX(3, ZERO_PAGE_BYTE);
+ OPCODE_END
+
+ OPCODE_BEGIN(A7) /* LAX $nn */
+ LAX(3, ZERO_PAGE_BYTE);
+ OPCODE_END
+
+ OPCODE_BEGIN(A8) /* TAY */
+ TAY();
+ OPCODE_END
+
+ OPCODE_BEGIN(A9) /* LDA #$nn */
+ LDA(2, IMMEDIATE_BYTE);
+ OPCODE_END
+
+ OPCODE_BEGIN(AA) /* TAX */
+ TAX();
+ OPCODE_END
+
+ OPCODE_BEGIN(AB) /* LXA #$nn */
+ LXA(2, IMMEDIATE_BYTE);
+ OPCODE_END
+
+ OPCODE_BEGIN(AC) /* LDY $nnnn */
+ LDY(4, ABSOLUTE_BYTE);
+ OPCODE_END
+
+ OPCODE_BEGIN(AD) /* LDA $nnnn */
+ LDA(4, ABSOLUTE_BYTE);
+ OPCODE_END
+
+ OPCODE_BEGIN(AE) /* LDX $nnnn */
+ LDX(4, ABSOLUTE_BYTE);
+ OPCODE_END
+
+ OPCODE_BEGIN(AF) /* LAX $nnnn */
+ LAX(4, ABSOLUTE_BYTE);
+ OPCODE_END
+
+ OPCODE_BEGIN(B0) /* BCS $nnnn */
+ BCS();
+ OPCODE_END
+
+ OPCODE_BEGIN(B1) /* LDA ($nn),Y */
+ LDA(5, INDIR_Y_BYTE_READ);
+ OPCODE_END
+
+ OPCODE_BEGIN(B3) /* LAX ($nn),Y */
+ LAX(5, INDIR_Y_BYTE_READ);
+ OPCODE_END
+
+ OPCODE_BEGIN(B4) /* LDY $nn,X */
+ LDY(4, ZP_IND_X_BYTE);
+ OPCODE_END
+
+ OPCODE_BEGIN(B5) /* LDA $nn,X */
+ LDA(4, ZP_IND_X_BYTE);
+ OPCODE_END
+
+ OPCODE_BEGIN(B6) /* LDX $nn,Y */
+ LDX(4, ZP_IND_Y_BYTE);
+ OPCODE_END
+
+ OPCODE_BEGIN(B7) /* LAX $nn,Y */
+ LAX(4, ZP_IND_Y_BYTE);
+ OPCODE_END
+
+ OPCODE_BEGIN(B8) /* CLV */
+ CLV();
+ OPCODE_END
+
+ OPCODE_BEGIN(B9) /* LDA $nnnn,Y */
+ LDA(4, ABS_IND_Y_BYTE_READ);
+ OPCODE_END
+
+ OPCODE_BEGIN(BA) /* TSX */
+ TSX();
+ OPCODE_END
+
+ OPCODE_BEGIN(BB) /* LAS $nnnn,Y */
+ LAS(4, ABS_IND_Y_BYTE_READ);
+ OPCODE_END
+
+ OPCODE_BEGIN(BC) /* LDY $nnnn,X */
+ LDY(4, ABS_IND_X_BYTE_READ);
+ OPCODE_END
+
+ OPCODE_BEGIN(BD) /* LDA $nnnn,X */
+ LDA(4, ABS_IND_X_BYTE_READ);
+ OPCODE_END
+
+ OPCODE_BEGIN(BE) /* LDX $nnnn,Y */
+ LDX(4, ABS_IND_Y_BYTE_READ);
+ OPCODE_END
+
+ OPCODE_BEGIN(BF) /* LAX $nnnn,Y */
+ LAX(4, ABS_IND_Y_BYTE_READ);
+ OPCODE_END
+
+ OPCODE_BEGIN(C0) /* CPY #$nn */
+ CPY(2, IMMEDIATE_BYTE);
+ OPCODE_END
+
+ OPCODE_BEGIN(C1) /* CMP ($nn,X) */
+ CMP(6, INDIR_X_BYTE);
+ OPCODE_END
+
+ OPCODE_BEGIN(C3) /* DCP ($nn,X) */
+ DCP(8, INDIR_X, mem_writebyte, addr);
+ OPCODE_END
+
+ OPCODE_BEGIN(C4) /* CPY $nn */
+ CPY(3, ZERO_PAGE_BYTE);
+ OPCODE_END
+
+ OPCODE_BEGIN(C5) /* CMP $nn */
+ CMP(3, ZERO_PAGE_BYTE);
+ OPCODE_END
+
+ OPCODE_BEGIN(C6) /* DEC $nn */
+ DEC(5, ZERO_PAGE, ZP_WRITEBYTE, baddr);
+ OPCODE_END
+
+ OPCODE_BEGIN(C7) /* DCP $nn */
+ DCP(5, ZERO_PAGE, ZP_WRITEBYTE, baddr);
+ OPCODE_END
+
+ OPCODE_BEGIN(C8) /* INY */
+ INY();
+ OPCODE_END
+
+ OPCODE_BEGIN(C9) /* CMP #$nn */
+ CMP(2, IMMEDIATE_BYTE);
+ OPCODE_END
+
+ OPCODE_BEGIN(CA) /* DEX */
+ DEX();
+ OPCODE_END
+
+ OPCODE_BEGIN(CB) /* SBX #$nn */
+ SBX(2, IMMEDIATE_BYTE);
+ OPCODE_END
+
+ OPCODE_BEGIN(CC) /* CPY $nnnn */
+ CPY(4, ABSOLUTE_BYTE);
+ OPCODE_END
+
+ OPCODE_BEGIN(CD) /* CMP $nnnn */
+ CMP(4, ABSOLUTE_BYTE);
+ OPCODE_END
+
+ OPCODE_BEGIN(CE) /* DEC $nnnn */
+ DEC(6, ABSOLUTE, mem_writebyte, addr);
+ OPCODE_END
+
+ OPCODE_BEGIN(CF) /* DCP $nnnn */
+ DCP(6, ABSOLUTE, mem_writebyte, addr);
+ OPCODE_END
+
+ OPCODE_BEGIN(D0) /* BNE $nnnn */
+ BNE();
+ OPCODE_END
+
+ OPCODE_BEGIN(D1) /* CMP ($nn),Y */
+ CMP(5, INDIR_Y_BYTE_READ);
+ OPCODE_END
+
+ OPCODE_BEGIN(D3) /* DCP ($nn),Y */
+ DCP(8, INDIR_Y, mem_writebyte, addr);
+ OPCODE_END
+
+ OPCODE_BEGIN(D5) /* CMP $nn,X */
+ CMP(4, ZP_IND_X_BYTE);
+ OPCODE_END
+
+ OPCODE_BEGIN(D6) /* DEC $nn,X */
+ DEC(6, ZP_IND_X, ZP_WRITEBYTE, baddr);
+ OPCODE_END
+
+ OPCODE_BEGIN(D7) /* DCP $nn,X */
+ DCP(6, ZP_IND_X, ZP_WRITEBYTE, baddr);
+ OPCODE_END
+
+ OPCODE_BEGIN(D8) /* CLD */
+ CLD();
+ OPCODE_END
+
+ OPCODE_BEGIN(D9) /* CMP $nnnn,Y */
+ CMP(4, ABS_IND_Y_BYTE_READ);
+ OPCODE_END
+
+ OPCODE_BEGIN(DB) /* DCP $nnnn,Y */
+ DCP(7, ABS_IND_Y, mem_writebyte, addr);
+ OPCODE_END
+
+ OPCODE_BEGIN(DD) /* CMP $nnnn,X */
+ CMP(4, ABS_IND_X_BYTE_READ);
+ OPCODE_END
+
+ OPCODE_BEGIN(DE) /* DEC $nnnn,X */
+ DEC(7, ABS_IND_X, mem_writebyte, addr);
+ OPCODE_END
+
+ OPCODE_BEGIN(DF) /* DCP $nnnn,X */
+ DCP(7, ABS_IND_X, mem_writebyte, addr);
+ OPCODE_END
+
+ OPCODE_BEGIN(E0) /* CPX #$nn */
+ CPX(2, IMMEDIATE_BYTE);
+ OPCODE_END
+
+ OPCODE_BEGIN(E1) /* SBC ($nn,X) */
+ SBC(6, INDIR_X_BYTE);
+ OPCODE_END
+
+ OPCODE_BEGIN(E3) /* ISB ($nn,X) */
+ ISB(8, INDIR_X, mem_writebyte, addr);
+ OPCODE_END
+
+ OPCODE_BEGIN(E4) /* CPX $nn */
+ CPX(3, ZERO_PAGE_BYTE);
+ OPCODE_END
+
+ OPCODE_BEGIN(E5) /* SBC $nn */
+ SBC(3, ZERO_PAGE_BYTE);
+ OPCODE_END
+
+ OPCODE_BEGIN(E6) /* INC $nn */
+ INC(5, ZERO_PAGE, ZP_WRITEBYTE, baddr);
+ OPCODE_END
+
+ OPCODE_BEGIN(E7) /* ISB $nn */
+ ISB(5, ZERO_PAGE, ZP_WRITEBYTE, baddr);
+ OPCODE_END
+
+ OPCODE_BEGIN(E8) /* INX */
+ INX();
+ OPCODE_END
+
+ OPCODE_BEGIN(E9) /* SBC #$nn */
+ OPCODE_BEGIN(EB) /* USBC #$nn */
+ SBC(2, IMMEDIATE_BYTE);
+ OPCODE_END
+
+ OPCODE_BEGIN(EA) /* NOP */
+ NOP();
+ OPCODE_END
+
+ OPCODE_BEGIN(EC) /* CPX $nnnn */
+ CPX(4, ABSOLUTE_BYTE);
+ OPCODE_END
+
+ OPCODE_BEGIN(ED) /* SBC $nnnn */
+ SBC(4, ABSOLUTE_BYTE);
+ OPCODE_END
+
+ OPCODE_BEGIN(EE) /* INC $nnnn */
+ INC(6, ABSOLUTE, mem_writebyte, addr);
+ OPCODE_END
+
+ OPCODE_BEGIN(EF) /* ISB $nnnn */
+ ISB(6, ABSOLUTE, mem_writebyte, addr);
+ OPCODE_END
+
+ OPCODE_BEGIN(F0) /* BEQ $nnnn */
+ BEQ();
+ OPCODE_END
+
+ OPCODE_BEGIN(F1) /* SBC ($nn),Y */
+ SBC(5, INDIR_Y_BYTE_READ);
+ OPCODE_END
+
+ OPCODE_BEGIN(F3) /* ISB ($nn),Y */
+ ISB(8, INDIR_Y, mem_writebyte, addr);
+ OPCODE_END
+
+ OPCODE_BEGIN(F5) /* SBC $nn,X */
+ SBC(4, ZP_IND_X_BYTE);
+ OPCODE_END
+
+ OPCODE_BEGIN(F6) /* INC $nn,X */
+ INC(6, ZP_IND_X, ZP_WRITEBYTE, baddr);
+ OPCODE_END
+
+ OPCODE_BEGIN(F7) /* ISB $nn,X */
+ ISB(6, ZP_IND_X, ZP_WRITEBYTE, baddr);
+ OPCODE_END
+
+ OPCODE_BEGIN(F8) /* SED */
+ SED();
+ OPCODE_END
+
+ OPCODE_BEGIN(F9) /* SBC $nnnn,Y */
+ SBC(4, ABS_IND_Y_BYTE_READ);
+ OPCODE_END
+
+ OPCODE_BEGIN(FB) /* ISB $nnnn,Y */
+ ISB(7, ABS_IND_Y, mem_writebyte, addr);
+ OPCODE_END
+
+ OPCODE_BEGIN(FD) /* SBC $nnnn,X */
+ SBC(4, ABS_IND_X_BYTE_READ);
+ OPCODE_END
+
+ OPCODE_BEGIN(FE) /* INC $nnnn,X */
+ INC(7, ABS_IND_X, mem_writebyte, addr);
+ OPCODE_END
+
+ OPCODE_BEGIN(FF) /* ISB $nnnn,X */
+ ISB(7, ABS_IND_X, mem_writebyte, addr);
+ OPCODE_END
+
+#ifdef NES6502_JUMPTABLE
+end_execute:
+
+#else /* !NES6502_JUMPTABLE */
+ }
+ }
+#endif /* !NES6502_JUMPTABLE */
+
+ /* store local copy of regs */
+ STORE_LOCAL_REGS();
+
+ /* Return our actual amount of executed cycles */
+ return (cpu.total_cycles - old_cycles);
+}
+
+/* (Retro-Go on NumPlay) the memory pages, for the cartridge RAM's writes and save states */
+uint8 **nes6502_pages(void)
+{
+ return cpu.mem_page;
+}
+
+/* Issue a CPU Reset */
+void nes6502_reset(void)
+{
+ cpu.p_reg = Z_FLAG | R_FLAG | I_FLAG; /* Reserved bit always 1 */
+ cpu.int_pending = 0; /* No pending interrupts */
+ cpu.int_latency = 0; /* No latent interrupts */
+ cpu.pc_reg = bank_readword(RESET_VECTOR); /* Fetch reset vector */
+ cpu.burn_cycles = RESET_CYCLES;
+ cpu.jammed = false;
+}
+
+/* following macro is used for below 2 functions */
+#define DECLARE_LOCAL_REGS \
+ uint32 PC; \
+ uint8 A, X, Y, S; \
+ uint8 n_flag, v_flag, b_flag; \
+ uint8 d_flag, i_flag, z_flag, c_flag;
+
+/* Non-maskable interrupt */
+void nes6502_nmi(void)
+{
+ DECLARE_LOCAL_REGS
+
+ if (false == cpu.jammed)
+ {
+ GET_GLOBAL_REGS();
+ NMI_PROC();
+ cpu.burn_cycles += INT_CYCLES;
+ STORE_LOCAL_REGS();
+ }
+}
+
+/* Interrupt request */
+void nes6502_irq(void)
+{
+ DECLARE_LOCAL_REGS
+
+ if (false == cpu.jammed)
+ {
+ GET_GLOBAL_REGS();
+ if (0 == i_flag)
+ {
+ IRQ_PROC();
+ cpu.burn_cycles += INT_CYCLES;
+ }
+ else
+ {
+ cpu.int_pending = 1;
+ }
+ STORE_LOCAL_REGS();
+ }
+}
+
+/* Set dead cycle period */
+void nes6502_burn(int cycles)
+{
+ cpu.burn_cycles += cycles;
+}
+
+/* Release our timeslice */
+void nes6502_release(void)
+{
+ remaining_cycles = 0;
+}
+
diff --git a/games/retrogo/src/nes/nes6502.h b/games/retrogo/src/nes/nes6502.h
new file mode 100644
index 00000000..d228a31e
--- /dev/null
+++ b/games/retrogo/src/nes/nes6502.h
@@ -0,0 +1,121 @@
+/*
+** Nofrendo (c) 1998-2000 Matthew Conte ([email protected])
+**
+**
+** This program is free software; you can redistribute it and/or modify it under the terms of
+** the GNU General Public License as published by the Free Software Foundation; either version 3
+** of the License, or (at your option) any later version. (Nofrendo was released under version
+** 2 of the GNU Library General Public License; as its section 3 allows, this copy, changed for
+** Retro-Go on NumPlay, is under the GNU General Public License instead.)
+**
+** This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY;
+** without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
+** See the GNU General Public License for more details.
+**
+** Any permitted reproduction of these routines, in whole or in part,
+** must bear this legend.
+**
+**
+** nes6502.h
+**
+** NES custom 6502 CPU definitions / prototypes
+** $Id: nes6502.h,v 1.2 2001/04/27 14:37:11 neil Exp $
+*/
+
+/* NOTE: 16-bit addresses avoided like the plague: use 32-bit values
+** wherever humanly possible
+*/
+#ifndef _NES6502_H_
+#define _NES6502_H_
+
+#include "noftypes.h"
+
+/* Define this to enable decimal mode in ADC / SBC (not needed in NES) */
+/*#define NES6502_DECIMAL*/
+
+#define NES6502_NUMBANKS 16
+#define NES6502_BANKSHIFT 12
+#define NES6502_BANKSIZE (0x10000 / NES6502_NUMBANKS)
+#define NES6502_BANKMASK (NES6502_BANKSIZE - 1)
+
+/* P (flag) register bitmasks */
+#define N_FLAG 0x80
+#define V_FLAG 0x40
+#define R_FLAG 0x20 /* Reserved, always 1 */
+#define B_FLAG 0x10
+#define D_FLAG 0x08
+#define I_FLAG 0x04
+#define Z_FLAG 0x02
+#define C_FLAG 0x01
+
+/* Vector addresses */
+#define NMI_VECTOR 0xFFFA
+#define RESET_VECTOR 0xFFFC
+#define IRQ_VECTOR 0xFFFE
+
+/* cycle counts for interrupts */
+#define INT_CYCLES 7
+#define RESET_CYCLES 6
+
+#define NMI_MASK 0x01
+#define IRQ_MASK 0x02
+
+/* Stack is located on 6502 page 1 */
+#define STACK_OFFSET 0x0100
+
+typedef struct
+{
+ uint32 min_range, max_range;
+ uint8 (*read_func)(uint32 address);
+} nes6502_memread;
+
+typedef struct
+{
+ uint32 min_range, max_range;
+ void (*write_func)(uint32 address, uint8 value);
+} nes6502_memwrite;
+
+typedef struct
+{
+ uint8 *mem_page[NES6502_NUMBANKS]; /* memory page pointers */
+
+ nes6502_memread *read_handler;
+ nes6502_memwrite *write_handler;
+
+ uint32 pc_reg;
+ uint8 a_reg, p_reg;
+ uint8 x_reg, y_reg;
+ uint8 s_reg;
+
+ uint8 jammed; /* is processor jammed? */
+
+ uint8 int_pending, int_latency;
+
+ int32 total_cycles, burn_cycles;
+} nes6502_context;
+
+#ifdef __cplusplus
+extern "C" {
+#endif /* __cplusplus */
+
+/* Functions which govern the 6502's execution */
+extern void nes6502_reset(void);
+extern int nes6502_execute(int total_cycles);
+extern void nes6502_nmi(void);
+extern void nes6502_irq(void);
+extern uint8 nes6502_getbyte(uint32 address);
+extern uint32 nes6502_getcycles(bool reset_flag);
+extern void nes6502_burn(int cycles);
+extern void nes6502_release(void);
+extern uint8 **nes6502_pages(void);
+
+/* Context get/set */
+extern void nes6502_setcontext(nes6502_context *cpu);
+extern void nes6502_getcontext(nes6502_context *cpu);
+
+#ifdef __cplusplus
+}
+#endif /* __cplusplus */
+
+#endif /* _NES6502_H_ */
+
diff --git a/games/retrogo/src/nes/nes_apu.c b/games/retrogo/src/nes/nes_apu.c
new file mode 100644
index 00000000..e8121048
--- /dev/null
+++ b/games/retrogo/src/nes/nes_apu.c
@@ -0,0 +1,61 @@
+/* The NES's sound registers without the sound: what $4015 reads back (the channels' length
+ * counters, the frame interrupt), for the games that wait on them. Written for Retro-Go on
+ * NumPlay; GPL-3.0-or-later. The length table and the halt bits are the 2A03's (NESdev wiki). */
+#include "nes_apu.h"
+#include "nes.h"
+
+apu_t apu;
+
+static const uint8 length_table[32] = {
+ 10, 254, 20, 2, 40, 4, 80, 6, 160, 8, 60, 10, 14, 12, 26, 14,
+ 12, 16, 24, 18, 48, 20, 96, 22, 192, 24, 72, 26, 16, 28, 32, 30,
+};
+
+void apu_reset(void)
+{
+ memset(&apu, 0, sizeof apu);
+}
+
+static bool halted(int ch)
+{
+ return ch == 2 ? (apu.regs[8] & 0x80) : (apu.regs[ch * 4] & 0x20);
+}
+
+void apu_halfframe(void)
+{
+ for (int ch = 0; ch < 4; ch++)
+ if (apu.length[ch] && !halted(ch))
+ apu.length[ch]--;
+}
+
+uint8 apu_read(uint32 address)
+{
+ if (address != 0x4015)
+ return (uint8) (address >> 8); /* (open bus) */
+ uint8 value = 0;
+ for (int ch = 0; ch < 4; ch++)
+ if (apu.length[ch])
+ value |= (uint8) (1 << ch);
+ return value | nes_clearfiq();
+}
+
+void apu_write(uint32 address, uint8 value)
+{
+ if (address == 0x4015)
+ {
+ apu.enabled = value & 0x1F;
+ for (int ch = 0; ch < 4; ch++)
+ if (!(value & (1 << ch)))
+ apu.length[ch] = 0;
+ return;
+ }
+ if (address < 0x4000 || address >= 0x4018)
+ return;
+ apu.regs[address - 0x4000] = value;
+ if (address < 0x4010 && (address & 3) == 3)
+ {
+ int ch = (int) ((address - 0x4000) >> 2);
+ if (apu.enabled & (1 << ch))
+ apu.length[ch] = length_table[value >> 3];
+ }
+}
diff --git a/games/retrogo/src/nes/nes_apu.h b/games/retrogo/src/nes/nes_apu.h
new file mode 100644
index 00000000..cadd277e
--- /dev/null
+++ b/games/retrogo/src/nes/nes_apu.h
@@ -0,0 +1,25 @@
+/* The NES's sound registers, for games that read them back (Retro-Go on NumPlay plays no sound:
+ * the calculator has no speaker). Written for Retro-Go on NumPlay; GPL-3.0-or-later. */
+#ifndef _NES_APU_H_
+#define _NES_APU_H_
+#include "noftypes.h"
+
+/* (the sound chips of some mappers: not emulated) */
+typedef struct apuext_s apuext_t;
+
+uint8 apu_read(uint32 address);
+void apu_write(uint32 address, uint8 value);
+void apu_reset(void);
+/* a 120th of a second: the length counters count down */
+void apu_halfframe(void);
+
+/* what a save state keeps */
+typedef struct
+{
+ uint8 regs[0x18];
+ uint8 enabled;
+ uint8 length[4];
+} apu_t;
+extern apu_t apu;
+
+#endif
diff --git a/games/retrogo/src/nes/nes_core.h b/games/retrogo/src/nes/nes_core.h
new file mode 100644
index 00000000..c69c0fe7
--- /dev/null
+++ b/games/retrogo/src/nes/nes_core.h
@@ -0,0 +1,30 @@
+/* The NES emulator (nofrendo), as Retro-Go's screens drive it. */
+#ifndef NES_CORE_H
+#define NES_CORE_H
+#include "../rg.h"
+
+#define NES_WIDTH 256
+#define NES_HEIGHT 240
+
+/* the palettes the Options offer */
+enum { NES_PAL_NOFRENDO, NES_PAL_NTSC, NES_PAL_COUNT };
+
+/* Loads an iNES ROM read in place; RG_OK or an RG_ERR_ code. */
+int nes_load(const uint8_t *data, uint32_t size);
+void nes_reset_machine(bool hard);
+void nes_run_frame(bool draw);
+void nes_set_pad(int rg_pad);
+void nes_set_palette(int pal);
+void nes_set_sprite_limit(bool on);
+/* the last frame drawn, line by line through rg_line again (under the menus) */
+void nes_redraw(void);
+int nes_mapper(void);
+
+/* the cartridge's battery RAM: NULL when it has no battery */
+uint8_t *nes_sram(uint32_t *size);
+bool nes_sram_dirty(void);
+void nes_sram_saved(void);
+
+int nes_state_chunks(rg_chunk_t *out);
+void nes_state_loaded(void);
+#endif
diff --git a/games/retrogo/src/nes/nes_mmc.c b/games/retrogo/src/nes/nes_mmc.c
new file mode 100644
index 00000000..d725f78b
--- /dev/null
+++ b/games/retrogo/src/nes/nes_mmc.c
@@ -0,0 +1,230 @@
+/*
+** Nofrendo (c) 1998-2000 Matthew Conte ([email protected])
+**
+**
+** This program is free software; you can redistribute it and/or modify it under the terms of
+** the GNU General Public License as published by the Free Software Foundation; either version 3
+** of the License, or (at your option) any later version. (Nofrendo was released under version
+** 2 of the GNU Library General Public License; as its section 3 allows, this copy, changed for
+** Retro-Go on NumPlay, is under the GNU General Public License instead.)
+**
+** This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY;
+** without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
+** See the GNU General Public License for more details.
+**
+** Any permitted reproduction of these routines, in whole or in part,
+** must bear this legend.
+**
+**
+** nes_mmc.c
+**
+** NES Memory Management Controller (mapper) emulation
+** $Id: nes_mmc.c,v 1.2 2001/04/27 14:37:11 neil Exp $
+*/
+
+#include <string.h>
+#include "noftypes.h"
+#include "nes6502.h"
+#include "nes_mmc.h"
+#include "nes_ppu.h"
+#include "mmclist.h"
+#include "nes_rom.h"
+
+#define MMC_8KROM (mmc.cart->rom_banks * 2)
+#define MMC_16KROM (mmc.cart->rom_banks)
+#define MMC_32KROM (mmc.cart->rom_banks / 2)
+#define MMC_8KVROM (mmc.cart->vrom_banks)
+#define MMC_4KVROM (mmc.cart->vrom_banks * 2)
+#define MMC_2KVROM (mmc.cart->vrom_banks * 4)
+#define MMC_1KVROM (mmc.cart->vrom_banks * 8)
+
+#define MMC_LAST8KROM (MMC_8KROM - 1)
+#define MMC_LAST16KROM (MMC_16KROM - 1)
+#define MMC_LAST32KROM (MMC_32KROM - 1)
+#define MMC_LAST8KVROM (MMC_8KVROM - 1)
+#define MMC_LAST4KVROM (MMC_4KVROM - 1)
+#define MMC_LAST2KVROM (MMC_2KVROM - 1)
+#define MMC_LAST1KVROM (MMC_1KVROM - 1)
+
+mmc_t mmc;
+
+rominfo_t *mmc_getinfo(void)
+{
+ return mmc.cart;
+}
+
+/* VROM bankswitching */
+void mmc_bankvrom(int size, uint32 address, int bank)
+{
+ if (0 == mmc.cart->vrom_banks)
+ return;
+
+ switch (size)
+ {
+ case 1:
+ if (bank == MMC_LASTBANK)
+ bank = MMC_LAST1KVROM;
+ ppu_setpage(1, address >> 10, &mmc.cart->vrom[((unsigned) bank % (unsigned) MMC_1KVROM) << 10] - address);
+ break;
+
+ case 2:
+ if (bank == MMC_LASTBANK)
+ bank = MMC_LAST2KVROM;
+ ppu_setpage(2, address >> 10, &mmc.cart->vrom[((unsigned) bank % (unsigned) MMC_2KVROM) << 11] - address);
+ break;
+
+ case 4:
+ if (bank == MMC_LASTBANK)
+ bank = MMC_LAST4KVROM;
+ ppu_setpage(4, address >> 10, &mmc.cart->vrom[((unsigned) bank % (unsigned) MMC_4KVROM) << 12] - address);
+ break;
+
+ case 8:
+ if (bank == MMC_LASTBANK)
+ bank = MMC_LAST8KVROM;
+ ppu_setpage(8, 0, &mmc.cart->vrom[((unsigned) bank % (unsigned) MMC_8KVROM) << 13]);
+ break;
+
+ default:
+ log_printf("invalid VROM bank size %d\n", size);
+ }
+}
+
+/* ROM bankswitching */
+void mmc_bankrom(int size, uint32 address, int bank)
+{
+ nes6502_context mmc_cpu;
+
+ nes6502_getcontext(&mmc_cpu);
+
+ switch (size)
+ {
+ case 8:
+ if (bank == MMC_LASTBANK)
+ bank = MMC_LAST8KROM;
+ {
+ int page = address >> NES6502_BANKSHIFT;
+ mmc_cpu.mem_page[page] = &mmc.cart->rom[((unsigned) bank % (unsigned) MMC_8KROM) << 13];
+ mmc_cpu.mem_page[page + 1] = mmc_cpu.mem_page[page] + 0x1000;
+ }
+
+ break;
+
+ case 16:
+ if (bank == MMC_LASTBANK)
+ bank = MMC_LAST16KROM;
+ {
+ int page = address >> NES6502_BANKSHIFT;
+ mmc_cpu.mem_page[page] = &mmc.cart->rom[((unsigned) bank % (unsigned) MMC_16KROM) << 14];
+ mmc_cpu.mem_page[page + 1] = mmc_cpu.mem_page[page] + 0x1000;
+ mmc_cpu.mem_page[page + 2] = mmc_cpu.mem_page[page] + 0x2000;
+ mmc_cpu.mem_page[page + 3] = mmc_cpu.mem_page[page] + 0x3000;
+ }
+ break;
+
+ case 32:
+ if (bank == MMC_LASTBANK)
+ bank = MMC_LAST32KROM;
+
+ if (0 == MMC_32KROM) /* (Retro-Go on NumPlay: 16 KB of PRG ROM, twice) */
+ {
+ for (int page = 8; page < 16; page++)
+ mmc_cpu.mem_page[page] = &mmc.cart->rom[(page & 3) << 12];
+ break;
+ }
+ mmc_cpu.mem_page[8] = &mmc.cart->rom[((unsigned) bank % (unsigned) MMC_32KROM) << 15];
+ mmc_cpu.mem_page[9] = mmc_cpu.mem_page[8] + 0x1000;
+ mmc_cpu.mem_page[10] = mmc_cpu.mem_page[8] + 0x2000;
+ mmc_cpu.mem_page[11] = mmc_cpu.mem_page[8] + 0x3000;
+ mmc_cpu.mem_page[12] = mmc_cpu.mem_page[8] + 0x4000;
+ mmc_cpu.mem_page[13] = mmc_cpu.mem_page[8] + 0x5000;
+ mmc_cpu.mem_page[14] = mmc_cpu.mem_page[8] + 0x6000;
+ mmc_cpu.mem_page[15] = mmc_cpu.mem_page[8] + 0x7000;
+ break;
+
+ default:
+ log_printf("invalid ROM bank size %d\n", size);
+ break;
+ }
+
+ nes6502_setcontext(&mmc_cpu);
+}
+
+/* Check to see if this mapper is supported */
+bool mmc_peek(int map_num)
+{
+ mapintf_t **map_ptr = mappers;
+
+ while (NULL != *map_ptr)
+ {
+ if ((*map_ptr)->number == map_num)
+ return true;
+ map_ptr++;
+ }
+
+ return false;
+}
+
+static void mmc_setpages(void)
+{
+ log_printf("setting up mapper %d\n", mmc.intf->number);
+
+ /* Switch ROM into CPU space, set VROM/VRAM (done for ALL ROMs) */
+ mmc_bankrom(16, 0x8000, 0);
+ mmc_bankrom(16, 0xC000, MMC_LASTBANK);
+ mmc_bankvrom(8, 0x0000, 0);
+
+ if (mmc.cart->flags & ROM_FLAG_FOURSCREEN)
+ {
+ ppu_mirror(0, 1, 2, 3);
+ }
+ else
+ {
+ if (MIRROR_VERT == mmc.cart->mirror)
+ ppu_mirror(0, 1, 0, 1);
+ else
+ ppu_mirror(0, 0, 1, 1);
+ }
+
+ /* if we have no VROM, switch in VRAM */
+ /* TODO: fix this hack implementation */
+ if (0 == mmc.cart->vrom_banks)
+ {
+ ASSERT(mmc.cart->vram);
+
+ ppu_setpage(8, 0, mmc.cart->vram);
+ ppu_mirrorhipages();
+ }
+}
+
+/* Mapper initialization routine */
+void mmc_reset(void)
+{
+ mmc_setpages();
+
+ ppu_setlatchfunc(NULL);
+ ppu_setvromswitch(NULL);
+
+ if (mmc.intf->init)
+ mmc.intf->init();
+
+ log_printf("reset memory mapper\n");
+}
+
+
+/* the cartridge's mapper: false if nofrendo has none for it */
+bool mmc_init(rominfo_t *rominfo)
+{
+ mapintf_t **map_ptr;
+
+ for (map_ptr = mappers; *map_ptr; map_ptr++)
+ {
+ if ((*map_ptr)->number == rominfo->mapper_number)
+ {
+ mmc.intf = *map_ptr;
+ mmc.cart = rominfo;
+ return true;
+ }
+ }
+ return false;
+}
diff --git a/games/retrogo/src/nes/nes_mmc.h b/games/retrogo/src/nes/nes_mmc.h
new file mode 100644
index 00000000..01775bd8
--- /dev/null
+++ b/games/retrogo/src/nes/nes_mmc.h
@@ -0,0 +1,82 @@
+/*
+** Nofrendo (c) 1998-2000 Matthew Conte ([email protected])
+**
+**
+** This program is free software; you can redistribute it and/or modify it under the terms of
+** the GNU General Public License as published by the Free Software Foundation; either version 3
+** of the License, or (at your option) any later version. (Nofrendo was released under version
+** 2 of the GNU Library General Public License; as its section 3 allows, this copy, changed for
+** Retro-Go on NumPlay, is under the GNU General Public License instead.)
+**
+** This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY;
+** without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
+** See the GNU General Public License for more details.
+**
+** Any permitted reproduction of these routines, in whole or in part,
+** must bear this legend.
+**
+**
+** nes_mmc.h
+**
+** NES Memory Management Controller (mapper) defines / prototypes
+** $Id: nes_mmc.h,v 1.2 2001/04/27 14:37:11 neil Exp $
+*/
+
+#ifndef _NES_MMC_H_
+#define _NES_MMC_H_
+
+#include "libsnss.h"
+#include "nes_apu.h"
+
+#define MMC_LASTBANK -1
+
+typedef struct
+{
+ uint32 min_range, max_range;
+ uint8 (*read_func)(uint32 address);
+} map_memread;
+
+typedef struct
+{
+ uint32 min_range, max_range;
+ void (*write_func)(uint32 address, uint8 value);
+} map_memwrite;
+
+
+typedef struct mapintf_s
+{
+ int number;
+ char *name;
+ void (*init)(void);
+ void (*vblank)(void);
+ void (*hblank)(int vblank);
+ void (*get_state)(SnssMapperBlock *state);
+ void (*set_state)(SnssMapperBlock *state);
+ map_memread *mem_read;
+ map_memwrite *mem_write;
+ apuext_t *sound_ext;
+} mapintf_t;
+
+
+#include "nes_rom.h"
+typedef struct mmc_s
+{
+ mapintf_t *intf;
+ rominfo_t *cart; /* link it back to the cart */
+} mmc_t;
+
+extern rominfo_t *mmc_getinfo(void);
+
+extern void mmc_bankvrom(int size, uint32 address, int bank);
+extern void mmc_bankrom(int size, uint32 address, int bank);
+
+/* Prototypes */
+extern mmc_t mmc;
+extern bool mmc_init(rominfo_t *rominfo);
+
+extern bool mmc_peek(int map_num);
+
+extern void mmc_reset(void);
+
+#endif /* _NES_MMC_H_ */
+
diff --git a/games/retrogo/src/nes/nes_ppu.c b/games/retrogo/src/nes/nes_ppu.c
new file mode 100644
index 00000000..3990bb12
--- /dev/null
+++ b/games/retrogo/src/nes/nes_ppu.c
@@ -0,0 +1,1058 @@
+/*
+** Nofrendo (c) 1998-2000 Matthew Conte ([email protected])
+**
+**
+** This program is free software; you can redistribute it and/or modify it under the terms of
+** the GNU General Public License as published by the Free Software Foundation; either version 3
+** of the License, or (at your option) any later version. (Nofrendo was released under version
+** 2 of the GNU Library General Public License; as its section 3 allows, this copy, changed for
+** Retro-Go on NumPlay, is under the GNU General Public License instead.)
+**
+** This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY;
+** without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
+** See the GNU General Public License for more details.
+**
+** Any permitted reproduction of these routines, in whole or in part,
+** must bear this legend.
+**
+**
+** nes_ppu.c
+**
+** NES PPU emulation
+** $Id: nes_ppu.c,v 1.2 2001/04/27 14:37:11 neil Exp $
+*/
+
+#include <string.h>
+#include <stdlib.h>
+#include "noftypes.h"
+#include "nes_ppu.h"
+#include "nes.h"
+#include "nes6502.h"
+#include "nes_mmc.h"
+
+#include "../rg.h"
+
+
+/* PPU access */
+#define PPU_MEM(x) ppu.page[((x) >> 10) & 15][(x)]
+
+/* Background (color 0) and solid sprite pixel flags */
+#define BG_TRANS 0x80
+#define SP_PIXEL 0x40
+#define BG_CLEAR(V) ((V) & BG_TRANS)
+#define BG_SOLID(V) (0 == BG_CLEAR(V))
+#define SP_CLEAR(V) (0 == ((V) & SP_PIXEL))
+
+/* Full BG color */
+#define FULLBG (ppu.palette[0] | BG_TRANS)
+
+/* the NES PPU */
+ppu_t ppu;
+bool ppu_limit_sprites = true;
+bool ppu_pages_changed = true; /* (since the last line drawn: for the lines kept for the menus) */
+
+/* a write to the PPU's memory: not into the cartridge's CHR ROM, read in place */
+static void ppu_poke(uint32 address, uint8 value)
+{
+ uint8 *p = &PPU_MEM(address & 0x3FFF);
+ if (p >= nes_rom_lo && p < nes_rom_hi)
+ return;
+ *p = value;
+}
+
+
+void ppu_setpage(int size, int page_num, uint8 *location)
+{
+ ppu_pages_changed = true;
+ /* deliberately fall through */
+ switch (size)
+ {
+ case 8:
+ ppu.page[page_num++] = location;
+ ppu.page[page_num++] = location;
+ ppu.page[page_num++] = location;
+ ppu.page[page_num++] = location;
+ case 4:
+ ppu.page[page_num++] = location;
+ ppu.page[page_num++] = location;
+ case 2:
+ ppu.page[page_num++] = location;
+ case 1:
+ ppu.page[page_num++] = location;
+ break;
+ }
+}
+
+/* make sure $3000-$3F00 mirrors $2000-$2F00 */
+void ppu_mirrorhipages(void)
+{
+ ppu_pages_changed = true;
+ ppu.page[12] = ppu.page[8] - 0x1000;
+ ppu.page[13] = ppu.page[9] - 0x1000;
+ ppu.page[14] = ppu.page[10] - 0x1000;
+ ppu.page[15] = ppu.page[11] - 0x1000;
+}
+
+void ppu_mirror(int nt1, int nt2, int nt3, int nt4)
+{
+ ppu_pages_changed = true;
+ ppu.page[8] = ppu.nametab + (nt1 << 10) - 0x2000;
+ ppu.page[9] = ppu.nametab + (nt2 << 10) - 0x2400;
+ ppu.page[10] = ppu.nametab + (nt3 << 10) - 0x2800;
+ ppu.page[11] = ppu.nametab + (nt4 << 10) - 0x2C00;
+ ppu.page[12] = ppu.page[8] - 0x1000;
+ ppu.page[13] = ppu.page[9] - 0x1000;
+ ppu.page[14] = ppu.page[10] - 0x1000;
+ ppu.page[15] = ppu.page[11] - 0x1000;
+}
+
+/* bleh, for snss */
+uint8 *ppu_getpage(int page)
+{
+ return ppu.page[page];
+}
+
+
+/* reset state of ppu */
+void ppu_reset(int reset_type)
+{
+ if (HARD_RESET == reset_type)
+ memset(ppu.oam, 0xFF, 256); /* (sprites off screen) */
+
+ ppu.ctrl0 = 0;
+ ppu.ctrl1 = PPU_CTRL1F_OBJON | PPU_CTRL1F_BGON;
+ ppu.stat = 0;
+ ppu.flipflop = 0;
+ ppu.vaddr = ppu.vaddr_latch = 0x2000;
+ ppu.oam_addr = 0;
+ ppu.tile_xofs = 0;
+
+ ppu.latch = 0;
+ ppu.vram_accessible = true;
+}
+
+/* we render a scanline of graphics first so we know exactly
+** where the sprite 0 strike is going to occur (in terms of
+** cpu cycles), using the relation that 3 pixels == 1 cpu cycle
+*/
+static void ppu_setstrike(int x_loc)
+{
+ if (false == ppu.strikeflag)
+ {
+ ppu.strikeflag = true;
+
+ /* 3 pixels per cpu cycle */
+ ppu.strike_cycle = nes6502_getcycles(false) + (x_loc / 3);
+ }
+}
+
+static void ppu_oamdma(uint8 value)
+{
+ uint32 cpu_address;
+ uint8 oam_loc;
+
+ cpu_address = (uint32) (value << 8);
+
+ /* Sprite DMA starts at the current SPRRAM address */
+ oam_loc = ppu.oam_addr;
+ do
+ {
+ ppu.oam[oam_loc++] = nes6502_getbyte(cpu_address++);
+ }
+ while (oam_loc != ppu.oam_addr);
+
+ /* TODO: enough with houdini */
+ cpu_address -= 256;
+ /* Odd address in $2003 */
+ if ((ppu.oam_addr >> 2) & 1)
+ {
+ for (oam_loc = 4; oam_loc < 8; oam_loc++)
+ ppu.oam[oam_loc] = nes6502_getbyte(cpu_address++);
+ cpu_address += 248;
+ for (oam_loc = 0; oam_loc < 4; oam_loc++)
+ ppu.oam[oam_loc] = nes6502_getbyte(cpu_address++);
+ }
+ /* Even address in $2003 */
+ else
+ {
+ for (oam_loc = 0; oam_loc < 8; oam_loc++)
+ ppu.oam[oam_loc] = nes6502_getbyte(cpu_address++);
+ }
+
+ /* make the CPU spin for DMA cycles */
+ nes6502_burn(513);
+ nes6502_release();
+}
+
+/* TODO: this isn't the PPU! */
+void ppu_writehigh(uint32 address, uint8 value)
+{
+ switch (address)
+ {
+ case PPU_OAMDMA:
+ ppu_oamdma(value);
+ break;
+
+ case PPU_JOY0:
+ /* VS system VROM switching - bleh!*/
+ if (ppu.vromswitch)
+ ppu.vromswitch(value);
+
+ /* see if we need to strobe them joypads */
+ value &= 1;
+
+ if (0 == value && ppu.strobe)
+ input_strobe();
+
+ ppu.strobe = value;
+ break;
+
+ case PPU_JOY1: /* frame IRQ control */
+ nes_setfiq(value);
+ break;
+
+ default:
+ break;
+ }
+}
+
+/* TODO: this isn't the PPU! */
+uint8 ppu_readhigh(uint32 address)
+{
+ uint8 value;
+
+ switch (address)
+ {
+ case PPU_JOY0:
+ value = input_get(INP_JOYPAD0);
+ break;
+
+ case PPU_JOY1:
+ /* TODO: better input handling */
+ value = input_get(INP_ZAPPER | INP_JOYPAD1
+ /*| INP_ARKANOID*/
+ /*| INP_POWERPAD*/);
+ break;
+
+ default:
+ value = 0xFF;
+ break;
+ }
+
+ return value;
+}
+
+/* Read from $2000-$2007 */
+uint8 ppu_read(uint32 address)
+{
+ uint8 value;
+
+ /* handle mirrored reads up to $3FFF */
+ switch (address & 0x2007)
+ {
+ case PPU_STAT:
+ value = (ppu.stat & 0xE0) | (ppu.latch & 0x1F);
+
+ if (ppu.strikeflag)
+ {
+ if (nes6502_getcycles(false) >= ppu.strike_cycle)
+ value |= PPU_STATF_STRIKE;
+ }
+
+ /* clear both vblank flag and vram address flipflop */
+ ppu.stat &= ~PPU_STATF_VBLANK;
+ ppu.flipflop = 0;
+ break;
+
+ case PPU_VDATA:
+ /* buffered VRAM reads */
+ value = ppu.latch = ppu.vdata_latch;
+
+ /* VRAM only accessible during VBL */
+ if ((ppu.bg_on || ppu.obj_on) && !ppu.vram_accessible)
+ {
+ ppu.vdata_latch = 0xFF;
+ }
+ else
+ {
+ uint32 addr = ppu.vaddr;
+ if (addr >= 0x3000)
+ addr -= 0x1000;
+ ppu.vdata_latch = PPU_MEM(addr);
+ }
+
+ ppu.vaddr += ppu.vaddr_inc;
+ ppu.vaddr &= 0x3FFF;
+ break;
+
+ case PPU_OAMDATA:
+ case PPU_CTRL0:
+ case PPU_CTRL1:
+ case PPU_OAMADDR:
+ case PPU_SCROLL:
+ case PPU_VADDR:
+ default:
+ value = ppu.latch;
+ break;
+ }
+
+ return value;
+}
+
+/* Write to $2000-$2007 */
+void ppu_write(uint32 address, uint8 value)
+{
+ /* write goes into ppu latch... */
+ ppu.latch = value;
+
+ switch (address & 0x2007)
+ {
+ case PPU_CTRL0:
+ ppu.ctrl0 = value;
+
+ ppu.obj_height = (value & PPU_CTRL0F_OBJ16) ? 16 : 8;
+ ppu.bg_base = (value & PPU_CTRL0F_BGADDR) ? 0x1000 : 0;
+ ppu.obj_base = (value & PPU_CTRL0F_OBJADDR) ? 0x1000 : 0;
+ ppu.vaddr_inc = (value & PPU_CTRL0F_ADDRINC) ? 32 : 1;
+ ppu.tile_nametab = value & PPU_CTRL0F_NAMETAB;
+
+ /* Mask out bits 10 & 11 in the ppu latch */
+ ppu.vaddr_latch &= ~0x0C00;
+ ppu.vaddr_latch |= ((value & 3) << 10);
+ break;
+
+ case PPU_CTRL1:
+ ppu.ctrl1 = value;
+
+ ppu.obj_on = (value & PPU_CTRL1F_OBJON) ? true : false;
+ ppu.bg_on = (value & PPU_CTRL1F_BGON) ? true : false;
+ ppu.obj_mask = (value & PPU_CTRL1F_OBJMASK) ? false : true;
+ ppu.bg_mask = (value & PPU_CTRL1F_BGMASK) ? false : true;
+ break;
+
+ case PPU_OAMADDR:
+ ppu.oam_addr = value;
+ break;
+
+ case PPU_OAMDATA:
+ ppu.oam[ppu.oam_addr++] = value;
+ break;
+
+ case PPU_SCROLL:
+ if (0 == ppu.flipflop)
+ {
+ /* Mask out bits 4 - 0 in the ppu latch */
+ ppu.vaddr_latch &= ~0x001F;
+ ppu.vaddr_latch |= (value >> 3); /* Tile number */
+ ppu.tile_xofs = (value & 7); /* Tile offset (0-7 pix) */
+ }
+ else
+ {
+ /* Mask out bits 14-12 and 9-5 in the ppu latch */
+ ppu.vaddr_latch &= ~0x73E0;
+ ppu.vaddr_latch |= ((value & 0xF8) << 2); /* Tile number */
+ ppu.vaddr_latch |= ((value & 7) << 12); /* Tile offset (0-7 pix) */
+ }
+
+ ppu.flipflop ^= 1;
+
+ break;
+
+ case PPU_VADDR:
+ if (0 == ppu.flipflop)
+ {
+ /* Mask out bits 15-8 in ppu latch */
+ ppu.vaddr_latch &= ~0xFF00;
+ ppu.vaddr_latch |= ((value & 0x3F) << 8);
+ }
+ else
+ {
+ /* Mask out bits 7-0 in ppu latch */
+ ppu.vaddr_latch &= ~0x00FF;
+ ppu.vaddr_latch |= value;
+ ppu.vaddr = ppu.vaddr_latch;
+ }
+
+ ppu.flipflop ^= 1;
+
+ break;
+
+ case PPU_VDATA:
+ if (ppu.vaddr < 0x3F00)
+ {
+ /* VRAM only accessible during scanlines 241-260 */
+ if ((ppu.bg_on || ppu.obj_on) && !ppu.vram_accessible)
+ {
+ ppu_poke(ppu.vaddr, 0xFF); /* corrupt */
+ }
+ else
+ {
+ uint32 addr = ppu.vaddr;
+
+ if (false == ppu.vram_present && addr >= 0x3000)
+ ppu.vaddr -= 0x1000;
+
+ ppu_poke(addr, value);
+ }
+ }
+ else
+ {
+ if (0 == (ppu.vaddr & 0x0F))
+ {
+ int i;
+
+ for (i = 0; i < 8; i ++)
+ ppu.palette[i << 2] = (value & 0x3F) | BG_TRANS;
+ }
+ else if (ppu.vaddr & 3)
+ {
+ ppu.palette[ppu.vaddr & 0x1F] = value & 0x3F;
+ }
+ }
+
+ ppu.vaddr += ppu.vaddr_inc;
+ ppu.vaddr &= 0x3FFF;
+ break;
+
+ default:
+ break;
+ }
+}
+
+void ppu_setlatchfunc(ppulatchfunc_t func)
+{
+ ppu.latchfunc = func;
+}
+
+void ppu_setvromswitch(ppuvromswitch_t func)
+{
+ ppu.vromswitch = func;
+}
+
+/* rendering routines */
+INLINE void draw_bgtile(uint8 *surface, uint8 pat1, uint8 pat2,
+ const uint8 *colors)
+{
+ uint32 pattern = ((pat2 & 0xAA) << 8) | ((pat2 & 0x55) << 1)
+ | ((pat1 & 0xAA) << 7) | (pat1 & 0x55);
+
+ *surface++ = colors[(pattern >> 14) & 3];
+ *surface++ = colors[(pattern >> 6) & 3];
+ *surface++ = colors[(pattern >> 12) & 3];
+ *surface++ = colors[(pattern >> 4) & 3];
+ *surface++ = colors[(pattern >> 10) & 3];
+ *surface++ = colors[(pattern >> 2) & 3];
+ *surface++ = colors[(pattern >> 8) & 3];
+ *surface = colors[pattern & 3];
+}
+
+INLINE int draw_oamtile(uint8 *surface, uint8 attrib, uint8 pat1,
+ uint8 pat2, const uint8 *col_tbl, bool check_strike)
+{
+ int strike_pixel = -1;
+ uint32 color = ((pat2 & 0xAA) << 8) | ((pat2 & 0x55) << 1)
+ | ((pat1 & 0xAA) << 7) | (pat1 & 0x55);
+
+ /* sprite is not 100% transparent */
+ if (color)
+ {
+ uint8 colors[8];
+
+ /* swap pixels around if our tile is flipped */
+ if (0 == (attrib & OAMF_HFLIP))
+ {
+ colors[0] = (color >> 14) & 3;
+ colors[1] = (color >> 6) & 3;
+ colors[2] = (color >> 12) & 3;
+ colors[3] = (color >> 4) & 3;
+ colors[4] = (color >> 10) & 3;
+ colors[5] = (color >> 2) & 3;
+ colors[6] = (color >> 8) & 3;
+ colors[7] = color & 3;
+ }
+ else
+ {
+ colors[7] = (color >> 14) & 3;
+ colors[6] = (color >> 6) & 3;
+ colors[5] = (color >> 12) & 3;
+ colors[4] = (color >> 4) & 3;
+ colors[3] = (color >> 10) & 3;
+ colors[2] = (color >> 2) & 3;
+ colors[1] = (color >> 8) & 3;
+ colors[0] = color & 3;
+ }
+
+ /* check for solid sprite pixel overlapping solid bg pixel */
+ if (check_strike)
+ {
+ if (colors[0] && BG_SOLID(surface[0]))
+ strike_pixel = 0;
+ else if (colors[1] && BG_SOLID(surface[1]))
+ strike_pixel = 1;
+ else if (colors[2] && BG_SOLID(surface[2]))
+ strike_pixel = 2;
+ else if (colors[3] && BG_SOLID(surface[3]))
+ strike_pixel = 3;
+ else if (colors[4] && BG_SOLID(surface[4]))
+ strike_pixel = 4;
+ else if (colors[5] && BG_SOLID(surface[5]))
+ strike_pixel = 5;
+ else if (colors[6] && BG_SOLID(surface[6]))
+ strike_pixel = 6;
+ else if (colors[7] && BG_SOLID(surface[7]))
+ strike_pixel = 7;
+ }
+
+ /* draw the character */
+ if (attrib & OAMF_BEHIND)
+ {
+ if (colors[0])
+ surface[0] = SP_PIXEL | (BG_CLEAR(surface[0]) ? col_tbl[colors[0]] : surface[0]);
+ if (colors[1])
+ surface[1] = SP_PIXEL | (BG_CLEAR(surface[1]) ? col_tbl[colors[1]] : surface[1]);
+ if (colors[2])
+ surface[2] = SP_PIXEL | (BG_CLEAR(surface[2]) ? col_tbl[colors[2]] : surface[2]);
+ if (colors[3])
+ surface[3] = SP_PIXEL | (BG_CLEAR(surface[3]) ? col_tbl[colors[3]] : surface[3]);
+ if (colors[4])
+ surface[4] = SP_PIXEL | (BG_CLEAR(surface[4]) ? col_tbl[colors[4]] : surface[4]);
+ if (colors[5])
+ surface[5] = SP_PIXEL | (BG_CLEAR(surface[5]) ? col_tbl[colors[5]] : surface[5]);
+ if (colors[6])
+ surface[6] = SP_PIXEL | (BG_CLEAR(surface[6]) ? col_tbl[colors[6]] : surface[6]);
+ if (colors[7])
+ surface[7] = SP_PIXEL | (BG_CLEAR(surface[7]) ? col_tbl[colors[7]] : surface[7]);
+ }
+ else
+ {
+ if (colors[0] && SP_CLEAR(surface[0]))
+ surface[0] = SP_PIXEL | col_tbl[colors[0]];
+ if (colors[1] && SP_CLEAR(surface[1]))
+ surface[1] = SP_PIXEL | col_tbl[colors[1]];
+ if (colors[2] && SP_CLEAR(surface[2]))
+ surface[2] = SP_PIXEL | col_tbl[colors[2]];
+ if (colors[3] && SP_CLEAR(surface[3]))
+ surface[3] = SP_PIXEL | col_tbl[colors[3]];
+ if (colors[4] && SP_CLEAR(surface[4]))
+ surface[4] = SP_PIXEL | col_tbl[colors[4]];
+ if (colors[5] && SP_CLEAR(surface[5]))
+ surface[5] = SP_PIXEL | col_tbl[colors[5]];
+ if (colors[6] && SP_CLEAR(surface[6]))
+ surface[6] = SP_PIXEL | col_tbl[colors[6]];
+ if (colors[7] && SP_CLEAR(surface[7]))
+ surface[7] = SP_PIXEL | col_tbl[colors[7]];
+ }
+ }
+
+ return strike_pixel;
+}
+
+static void ppu_renderbg(uint8 *vidbuf)
+{
+ uint8 *bmp_ptr, *data_ptr, *tile_ptr, *attrib_ptr;
+ uint32 refresh_vaddr, bg_offset, attrib_base;
+ int tile_count;
+ uint8 tile_index, x_tile, y_tile;
+ uint8 col_high, attrib, attrib_shift;
+
+ /* draw a line of transparent background color if bg is disabled */
+ if (false == ppu.bg_on)
+ {
+ memset(vidbuf, FULLBG, NES_SCREEN_WIDTH);
+ return;
+ }
+
+ bmp_ptr = vidbuf - ppu.tile_xofs; /* scroll x */
+ refresh_vaddr = 0x2000 + (ppu.vaddr & 0x0FE0); /* mask out x tile */
+ x_tile = ppu.vaddr & 0x1F;
+ y_tile = (ppu.vaddr >> 5) & 0x1F; /* to simplify calculations */
+ bg_offset = ((ppu.vaddr >> 12) & 7) + ppu.bg_base; /* offset in y tile */
+
+ /* calculate initial values */
+ tile_ptr = &PPU_MEM(refresh_vaddr + x_tile); /* pointer to tile index */
+ attrib_base = (refresh_vaddr & 0x2C00) + 0x3C0 + ((y_tile & 0x1C) << 1);
+ attrib_ptr = &PPU_MEM(attrib_base + (x_tile >> 2));
+ attrib = *attrib_ptr++;
+ attrib_shift = (x_tile & 2) + ((y_tile & 2) << 1);
+ col_high = ((attrib >> attrib_shift) & 3) << 2;
+
+ /* ppu fetches 33 tiles */
+ tile_count = 33;
+ while (tile_count--)
+ {
+ /* Tile number from nametable */
+ tile_index = *tile_ptr++;
+ data_ptr = &PPU_MEM(bg_offset + (tile_index << 4));
+
+ /* Handle $FD/$FE tile VROM switching (PunchOut) */
+ if (ppu.latchfunc)
+ ppu.latchfunc(ppu.bg_base, tile_index);
+
+ draw_bgtile(bmp_ptr, data_ptr[0], data_ptr[8], ppu.palette + col_high);
+ bmp_ptr += 8;
+
+ x_tile++;
+
+ if (0 == (x_tile & 1)) /* check every 2 tiles */
+ {
+ if (0 == (x_tile & 3)) /* check every 4 tiles */
+ {
+ if (32 == x_tile) /* check every 32 tiles */
+ {
+ x_tile = 0;
+ refresh_vaddr ^= (1 << 10); /* switch nametable */
+ attrib_base ^= (1 << 10);
+
+ /* recalculate pointers */
+ tile_ptr = &PPU_MEM(refresh_vaddr);
+ attrib_ptr = &PPU_MEM(attrib_base);
+ }
+
+ /* Get the attribute byte */
+ attrib = *attrib_ptr++;
+ }
+
+ attrib_shift ^= 2;
+ col_high = ((attrib >> attrib_shift) & 3) << 2;
+ }
+ }
+
+ /* Blank left hand column if need be */
+ if (ppu.bg_mask)
+ {
+ uint32 *buf_ptr = (uint32 *) vidbuf;
+ uint32 bg_clear = (uint32) FULLBG * 0x01010101u;
+
+ ((uint32 *) buf_ptr)[0] = bg_clear;
+ ((uint32 *) buf_ptr)[1] = bg_clear;
+ }
+}
+
+/* OAM entry */
+typedef struct obj_s
+{
+ uint8 y_loc;
+ uint8 tile;
+ uint8 atr;
+ uint8 x_loc;
+} obj_t;
+
+/* TODO: fetch valid OAM a scanline before, like the Real Thing */
+static void ppu_renderoam(uint8 *vidbuf, int scanline)
+{
+ uint8 *buf_ptr;
+ uint32 vram_offset, savecol[2];
+ int sprite_num, spritecount;
+ obj_t *sprite_ptr;
+ uint8 sprite_height;
+
+ if (false == ppu.obj_on)
+ return;
+
+ /* Get our buffer pointer */
+ buf_ptr = vidbuf;
+
+ /* Save left hand column? */
+ if (ppu.obj_mask)
+ {
+ savecol[0] = ((uint32 *) buf_ptr)[0];
+ savecol[1] = ((uint32 *) buf_ptr)[1];
+ }
+
+ sprite_height = ppu.obj_height;
+ vram_offset = ppu.obj_base;
+ spritecount = 0;
+
+ sprite_ptr = (obj_t *) ppu.oam;
+
+ for (sprite_num = 0; sprite_num < 64; sprite_num++, sprite_ptr++)
+ {
+ uint8 *data_ptr, *bmp_ptr;
+ uint32 vram_adr;
+ int y_offset;
+ uint8 tile_index, attrib, col_high;
+ uint8 sprite_y, sprite_x;
+ bool check_strike;
+ int strike_pixel;
+
+ sprite_y = sprite_ptr->y_loc + 1;
+
+ /* Check to see if sprite is out of range */
+ if ((sprite_y > scanline) || (sprite_y <= (scanline - sprite_height))
+ || (0 == sprite_y) || (sprite_y >= 240))
+ continue;
+
+ sprite_x = sprite_ptr->x_loc;
+ tile_index = sprite_ptr->tile;
+ attrib = sprite_ptr->atr;
+
+ bmp_ptr = buf_ptr + sprite_x;
+
+ /* Handle $FD/$FE tile VROM switching (PunchOut) */
+ if (ppu.latchfunc)
+ ppu.latchfunc(vram_offset, tile_index);
+
+ /* Get upper two bits of color */
+ col_high = ((attrib & 3) << 2);
+
+ /* 8x16 even sprites use $0000, odd use $1000 */
+ if (16 == ppu.obj_height)
+ vram_adr = ((tile_index & 1) << 12) | ((tile_index & 0xFE) << 4);
+ else
+ vram_adr = vram_offset + (tile_index << 4);
+
+ /* Get the address of the tile */
+ data_ptr = &PPU_MEM(vram_adr);
+
+ /* Calculate offset (line within the sprite) */
+ y_offset = scanline - sprite_y;
+ if (y_offset > 7)
+ y_offset += 8;
+
+ /* Account for vertical flippage */
+ if (attrib & OAMF_VFLIP)
+ {
+ if (16 == ppu.obj_height)
+ y_offset -= 23;
+ else
+ y_offset -= 7;
+
+ data_ptr -= y_offset;
+ }
+ else
+ {
+ data_ptr += y_offset;
+ }
+
+ /* if we're on sprite 0 and sprite 0 strike flag isn't set,
+ ** check for a strike
+ */
+ check_strike = (0 == sprite_num) && (false == ppu.strikeflag);
+ strike_pixel = draw_oamtile(bmp_ptr, attrib, data_ptr[0], data_ptr[8], ppu.palette + 16 + col_high, check_strike);
+ if (strike_pixel >= 0)
+ ppu_setstrike(strike_pixel);
+
+ /* maximum of 8 sprites per scanline */
+ if (++spritecount == PPU_MAXSPRITE)
+ {
+ ppu.stat |= PPU_STATF_MAXSPRITE;
+ if (ppu_limit_sprites)
+ break;
+ }
+ }
+
+ /* Restore lefthand column */
+ if (ppu.obj_mask)
+ {
+ ((uint32 *) buf_ptr)[0] = savecol[0];
+ ((uint32 *) buf_ptr)[1] = savecol[1];
+ }
+}
+
+/* Fake rendering a line */
+/* This is needed for sprite 0 hits when we're skipping drawing a frame */
+static void ppu_fakeoam(int scanline)
+{
+ uint8 *data_ptr;
+ obj_t *sprite_ptr;
+ uint32 vram_adr, color;
+ int y_offset;
+ uint8 pat1, pat2;
+ uint8 tile_index, attrib;
+ uint8 sprite_height, sprite_y, sprite_x;
+
+ /* we don't need to be here if strike flag is set */
+
+ if (false == ppu.obj_on || ppu.strikeflag)
+ return;
+
+ sprite_height = ppu.obj_height;
+ sprite_ptr = (obj_t *) ppu.oam;
+ sprite_y = sprite_ptr->y_loc + 1;
+
+ /* Check to see if sprite is out of range */
+ if ((sprite_y > scanline) || (sprite_y <= (scanline - sprite_height))
+ || (0 == sprite_y) || (sprite_y > 240))
+ return;
+
+ sprite_x = sprite_ptr->x_loc;
+ tile_index = sprite_ptr->tile;
+ attrib = sprite_ptr->atr;
+
+ /* 8x16 even sprites use $0000, odd use $1000 */
+ if (16 == ppu.obj_height)
+ vram_adr = ((tile_index & 1) << 12) | ((tile_index & 0xFE) << 4);
+ else
+ vram_adr = ppu.obj_base + (tile_index << 4);
+
+ data_ptr = &PPU_MEM(vram_adr);
+
+ /* Calculate offset (line within the sprite) */
+ y_offset = scanline - sprite_y;
+ if (y_offset > 7)
+ y_offset += 8;
+
+ /* Account for vertical flippage */
+ if (attrib & OAMF_VFLIP)
+ {
+ if (16 == ppu.obj_height)
+ y_offset -= 23;
+ else
+ y_offset -= 7;
+ data_ptr -= y_offset;
+ }
+ else
+ {
+ data_ptr += y_offset;
+ }
+
+ /* check for a solid sprite 0 pixel */
+ pat1 = data_ptr[0];
+ pat2 = data_ptr[8];
+ color = ((pat2 & 0xAA) << 8) | ((pat2 & 0x55) << 1)
+ | ((pat1 & 0xAA) << 7) | (pat1 & 0x55);
+
+ if (color)
+ {
+ uint8 colors[8];
+
+ /* buckle up, it's going to get ugly... */
+ if (0 == (attrib & OAMF_HFLIP))
+ {
+ colors[0] = (color >> 14) & 3;
+ colors[1] = (color >> 6) & 3;
+ colors[2] = (color >> 12) & 3;
+ colors[3] = (color >> 4) & 3;
+ colors[4] = (color >> 10) & 3;
+ colors[5] = (color >> 2) & 3;
+ colors[6] = (color >> 8) & 3;
+ colors[7] = color & 3;
+ }
+ else
+ {
+ colors[7] = (color >> 14) & 3;
+ colors[6] = (color >> 6) & 3;
+ colors[5] = (color >> 12) & 3;
+ colors[4] = (color >> 4) & 3;
+ colors[3] = (color >> 10) & 3;
+ colors[2] = (color >> 2) & 3;
+ colors[1] = (color >> 8) & 3;
+ colors[0] = color & 3;
+ }
+
+ if (colors[0])
+ ppu_setstrike(sprite_x + 0);
+ else if (colors[1])
+ ppu_setstrike(sprite_x + 1);
+ else if (colors[2])
+ ppu_setstrike(sprite_x + 2);
+ else if (colors[3])
+ ppu_setstrike(sprite_x + 3);
+ else if (colors[4])
+ ppu_setstrike(sprite_x + 4);
+ else if (colors[5])
+ ppu_setstrike(sprite_x + 5);
+ else if (colors[6])
+ ppu_setstrike(sprite_x + 6);
+ else if (colors[7])
+ ppu_setstrike(sprite_x + 7);
+ }
+}
+
+bool ppu_enabled(void)
+{
+ return (ppu.bg_on || ppu.obj_on);
+}
+
+/* one line: 8 pixels of overdraw on each side for the scroll and the sprites */
+static uint8 linebuf[8 + NES_SCREEN_WIDTH + 16] __attribute__((aligned(4)));
+static uint16 line565[NES_SCREEN_WIDTH];
+const uint16 *nes_palette565 = NULL;
+
+/* (Retro-Go on NumPlay) what each line of the last frame drawn was drawn with: the scroll, the
+ controls and the CHR and nametable banks (a few sets a frame, for the games that switch them
+ for a status bar) */
+#define CHR_SETS 4
+static struct
+{
+ uint16 vaddr;
+ uint8 xofs, ctrl0, ctrl1, set, drawn;
+} snap[NES_SCREEN_HEIGHT];
+static uint8 *chr_sets[CHR_SETS][12];
+static int chr_used;
+
+static void ppu_snapshot(int scanline)
+{
+ int i;
+ if (0 == scanline)
+ {
+ chr_used = 0;
+ memset(snap, 0, sizeof snap);
+ }
+ /* (most lines have the banks of the line before) */
+ i = scanline && snap[scanline - 1].drawn ? snap[scanline - 1].set : chr_used;
+ if (i >= chr_used || ppu_pages_changed)
+ for (i = 0; i < chr_used; i++)
+ if (!memcmp(chr_sets[i], ppu.page, sizeof chr_sets[0]))
+ break;
+ ppu_pages_changed = false;
+ if (i == chr_used)
+ {
+ if (chr_used == CHR_SETS)
+ i = CHR_SETS - 1; /* (more than that in a frame: the last one stands for the rest) */
+ else
+ chr_used++;
+ memcpy(chr_sets[i], ppu.page, sizeof chr_sets[0]);
+ }
+ snap[scanline].vaddr = (uint16) ppu.vaddr;
+ snap[scanline].xofs = (uint8) ppu.tile_xofs;
+ snap[scanline].ctrl0 = ppu.ctrl0;
+ snap[scanline].ctrl1 = ppu.ctrl1;
+ snap[scanline].set = (uint8) i;
+ snap[scanline].drawn = 1;
+}
+
+/* what the two control registers decide (ppu_write's) */
+static void ppu_controls(uint8 ctrl0, uint8 ctrl1)
+{
+ ppu.obj_height = (ctrl0 & PPU_CTRL0F_OBJ16) ? 16 : 8;
+ ppu.bg_base = (ctrl0 & PPU_CTRL0F_BGADDR) ? 0x1000 : 0;
+ ppu.obj_base = (ctrl0 & PPU_CTRL0F_OBJADDR) ? 0x1000 : 0;
+ ppu.obj_on = (ctrl1 & PPU_CTRL1F_OBJON) ? true : false;
+ ppu.bg_on = (ctrl1 & PPU_CTRL1F_BGON) ? true : false;
+ ppu.obj_mask = (ctrl1 & PPU_CTRL1F_OBJMASK) ? false : true;
+ ppu.bg_mask = (ctrl1 & PPU_CTRL1F_BGMASK) ? false : true;
+}
+
+static void ppu_renderscanline(int scanline, bool draw_flag)
+{
+ uint8 *buf = linebuf + 8;
+
+ /* start scanline - transfer ppu latch into vaddr */
+ if (ppu.bg_on || ppu.obj_on)
+ {
+ if (0 == scanline)
+ {
+ ppu.vaddr = ppu.vaddr_latch;
+ }
+ else
+ {
+ ppu.vaddr &= ~0x041F;
+ ppu.vaddr |= (ppu.vaddr_latch & 0x041F);
+ }
+ }
+
+ if (draw_flag)
+ {
+ ppu_snapshot(scanline);
+ ppu_renderbg(buf);
+ }
+
+ /* TODO: fetch obj data 1 scanline before */
+ if (true == draw_flag)
+ {
+ ppu_renderoam(buf, scanline);
+ for (int x = 0; x < NES_SCREEN_WIDTH; x++)
+ line565[x] = nes_palette565[buf[x] & 0x3F];
+ rg_line(scanline, line565);
+ }
+ else
+ ppu_fakeoam(scanline);
+}
+
+/* (Retro-Go on NumPlay) The last frame drawn, again, under Retro-Go's menus: each line with the
+ scroll, controls and CHR banks it had; the PPU is left as it was. */
+void ppu_redraw(void)
+{
+ ppu_t saved;
+ saved = ppu;
+ for (int y = 0; y < NES_SCREEN_HEIGHT; y++)
+ {
+ uint8 *buf = linebuf + 8;
+ if (!snap[y].drawn)
+ {
+ for (int x = 0; x < NES_SCREEN_WIDTH; x++)
+ line565[x] = 0;
+ rg_line(y, line565);
+ continue;
+ }
+ ppu.vaddr = snap[y].vaddr;
+ ppu.tile_xofs = snap[y].xofs;
+ ppu_controls(snap[y].ctrl0, snap[y].ctrl1);
+ memcpy(ppu.page, chr_sets[snap[y].set], sizeof chr_sets[0]);
+ ppu.latchfunc = NULL;
+ ppu.strikeflag = true;
+ ppu_renderbg(buf);
+ ppu_renderoam(buf, y);
+ for (int x = 0; x < NES_SCREEN_WIDTH; x++)
+ line565[x] = nes_palette565[buf[x] & 0x3F];
+ rg_line(y, line565);
+ }
+ ppu = saved;
+ ppu_pages_changed = true;
+}
+
+
+void ppu_endscanline(int scanline)
+{
+ /* modify vram address at end of scanline */
+ if (scanline < 240 && (ppu.bg_on || ppu.obj_on))
+ {
+ int ytile;
+
+ /* check for max 3 bit y tile offset */
+ if (7 == (ppu.vaddr >> 12))
+ {
+ ppu.vaddr &= ~0x7000; /* clear y tile offset */
+ ytile = (ppu.vaddr >> 5) & 0x1F;
+
+ if (29 == ytile)
+ {
+ ppu.vaddr &= ~0x03E0; /* clear y tile */
+ ppu.vaddr ^= 0x0800; /* toggle nametable */
+ }
+ else if (31 == ytile)
+ {
+ ppu.vaddr &= ~0x03E0; /* clear y tile */
+ }
+ else
+ {
+ ppu.vaddr += 0x20; /* increment y tile */
+ }
+ }
+ else
+ {
+ ppu.vaddr += 0x1000; /* increment tile y offset */
+ }
+ }
+}
+
+void ppu_checknmi(void)
+{
+ if (ppu.ctrl0 & PPU_CTRL0F_NMI)
+ nes_nmi();
+}
+
+void ppu_scanline(int scanline, bool draw_flag)
+{
+ if (scanline < 240)
+ {
+ /* Lower the Max Sprite per scanline flag */
+ ppu.stat &= ~PPU_STATF_MAXSPRITE;
+ ppu_renderscanline(scanline, draw_flag);
+ }
+ else if (241 == scanline)
+ {
+ ppu.stat |= PPU_STATF_VBLANK;
+ ppu.vram_accessible = true;
+ }
+ else if (261 == scanline)
+ {
+ ppu.stat &= ~PPU_STATF_VBLANK;
+ ppu.strikeflag = false;
+ ppu.strike_cycle = (uint32) -1;
+
+ ppu.vram_accessible = false;
+ }
+}
+
diff --git a/games/retrogo/src/nes/nes_ppu.h b/games/retrogo/src/nes/nes_ppu.h
new file mode 100644
index 00000000..5c819179
--- /dev/null
+++ b/games/retrogo/src/nes/nes_ppu.h
@@ -0,0 +1,144 @@
+/*
+** Nofrendo (c) 1998-2000 Matthew Conte ([email protected])
+**
+**
+** This program is free software; you can redistribute it and/or modify it under the terms of
+** the GNU General Public License as published by the Free Software Foundation; either version 3
+** of the License, or (at your option) any later version. (Nofrendo was released under version
+** 2 of the GNU Library General Public License; as its section 3 allows, this copy, changed for
+** Retro-Go on NumPlay, is under the GNU General Public License instead.)
+**
+** This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY;
+** without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
+** See the GNU General Public License for more details.
+**
+** Any permitted reproduction of these routines, in whole or in part,
+** must bear this legend.
+**
+**
+** nes_ppu.h
+**
+** NES Picture Processing Unit (PPU) emulation header file
+** $Id: nes_ppu.h,v 1.2 2001/04/27 14:37:11 neil Exp $
+*/
+
+#ifndef _NES_PPU_H_
+#define _NES_PPU_H_
+
+#include "noftypes.h"
+
+/* PPU register defines */
+#define PPU_CTRL0 0x2000
+#define PPU_CTRL1 0x2001
+#define PPU_STAT 0x2002
+#define PPU_OAMADDR 0x2003
+#define PPU_OAMDATA 0x2004
+#define PPU_SCROLL 0x2005
+#define PPU_VADDR 0x2006
+#define PPU_VDATA 0x2007
+
+#define PPU_OAMDMA 0x4014
+#define PPU_JOY0 0x4016
+#define PPU_JOY1 0x4017
+
+/* $2000 */
+#define PPU_CTRL0F_NMI 0x80
+#define PPU_CTRL0F_OBJ16 0x20
+#define PPU_CTRL0F_BGADDR 0x10
+#define PPU_CTRL0F_OBJADDR 0x08
+#define PPU_CTRL0F_ADDRINC 0x04
+#define PPU_CTRL0F_NAMETAB 0x03
+
+/* $2001 */
+#define PPU_CTRL1F_OBJON 0x10
+#define PPU_CTRL1F_BGON 0x08
+#define PPU_CTRL1F_OBJMASK 0x04
+#define PPU_CTRL1F_BGMASK 0x02
+
+/* $2002 */
+#define PPU_STATF_VBLANK 0x80
+#define PPU_STATF_STRIKE 0x40
+#define PPU_STATF_MAXSPRITE 0x20
+
+/* Sprite attribute byte bitmasks */
+#define OAMF_VFLIP 0x80
+#define OAMF_HFLIP 0x40
+#define OAMF_BEHIND 0x20
+
+/* Maximum number of sprites per horizontal scanline */
+#define PPU_MAXSPRITE 8
+
+/* some mappers do *dumb* things */
+typedef void (*ppulatchfunc_t)(uint32 address, uint8 value);
+typedef void (*ppuvromswitch_t)(uint8 value);
+
+typedef struct ppu_s
+{
+ /* big nasty memory chunks */
+ uint8 nametab[0x1000];
+ uint8 oam[256];
+ uint8 palette[32];
+ uint8 *page[16];
+
+ /* hardware registers */
+ uint8 ctrl0, ctrl1, stat, oam_addr;
+ uint32 vaddr, vaddr_latch;
+ int tile_xofs, flipflop;
+ int vaddr_inc;
+ uint32 tile_nametab;
+
+ uint8 obj_height;
+ uint32 obj_base, bg_base;
+
+ bool bg_on, obj_on;
+ bool obj_mask, bg_mask;
+
+ uint8 latch, vdata_latch;
+ uint8 strobe;
+
+ bool strikeflag;
+ uint32 strike_cycle;
+
+ /* callbacks for naughty mappers */
+ ppulatchfunc_t latchfunc;
+ ppuvromswitch_t vromswitch;
+
+ bool vram_accessible;
+
+ bool vram_present;
+} ppu_t;
+
+extern ppu_t ppu;
+extern bool ppu_pages_changed;
+extern bool ppu_limit_sprites; /* 8 sprites a line at most, as the NES (an option) */
+extern const uint16 *nes_palette565; /* the 64 NES colours in RGB565 */
+
+/* TODO: should use this pointers */
+extern void ppu_setlatchfunc(ppulatchfunc_t func);
+extern void ppu_setvromswitch(ppuvromswitch_t func);
+
+/* Mirroring */
+/* TODO: this is only used bloody once */
+extern void ppu_mirrorhipages(void);
+
+extern void ppu_mirror(int nt1, int nt2, int nt3, int nt4);
+
+extern void ppu_setpage(int size, int page_num, uint8 *location);
+extern uint8 *ppu_getpage(int page);
+
+
+/* control */
+extern void ppu_reset(int reset_type);
+extern bool ppu_enabled(void);
+extern void ppu_scanline(int scanline, bool draw_flag);
+extern void ppu_endscanline(int scanline);
+extern void ppu_checknmi();
+extern void ppu_redraw(void);
+
+/* IO */
+extern uint8 ppu_read(uint32 address);
+extern void ppu_write(uint32 address, uint8 value);
+extern uint8 ppu_readhigh(uint32 address);
+extern void ppu_writehigh(uint32 address, uint8 value);
+
+#endif /* _NES_PPU_H_ */
diff --git a/games/retrogo/src/nes/nes_rom.h b/games/retrogo/src/nes/nes_rom.h
new file mode 100644
index 00000000..540abe2e
--- /dev/null
+++ b/games/retrogo/src/nes/nes_rom.h
@@ -0,0 +1,61 @@
+/*
+** Nofrendo (c) 1998-2000 Matthew Conte ([email protected])
+**
+**
+** This program is free software; you can redistribute it and/or modify it under the terms of
+** the GNU General Public License as published by the Free Software Foundation; either version 3
+** of the License, or (at your option) any later version. (Nofrendo was released under version
+** 2 of the GNU Library General Public License; as its section 3 allows, this copy, changed for
+** Retro-Go on NumPlay, is under the GNU General Public License instead.)
+**
+** This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY;
+** without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
+** See the GNU General Public License for more details.
+**
+** Any permitted reproduction of these routines, in whole or in part,
+** must bear this legend.
+**
+**
+** nes_rom.h
+**
+** NES ROM loading/saving related defines / prototypes
+** $Id: nes_rom.h,v 1.2 2001/04/27 14:37:11 neil Exp $
+*/
+
+#ifndef _NES_ROM_H_
+#define _NES_ROM_H_
+
+#include "noftypes.h"
+
+typedef enum
+{
+ MIRROR_HORIZ = 0,
+ MIRROR_VERT = 1
+} mirror_t;
+
+#define ROM_FLAG_BATTERY 0x01
+#define ROM_FLAG_TRAINER 0x02
+#define ROM_FLAG_FOURSCREEN 0x04
+#define ROM_FLAG_VERSUS 0x08
+
+typedef struct rominfo_s
+{
+ /* pointers to ROM and VROM: the cartridge read in place, never written */
+ uint8 *rom, *vrom;
+
+ /* pointers to SRAM and VRAM */
+ uint8 *sram, *vram;
+
+ /* number of banks */
+ int rom_banks, vrom_banks;
+ int sram_banks, vram_banks;
+
+ int mapper_number;
+ mirror_t mirror;
+
+ uint8 flags;
+} rominfo_t;
+
+
+#endif /* _NES_ROM_H_ */
+
diff --git a/games/retrogo/src/nes/noftypes.h b/games/retrogo/src/nes/noftypes.h
new file mode 100644
index 00000000..a6c52667
--- /dev/null
+++ b/games/retrogo/src/nes/noftypes.h
@@ -0,0 +1,46 @@
+/*
+** Nofrendo (c) 1998-2000 Matthew Conte ([email protected])
+**
+** This program is free software; you can redistribute it and/or modify it under the terms of
+** the GNU General Public License as published by the Free Software Foundation; either version 3
+** of the License, or (at your option) any later version. (Nofrendo was released under version
+** 2 of the GNU Library General Public License; as its section 3 allows, this copy, changed for
+** Retro-Go on NumPlay, is under the GNU General Public License instead.)
+**
+** This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY;
+** without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
+** See the GNU General Public License for more details.
+**
+** Any permitted reproduction of these routines, in whole or in part, must bear this legend.
+**
+** noftypes.h: the types nofrendo uses.
+*/
+
+#ifndef _TYPES_H_
+#define _TYPES_H_
+
+#include <stdbool.h>
+#include <stddef.h>
+#include <stdint.h>
+#include <string.h>
+
+#define HOST_LITTLE_ENDIAN
+#define INLINE static inline
+#define ZERO_LENGTH 0
+
+/* quell stupid compiler warnings */
+#define UNUSED(x) ((void)(x))
+
+typedef signed char int8;
+typedef signed short int16;
+typedef signed int int32;
+typedef unsigned char uint8;
+typedef unsigned short uint16;
+typedef unsigned int uint32;
+
+#define ASSERT(expr)
+#define ASSERT_MSG(msg)
+#define log_printf(...)
+#define __PACKED__ __attribute__((packed))
+
+#endif /* _TYPES_H_ */
diff --git a/games/retrogo/src/pack.c b/games/retrogo/src/pack.c
new file mode 100644
index 00000000..094f825e
--- /dev/null
+++ b/games/retrogo/src/pack.c
@@ -0,0 +1,81 @@
+/* A small LZ77 packer for Retro-Go's saves.
+ *
+ * The packed stream: a byte under 0x80 is a run of that many plus one bytes as they are; from
+ * 0x80, a match: its length minus 3 in the low 7 bits (127: the rest follows in bytes, 255
+ * meaning there is more), then its distance back minus 1 in two bytes (little-endian). A match
+ * can be as long as the data, so a cartridge RAM of zeros packs to a few bytes. */
+#include "pack.h"
+#include <string.h>
+
+static uint32_t hash(const uint8_t *p) {
+ return (((uint32_t)p[0] << 8 ^ (uint32_t)p[1] << 4 ^ p[2]) * 2654435761u >> 20) & (RG_PACK_HASH - 1);
+}
+
+uint32_t rg_pack(const uint8_t *in, uint32_t n, uint8_t *out, uint16_t *table) {
+ for (int i = 0; i < RG_PACK_HASH; i++) table[i] = 0xFFFF;
+ if (n > RG_PACK_MAX) n = RG_PACK_MAX;
+ uint32_t o = 0, i = 0, lit = 0, lit_at = 0;
+ while (i < n) {
+ uint32_t len = 0, dist = 0;
+ if (i + 3 <= n) {
+ uint32_t h = hash(in + i), cand = table[h];
+ table[h] = (uint16_t)i;
+ if (cand != 0xFFFF && cand < i) {
+ while (i + len < n && in[cand + len] == in[i + len]) len++;
+ dist = i - cand;
+ }
+ }
+ if (len >= 3) {
+ lit = 0;
+ uint32_t l = len - 3;
+ if (out) out[o] = (uint8_t)(0x80 | (l < 127 ? l : 127));
+ o++;
+ if (l >= 127) {
+ for (l -= 127; l >= 255; l -= 255) {
+ if (out) out[o] = 255;
+ o++;
+ }
+ if (out) out[o] = (uint8_t)l;
+ o++;
+ }
+ if (out) out[o] = (uint8_t)(dist - 1), out[o + 1] = (uint8_t)((dist - 1) >> 8);
+ o += 2;
+ /* (the bytes inside the match go into the table too, every fourth in a long one) */
+ for (uint32_t k = 1; k < len && i + k + 3 <= n; k += len > 64 ? 4 : 1) table[hash(in + i + k)] = (uint16_t)(i + k);
+ i += len;
+ } else {
+ if (!lit || lit == 128) lit_at = o++, lit = 0;
+ if (out) out[lit_at] = (uint8_t)lit, out[o] = in[i];
+ o++, i++, lit++;
+ }
+ }
+ return o;
+}
+
+bool rg_unpack(const uint8_t *in, uint32_t n, uint8_t *out, uint32_t size) {
+ uint32_t i = 0, o = 0;
+ while (i < n) {
+ uint32_t t = in[i++];
+ if (t < 0x80) {
+ uint32_t run = t + 1;
+ if (run > n - i || run > size - o) return false;
+ memcpy(out + o, in + i, run);
+ i += run, o += run;
+ } else {
+ uint32_t len = (t & 127) + 3;
+ if ((t & 127) == 127)
+ for (;;) {
+ if (i >= n || len > size) return false;
+ uint32_t b = in[i++];
+ len += b;
+ if (b < 255) break;
+ }
+ if (n - i < 2) return false;
+ uint32_t dist = ((uint32_t)in[i] | (uint32_t)in[i + 1] << 8) + 1;
+ i += 2;
+ if (dist > o || len > size - o) return false;
+ for (uint32_t k = 0; k < len; k++, o++) out[o] = out[o - dist];
+ }
+ }
+ return o == size;
+}
diff --git a/games/retrogo/src/pack.h b/games/retrogo/src/pack.h
new file mode 100644
index 00000000..ec63a270
--- /dev/null
+++ b/games/retrogo/src/pack.h
@@ -0,0 +1,16 @@
+/* Retro-Go's saves, packed (pack.c): the cartridges' RAM and the save states are mostly zeros
+ * and repeats, and the calculator's file system holds 42 KB. */
+#ifndef RG_PACK_H
+#define RG_PACK_H
+#include <stdbool.h>
+#include <stdint.h>
+
+#define RG_PACK_HASH 4096 /* entries of the packer's table (uint16_t each) */
+#define RG_PACK_MAX 65535 /* the most bytes packed at a time */
+
+/* n bytes packed into out (NULL: only measured); the packed size */
+uint32_t rg_pack(const uint8_t *in, uint32_t n, uint8_t *out, uint16_t *table);
+/* exactly `size` bytes unpacked from n; false if the data doesn't hold together (out may then be
+ partly written) */
+bool rg_unpack(const uint8_t *in, uint32_t n, uint8_t *out, uint32_t size);
+#endif
diff --git a/games/retrogo/src/rg.h b/games/retrogo/src/rg.h
new file mode 100644
index 00000000..8b61d190
--- /dev/null
+++ b/games/retrogo/src/rg.h
@@ -0,0 +1,42 @@
+/* What Retro-Go's screens (main.c) and its emulators (gb/, nes/) share. */
+#ifndef RG_H
+#define RG_H
+#include <stdbool.h>
+#include <stddef.h>
+#include <stdint.h>
+
+/* The running emulator's memory: one static block, handed out at load and taken back at the
+ next. rg_alloc gives zeroed, 8-aligned memory, or NULL when the block is full. */
+void *rg_alloc(uint32_t size);
+void rg_alloc_reset(void);
+/* the block's size: a Game Boy Color game's 32 KB of work RAM, 16 KB of video RAM and 32 KB of
+ cartridge RAM, the most a game asks for */
+#define RG_HEAP_SIZE (82 * 1024)
+
+/* The picture: a core hands over each line of its frame as RGB565 pixels, top to bottom,
+ when the frame is drawn (rg_drawing). */
+extern bool rg_drawing;
+void rg_line(int y, const uint16_t *px);
+
+/* The parts of a running machine a save state keeps, in order. */
+typedef struct {
+ void *at;
+ uint32_t size;
+} rg_chunk_t;
+#define RG_MAX_CHUNKS 16
+
+/* The cores' failures when loading a game, shown by the screens. */
+enum {
+ RG_OK = 0,
+ RG_ERR_ROM = -1, /* not a ROM this emulator can read */
+ RG_ERR_MAPPER = -2, /* a cartridge type it doesn't emulate */
+ RG_ERR_MEMORY = -3, /* needs more RAM than the calculator has */
+};
+
+/* the pad's buttons, for every system */
+enum {
+ RG_PAD_A = 1, RG_PAD_B = 2, RG_PAD_SELECT = 4, RG_PAD_START = 8,
+ RG_PAD_UP = 16, RG_PAD_DOWN = 32, RG_PAD_LEFT = 64, RG_PAD_RIGHT = 128
+};
+
+#endif
diff --git a/games/retrogo/src/roms.ld b/games/retrogo/src/roms.ld
new file mode 100644
index 00000000..f1678345
--- /dev/null
+++ b/games/retrogo/src/roms.ld
@@ -0,0 +1,6 @@
+/* RetroGo.nwa on its own: the table of games keeps its own section, and np_retrogo_end marks
+ its end, as NumPlay's numplay.ld marks the end of Retro-Go's block (main.c reads no game past
+ it). */
+SECTIONS {
+ .rodata.np_roms : { KEEP(*(.rodata.np_roms)) np_retrogo_end = .; }
+}
diff --git a/games/retrogo/src/romtable.c b/games/retrogo/src/romtable.c
new file mode 100644
index 00000000..439c9fcc
--- /dev/null
+++ b/games/retrogo/src/romtable.c
@@ -0,0 +1,59 @@
+/* Reading Retro-Go's table of games (the layout is in tools/romtable.py). Whatever the table
+ * holds, nothing is read past `limit` and no game points outside it. */
+#include "romtable.h"
+
+static uint32_t rd32(const uint8_t *p) {
+ return (uint32_t)p[0] | (uint32_t)p[1] << 8 | (uint32_t)p[2] << 16 | (uint32_t)p[3] << 24;
+}
+
+static int lower(int c) { return c >= 'A' && c <= 'Z' ? c + 32 : c; }
+
+/* by system, then by name as Retro-Go sorts its lists (letters before case) */
+static bool before(const rg_rom_t *a, const rg_rom_t *b) {
+ if (a->system != b->system) return a->system < b->system;
+ for (int i = 0; i < RG_ROMS_NAME; i++) {
+ int x = lower(a->name[i]), y = lower(b->name[i]);
+ if (x != y) return x < y;
+ if (!x) break;
+ }
+ return a->data < b->data;
+}
+
+int rg_romtable_read(const uint8_t *table, uint32_t limit, rg_rom_t *out, int max) {
+ if (!table || limit < 12 || rd32(table) != RG_ROMS_MAGIC || rd32(table + 4) != RG_ROMS_VERSION) return -1;
+ uint32_t count = rd32(table + 8);
+ /* (as many entries as the readable bytes hold) */
+ if (count > (limit - 12) / RG_ROMS_ENTRY) count = (limit - 12) / RG_ROMS_ENTRY;
+ uint32_t first = 12 + count * RG_ROMS_ENTRY;
+ int n = 0;
+ for (uint32_t i = 0; i < count && n < max; i++) {
+ const uint8_t *e = table + 12 + i * RG_ROMS_ENTRY;
+ uint32_t at = rd32(e), size = rd32(e + 4);
+ uint8_t system = e[8];
+ if (at < first || (at & 3) || at > limit || !size || size > limit - at) continue;
+ if (system < RG_SYS_GB || system >= RG_SYS_COUNT) continue;
+ rg_rom_t r = {table + at, size, e + 12, system};
+ int k = n++;
+ for (; k > 0 && before(&r, &out[k - 1]); k--) out[k] = out[k - 1];
+ out[k] = r;
+ }
+ return n;
+}
+
+void rg_rom_name(const rg_rom_t *rom, char *out, int n) {
+ int o = 0;
+ for (int i = 0; i < RG_ROMS_NAME && o < n - 1; i++) {
+ uint8_t c = rom->name[i];
+ if (!c) break;
+ if (c >= 0x80) { /* one letter of UTF-8: its continuation bytes go with it */
+ while (i + 1 < RG_ROMS_NAME && (rom->name[i + 1] & 0xC0) == 0x80) i++;
+ c = '?';
+ } else if (c < 0x20 || c == 0x7F) {
+ c = ' ';
+ }
+ out[o++] = (char)c;
+ }
+ while (o > 0 && out[o - 1] == ' ') o--;
+ if (!o && n > 1) out[o++] = '?';
+ out[o] = 0;
+}
diff --git a/games/retrogo/src/romtable.h b/games/retrogo/src/romtable.h
new file mode 100644
index 00000000..d2485018
--- /dev/null
+++ b/games/retrogo/src/romtable.h
@@ -0,0 +1,29 @@
+/* Retro-Go's games: the table np_roms in the app's flash (tools/romtable.py and the customizer
+ * website write it), read in place. */
+#ifndef RG_ROMTABLE_H
+#define RG_ROMTABLE_H
+#include <stdbool.h>
+#include <stdint.h>
+
+#define RG_ROMS_MAGIC 0x4D52504Eu /* "NPRM" */
+#define RG_ROMS_VERSION 1
+#define RG_ROMS_ENTRY 52
+#define RG_ROMS_NAME 40
+#define RG_MAX_ROMS 96
+
+enum { RG_SYS_GB = 1, RG_SYS_GBC, RG_SYS_NES, RG_SYS_SMS, RG_SYS_GG, RG_SYS_COUNT };
+
+typedef struct {
+ const uint8_t *data;
+ uint32_t size;
+ const uint8_t *name; /* RG_ROMS_NAME bytes in the table, zero-padded (maybe not ended) */
+ uint8_t system;
+} rg_rom_t;
+
+/* The games in a table of which `limit` bytes can be read, at most `max`, sorted by system and
+ then by name; entries that don't hold together are left out. -1 when it isn't a table at all. */
+int rg_romtable_read(const uint8_t *table, uint32_t limit, rg_rom_t *out, int max);
+/* a game's name as the screens can show it: ASCII, '?' for any other letter, n bytes at most
+ with the ending zero */
+void rg_rom_name(const rg_rom_t *rom, char *out, int n);
+#endif
diff --git a/games/retrogo/tests/fps.py b/games/retrogo/tests/fps.py
new file mode 100644
index 00000000..681bd2bc
--- /dev/null
+++ b/games/retrogo/tests/fps.py
@@ -0,0 +1,51 @@
+#!/usr/bin/env python3
+"""Retro-Go's speed in tools/emu.py: starts the one game of a RetroGo.nwa built with ROMS="that game"
+(OK on the tab, OK on the game, New game, OK on the controls), plays it with the keys given, and prints
+the frames emulated and drawn a second, from the app's perf_frames and perf_drawn counters.
+
+ fps.py RetroGo.nwa [--model n0110|n0120] [--keys "ms-ms:key,..."] [--ms 20000]
+
+tools/emu.py runs the CPU at 216 million instructions a second (the N0110 and N0115's clock);
+--model n0120 runs it at 550 million, the N0120's. Build retrogo-full.nwa (unstripped) for this."""
+import argparse
+import os
+import struct
+import sys
+
+here = os.path.dirname(os.path.abspath(__file__))
+sys.path.insert(0, os.path.join(here, "..", "..", "..", "tools"))
+import emu # noqa: E402
+
+ap = argparse.ArgumentParser()
+ap.add_argument("nwa")
+ap.add_argument("--model", choices=["n0110", "n0120"], default="n0120")
+ap.add_argument("--keys", default="")
+ap.add_argument("--ms", type=int, default=20000)
+ap.add_argument("--from-ms", type=int, default=8000, help="when the counting starts")
+ap.add_argument("--shot", help="a picture of the end, PNG")
+a = ap.parse_args()
+
+emu.configure(a.model)
+emu.CPU_HZ = 550_000_000 if a.model == "n0120" else 216_000_000
+c = emu.Calculator(a.nwa)
+start = "300-400:ok,900-1000:ok,1500-1600:ok,2100-2200:ok" # tab, game, New game, controls
+c.keys = emu.parse_keys(start + ("," + a.keys if a.keys else ""))
+
+
+def counters():
+ f = struct.unpack("<I", bytes(c.uc.mem_read(c.symbols["perf_frames"], 4)))[0]
+ d = struct.unpack("<I", bytes(c.uc.mem_read(c.symbols["perf_drawn"], 4)))[0]
+ return f, d
+
+
+c.run(a.from_ms)
+f0, d0 = counters()
+t0, s0 = c.now_ms, c.slept_ms
+c.run(a.ms)
+f1, d1 = counters()
+span = (c.now_ms - t0) / 1000
+busy = 100 - 100 * (c.slept_ms - s0) / max(c.now_ms - t0, 1)
+print(f"{os.path.basename(a.nwa)} {a.model}: {(f1 - f0) / span:.1f} frames emulated a second, "
+ f"{(d1 - d0) / span:.1f} drawn, CPU busy {busy:.0f}%")
+if a.shot:
+ c.save_png(a.shot)
diff --git a/games/retrogo/tests/host_core.c b/games/retrogo/tests/host_core.c
new file mode 100644
index 00000000..1f24a224
--- /dev/null
+++ b/games/retrogo/tests/host_core.c
@@ -0,0 +1,148 @@
+/* Retro-Go's emulators on a computer: runs a ROM for some frames, with random keys if asked,
+ * and writes the last frame as a PPM picture.
+ * host_core ROM FRAMES OUT.ppm [SEED] (SEED: random pad presses; 0 for none)
+ * The system comes from the file's extension (.gb .gbc .nes). */
+#include <stdio.h>
+#include <stdlib.h>
+#include <string.h>
+#include <sys/mman.h>
+#include "../src/rg.h"
+#include "../src/gb/gb.h"
+#include "../src/nes/nes_core.h"
+
+static uint8_t heap[RG_HEAP_SIZE] __attribute__((aligned(8)));
+static uint32_t used;
+bool rg_drawing = true;
+static uint16_t frame[256 * 240];
+static int width = 160, lines_seen;
+
+void *rg_alloc(uint32_t size) {
+ size = (size + 7) & ~7u;
+ if (used + size > sizeof heap) return NULL;
+ void *p = heap + used;
+ used += size;
+ memset(p, 0, size);
+ return p;
+}
+void rg_alloc_reset(void) { used = 0; }
+
+void rg_line(int y, const uint16_t *px) {
+ if (y < 0 || y >= 240) {
+ fprintf(stderr, "line %d out of the picture\n", y);
+ abort();
+ }
+ memcpy(frame + y * 256, px, (size_t)width * 2);
+ lines_seen++;
+}
+
+/* the ROM, read only as the calculator's flash is: a write into it stops the test */
+static uint8_t *load(const char *path, uint32_t *size) {
+ FILE *f = fopen(path, "rb");
+ if (!f) return NULL;
+ fseek(f, 0, SEEK_END);
+ long n = ftell(f);
+ fseek(f, 0, SEEK_SET);
+ size_t pages = ((size_t)n + 4095) / 4096 * 4096;
+ uint8_t *d = mmap(NULL, pages, PROT_READ | PROT_WRITE, MAP_PRIVATE | MAP_ANON, -1, 0);
+ if (d == MAP_FAILED || fread(d, 1, (size_t)n, f) != (size_t)n) return NULL;
+ fclose(f);
+ mprotect(d, pages, PROT_READ);
+ *size = (uint32_t)n;
+ return d;
+}
+
+int main(int argc, char **argv) {
+ if (argc < 4) return fprintf(stderr, "usage: host_core ROM FRAMES OUT.ppm [SEED]\n"), 2;
+ uint32_t size;
+ uint8_t *rom = load(argv[1], &size);
+ if (!rom) return fprintf(stderr, "can't read %s\n", argv[1]), 1;
+ int frames = atoi(argv[2]);
+ unsigned seed = argc > 4 ? (unsigned)atoi(argv[4]) : 0;
+ const char *ext = strrchr(argv[1], '.');
+ bool nes = ext && !strcmp(ext, ".nes");
+ int r = nes ? nes_load(rom, size) : gb_load(rom, size);
+ if (r != RG_OK) return fprintf(stderr, "load failed: %d\n", r), 1;
+ int h = nes ? 240 : 144;
+ width = nes ? 256 : 160;
+ int pad = 0;
+ const char *script = argc > 5 ? argv[5] : ""; /* "FRAME=PAD,FRAME=PAD...": the pad from then on */
+ for (int i = 0; i < frames; i++) {
+ if (seed) {
+ seed = seed * 1103515245u + 12345u;
+ if ((seed >> 16) % 8 == 0) pad = (int)((seed >> 8) & 0xFF);
+ }
+ while (*script && atoi(script) == i) {
+ const char *eq = strchr(script, '=');
+ if (!eq) break;
+ pad = atoi(eq + 1);
+ const char *comma = strchr(eq, ',');
+ script = comma ? comma + 1 : "";
+ }
+ if (nes) nes_set_pad(pad), nes_run_frame(true);
+ else gb_set_pad(pad), gb_run_frame(true);
+ }
+ /* STATE=1: a save state taken now, 120 more frames, the state put back, the same 120 frames:
+ the same picture at the end (the state holds the whole machine); then states of random
+ bytes, which must not crash it. REDRAW=1: the last frame drawn again is the same picture. */
+ if (getenv("STATE")) {
+ rg_chunk_t parts[RG_MAX_CHUNKS];
+ int n = nes ? nes_state_chunks(parts) : gb_state_chunks(parts);
+ static uint8_t copy[RG_HEAP_SIZE + 65536];
+ uint32_t at = 0;
+ for (int i = 0; i < n; i++) memcpy(copy + at, parts[i].at, parts[i].size), at += parts[i].size;
+ static uint16_t first[256 * 240];
+ for (int pass = 0; pass < 2; pass++) {
+ if (pass) {
+ n = nes ? nes_state_chunks(parts) : gb_state_chunks(parts);
+ at = 0;
+ for (int i = 0; i < n; i++) memcpy(parts[i].at, copy + at, parts[i].size), at += parts[i].size;
+ if (nes) nes_state_loaded();
+ else gb_state_loaded();
+ }
+ for (int i = 0; i < 120; i++) {
+ int p = (i / 10) % 3 ? 0 : RG_PAD_RIGHT | (i & 16 ? RG_PAD_A : 0);
+ if (nes) nes_set_pad(p), nes_run_frame(true);
+ else gb_set_pad(p), gb_run_frame(true);
+ }
+ if (!pass) memcpy(first, frame, sizeof first);
+ }
+ printf("state %s\n", memcmp(first, frame, sizeof first) ? "differs" : "same");
+ for (int k = 0; k < 30; k++) {
+ n = nes ? nes_state_chunks(parts) : gb_state_chunks(parts);
+ for (int i = 0; i < n; i++)
+ for (uint32_t j = 0; j < parts[i].size; j++)
+ if (k < 10 || (j * 7 + (unsigned)k) % 13 == 0) {
+ seed = seed * 1103515245u + 12345u + (unsigned)k;
+ ((uint8_t *)parts[i].at)[j] = (uint8_t)(seed >> 16);
+ }
+ if (nes) nes_state_loaded();
+ else gb_state_loaded();
+ for (int i = 0; i < 30; i++) {
+ if (nes) nes_set_pad(i & 0xFF), nes_run_frame(true);
+ else gb_set_pad(i & 0xFF), gb_run_frame(true);
+ }
+ }
+ printf("random states: no crash\n");
+ }
+ if (getenv("REDRAW")) {
+ static uint16_t last[256 * 240];
+ memcpy(last, frame, sizeof last);
+ if (nes) nes_redraw();
+ else gb_redraw();
+ int differ = 0;
+ for (int i = 0; i < 256 * h; i++) differ += last[i] != frame[i];
+ printf("redraw: %d pixels differ\n", differ);
+ }
+ FILE *o = fopen(argv[3], "wb");
+ fprintf(o, "P6\n%d %d\n255\n", width, h);
+ for (int y = 0; y < h; y++)
+ for (int x = 0; x < width; x++) {
+ uint16_t c = frame[y * 256 + x];
+ fputc((c >> 11) << 3 | (c >> 13), o);
+ fputc(((c >> 5) & 63) << 2 | ((c >> 9) & 3), o);
+ fputc((c & 31) << 3 | ((c >> 2) & 7), o);
+ }
+ fclose(o);
+ printf("%d frames, %d lines, %u bytes of RAM\n", frames, lines_seen, used);
+ return 0;
+}
diff --git a/games/retrogo/tests/host_pack.c b/games/retrogo/tests/host_pack.c
new file mode 100644
index 00000000..c0ef7b1d
--- /dev/null
+++ b/games/retrogo/tests/host_pack.c
@@ -0,0 +1,58 @@
+/* The saves' packer on a computer (with the sanitizers): every kind of data comes back as it
+ * was, and damaged packed data is turned down without reading or writing past either buffer. */
+#include <stdio.h>
+#include <stdlib.h>
+#include <string.h>
+#include "../src/pack.h"
+
+static uint32_t seed = 12345;
+static uint32_t rnd(void) {
+ seed ^= seed << 13, seed ^= seed >> 17, seed ^= seed << 5;
+ return seed;
+}
+
+int main(void) {
+ static uint16_t table[RG_PACK_HASH];
+ int failures = 0;
+ for (int round = 0; round < 400; round++) {
+ uint32_t n = round < 8 ? (uint32_t[]){0, 1, 2, 3, 18, 130, 131, 65535}[round] : rnd() % 40000;
+ uint8_t *in = malloc(n ? n : 1);
+ int kind = round % 5;
+ for (uint32_t i = 0; i < n; i++)
+ in[i] = kind == 0 ? 0 /* a cartridge RAM never written */
+ : kind == 1 ? (uint8_t)rnd() /* noise */
+ : kind == 2 ? (uint8_t)(i % 7 == 0 ? rnd() : 0xFF) /* sparse */
+ : kind == 3 ? (uint8_t)(i / 300) /* runs */
+ : (uint8_t)(rnd() % 4); /* few values */
+ uint32_t size = rg_pack(in, n, NULL, table);
+ uint8_t *packed = malloc(size ? size : 1), *back = malloc(n ? n : 1);
+ if (rg_pack(in, n, packed, table) != size || !rg_unpack(packed, size, back, n) || memcmp(in, back, n)) {
+ printf("FAIL round %d: %u bytes (kind %d) don't come back\n", round, n, kind);
+ failures++;
+ }
+ if (kind == 0 && n == 65535 && size > 600) printf("FAIL: 64 KB of zeros packed to %u bytes\n", size), failures++;
+ /* damaged: bytes changed, cut short, or a size that doesn't match; must not crash */
+ for (int k = 0; k < 20 && size; k++) {
+ uint8_t *bad = malloc(size);
+ memcpy(bad, packed, size);
+ for (int j = 0; j < 1 + k % 4; j++) bad[rnd() % size] = (uint8_t)rnd();
+ uint32_t cut = k % 3 == 0 ? rnd() % size : size, want = k % 5 == 0 ? (n ? rnd() % n : 0) : n;
+ uint8_t *out = malloc(want ? want : 1);
+ (void)rg_unpack(bad, cut, out, want);
+ free(out);
+ free(bad);
+ }
+ free(in), free(packed), free(back);
+ }
+ /* random bytes as packed data */
+ for (int k = 0; k < 2000; k++) {
+ uint32_t n = rnd() % 300, want = rnd() % 5000;
+ uint8_t *junk = malloc(n ? n : 1), *out = malloc(want ? want : 1);
+ for (uint32_t i = 0; i < n; i++) junk[i] = (uint8_t)rnd();
+ (void)rg_unpack(junk, n, out, want);
+ free(junk), free(out);
+ }
+ printf(failures ? "%d failures\n" : "ok the packer: 400 buffers back as they were, 10000 damaged ones turned down\n",
+ failures);
+ return failures != 0;
+}
diff --git a/games/retrogo/tests/host_romtable.c b/games/retrogo/tests/host_romtable.c
new file mode 100644
index 00000000..dc741829
--- /dev/null
+++ b/games/retrogo/tests/host_romtable.c
@@ -0,0 +1,31 @@
+/* Retro-Go's ROM table reader on a computer: reads a table file (tools/romtable.py --bin, or
+ * a damaged one) from a buffer of exactly its size, so that the sanitizer stops any read past
+ * it, touches every byte of every game it finds and prints them:
+ * host_romtable TABLE.bin prints the count (-1: not a table), then "system size name" */
+#include <stdio.h>
+#include <stdlib.h>
+#include "../src/romtable.h"
+
+int main(int argc, char **argv) {
+ if (argc < 2) return 2;
+ FILE *f = fopen(argv[1], "rb");
+ if (!f) return 2;
+ fseek(f, 0, SEEK_END);
+ long n = ftell(f);
+ fseek(f, 0, SEEK_SET);
+ uint8_t *t = malloc(n ? (size_t)n : 1);
+ if (fread(t, 1, (size_t)n, f) != (size_t)n) return 2;
+ fclose(f);
+ static rg_rom_t roms[RG_MAX_ROMS];
+ int count = rg_romtable_read(t, (uint32_t)n, roms, RG_MAX_ROMS);
+ printf("%d\n", count);
+ for (int i = 0; i < count; i++) {
+ unsigned sum = 0;
+ for (uint32_t k = 0; k < roms[i].size; k++) sum += roms[i].data[k];
+ char name[41];
+ rg_rom_name(&roms[i], name, sizeof name);
+ printf("%d %u %u %s\n", roms[i].system, (unsigned)roms[i].size, sum & 0xFF, name);
+ }
+ free(t);
+ return 0;
+}
diff --git a/games/retrogo/tests/test_app.py b/games/retrogo/tests/test_app.py
new file mode 100644
index 00000000..ca6a9f5b
--- /dev/null
+++ b/games/retrogo/tests/test_app.py
@@ -0,0 +1,171 @@
+#!/usr/bin/env python3
+"""Retro-Go in tools/emu.py, with two small games this test makes: a Game Boy cartridge with battery
+RAM and an NES one with battery RAM, each counting its frames in that RAM. For each: a new game,
+Home (the battery save and a state are written), then Resume from the state and On/Off: the count
+goes on from where it was. All along: what tests/test_games.py checks (Home and On/Off quit, the
+RAM handed back clean, no write to flash, so nothing written into a cartridge read in place, no
+unaligned multi-word read of the file system, the firmware's RAM untouched, the stack).
+
+usage: test_app.py [--keep DIR] (builds output/test/retrogo-full.nwa with ROMS set to the two games)"""
+import argparse
+import os
+import struct
+import subprocess
+import sys
+import tempfile
+
+here = os.path.dirname(os.path.abspath(__file__))
+game = os.path.dirname(here)
+sys.path.insert(0, os.path.join(game, "..", "..", "tools"))
+import emu # noqa: E402
+
+K = emu.KEYS
+
+
+def gb_rom():
+ """MBC1 + RAM + battery, 8 KB of RAM: a 16-bit count at $A000, one more each frame."""
+ rom = bytearray(0x8000)
+ rom[0x100:0x104] = bytes([0x00, 0xC3, 0x50, 0x01]) # nop; jp $0150
+ rom[0x134:0x13C] = b"COUNTER\0"
+ rom[0x147], rom[0x148], rom[0x149] = 0x03, 0x00, 0x02
+ code = [0x3E, 0x0A, 0xEA, 0x00, 0x00, # ld a,$0A; ld ($0000),a: RAM on
+ 0x21, 0x00, 0xA0, # loop: ld hl,$A000
+ 0x34, 0x20, 0x02, 0x23, 0x34, # inc (hl); jr nz,+2; inc hl; inc (hl)
+ 0xF0, 0x44, 0xFE, 0x90, 0x20, 0xFA, # wait for LY = 144
+ 0xF0, 0x44, 0xFE, 0x91, 0x20, 0xFA, # then 145
+ 0x18, 0xEA] # jr loop
+ rom[0x150:0x150 + len(code)] = bytes(code)
+ return bytes(rom)
+
+
+def nes_rom():
+ """NROM, battery: a 16-bit count at $6000, one more each frame (each vertical blank)."""
+ prg = bytearray(0x4000)
+ code = [0x78, 0xD8, 0xA2, 0xFF, 0x9A, # sei; cld; ldx #$FF; txs
+ 0xEE, 0x00, 0x60, 0xD0, 0x03, 0xEE, 0x01, 0x60, # loop: inc $6000; bne +3; inc $6001
+ 0x2C, 0x02, 0x20, 0x10, 0xFB, # wait: bit $2002; bpl wait
+ 0x4C, 0x05, 0xC0, # jmp loop
+ 0x40] # (NMI, IRQ) rti
+ prg[:len(code)] = bytes(code)
+ struct.pack_into("<HHH", prg, 0x3FFA, 0xC015, 0xC000, 0xC015)
+ return b"NES\x1a" + bytes([1, 1, 0x02, 0]) + bytes(8) + bytes(prg) + bytes(0x2000)
+
+
+def unpack(data, size):
+ """games/retrogo/src/pack.c's format"""
+ out, i = bytearray(), 0
+ while i < len(data):
+ t = data[i]
+ i += 1
+ if t < 0x80:
+ out += data[i:i + t + 1]
+ i += t + 1
+ else:
+ n = (t & 127) + 3
+ if t & 127 == 127:
+ while True:
+ b = data[i]
+ i += 1
+ n += b
+ if b < 255:
+ break
+ d = data[i] | data[i + 1] << 8
+ i += 2
+ for _ in range(n):
+ out.append(out[-d - 1])
+ assert len(out) == size
+ return bytes(out)
+
+
+def battery(recs, name):
+ """the count in a battery save ("RGSR": header, part sizes, then the packed parts)"""
+ v = recs[name]
+ magic, version, system, parts, rom, seq, check = struct.unpack_from("<IBBHIII", v, 0)
+ assert magic == 0x52534752 and version == 1, "not a battery save"
+ raw, packed = struct.unpack_from("<II", v, 20)
+ ram = unpack(v[20 + 8 * parts:20 + 8 * parts + packed], raw)
+ return ram[0] | ram[1] << 8
+
+
+def records(buf):
+ out, p = {}, 0
+ while p + 2 <= len(buf):
+ n, = struct.unpack_from("<H", buf, p)
+ if n == 0:
+ return out
+ name = buf[p + 2:buf.index(b"\0", p + 2)].decode("latin1")
+ out[name] = bytes(buf[p + 3 + len(name):p + n])
+ p += n
+ raise ValueError("no end of the record list")
+
+
+def session(nwa, storage, keys, quit_at, quit_key, problems, tag):
+ c = emu.Calculator(nwa, storage_file=storage)
+ c.enable_checks(reads=True)
+ c.keys = emu.parse_keys(keys + f",{quit_at}-{quit_at + 400}:{quit_key}")
+ c.run(quit_at + 3000)
+ if not c.exited:
+ problems.append(f"{tag}: did not quit on {quit_key}")
+ problems += [f"{tag}: {v}" for v in sorted(set(c.violations))[:8]]
+ if not c.app_ram_clean():
+ problems.append(f"{tag}: RAM not cleared on exit")
+ if c.max_locks != 1 or c.locks != 0:
+ problems.append(f"{tag}: Home lock not held and released once")
+ if c.firmware_ram_changes():
+ problems.append(f"{tag}: the firmware's RAM changed")
+ if c.stack_used() > 30 * 1024:
+ problems.append(f"{tag}: stack use {c.stack_used()} bytes")
+ return records(open(storage, "rb").read()), c.stack_used()
+
+
+def main():
+ ap = argparse.ArgumentParser()
+ ap.add_argument("--keep")
+ a = ap.parse_args()
+ out = os.path.join(game, "output", "test")
+ os.makedirs(out, exist_ok=True)
+ roms = [os.path.join(out, "Counter.gb"), os.path.join(out, "Counter.nes")]
+ open(roms[0], "wb").write(gb_rom())
+ open(roms[1], "wb").write(nes_rom())
+ nwa = os.path.join(out, "retrogo-full.nwa")
+ if os.path.exists(os.path.join(game, "output", "retrogo-full.nwa")):
+ os.remove(os.path.join(game, "output", "retrogo-full.nwa"))
+ subprocess.run(["make", "-C", game, "output/retrogo-full.nwa", "ROMS=" + " ".join(roms),
+ "NWLINK=" + os.environ.get("NWLINK", "nwlink")], check=True, stdout=subprocess.DEVNULL)
+ os.replace(os.path.join(game, "output", "retrogo-full.nwa"), nwa)
+ problems = []
+ with tempfile.TemporaryDirectory() as d:
+ storage = os.path.join(a.keep or d, "storage.bin")
+ if os.path.exists(storage):
+ os.remove(storage)
+ stack = 0
+ for sys_tab, label in ((1, "Game Boy"), (0, "NES")): # (the tabs: NES, then Game Boy)
+ right = "300-400:right," if sys_tab else ""
+ back = "300-400:back,600-700:left," if label == "NES" else "" # (from the Game Boy list to the NES tab)
+ # a new game (the controls the first time), then Home
+ first = f"{back}{right}900-1000:ok,1500-1600:ok,2100-2200:ok" + (",2700-2800:ok" if sys_tab else "")
+ recs, s = session(nwa, storage, first, 6000, "home", problems, f"{label}, new game")
+ stack = max(stack, s)
+ srm = [n for n in recs if n.startswith("rg_") and n.endswith(".srm")]
+ st = [n for n in recs if n.startswith("rg_") and n.endswith(".st0")]
+ if len(srm) != 2 - sys_tab or len(st) != 2 - sys_tab:
+ problems.append(f"{label}: saves after Home: {sorted(recs)}")
+ continue
+ name = [n for n in srm if recs[n][5] == (1 if sys_tab else 3)][0] # (its system byte)
+ count1 = battery(recs, name)
+ # Resume (the file menu's first choice), the slot last used, then On/Off
+ recs, s = session(nwa, storage, "900-1000:ok,1500-1600:ok,2100-2200:ok", 5000, "onoff", problems,
+ f"{label}, resumed")
+ stack = max(stack, s)
+ count2 = battery(recs, name)
+ if not 30 < count1 < count2:
+ problems.append(f"{label}: the count went {count1}, then {count2}")
+ print(f"{'ok ' if not problems else 'FAIL'} {label}: counted {count1} frames, then {count2} after Resume")
+ print(f" stack {stack} bytes at most, records {sorted(recs)}")
+ for p in problems:
+ print(" ", p)
+ sys.exit(1 if problems else 0)
+
+
+if __name__ == "__main__":
+ main()
diff --git a/games/retrogo/tests/test_cores.py b/games/retrogo/tests/test_cores.py
new file mode 100644
index 00000000..1c1f033b
--- /dev/null
+++ b/games/retrogo/tests/test_cores.py
@@ -0,0 +1,137 @@
+#!/usr/bin/env python3
+"""Retro-Go's emulators on this computer (tests/host_core.c, built with the address and undefined
+behaviour sanitizers, the ROM read only like the calculator's flash):
+
+- test ROMs give the pictures they should (Blargg's cpu_instrs and instr_timing, dmg-acid2 and
+ cgb-acid2, nestest), when they are in the test ROM folder;
+- every ROM there plays a few hundred runs of random keys without a crash;
+- broken ROMs (random bytes, headers made up, files cut short) never crash either.
+
+usage: test_cores.py HOST_CORE [TEST_ROM_FOLDER]
+Only freely distributable test ROMs and homebrew go in the folder (see games/retrogo/README.md)."""
+import hashlib
+import os
+import random
+import struct
+import subprocess
+import sys
+import tempfile
+
+core = sys.argv[1]
+folder = sys.argv[2] if len(sys.argv) > 2 else ""
+tmp = tempfile.mkdtemp()
+failures = []
+
+# the pictures the test ROMs end on (checked by eye: "Passed all tests", the faces, all OK)
+EXPECTED = {
+ "blargg/cpu_instrs/cpu_instrs.gb": (3600, "", "a19050f9b9ef"),
+ "blargg/instr_timing/instr_timing.gb": (600, "", "88e27ef287f2"),
+ "dmg-acid2.gb": (120, "", "1b496ea223ab"),
+ "cgb-acid2.gbc": (120, "", "3e99d1d0cb67"),
+ "nestests/nes-test-roms-master/other/nestest.nes": (400, "30=8,35=0", "9c699fb5f8ff"),
+}
+
+
+def run(rom, frames, seed=0, script=""):
+ out = os.path.join(tmp, "f.ppm")
+ if os.path.exists(out):
+ os.remove(out)
+ r = subprocess.run([core, rom, str(frames), out, str(seed), script], capture_output=True, text=True,
+ timeout=600)
+ picture = open(out, "rb").read() if os.path.exists(out) else b""
+ return r, picture
+
+
+def check(name, r, allow_load_error=False):
+ if r.returncode == 0 or (allow_load_error and "load failed" in r.stderr):
+ return True
+ failures.append(f"{name}: exit {r.returncode}: {r.stderr.strip()[-600:]}")
+ print("FAIL", name, r.stderr.strip()[-600:])
+ return False
+
+
+# ---- the test ROMs' pictures
+roms = []
+if folder and os.path.isdir(folder):
+ for rel, (frames, script, digest) in EXPECTED.items():
+ path = os.path.join(folder, rel)
+ if not os.path.exists(path):
+ print("skip", rel)
+ continue
+ r, pic = run(path, frames, 0, script)
+ got = hashlib.sha1(pic).hexdigest()[:12]
+ if check(rel, r) and got != digest:
+ failures.append(f"{rel}: picture {got}, expected {digest}")
+ print("FAIL", rel, "picture", got)
+ else:
+ print("ok ", rel)
+ for root, _, files in os.walk(folder):
+ for f in sorted(files):
+ if f.lower().endswith((".gb", ".gbc", ".nes")):
+ roms.append(os.path.join(root, f))
+
+# ---- save states: the machine goes on the same after its state is put back, and random states
+# don't crash it
+for rel in ("libbet.gb", "ucity_compat.gbc", "cgb-acid2.gbc", "thwaite.nes", "croom.nes", "240pee.nes"):
+ path = os.path.join(folder, rel) if folder else ""
+ if not os.path.exists(path):
+ continue
+ r = subprocess.run([core, path, "300", os.path.join(tmp, "s.ppm"), "5"], capture_output=True, text=True,
+ timeout=600, env=dict(os.environ, STATE="1"))
+ if check(rel + " (states)", r) and ("state same" not in r.stdout or "no crash" not in r.stdout):
+ failures.append(f"{rel}: {r.stdout.strip()}")
+ print("FAIL", rel, r.stdout.strip())
+ elif r.returncode == 0:
+ print("ok ", rel, "states")
+
+# ---- random keys on every ROM
+runs = int(os.environ.get("FUZZ_RUNS", "300"))
+rng = random.Random(1)
+if roms:
+ for k in range(runs):
+ rom = roms[k % len(roms)]
+ r, _ = run(rom, rng.randint(30, 400), rng.randint(1, 1 << 30))
+ check(f"{os.path.relpath(rom, folder)} (random keys, run {k})", r, allow_load_error=True)
+ print(f"ok {runs} runs of random keys on {len(roms)} ROMs")
+
+# ---- broken ROMs
+def write(name, data):
+ path = os.path.join(tmp, name)
+ open(path, "wb").write(data)
+ return path
+
+
+broken = []
+for k in range(120):
+ kind = k % 6
+ if kind == 0: # random bytes, a GB header's size
+ data = bytes(rng.getrandbits(8) for _ in range(rng.choice([0x8000, 0x10000, 0x20000])))
+ broken.append(write(f"rand{k}.gb", data))
+ elif kind == 1: # a made up GB header: any cartridge type, ROM and RAM size
+ data = bytearray(rng.getrandbits(8) for _ in range(0x8000))
+ data[0x143] = rng.choice([0, 0x80, 0xC0])
+ data[0x147], data[0x148], data[0x149] = rng.getrandbits(8), rng.getrandbits(8), rng.getrandbits(8)
+ broken.append(write(f"hdr{k}.gbc", bytes(data)))
+ elif kind == 2: # a GB ROM cut short
+ broken.append(write(f"short{k}.gb", bytes(rng.getrandbits(8) for _ in range(rng.randint(0, 0x9000)))))
+ elif kind == 3: # an iNES header with any mapper and sizes, random contents
+ prg, chr_ = rng.randint(0, 8), rng.randint(0, 8)
+ head = b"NES\x1a" + bytes([prg, chr_, rng.getrandbits(8), rng.getrandbits(8)]) + bytes(8)
+ body = bytes(rng.getrandbits(8) for _ in range(prg * 0x4000 + chr_ * 0x2000 + rng.choice([0, 512])))
+ broken.append(write(f"ines{k}.nes", head + body))
+ elif kind == 4: # an iNES file cut short
+ prg, chr_ = rng.randint(1, 8), rng.randint(0, 8)
+ head = b"NES\x1a" + bytes([prg, chr_, rng.getrandbits(8) & 0xF4, 0]) + bytes(8)
+ body = bytes(rng.getrandbits(8) for _ in range(rng.randint(0, prg * 0x4000 + chr_ * 0x2000)))
+ broken.append(write(f"cut{k}.nes", head + body))
+ else: # random bytes as an NES file
+ broken.append(write(f"rand{k}.nes", bytes(rng.getrandbits(8) for _ in range(rng.randint(0, 0x30000)))))
+for path in broken:
+ r, _ = run(path, rng.randint(20, 120), rng.randint(1, 1 << 30))
+ check(os.path.basename(path), r, allow_load_error=True)
+print(f"ok {len(broken)} broken ROMs")
+
+if failures:
+ print(f"{len(failures)} failures")
+ sys.exit(1)
+print("all good")
diff --git a/games/retrogo/tests/test_romtable.py b/games/retrogo/tests/test_romtable.py
new file mode 100644
index 00000000..ba722721
--- /dev/null
+++ b/games/retrogo/tests/test_romtable.py
@@ -0,0 +1,196 @@
+#!/usr/bin/env python3
+"""Retro-Go's ROM table: tools/romtable.py's tables read back as they were written, and damaged
+tables (bad magic or version, counts too big, offsets and sizes out of range, misaligned, names
+without an end or with broken UTF-8, cut short, random bytes) never read past the table nor crash.
+
+usage: test_romtable.py HOST_ROMTABLE"""
+import os
+import random
+import struct
+import subprocess
+import sys
+import tempfile
+
+here = os.path.dirname(os.path.abspath(__file__))
+sys.path.insert(0, os.path.join(here, "..", "..", "..", "tools"))
+import romtable # noqa: E402
+
+reader = sys.argv[1]
+tmp = tempfile.mkdtemp()
+failures = []
+
+
+def read(blob):
+ path = os.path.join(tmp, "t.bin")
+ open(path, "wb").write(blob)
+ r = subprocess.run([reader, path], capture_output=True, text=True, timeout=60)
+ if r.returncode != 0:
+ failures.append(f"crash ({r.returncode}): {r.stderr[-400:]}")
+ return None
+ lines = r.stdout.splitlines()
+ return int(lines[0]), [line.split(" ", 3) for line in lines[1:]]
+
+
+def expect(what, ok):
+ print(("ok " if ok else "FAIL ") + what)
+ if not ok:
+ failures.append(what)
+
+
+def roms_file(name, data):
+ p = os.path.join(tmp, name)
+ open(p, "wb").write(data)
+ return p
+
+
+rng = random.Random(7)
+# ---- written, then read back
+empty = romtable.table([])
+expect("the empty table: 12 bytes, no game", len(empty) == 12 and read(empty) == (0, []))
+games = [roms_file("Zelda Like.gb", bytes(rng.getrandbits(8) for _ in range(0x8000))),
+ roms_file("alpha.nes", b"NES\x1a" + bytes(rng.getrandbits(8) for _ in range(0x6000 - 4 + 7))),
+ roms_file("Colour.gbc", bytes(rng.getrandbits(8) for _ in range(0x10001))),
+ roms_file("Only Color.gb", bytes(0x143) + b"\xc0" + bytes(0x8000 - 0x144)),
+ roms_file("Ünïcödé name that is far too long for forty bytes.gb", bytes(0x8000))]
+blob = romtable.table(games)
+got = read(blob)
+expect("five games read back", got is not None and got[0] == 5)
+if got:
+ systems = [g[0] for g in got[1]]
+ names = [g[3] for g in got[1]]
+ expect("sorted by system, then name", systems == ["1", "1", "1", "2", "3"] and
+ names[0] == "Only Color" and names[1] == "Zelda Like")
+ expect("names: ASCII, '?' for other letters, cut short", names[2].startswith("?n?c?d? name") and
+ len(names[2]) <= 40)
+# the layout, rebuilt here the way the website builds it: offsets, padding, names, the end
+ref = bytearray(struct.pack("<III", romtable.MAGIC, 1, len(games)) + bytes(52 * len(games)))
+for i, p in enumerate(games):
+ data = open(p, "rb").read()
+ ref += bytes(-len(ref) % 4)
+ nm = os.path.splitext(os.path.basename(p))[0].encode()
+ k = min(len(nm), 40)
+ while k < len(nm) and (nm[k] & 0xC0) == 0x80:
+ k -= 1
+ ext = os.path.splitext(p)[1].lower()
+ struct.pack_into("<IIB3x40s", ref, 12 + 52 * i, len(ref), len(data),
+ {".gb": 1, ".gbc": 2, ".nes": 3}[ext], nm[:k].ljust(40, b"\0"))
+ ref += data
+ref += bytes(-len(ref) % 4)
+expect("the same bytes as the layout's rules", bytes(ref) == blob)
+
+
+def section(obj, wanted):
+ """the bytes and flags of an ELF32 section, and the np_roms symbol's value and size"""
+ shoff, = struct.unpack_from("<I", obj, 0x20)
+ shnum, shstrndx = struct.unpack_from("<HH", obj, 0x30)
+ secs = [struct.unpack_from("<10I", obj, shoff + 40 * i) for i in range(shnum)]
+ names = secs[shstrndx]
+ sym = None
+ for s in secs:
+ if s[1] == 2: # the symbol table
+ strtab = secs[s[6]]
+ for k in range(s[5] // 16):
+ n, value, size, info, _, shndx = struct.unpack_from("<IIIBBH", obj, s[4] + 16 * k)
+ nm = obj[strtab[4] + n:obj.index(b"\0", strtab[4] + n)]
+ if nm == b"np_roms":
+ sym = (value, size, info, shndx)
+ for i, s in enumerate(secs):
+ nm = obj[names[4] + s[0]:obj.index(b"\0", names[4] + s[0])]
+ if nm == wanted:
+ return obj[s[4]:s[4] + s[5]], s[2], s[8], i, sym
+ return None
+
+
+# the object, for two ROMs, one with a long accented name: its section is the table, byte for byte
+# (to compare with the website: "alpha.nes" is NES\x1a then 0x6003 zero bytes, 24583 bytes in all;
+# the .gb is the bytes 0 to 255 over and over, 33280 bytes)
+two = [roms_file("alpha.nes", b"NES\x1a" + bytes(0x6003)),
+ roms_file("Légende de l'Été à Montréal, édition complète.gb", bytes(range(256)) * 130)]
+obj_path = os.path.join(tmp, "roms.o")
+subprocess.run([sys.executable, os.path.join(here, "..", "..", "..", "tools", "romtable.py"), "-o", obj_path] + two,
+ check=True)
+found = section(open(obj_path, "rb").read(), b".rodata.np_roms")
+ref2 = bytearray(struct.pack("<III", romtable.MAGIC, 1, 2) + bytes(104))
+for i, p in enumerate(two):
+ data = open(p, "rb").read()
+ ref2 += bytes(-len(ref2) % 4)
+ nm = os.path.splitext(os.path.basename(p))[0].encode()
+ k = min(len(nm), 40)
+ while k < len(nm) and (nm[k] & 0xC0) == 0x80:
+ k -= 1
+ struct.pack_into("<IIB3x40s", ref2, 12 + 52 * i, len(ref2), len(data), (3, 1)[i], nm[:k].ljust(40, b"\0"))
+ ref2 += data
+ref2 += bytes(-len(ref2) % 4)
+expect("the object's .rodata.np_roms is the table, byte for byte", found is not None and found[0] == bytes(ref2))
+if found:
+ data, flags, align, index, sym = found
+ expect("read-only, 4-byte aligned", flags == 2 and align == 4)
+ expect("np_roms: global, at its start, its size", sym == (0, len(ref2), 0x11, index))
+ import hashlib
+ print(" two-ROM table:", len(ref2), "bytes, sha1", hashlib.sha1(bytes(ref2)).hexdigest())
+long_name = roms_file("A" * 40 + ".nes", b"NES\x1a" + bytes(0x6000))
+got = read(romtable.table([long_name]))
+expect("a name of all 40 bytes, without an ending zero", got is not None and got[1][0][3] == "A" * 40)
+# every ROM starts 4-byte aligned, inside the table
+count = struct.unpack_from("<I", blob, 8)[0]
+for i in range(count):
+ at, size = struct.unpack_from("<II", blob, 12 + 52 * i)
+ expect(f"game {i}: aligned and inside", at % 4 == 0 and at + size <= len(blob))
+
+# ---- damaged tables
+def entry(at, size, system, name=b"x"):
+ return struct.pack("<IIB3x", at, size, system) + name.ljust(40, b"\0")[:40]
+
+
+head = lambda n, magic=romtable.MAGIC, version=1: struct.pack("<III", magic, version, n) # noqa: E731
+cases = {
+ "bad magic": head(0, 0x12345678),
+ "bad version": head(0, version=2),
+ "cut inside the header": head(1)[:7],
+ "count far too big": head(0xFFFFFFFF),
+ "count bigger than the entries": head(3) + entry(64, 4, 1),
+ "offset past the end": head(1) + entry(0x10000, 4, 1) + bytes(8),
+ "offset inside the entries": head(1) + entry(12, 8, 1) + bytes(16),
+ "offset not aligned": head(1) + entry(66, 2, 1) + bytes(8),
+ "size past the end": head(1) + entry(64, 0x7FFFFFFF, 1) + bytes(8),
+ "offset and size wrapping around": head(1) + entry(64, 0xFFFFFFF0, 1) + bytes(8),
+ "size zero": head(1) + entry(64, 0, 1) + bytes(8),
+ "system zero": head(1) + entry(64, 4, 0) + bytes(8),
+ "system unknown": head(1) + entry(64, 4, 9) + bytes(8),
+ "name with no end": head(1) + entry(64, 4, 3, b"N" * 40) + bytes(8),
+ "name of broken UTF-8": head(1) + entry(64, 4, 3, b"\xff\xfe\x80\xc3") + bytes(8),
+ "name of control letters": head(1) + entry(64, 4, 3, b"\x01\x02\x7f\t") + bytes(8),
+}
+for what, blob in cases.items():
+ got = read(blob)
+ if got is None:
+ expect(what + ": no crash", False)
+ continue
+ n, entries = got
+ ok = n <= 1 and all(int(e[1]) > 0 for e in entries)
+ if what in ("bad magic", "bad version", "cut inside the header"):
+ ok = n == -1
+ if what in ("name with no end", "name of broken UTF-8", "name of control letters"):
+ ok = n == 1 and all(32 <= ord(c) < 127 for c in entries[0][3]) and len(entries[0][3]) <= 40
+ expect(what, ok)
+# random damage to a good table, and random bytes after a good header
+good = romtable.table(games)
+for k in range(300):
+ b = bytearray(good)
+ for _ in range(rng.randint(1, 12)):
+ i = rng.randrange(0, min(len(b), 12 + 52 * 5 + 8))
+ b[i] = rng.getrandbits(8)
+ if rng.random() < 0.3:
+ b = b[:rng.randrange(0, len(b))]
+ if read(bytes(b)) is None:
+ break
+for k in range(200):
+ blob = head(rng.randint(0, 200)) + bytes(rng.getrandbits(8) for _ in range(rng.randint(0, 2000)))
+ if read(blob) is None:
+ break
+expect("500 damaged tables: no crash, nothing read past the end", not any("crash" in f for f in failures))
+
+if failures:
+ print(f"{len(failures)} failures")
+ sys.exit(1)
+print("all good")
diff --git a/games/retrogo/tools/icon.py b/games/retrogo/tools/icon.py
new file mode 100644
index 00000000..6aa397d7
--- /dev/null
+++ b/games/retrogo/tools/icon.py
@@ -0,0 +1,39 @@
+#!/usr/bin/env python3
+"""Draws Retro-Go's icon (55x56): the three systems' colours of Retro-Go's tabs (NES red, Game Boy
+orange, Game Boy Color blue) in bands, and a white handheld over them, tilted like the tabs' consoles.
+Then ../../../tools/round_icons.py gives it NumPlay's corners.
+
+usage: icon.py out.png"""
+import math
+import sys
+
+from PIL import Image, ImageDraw
+
+SS = 8
+W, H = 55, 56
+BANDS = [(0xE8, 0x4B, 0x39), (0xE8, 0x81, 0x1F), (0x31, 0x99, 0xDC)]
+
+im = Image.new("RGB", (W * SS, H * SS))
+d = ImageDraw.Draw(im)
+# diagonal bands, top left to bottom right
+for y in range(H * SS):
+ for x in range(W * SS):
+ t = (x + y) / ((W + H) * SS)
+ im.putpixel((x, y), BANDS[min(2, int(t * 3))])
+# the handheld, drawn upright then turned
+hh = Image.new("RGBA", (W * SS, H * SS), (0, 0, 0, 0))
+h = ImageDraw.Draw(hh)
+cx, cy = W * SS / 2, H * SS / 2
+bw, bh = 26 * SS, 40 * SS
+h.rounded_rectangle([cx - bw / 2, cy - bh / 2, cx + bw / 2, cy + bh / 2], radius=4 * SS, fill=(255, 255, 255, 255))
+h.rectangle([cx - bw / 2 + 4 * SS, cy - bh / 2 + 4 * SS, cx + bw / 2 - 4 * SS, cy - 2 * SS], fill=(40, 46, 70, 255))
+# d-pad and buttons
+px, py = cx - 6 * SS, cy + 8 * SS
+h.rectangle([px - 4 * SS, py - 1.2 * SS, px + 4 * SS, py + 1.2 * SS], fill=(40, 46, 70, 255))
+h.rectangle([px - 1.2 * SS, py - 4 * SS, px + 1.2 * SS, py + 4 * SS], fill=(40, 46, 70, 255))
+for bx, by in ((cx + 5 * SS, cy + 9.5 * SS), (cx + 8.5 * SS, cy + 6 * SS)):
+ h.ellipse([bx - 2 * SS, by - 2 * SS, bx + 2 * SS, by + 2 * SS], fill=(232, 75, 57, 255))
+hh = hh.rotate(-20, resample=Image.BICUBIC, center=(cx, cy))
+im.paste(hh, (0, 0), hh)
+im = im.resize((W, H), Image.LANCZOS)
+im.save(sys.argv[1])
diff --git a/games/retrogo/tools/nespal.py b/games/retrogo/tools/nespal.py
new file mode 100644
index 00000000..2b7145ca
--- /dev/null
+++ b/games/retrogo/tools/nespal.py
@@ -0,0 +1,77 @@
+#!/usr/bin/env python3
+"""The NES palettes of Retro-Go on NumPlay (src/nes/nes.c), as C tables of RGB565:
+- Nofrendo: nofrendo's own palette, from its generator (nes_pal.c: hue 334, tint 0.4);
+- NTSC: the 2C02's composite signal decoded: the luma levels of the NESdev wiki, the chroma a
+ 30-degree step for each of the 12 hues (hue 1 blue, 6 red, 10 green).
+
+usage: nespal.py [picture.png] (prints the tables; the picture shows both, 16 colours a row)"""
+import math
+import sys
+
+
+def nofrendo():
+ brightness = [[0.50, 0.75, 1.00, 1.00], [0.29, 0.45, 0.73, 0.90], [0.00, 0.24, 0.47, 0.77],
+ [0.02, 0.04, 0.05, 0.07]]
+ angles = [0, 240, 210, 180, 150, 120, 90, 60, 30, 0, 330, 300, 270, 0, 0, 0]
+ hue, tint = 334.0, 0.4
+ out = [None] * 64
+ for x in range(4):
+ for z in range(16):
+ if z == 0:
+ s, y = 0, brightness[0][x]
+ elif z == 13:
+ s, y = 0, brightness[2][x]
+ elif z in (14, 15):
+ s, y = 0, brightness[3][x]
+ else:
+ s, y = tint, brightness[1][x]
+ t = math.pi * ((angles[z] + hue) / 180.0)
+ r = int(256.0 * (y + s * math.sin(t)))
+ g = int(256.0 * (y - ((27 / 53.0) * s * math.sin(t)) + ((10 / 53.0) * s * math.cos(t))))
+ b = int(256.0 * (y - (s * math.cos(t))))
+ out[(x << 4) + z] = tuple(max(0, min(255, v)) for v in (r, g, b))
+ return out
+
+
+def ntsc():
+ lo = [0.228, 0.312, 0.552, 0.880] # each luma level's low and high voltage
+ hi = [0.616, 0.840, 1.100, 1.100]
+ black, white = lo[1], hi[3]
+ out = []
+ for c in range(64):
+ level, h = c >> 4, c & 15
+ if h >= 14:
+ out.append((0, 0, 0))
+ continue
+ # luma: the square wave's mean; chroma: its fundamental
+ if h == 0:
+ y, a = (hi[level] - black) / (white - black), 0.0
+ elif h == 13:
+ y, a = (lo[level] - black) / (white - black), 0.0
+ else:
+ y = ((hi[level] + lo[level]) / 2 - black) / (white - black)
+ a = (hi[level] - lo[level]) / (white - black) * 2 / math.pi * 0.72
+ ang = math.radians(181 - 30 * h)
+ i, q = a * math.cos(ang), a * math.sin(ang)
+ rgb = (y + 0.956 * i + 0.621 * q, y - 0.272 * i - 0.647 * q, y - 1.106 * i + 1.703 * q)
+ out.append(tuple(int(round(255 * max(0.0, min(1.0, v)))) for v in rgb))
+ return out
+
+
+def c_table(pal):
+ vals = ["0x%04X" % (((r >> 3) << 11) | ((g >> 2) << 5) | (b >> 3)) for r, g, b in pal]
+ return " {\n " + ",\n ".join(", ".join(vals[k:k + 8]) for k in range(0, 64, 8)) + "\n },"
+
+
+if __name__ == "__main__":
+ print(c_table(nofrendo()))
+ print(c_table(ntsc()))
+ if len(sys.argv) > 1:
+ from PIL import Image
+ im = Image.new("RGB", (16 * 16, 8 * 16))
+ for k, pal in enumerate((nofrendo(), ntsc())):
+ for c, rgb in enumerate(pal):
+ for yy in range(16):
+ for xx in range(16):
+ im.putpixel(((c & 15) * 16 + xx, (k * 4 + (c >> 4)) * 16 + yy), rgb)
+ im.save(sys.argv[1])
diff --git a/launcher/lang/fr.txt b/launcher/lang/fr.txt
index d8624234..45284d96 100644
--- a/launcher/lang/fr.txt
+++ b/launcher/lang/fr.txt
@@ -98,12 +98,14 @@ Clear the field, flag the mines Déblaie le terrain, pose les drapeaux
Block Breaker Casse-briques
Break every brick Casse toutes les briques
Backgrounds, clocks, timers Fonds, horloges, minuteurs
+Game Boy and NES games Jeux Game Boy et NES
# (names that stay as they are)
NumDash NumDash
NumBlocks NumBlocks
NumDrive NumDrive
2048 2048
NumVisuals NumVisuals
+Retro-Go Retro-Go
# the games' credits
Inspired by Minecraft, not affiliated with Mojang Inspiré de Minecraft, sans lien avec Mojang
By Tatone26, from All the Apps Par Tatone26, tiré d'All the Apps
@@ -111,6 +113,7 @@ Inspired by Tatone26's All the Apps Inspiré d'All the Apps de Tatone26
Based on 2048 by Gabriele Cirulli D'après 2048 de Gabriele Cirulli
Based on Block Blast! by Hungry Studio D'après Block Blast! de Hungry Studio
Based on Chrome's dinosaur game by Google D'après le jeu du dinosaure de Chrome, de Google
+Based on Retro-Go by ducalex D'après Retro-Go de ducalex
# a game the RAM of the calculator's software is too small for
Needs Il manque
KB more memory Ko de mémoire
diff --git a/launcher/lang/zh.txt b/launcher/lang/zh.txt
index b4447fa4..62479fc5 100644
--- a/launcher/lang/zh.txt
+++ b/launcher/lang/zh.txt
@@ -97,12 +97,14 @@ Clear the field, flag the mines 清理雷区,标出地雷
Block Breaker 打砖块
Break every brick 打碎每一块砖
Backgrounds, clocks, timers 背景、时钟、计时器
+Game Boy and NES games Game Boy 和 NES 游戏
# (names that stay as they are)
NumDash NumDash
NumBlocks NumBlocks
NumDrive NumDrive
2048 2048
NumVisuals NumVisuals
+Retro-Go Retro-Go
# the games' credits
Inspired by Minecraft, not affiliated with Mojang 灵感来自《我的世界》,与 Mojang 无关
By Tatone26, from All the Apps 作者 Tatone26,出自 All the Apps
@@ -110,6 +112,7 @@ Inspired by Tatone26's All the Apps 灵感来自 Tatone26 的 All the Apps
Based on 2048 by Gabriele Cirulli 改编自 Gabriele Cirulli 的 2048
Based on Block Blast! by Hungry Studio 改编自 Hungry Studio 的 Block Blast!
Based on Chrome's dinosaur game by Google 改编自 Google Chrome 的小恐龙游戏
+Based on Retro-Go by ducalex 改编自 ducalex 的 Retro-Go
# a game the RAM of the calculator's software is too small for
Needs 内存还差
KB more memory KB
diff --git a/tests/test_games.py b/tests/test_games.py
index 3a18a000..59d62fa8 100644
--- a/tests/test_games.py
+++ b/tests/test_games.py
@@ -139,6 +139,10 @@ GAMES = {
# Press OK to Play: the first scenario, its first goal closed, the city runs; then Continue
"finalearth2": ("FinalEarth2.nwa", "finalearth2.sav", presses((2000, "ok"), (3000, "ok")), 9000,
presses((2000, "ok")), 6000),
+ # no games in its table: the welcome; Backspace, Options, Scaling from Fit to Full, back; next time to 1x
+ "retrogo": ("RetroGo.nwa", "retrogo.cfg",
+ presses((1500, "backspace"), (2200, "ok"), (2900, "right"), (3500, "back")), 4500,
+ presses((1500, "backspace"), (2200, "ok"), (2900, "right"), (3500, "back")), 4500),
# a level, its message, then play; then back to the level select
"portal": ("PortalReturns.nwa", "portal.sav",
presses((1500, "ok"), (2500, "ok"), (3500, "ok")) + every(4000, 7000, 400, "right", 300), 8000,
@@ -222,6 +226,8 @@ CHECKS = {
lambda v: v[2] & 1 and struct.unpack_from("<I", v, 12)[0] >= 2),
"breakout": (lambda v: len(v) == 12 and v[:2] == b"B\2" and v[4] == 1 and struct.unpack_from("<I", v, 8)[0] >= 10,
lambda v: v[4] == 0 and struct.unpack_from("<I", v, 8)[0] >= 1), # best kept, shake off
+ # the scaling (third byte): Full, then 1x
+ "retrogo": (lambda v: len(v) == 19 and v[:2] == b"R\1" and v[2] == 2, lambda v: v[2] == 0),
}
@@ -280,7 +286,7 @@ def main():
ap.add_argument("--numplay", help="play the games inside this NumPlay.nwa instead")
a = ap.parse_args()
order = [g["id"] for g in json.load(open(os.path.join(os.path.dirname(os.path.abspath(__file__)), "..", "games",
- "games.json")))]
+ "games.json"))) if g.get("default", True)] # (in NumPlay.nwa)
os.makedirs(a.out, exist_ok=True)
failed = False
for name, (nwa, save, keys1, home1, keys2, home2) in GAMES.items():
diff --git a/tests/test_progress.py b/tests/test_progress.py
index 2e5a6eb3..b978aef7 100644
--- a/tests/test_progress.py
+++ b/tests/test_progress.py
@@ -139,7 +139,9 @@ def main():
ap.add_argument("--out", default="build/test_progress")
a = ap.parse_args()
os.makedirs(a.out, exist_ok=True)
- games = json.load(open(os.path.join(os.path.dirname(os.path.abspath(__file__)), "..", "games", "games.json")))
+ # (the games in NumPlay.nwa: not those the customizer adds, "default": false)
+ games = [g for g in json.load(open(os.path.join(os.path.dirname(os.path.abspath(__file__)), "..", "games", "games.json")))
+ if g.get("default", True)]
rnd = random.Random(7)
script = ("pi.py", b"\x01print(3.14159)\n\x00")
# a save for every file the games write (binary, zeros included), and NumPlay's settings
diff --git a/tests/test_uninstall.py b/tests/test_uninstall.py
index a2db0a05..0950daee 100644
--- a/tests/test_uninstall.py
+++ b/tests/test_uninstall.py
@@ -41,7 +41,7 @@ def main():
c = emu.Calculator(a.nwa)
manifest = os.path.join(os.path.dirname(os.path.abspath(__file__)), "..", "games", "games.json")
manifest = json.load(open(manifest))
- games = [g["id"] for g in manifest]
+ games = [g["id"] for g in manifest if g.get("default", True)] # (what NumPlay.nwa holds)
order = sorted(games, key=lambda g: c.symbols[f"np_{g}_begin"])
target = a.game
if target not in order:
diff --git a/tools/games_mk.py b/tools/games_mk.py
index 526cbbae..6dd51814 100644
--- a/tools/games_mk.py
+++ b/tools/games_mk.py
@@ -4,13 +4,18 @@
A game with an "app" entry (its release file, e.g. "Snake.nwa") is in the
standard layout of games/numvisuals: its Makefile's `build`, `module` and
`sim-module` targets make output/<id>.nwa, module.o and sim-module.o, so the
-top-level Makefile needs nothing else for it (STD_GAMES)."""
+top-level Makefile needs nothing else for it (STD_GAMES).
+
+A game with "default": false (Retro-Go) is not in the default NumPlay.nwa:
+GAMES leaves it out and OPTIONAL_GAMES lists it, for the customizer website's
+kit; it is still built on its own when it has an "app"."""
import json
import sys
games = json.load(open(sys.argv[1]))
print("# Generated by tools/games_mk.py from games/games.json")
-print("GAMES := " + " ".join(g["id"] for g in games))
+print("GAMES := " + " ".join(g["id"] for g in games if g.get("default", True)))
+print("OPTIONAL_GAMES := " + " ".join(g["id"] for g in games if not g.get("default", True)))
for n, g in enumerate(games, 1):
i = g["id"]
print(f"INDEX_{i} := {n}")
diff --git a/tools/release.py b/tools/release.py
index 07a8754a..2e0c2cda 100644
--- a/tools/release.py
+++ b/tools/release.py
@@ -66,7 +66,8 @@ def main():
ap.add_argument("--notes", required=True)
ap.add_argument("--build", default="build")
a = ap.parse_args()
- games = json.load(open(os.path.join(ROOT, "games", "games.json")))
+ # (a game the default NumPlay.nwa leaves out, "default": false, comes from the customizer website)
+ games = [g for g in json.load(open(os.path.join(ROOT, "games", "games.json"))) if g.get("default", True)]
apps = standalone_names()
count = sum(1 for g in games if g["id"] not in EXTRAS)
extras = " and ".join(g["title"] for g in games if g["id"] in EXTRAS)
diff --git a/tools/romtable.py b/tools/romtable.py
new file mode 100644
index 00000000..cd05f6e5
--- /dev/null
+++ b/tools/romtable.py
@@ -0,0 +1,122 @@
+#!/usr/bin/env python3
+"""Makes Retro-Go's table of games, np_roms, as an object file to link into RetroGo.nwa or NumPlay.
+
+The table (the customizer website makes the same one; games/retrogo reads it in place, in flash)
+is one read-only section, .rodata.np_roms, 4-byte aligned, global symbol np_roms:
+ u32 magic 0x4D52504E ("NPRM"), u32 version 1, u32 count;
+ count entries of 52 bytes: u32 offset (from the start of np_roms to the ROM's bytes), u32 size,
+ u8 system (1 Game Boy, 2 Game Boy Color, 3 NES, 4 Master System, 5 Game Gear), u8 reserved[3]
+ (zero), char name[40] (UTF-8, zero-padded);
+ then the ROMs' bytes, each starting 4-byte aligned.
+All numbers are little-endian. To be the same byte for byte as the website's for the same files:
+- the ROMs come in the order given, the first at 12 + 52 * count rounded up to a multiple of 4,
+ each next one at the end of the one before rounded up to a multiple of 4, zeros in between;
+- the table ends with the last ROM's bytes, then zeros up to a multiple of 4 (no ROMs: the 12-byte
+ header with count 0);
+- the system comes from the file's extension, in any case: .gb 1, .gbc 2, .nes 3, .sms 4, .gg 5;
+- the name is the file's name without its last extension, its UTF-8 bytes cut to the longest
+ start of at most 40 bytes that ends on a whole letter, zero-padded to 40 (no ending zero when it
+ takes all 40).
+
+usage:
+ romtable.py -o roms.o [ROM...] an ARM object for the calculator (the default)
+ romtable.py --c roms.c [ROM...] the same table as C, for the simulator and tests
+ romtable.py --bin roms.bin [ROM...] just the table's bytes"""
+import argparse
+import os
+import struct
+import sys
+
+MAGIC, VERSION, ENTRY, NAME = 0x4D52504E, 1, 52, 40
+SYSTEMS = {".gb": 1, ".gbc": 2, ".nes": 3, ".sms": 4, ".gg": 5}
+
+
+def entry_name(path):
+ name = os.path.splitext(os.path.basename(path))[0].encode("utf-8")
+ k = min(len(name), NAME)
+ while k < len(name) and k > 0 and (name[k] & 0xC0) == 0x80: # not inside a letter
+ k -= 1
+ return name[:k]
+
+
+def table(paths):
+ roms = []
+ for p in paths:
+ ext = os.path.splitext(p)[1].lower()
+ if ext not in SYSTEMS:
+ sys.exit(f"romtable: {p}: not a .gb, .gbc, .nes, .sms or .gg file")
+ roms.append((open(p, "rb").read(), SYSTEMS[ext], entry_name(p)))
+ out = bytearray(struct.pack("<III", MAGIC, VERSION, len(roms)))
+ out += bytes(ENTRY * len(roms))
+ for i, (data, system, name) in enumerate(roms):
+ out += bytes(-len(out) % 4)
+ struct.pack_into("<IIB3x40s", out, 12 + ENTRY * i, len(out), len(data), system, name.ljust(NAME, b"\0"))
+ out += data
+ out += bytes(-len(out) % 4)
+ return bytes(out)
+
+
+def elf_object(blob):
+ """A 32-bit ARM relocatable object: .rodata.np_roms, and np_roms in its symbol table."""
+ shstr = b"\0.rodata.np_roms\0.symtab\0.strtab\0.shstrtab\0"
+ strtab = b"\0np_roms\0"
+ STB_GLOBAL, STT_OBJECT, STT_SECTION = 1, 1, 3
+ symtab = struct.pack("<IIIBBH", 0, 0, 0, 0, 0, 0)
+ symtab += struct.pack("<IIIBBH", 0, 0, 0, STT_SECTION, 0, 1)
+ symtab += struct.pack("<IIIBBH", 1, 0, len(blob), STB_GLOBAL << 4 | STT_OBJECT, 0, 1)
+ out = bytearray(52)
+ offs = []
+ for part in (blob, symtab, strtab, shstr):
+ out += bytes(-len(out) % 4)
+ offs.append(len(out))
+ out += part
+ out += bytes(-len(out) % 4)
+ shoff = len(out)
+ SHT_PROGBITS, SHT_SYMTAB, SHT_STRTAB, SHF_ALLOC = 1, 2, 3, 2
+ sections = [
+ (0, 0, 0, 0, 0, 0, 0, 0, 0, 0),
+ (shstr.index(b".rodata.np_roms"), SHT_PROGBITS, SHF_ALLOC, 0, offs[0], len(blob), 0, 0, 4, 0),
+ (shstr.index(b".symtab"), SHT_SYMTAB, 0, 0, offs[1], len(symtab), 3, 2, 4, 16),
+ (shstr.index(b".strtab"), SHT_STRTAB, 0, 0, offs[2], len(strtab), 0, 0, 1, 0),
+ (shstr.index(b".shstrtab"), SHT_STRTAB, 0, 0, offs[3], len(shstr), 0, 0, 1, 0),
+ ]
+ for s in sections:
+ out += struct.pack("<10I", *s)
+ ident = b"\x7fELF\x01\x01\x01" + bytes(9)
+ struct.pack_into("<16sHHIIIIIHHHHHH", out, 0, ident, 1, 40, 1, 0, 0, shoff, 0, 52, 0, 0, 40,
+ len(sections), 4)
+ return bytes(out)
+
+
+def c_source(blob):
+ lines = [",".join(str(b) for b in blob[k:k + 32]) for k in range(0, len(blob), 32)]
+ return ("/* Made by tools/romtable.py: Retro-Go's table of games (see that file). */\n"
+ "#include <stdint.h>\n"
+ f"const uint8_t np_roms[{len(blob)}] __attribute__((aligned(4))) = {{\n" +
+ ",\n".join(lines) + "\n};\n"
+ f"const uint32_t np_roms_size = {len(blob)};\n")
+
+
+def main():
+ ap = argparse.ArgumentParser(description="Retro-Go's table of games (np_roms)")
+ ap.add_argument("-o", dest="obj", help="ARM object to write")
+ ap.add_argument("--c", dest="csrc", help="C source to write")
+ ap.add_argument("--bin", dest="bin", help="raw table to write")
+ ap.add_argument("roms", nargs="*")
+ a = ap.parse_args()
+ if not (a.obj or a.csrc or a.bin):
+ ap.error("say where: -o, --c or --bin")
+ blob = table(a.roms)
+ for path, data in ((a.obj, lambda: elf_object(blob)), (a.csrc, lambda: c_source(blob).encode()),
+ (a.bin, lambda: blob)):
+ if not path:
+ continue
+ data = data()
+ # (a file that would stay the same is left alone: make links nothing again)
+ if not os.path.exists(path) or open(path, "rb").read() != data:
+ open(path, "wb").write(data)
+ print(f"ROMS {path}: {len(a.roms)} games, {len(blob)} bytes")
+
+
+if __name__ == "__main__":
+ main()