1use std::any::Any;
21
22use huc6280::{Bus, Pins};
23use serde::{Deserialize, Serialize};
24
25use crate::board::Board;
26use crate::cards::RomCard;
27use crate::machine::{py_floordiv, HARDWARE_FIRST_PAGE, MASTER_HZ};
28use crate::sockets::{
29 AudioSource, BoardPins, Card, ControllerPort, DeviceState, PageHandler, PixelPath, PortDevice,
30 ResetKind, VideoTiming,
31};
32
33pub struct FakeCard {
37 ranges: Vec<(usize, usize)>,
38 pub fill: u8,
39 pub grounds_cd: bool,
40 pub reads: Vec<(u32, i64)>,
41 pub writes: Vec<(u32, u8, i64)>,
42 pub resets: Vec<ResetKind>,
43}
44
45impl FakeCard {
46 pub fn new(ranges: Vec<(usize, usize)>) -> FakeCard {
47 FakeCard {
48 ranges,
49 fill: 0xAA,
50 grounds_cd: true,
51 reads: Vec::new(),
52 writes: Vec::new(),
53 resets: Vec::new(),
54 }
55 }
56}
57
58impl DeviceState for FakeCard {}
59
60impl PageHandler for FakeCard {
61 fn read(&mut self, address: u32, mclk: i64, _pins: &mut BoardPins) -> u8 {
62 self.reads.push((address, mclk));
63 self.fill
64 }
65
66 fn write(&mut self, address: u32, value: u8, mclk: i64, _pins: &mut BoardPins) {
67 self.writes.push((address, value, mclk));
68 }
69}
70
71impl Card for FakeCard {
72 fn grounds_cd(&self) -> bool {
73 self.grounds_cd
74 }
75
76 fn claims(&self) -> Vec<(usize, usize)> {
77 self.ranges.clone()
78 }
79
80 fn reset(&mut self, kind: ResetKind, _pins: &mut BoardPins) {
81 self.resets.push(kind);
82 }
83
84 fn as_any_mut(&mut self) -> &mut dyn Any {
85 self
86 }
87}
88
89pub struct FakePort {
92 ranges: Vec<(usize, usize)>,
93 pub fill: u8,
94 pub present: bool,
95 pub reads: Vec<(u32, i64)>,
96 pub writes: Vec<(u32, u8, i64)>,
97 pub resets: Vec<ResetKind>,
98 pub caught_up: Vec<i64>,
99 pub alarm_due: Option<i64>,
101}
102
103impl FakePort {
104 pub fn new(ranges: Vec<(usize, usize)>) -> FakePort {
105 FakePort {
106 ranges,
107 fill: 0xCC,
108 present: true,
109 reads: Vec::new(),
110 writes: Vec::new(),
111 resets: Vec::new(),
112 caught_up: Vec::new(),
113 alarm_due: None,
114 }
115 }
116
117 pub fn set_irq2(&mut self, level: bool, pins: &mut BoardPins) {
118 pins.irq2.set("fake-port", level);
119 }
120}
121
122impl DeviceState for FakePort {}
123
124impl PageHandler for FakePort {
125 fn read(&mut self, address: u32, mclk: i64, _pins: &mut BoardPins) -> u8 {
126 self.reads.push((address, mclk));
127 self.fill
128 }
129
130 fn write(&mut self, address: u32, value: u8, mclk: i64, _pins: &mut BoardPins) {
131 self.writes.push((address, value, mclk));
132 }
133}
134
135impl PortDevice for FakePort {
136 fn present(&self) -> bool {
137 self.present
138 }
139
140 fn claims(&self) -> Vec<(usize, usize)> {
141 self.ranges.clone()
142 }
143
144 fn catch_up(&mut self, mclk: i64, pins: &mut BoardPins) {
145 self.caught_up.push(mclk);
146 if self.alarm_due.is_some_and(|due| mclk >= due) {
147 self.set_irq2(true, pins);
148 }
149 }
150
151 fn reset(&mut self, kind: ResetKind, _pins: &mut BoardPins) {
152 self.resets.push(kind);
153 }
154
155 fn as_any_mut(&mut self) -> &mut dyn Any {
156 self
157 }
158}
159
160#[derive(Default)]
161pub struct FakeAudioSource;
162
163impl DeviceState for FakeAudioSource {}
164
165impl AudioSource for FakeAudioSource {
166 fn rate_hz(&self) -> f64 {
167 44100.0
168 }
169
170 fn gain(&self) -> f64 {
171 0.5
172 }
173
174 fn take_samples(&mut self, _mclk: i64) -> Vec<(i32, i32)> {
175 vec![(1, -1)]
176 }
177}
178
179pub struct FakeController {
181 pub nibble: u8,
182 pub writes: Vec<(bool, bool)>,
183}
184
185impl FakeController {
186 pub fn new(nibble: u8) -> FakeController {
187 FakeController {
188 nibble,
189 writes: Vec::new(),
190 }
191 }
192}
193
194impl DeviceState for FakeController {}
195
196impl ControllerPort for FakeController {
197 fn write(&mut self, sel: bool, clr: bool) {
198 self.writes.push((sel, clr));
199 }
200
201 fn read(&mut self, _sel: bool, _clr: bool) -> u8 {
202 self.nibble
203 }
204
205 fn as_any_mut(&mut self) -> &mut dyn Any {
206 self
207 }
208}
209
210#[derive(Default)]
213pub struct FakePixelPath {
214 pub lines_seen: usize,
215 pub timings: Vec<VideoTiming>,
216 pub row_counts: Vec<usize>,
217}
218
219fn second_wins(mut rows: Vec<Vec<u16>>) -> Vec<u16> {
220 if rows.len() == 1 {
221 return rows.swap_remove(0);
222 }
223 rows[0]
224 .iter()
225 .zip(rows[1].iter())
226 .map(|(&a, &b)| if b != 0 { b } else { a })
227 .collect()
228}
229
230impl DeviceState for FakePixelPath {}
231
232impl PixelPath for FakePixelPath {
233 fn mix(&mut self, timing: &VideoTiming, rows: Vec<Vec<u16>>) -> Vec<u16> {
234 self.lines_seen += 1;
235 self.timings.push(*timing);
236 self.row_counts.push(rows.len());
237 second_wins(rows)
238 }
239
240 fn as_any_mut(&mut self) -> &mut dyn Any {
241 self
242 }
243}
244
245pub struct ScriptedCpu {
247 pub board: Board,
248 pub pins: Pins,
249}
250
251impl ScriptedCpu {
252 #[allow(clippy::field_reassign_with_default)] pub fn new(mut board: Board, high_speed: bool) -> ScriptedCpu {
254 let mut pins = Pins::default();
255 pins.high_speed = high_speed;
256 pins.set_irq_disable(board.cpu_io.irq.disable);
257 board.deliver_lines(Some(&mut pins), true);
258 ScriptedCpu { board, pins }
259 }
260
261 pub fn read(&mut self, address: u32) -> u8 {
262 self.board.read(address, &mut self.pins)
263 }
264
265 pub fn write(&mut self, address: u32, value: u8) {
266 self.board.write(address, value, &mut self.pins);
267 }
268
269 pub fn idle(&mut self, cycles: usize) {
270 for _ in 0..cycles {
271 self.board.idle(None, &mut self.pins);
272 }
273 }
274}
275
276fn decode<T: for<'a> Deserialize<'a>>(data: &[u8]) -> Result<T, String> {
279 bincode::deserialize(data).map_err(|error| format!("a test device's state: {error}"))
280}
281
282pub struct LockstepCard {
285 rom: RomCard,
286 pub ram: Vec<u8>,
287 pub writes: u64,
288}
289
290impl LockstepCard {
291 pub fn new(data: &[u8]) -> Result<LockstepCard, String> {
292 Ok(LockstepCard {
293 rom: RomCard::new(data)?,
294 ram: vec![0; 0x2000],
295 writes: 0,
296 })
297 }
298}
299
300impl DeviceState for LockstepCard {
301 fn save_state(&self) -> Vec<u8> {
302 bincode::serialize(&(&self.ram, self.writes)).unwrap()
303 }
304
305 fn load_state(&mut self, data: &[u8]) -> Result<(), String> {
306 (self.ram, self.writes) = decode(data)?;
307 Ok(())
308 }
309
310 fn state_identity(&self) -> String {
311 format!("LockstepCard {}", self.rom.state_identity())
312 }
313}
314
315impl PageHandler for LockstepCard {
316 fn read(&mut self, address: u32, mclk: i64, pins: &mut BoardPins) -> u8 {
317 if address >= 0x1F0000 {
318 return self.ram[(address & 0x1FFF) as usize];
319 }
320 self.rom.read(address, mclk, pins)
321 }
322
323 fn write(&mut self, address: u32, value: u8, _mclk: i64, pins: &mut BoardPins) {
324 if address >= 0x1F0000 {
325 self.ram[(address & 0x1FFF) as usize] = value;
326 self.writes += 1;
327 if self.writes % 4096 == 0 {
328 pins.hold(3);
329 }
330 }
331 }
332}
333
334impl Card for LockstepCard {
335 fn grounds_cd(&self) -> bool {
336 true
337 }
338
339 fn claims(&self) -> Vec<(usize, usize)> {
340 vec![(0x0000, 0x0FFF), (0x1F00, 0x1F7F)]
341 }
342
343 fn reset(&mut self, _kind: ResetKind, _pins: &mut BoardPins) {
344 self.writes = 0;
345 }
346
347 fn as_any_mut(&mut self) -> &mut dyn Any {
348 self
349 }
350}
351
352#[derive(Clone, Debug, Default, Serialize, Deserialize)]
354pub struct LockstepTone {
355 pub produced: i64,
356}
357
358impl DeviceState for LockstepTone {}
359
360impl AudioSource for LockstepTone {
361 fn rate_hz(&self) -> f64 {
362 32000.0
363 }
364
365 fn gain(&self) -> f64 {
366 0.25
367 }
368
369 fn take_samples(&mut self, mclk: i64) -> Vec<(i32, i32)> {
370 let total = py_floordiv(mclk * 32000, MASTER_HZ);
371 let out = (self.produced..total)
372 .map(|i| {
373 (
374 ((i * 37) % 2001 - 1000) as i32,
375 ((i * 53) % 1501 - 750) as i32,
376 )
377 })
378 .collect();
379 self.produced = self.produced.max(total);
380 out
381 }
382}
383
384pub struct LockstepPort {
388 pub register: u8,
389 pub tone: LockstepTone,
390}
391
392impl LockstepPort {
393 pub const PERIOD: i64 = 300_000;
394 pub const WIDTH: i64 = 700;
395
396 pub fn new() -> LockstepPort {
397 LockstepPort {
398 register: 0,
399 tone: LockstepTone::default(),
400 }
401 }
402}
403
404impl Default for LockstepPort {
405 fn default() -> Self {
406 LockstepPort::new()
407 }
408}
409
410impl DeviceState for LockstepPort {
411 fn save_state(&self) -> Vec<u8> {
412 bincode::serialize(&(self.register, &self.tone)).unwrap()
413 }
414
415 fn load_state(&mut self, data: &[u8]) -> Result<(), String> {
416 (self.register, self.tone) = decode(data)?;
417 Ok(())
418 }
419
420 fn state_identity(&self) -> String {
421 "LockstepPort".to_string()
422 }
423}
424
425impl PageHandler for LockstepPort {
426 fn read(&mut self, _address: u32, _mclk: i64, _pins: &mut BoardPins) -> u8 {
427 self.register
428 }
429
430 fn write(&mut self, _address: u32, value: u8, _mclk: i64, _pins: &mut BoardPins) {
431 self.register = value;
432 }
433}
434
435impl PortDevice for LockstepPort {
436 fn present(&self) -> bool {
437 true
438 }
439
440 fn claims(&self) -> Vec<(usize, usize)> {
441 vec![(0x1FF8, 0x1FF8)]
442 }
443
444 fn catch_up(&mut self, mclk: i64, pins: &mut BoardPins) {
445 let level = mclk >= Self::PERIOD && mclk % Self::PERIOD < Self::WIDTH;
446 pins.irq2.set("lockstep-port", level);
447 }
448
449 fn reset(&mut self, _kind: ResetKind, _pins: &mut BoardPins) {
450 self.register = 0;
451 }
452
453 fn audio_sources(&mut self) -> Vec<&mut dyn AudioSource> {
454 vec![&mut self.tone]
455 }
456
457 fn as_any_mut(&mut self) -> &mut dyn Any {
458 self
459 }
460}
461
462pub const ST_OPCODES: [u8; 3] = [0x03, 0x13, 0x23];
464
465#[derive(Default)]
470pub struct LockstepPath {
471 pub lines_seen: u64,
472}
473
474impl DeviceState for LockstepPath {
475 fn save_state(&self) -> Vec<u8> {
476 bincode::serialize(&self.lines_seen).unwrap()
477 }
478
479 fn load_state(&mut self, data: &[u8]) -> Result<(), String> {
480 self.lines_seen = decode(data)?;
481 Ok(())
482 }
483
484 fn state_identity(&self) -> String {
485 "LockstepPath".to_string()
486 }
487}
488
489impl PixelPath for LockstepPath {
490 fn mix(&mut self, _timing: &VideoTiming, rows: Vec<Vec<u16>>) -> Vec<u16> {
491 self.lines_seen += 1;
492 second_wins(rows)
493 }
494
495 fn claims(&self) -> Vec<(usize, usize)> {
496 vec![(HARDWARE_FIRST_PAGE, HARDWARE_FIRST_PAGE + 3)]
497 }
498
499 fn read(&mut self, address: u32, mclk: i64, pins: &mut BoardPins) -> u8 {
500 let port = address & 3;
501 let value = pins.vdcs[0].read(port, mclk);
502 if port == 0 {
503 pins.vdcs[1].read(port, mclk);
504 }
505 value
506 }
507
508 fn write(&mut self, address: u32, value: u8, mclk: i64, pins: &mut BoardPins) {
509 let port = address & 3;
510 pins.vdcs[0].write(port, value, mclk);
511 if ST_OPCODES.contains(&pins.opcode) {
512 pins.vdcs[1].write(port, value, mclk);
513 }
514 }
515
516 fn as_any_mut(&mut self) -> &mut dyn Any {
517 self
518 }
519}