Skip to main content

gte_core/
emulator.rs

1use alloc::boxed::Box;
2use alloc::vec;
3use alloc::vec::Vec;
4use gte_w65c02s::{System, W65C02S};
5use log::{debug, error, info, warn};
6use gte_w65c02s::State::AwaitingInterrupt;
7use core::fmt::{Debug, Formatter};
8use bytemuck::bytes_of;
9use heapless::{FnvIndexMap};
10use rtrb::PushError;
11use gte_acp::audio_output::GameTankAudio;
12use crate::blitter::Blitter;
13use crate::cartridges::CartridgeType;
14use crate::emulator::PlayState::{Paused, Playing, WasmInit};
15use crate::gametank_bus::{CpuBus};
16use gte_acp::AcpBus;
17use crate::inputs::{ControllerButton, InputCommand, KeyState};
18use crate::inputs::ControllerButton::{Down, Left, Right, Start, Up, A, B, C};
19use crate::inputs::InputCommand::{Controller1, Controller2, HardReset, PlayPause, SoftReset};
20use crate::inputs::KeyState::JustReleased;
21
22pub const WIDTH: u32 = 128;
23pub const HEIGHT: u32 = 128;
24
25#[derive(Copy, Clone, Debug, PartialEq)]
26pub enum PlayState {
27    WasmInit,
28    Paused,
29    Playing,
30}
31
32pub trait TimeDaemon {
33    fn get_now_ms(&self) -> f64;
34}
35
36/// Snapshot measuring the last 1 second-ish of ACP load
37#[derive(Copy, Clone, Debug, Default)]
38pub struct AcpLoadStats {
39    /// Worst-case ACP cycles the audio ISR took to run in the last window.
40    pub worst_case_cycles: i32,
41    /// ACP cycle budget available per sample at the current sample rate.
42    pub budget_cycles: i32,
43    /// Percentage (0-100) of samples in the last window where the ISR was
44    /// still running when the next sample's IRQ came due (i.e. dropped).
45    pub overrun_percent: u32,
46    /// The ACP's current sample rate in Hz, derived from the rate register.
47    pub sample_rate_hz: u32,
48    /// Number of sample periods the last window covers (for context).
49    pub periods_measured: u32,
50}
51
52/// Tracks whether the ACP firmware is keeping up with its sample deadline.
53#[derive(Default, Debug)]
54struct AcpStats {
55    periods: u32,
56    overruns: u32,
57    worst_compute: i32,
58
59    cycles_awake: i32,
60    asleep: bool,
61
62    last_worst_compute: i32,
63    last_budget: i32,
64    last_overrun_percent: u32,
65    last_sample_rate: u32,
66    last_periods: u32,
67}
68
69impl AcpStats {
70    fn tick(&mut self, cycles: i32, waiting: bool) {
71        if self.asleep {
72            return;
73        }
74        self.cycles_awake += cycles;
75        if waiting {
76            self.worst_compute = self.worst_compute.max(self.cycles_awake);
77            self.asleep = true;
78        }
79    }
80
81    fn record(&mut self) {
82        self.periods += 1;
83        if self.asleep {
84            // woken by this IRQ; start timing the next sample
85            self.asleep = false;
86            self.cycles_awake = 0;
87        } else {
88            // still computing when the next sample came due
89            self.overruns += 1;
90        }
91    }
92
93    fn report(&mut self, interval: u32, budget: i32, reg: u8) {
94        if self.periods < interval {
95            return;
96        }
97        if self.overruns > 0 {
98            warn!(
99            "ACP: {}cy/sample, ${:02X} budgets {}cy - {}% of samples duplicated",
100            self.worst_compute,
101            reg,
102            budget,
103            self.overruns * 100 / self.periods,
104        );
105        }
106        self.last_worst_compute = self.worst_compute;
107        self.last_budget = budget;
108        self.last_overrun_percent = self.overruns * 100 / self.periods.max(1);
109        self.last_sample_rate = interval;
110        self.last_periods = self.periods;
111        self.periods = 0;
112        self.overruns = 0;
113        self.worst_compute = 0;
114    }
115}
116
117pub struct Emulator<Clock: TimeDaemon> {
118    pub cpu_bus: CpuBus,
119    pub acp_bus: AcpBus,
120    pub cpu: W65C02S,
121    pub acp: W65C02S,
122    pub blitter: Blitter,
123    pub clock_cycles_to_vblank: i32,
124    pub last_emu_tick: f64,
125    pub cpu_ns_per_cycle: f64,
126    pub cpu_frequency_hz: f64,
127    pub last_render_time: f64,
128    pub audio_out: Option<GameTankAudio>,
129    pub target_sample_rate: f64,
130    pub play_state: PlayState,
131    pub wait_counter: u64,
132    pub input_state: FnvIndexMap<InputCommand, KeyState, 32>, // capacity of 32 entries
133    pub clock: Clock,
134    pub mouse_paddle_enabled: bool,
135
136    acp_stats: AcpStats,
137}
138
139impl <Clock: TimeDaemon> Emulator<Clock> {
140    pub fn load_rom(&mut self, bytes: &[u8]) {
141        warn!("loading new rom from memory, size: {}", bytes.len());
142        self.cpu_bus.cartridge = CartridgeType::from_slice(bytes);
143        warn!(" - cartridge loaded from memory");
144        self.cpu.reset();
145        warn!(" - cpu reset");
146        self.acp.reset();
147        warn!(" - acp reset");
148        self.blitter.clear_irq_trigger();
149        warn!(" - blitter irq cleared");
150    }
151}
152
153impl <Clock: TimeDaemon> Debug for Emulator<Clock> {
154    fn fmt(&self, f: &mut Formatter) -> core::fmt::Result {
155        f.debug_struct("Emulator")
156            .field("cpu_bus", &self.cpu_bus)
157            .field("acp_bus", &self.acp_bus)
158            .field("cpu", &self.cpu)
159            .field("acp", &self.acp)
160            .field("blitter", &self.blitter)
161            .field("clock_cycles_to_vblank", &self.clock_cycles_to_vblank)
162            .field("last_emu_tick", &self.last_emu_tick)
163            .finish()
164    }
165}
166
167impl <Clock: TimeDaemon> Emulator<Clock> {
168    pub fn wasm_init(&mut self) {
169        if self.play_state == WasmInit {
170            self.play_state = Playing;
171            self.last_emu_tick = self.clock.get_now_ms();
172            self.last_render_time = self.clock.get_now_ms();
173        }
174    }
175
176    pub fn init(clock: Clock, target_sample_rate: f64) -> Self {
177        let play_state = WasmInit;
178
179        let mut bus = CpuBus::default();
180        let mut cpu = W65C02S::new();
181        cpu.step(&mut bus); // take one initial step, to get through the reset vector
182
183        let acp = W65C02S::new();
184        let blitter = Blitter::default();
185
186        let last_cpu_tick_ms = clock.get_now_ms();
187        let cpu_frequency_hz = 3_579_545.0; // Precise frequency
188        let cpu_ns_per_cycle = 1_000_000_000.0 / cpu_frequency_hz; // Nanoseconds per cycle
189        let last_render_time = last_cpu_tick_ms;
190
191        Emulator {
192            play_state,
193            cpu_bus: bus,
194            acp_bus: AcpBus::default(),
195            cpu,
196            acp,
197            blitter,
198            clock_cycles_to_vblank: 59659,
199            last_emu_tick: last_cpu_tick_ms,
200            cpu_frequency_hz,
201            cpu_ns_per_cycle,
202            last_render_time,
203            audio_out: None,
204            target_sample_rate,
205            wait_counter: 0,
206            input_state: Default::default(),
207            clock,
208            acp_stats: AcpStats::default(),
209            mouse_paddle_enabled: false
210        }
211    }
212
213    pub fn process_cycles(&mut self, is_web: bool) {
214        self.process_inputs();
215
216        if self.play_state != Playing {
217            return
218        }
219
220        let now_ms = self.clock.get_now_ms();
221        let mut elapsed_ms = now_ms - self.last_emu_tick;
222
223        if elapsed_ms > 33.0 {
224            warn!("emulator took more than 33ms to process cycles");
225            elapsed_ms = 16.667;
226        }
227
228        let elapsed_ns = elapsed_ms * 1000000.0;
229        let mut remaining_cycles: i32 = (elapsed_ns / self.cpu_ns_per_cycle) as i32;
230        let mut acp_cycle_accumulator = 0;
231
232        while remaining_cycles > 0 {
233            if self.cpu.get_state() == AwaitingInterrupt {
234                self.wait_counter += 1;
235                // get cpu's current asm code
236            } else if self.wait_counter > 0 {
237                debug!("waited {} cycles", self.wait_counter);
238                self.wait_counter = 0;
239            }
240
241            let cpu_cycles = self.cpu.step(&mut self.cpu_bus);
242            remaining_cycles -= cpu_cycles;
243            acp_cycle_accumulator += cpu_cycles * 4;
244
245            // pass aram to acp
246            if self.cpu_bus.system_control.acp_enabled() {
247                self.run_acp(&mut acp_cycle_accumulator);
248            }
249
250            // blit
251            for _ in 0..cpu_cycles {
252                self.blitter.cycle(&mut self.cpu_bus);
253            }
254
255            // TODO: instant blit option
256            let blit_irq = self.blitter.irq_trigger;
257            if blit_irq {
258                debug!("blit irq");
259            }
260            self.cpu.set_irq(blit_irq);
261
262            self.clock_cycles_to_vblank -= cpu_cycles;
263            if self.clock_cycles_to_vblank <= 0 {
264                self.vblank();
265            }
266        }
267
268        self.last_emu_tick = now_ms;
269
270        if !is_web && (now_ms - self.last_render_time) >= 16.67 {
271            debug!("time since last render: {}", now_ms - self.last_render_time);
272            self.last_render_time = now_ms;
273        }
274    }
275
276    fn run_acp(&mut self, acp_cycle_accumulator: &mut i32) {
277        if self.cpu_bus.system_control.clear_acp_reset() {
278            self.acp.reset();
279        }
280
281        if self.cpu_bus.system_control.clear_acp_nmi() {
282            self.acp.set_nmi(true);
283        }
284
285        while *acp_cycle_accumulator > 0 {
286            let acp_cycles = self.acp.step(&mut self.acp_bus);
287            *acp_cycle_accumulator -= acp_cycles;
288            self.acp_bus.irq_counter -= acp_cycles;
289            self.acp_bus.cycles_since_write += acp_cycles;
290            self.acp_stats.tick(acp_cycles, self.acp.get_state() == AwaitingInterrupt);
291
292            // clear stuff ig
293            self.acp.set_irq(false);
294            self.acp.set_nmi(false);
295
296            if self.acp_bus.irq_counter <= 0 {
297                let divisor = self.cpu_bus.system_control.sample_divisor() as i32;
298                let budget = divisor * 4;
299
300                self.acp_bus.irq_counter = budget;
301                self.acp.set_irq(true);
302
303                self.acp_stats.record();
304                self.acp_stats.report(
305                    (self.cpu_frequency_hz / divisor as f64) as u32,
306                    budget,
307                    self.cpu_bus.system_control.audio_enable_sample_rate,
308                );
309
310                self.emit_sample(divisor);
311            }
312        }
313    }
314
315    /// Push the latched DAC value into the audio pipeline, recreating the
316    /// output stream if the program changed the sample rate.
317    fn emit_sample(&mut self, divisor: i32) {
318        let sample_rate = self.cpu_frequency_hz / divisor as f64;
319
320        if self.audio_out.as_ref().is_none_or(|gta| gta.sample_rate != sample_rate) {
321            warn!(
322                "recreated audio stream with new sample rate: {:.3}Hz (${:02X})",
323                sample_rate, self.cpu_bus.system_control.audio_enable_sample_rate
324            );
325            self.audio_out = Some(GameTankAudio::new(sample_rate, self.target_sample_rate));
326        }
327
328        if let Some(audio) = &mut self.audio_out {
329            if let Err(e) = audio.producer.push(self.acp_bus.sample) {
330                error!("not enough slots in audio producer: {e}");
331            }
332            audio.convert_to_output_buffers();
333        }
334    }
335
336    fn vblank(&mut self) {
337        self.clock_cycles_to_vblank += 59659;
338
339        if self.cpu_bus.vblank_nmi_enabled() {
340            self.cpu.set_nmi(true);
341            debug!("vblanked");
342        }
343    }
344
345    pub fn set_input_state(&mut self, input_command: InputCommand, state: KeyState) {
346        self.input_state.insert(input_command, state).expect("shit's full dog ://");
347    }
348
349    pub fn opcode_cycle_profile(&self) -> gte_w65c02s::OpcodeCycleProfile {
350        self.cpu.get_cycle_profile()
351    }
352
353    pub fn set_opcode_cycle_profile(&mut self, profile: gte_w65c02s::OpcodeCycleProfile) {
354        self.cpu.set_cycle_profile(profile);
355        self.acp.set_cycle_profile(profile);
356    }
357
358    pub fn acp_load_stats(&self) -> AcpLoadStats {
359        AcpLoadStats {
360            worst_case_cycles: self.acp_stats.last_worst_compute,
361            budget_cycles: self.acp_stats.last_budget,
362            overrun_percent: self.acp_stats.last_overrun_percent,
363            sample_rate_hz: self.acp_stats.last_sample_rate,
364            periods_measured: self.acp_stats.last_periods,
365        }
366    }
367
368    fn process_inputs(&mut self) {
369        let keys: Vec<_> = self.input_state.keys().cloned().collect();  // Clone keys to avoid borrowing conflicts
370
371        if keys.len() > 0 && self.play_state == WasmInit {
372            self.play_state = Playing;
373        }
374
375        for key in &keys {
376            match key {
377                Controller1(button) => { self.set_gamepad_input(0, &key, &button); }
378                Controller2(button) => { self.set_gamepad_input(1, &key, &button); }
379                PlayPause => {
380                    if self.input_state[key] == JustReleased {
381                        match self.play_state {
382                            Paused => { self.play_state = Playing; }
383                            Playing => { self.play_state = Paused; }
384                            WasmInit => { self.play_state = Playing; }
385                        }
386                    }
387                }
388                SoftReset => {
389                    self.cpu.reset();
390                }
391                HardReset => {
392                    // hard reset reinitializes memory/cpus
393                    let cart = self.cpu_bus.cartridge.clone();
394                    self.cpu_bus = CpuBus::default();
395                    self.cpu_bus.cartridge = cart;
396                    self.cpu = W65C02S::new();
397                    self.cpu.step(&mut self.cpu_bus); // take one initial step, to get through the reset vector
398                    self.acp = W65C02S::new();
399                    self.blitter = Blitter::default();
400                }
401            }
402
403            self.input_state.insert(*key, self.input_state[key].update()).expect("shit's full dog ://");
404        }
405    }
406
407    pub fn apply_paddle_delta(&mut self, delta: i8) {
408        self.cpu_bus.system_control.apply_paddle_delta(delta);
409    }
410    
411    pub fn set_mouse_paddle_enabled(&mut self, enabled: bool) {
412        self.mouse_paddle_enabled = enabled;
413    }
414
415    fn set_gamepad_input(&mut self, gamepad: usize, key: &InputCommand, button: &ControllerButton) {
416        let gamepad = &mut self.cpu_bus.system_control.gamepads[gamepad];
417        match button {
418            Up =>     { gamepad.up    = self.input_state[&key].is_pressed(); }
419            Down =>   { gamepad.down  = self.input_state[&key].is_pressed(); }
420            Left =>   { gamepad.left  = self.input_state[&key].is_pressed(); }
421            Right =>  { gamepad.right = self.input_state[&key].is_pressed(); }
422            B =>      { gamepad.b     = self.input_state[&key].is_pressed(); }
423            A =>      { gamepad.a     = self.input_state[&key].is_pressed(); }
424            Start =>  { gamepad.start = self.input_state[&key].is_pressed(); }
425            C =>      { gamepad.c     = self.input_state[&key].is_pressed(); }
426        }
427    }
428}