view clojure/com/aurellem/gb_driver.clj @ 73:8a895ed4c0f9

added history facilities
author Robert McIntyre <rlm@mit.edu>
date Thu, 08 Mar 2012 04:37:10 -0600
parents 39928bf4622d
children aaddd7b72a0e
line wrap: on
line source
1 (ns com.aurellem.gb-driver
2 (:import com.aurellem.gb.Gb)
3 (:import java.io.File)
4 (:import (java.nio IntBuffer ByteOrder)))
6 (Gb/loadVBA)
8 (def yellow-rom-image
9 (File. "/home/r/proj/pokemon-escape/roms/yellow.gbc"))
11 (def yellow-save-file
12 (File. "/home/r/proj/pokemon-escape/roms/yellow.sav"))
14 (def current-frame (atom 0))
16 (defn vba-init []
17 (reset! current-frame 0)
18 (.delete yellow-save-file)
19 (Gb/startEmulator (.getCanonicalPath yellow-rom-image)))
21 (defn shutdown [] (Gb/shutdown))
23 (defn reset [] (shutdown) (vba-init))
25 (defn cpu-data [size arr-fn]
26 (let [store (int-array size)]
27 (fn []
28 (arr-fn store)
29 store)))
31 (def ram
32 (cpu-data (Gb/getRAMSize) #(Gb/getRAM %)))
34 (def rom
35 (cpu-data (Gb/getROMSize) #(Gb/getROM %)))
37 (def working-ram
38 (cpu-data Gb/WRAM_SIZE #(Gb/getWRAM %)))
40 (def video-ram
41 (cpu-data Gb/VRAM_SIZE #(Gb/getVRAM %)))
43 (def registers
44 (cpu-data Gb/NUM_REGISTERS #(Gb/getRegisters %)))
46 (def button-code
47 {;; main buttons
48 :a 0x0001
49 :b 0x0002
51 ;; directional pad
52 :r 0x0010
53 :l 0x0020
54 :u 0x0040
55 :d 0x0080
57 ;; meta buttons
58 :select 0x0004
59 :start 0x0008
61 ;; hard reset -- not really a button
62 :reset 0x0800})
64 (defn button-mask [buttons]
65 (reduce bit-or 0x0000 (map button-code buttons)))
67 (defn buttons [mask]
68 (loop [buttons []
69 masks (seq button-code)]
70 (if (empty? masks) buttons
71 (let [[button value] (first masks)]
72 (if (not= 0x0000 (bit-and value mask))
73 (recur (conj buttons button) (rest masks))
74 (recur buttons (rest masks)))))))
77 (defn save-state [] (Gb/saveState))
79 (def history (atom {}))
81 (defn goto [frame]
82 (let [save (@history frame)]
83 (if (not (nil? save))
84 (do
85 (reset! current-frame frame)
86 (Gb/loadState save))
87 (println "no backup state"))))
89 (defn clear-history [] (reset! history {}))
91 (defn rewind [] (goto (dec @current-frame)))
93 (defn backup-state [frame]
94 (swap! history #(assoc % frame (save-state))))
96 (def ^:dynamic *save-history* true)
98 (defn advance []
99 (let [save (save-state)]
100 (backup-state @current-frame)
101 (swap! current-frame inc)))
103 (defn step
104 ([] (advance) (Gb/step))
105 ([mask-or-buttons]
106 (advance)
107 (if (number? mask-or-buttons)
108 (Gb/step mask-or-buttons)
109 (Gb/step (button-mask mask-or-buttons)))))
111 (defn frame [] @current-frame)