1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
|
use std::time::SystemTime;
use std::{thread, time};
use crate::consts;
use crate::state::GBState;
pub trait Input {
fn update_events(&mut self, cycles: u128) -> Option<u128>;
fn get_action_gamepad_reg(&self) -> u8;
fn get_direction_gamepad_reg(&self) -> u8;
fn save_state(&mut self) -> bool;
}
impl<T: Input + ?Sized> Input for Box<T> {
fn update_events(&mut self, cycles: u128) -> Option<u128> {
(**self).update_events(cycles)
}
fn get_action_gamepad_reg(&self) -> u8 {
(**self).get_action_gamepad_reg()
}
fn get_direction_gamepad_reg(&self) -> u8 {
(**self).get_direction_gamepad_reg()
}
fn save_state(&mut self) -> bool {
(**self).save_state()
}
}
pub enum WindowSignal {
Exit,
}
pub trait Window {
fn update(&mut self, fb: &[u32; 160 * 144]) -> Option<WindowSignal>;
}
pub trait Serial {
// Should not be blocking
fn write(&mut self, byte: u8);
fn read(&mut self) -> u8;
fn new_transfer(&mut self) -> bool; // since last read
fn clock_master(&mut self) -> bool;
fn set_clock_master(&mut self, clock_master: bool);
}
pub trait Audio {
fn new<S: Iterator<Item = f32> + Send + 'static>(wave: S) -> Self;
}
pub trait LoadSave
where
Self::Error: std::fmt::Display,
Self::Error: std::fmt::Debug,
{
type Error;
fn load_bootrom(&self, boot_rom: &mut [u8]) -> Result<(), Self::Error>;
fn load_rom(&self, rom: &mut [u8]) -> Result<(), Self::Error>;
fn load_external_ram(&self, external_ram: &mut [u8]) -> Result<(), Self::Error>;
fn save_external_ram(&self, external_ram: &[u8]) -> Result<(), Self::Error>;
fn dump_state<S: Serial, A: Audio>(&self, state: &GBState<S, A>) -> Result<(), Self::Error>;
fn save_state<S: Serial, A: Audio>(&self, state: &GBState<S, A>) -> Result<(), Self::Error>;
fn load_state<S: Serial, A: Audio>(&self, state: &mut GBState<S, A>)
-> Result<(), Self::Error>;
}
pub struct Gameboy<I: Input, W: Window, S: Serial, A: Audio, LS: LoadSave> {
input: I,
window: W,
speed: f64,
state: GBState<S, A>,
load_save: LS,
}
impl<I: Input, W: Window, S: Serial, A: Audio, LS: LoadSave> Gameboy<I, W, S, A, LS> {
pub fn new(input: I, window: W, serial: S, load_save: LS, speed: f64) -> Self {
Self {
input,
window,
speed,
state: GBState::<S, A>::new(serial),
load_save,
}
}
pub fn load_state(&mut self) -> Result<(), LS::Error> {
self.load_save.load_state(&mut self.state)?;
Ok(())
}
pub fn debug(&mut self) {
self.state.is_debug = true;
}
pub fn start(self) {
let Self {
mut window,
mut input,
speed,
mut state,
load_save,
} = self;
load_save.load_bootrom(state.mem.boot_rom.as_mut()).unwrap();
load_save.load_rom(state.mem.rom.as_mut()).unwrap();
if let Err(err) = load_save.load_external_ram(state.mem.external_ram.as_mut()) {
println!(
"Loading save failed ({}). Initializing new external ram.",
err
);
}
let mut total_cycle_counter: u128 = 0;
let mut nanos_sleep: f64 = 0.0;
let mut halt_time = 0;
let mut was_previously_halted = false;
let mut last_ram_bank_enabled = false;
let mut now = SystemTime::now();
let mut next_precise_gamepad_update: Option<u128> = None;
loop {
if was_previously_halted && !state.mem.halt {
println!("Halt cycles {}", halt_time);
halt_time = 0;
}
was_previously_halted = state.mem.halt;
let c = if !state.mem.halt {
state.exec_opcode()
} else {
halt_time += 4;
4
};
state.cpu.dbg_cycle_counter += c;
total_cycle_counter += c as u128;
state.div_timer(c);
state.tima_timer(c);
state.update_display_interrupts(c);
state.check_interrupts();
state.mem.update_serial();
nanos_sleep += c as f64 * (consts::CPU_CYCLE_LENGTH_NANOS as f64 / speed) as f64;
if nanos_sleep >= 0.0
|| next_precise_gamepad_update.map_or(false, |c| (c >= total_cycle_counter))
{
next_precise_gamepad_update = input.update_events(total_cycle_counter);
let (action_button_reg, direction_button_reg, save_state) = (
input.get_action_gamepad_reg(),
input.get_direction_gamepad_reg(),
input.save_state(),
);
if save_state {
if let Err(err) = load_save.save_state(&state) {
eprintln!("FAILED SAVE STATE: {:?}", err);
}
}
if state.mem.joypad_is_action
&& (action_button_reg & (state.mem.joypad_reg >> 4))
!= (state.mem.joypad_reg >> 4)
|| (!state.mem.joypad_is_action
&& (direction_button_reg & state.mem.joypad_reg & 0b1111)
!= (state.mem.joypad_reg & 0b1111))
{
state.mem.io[0x0f] |= 0b10000;
}
state.mem.joypad_reg = direction_button_reg | (action_button_reg << 4);
}
if nanos_sleep > 0.0 {
if let Some(fb) = state.mem.display.redraw_request {
if let Some(WindowSignal::Exit) = window.update(&fb) {
break;
}
}
thread::sleep(time::Duration::from_nanos(nanos_sleep as u64 / 10));
nanos_sleep =
nanos_sleep - SystemTime::now().duration_since(now).unwrap().as_nanos() as f64;
now = SystemTime::now();
if last_ram_bank_enabled && !state.mem.ram_bank_enabled {
if let Err(err) = load_save.save_external_ram(state.mem.external_ram.as_ref()) {
println!("Failed to save external RAM ({})", err);
}
}
last_ram_bank_enabled = state.mem.ram_bank_enabled;
}
}
}
}
|