1use huc6280::{Bus, Pins};
34
35use crate::cpu_io::CpuIo;
36use crate::hardware_page::map_hardware_page;
37use crate::machine::{
38 Machine, ADDRESS_MASK, CPU_CLOCKS_HIGH, CPU_CLOCKS_LOW, HARDWARE_FIRST_PAGE, HSYNC_CLOCKS,
39 LINE_CLOCKS, PAGE_BITS, PC_ENGINE,
40};
41use crate::mixer::Mixer;
42use crate::mt::PythonRandom;
43use crate::pagetable::{Handler, PageTable, Ram};
44use crate::psg::{Psg, PsgSwitches};
45use crate::sockets::{
46 AudioSource, BoardPins, Card, CardSlot, ControllerPort, DirectPath, IrqLine, PixelPath,
47 PortDevice, ResetKind, VdcAccess, VideoTiming,
48};
49use crate::vce::Vce;
50use crate::vdc::Vdc;
51use crate::video::{Capture, Timeline};
52
53pub struct BoardOptions {
55 pub machine: Machine,
56 pub card: Option<Box<dyn Card>>,
57 pub port: Option<Box<dyn PortDevice>>,
58 pub pad: Option<Box<dyn ControllerPort>>,
59 pub pixel_path: Option<Box<dyn PixelPath>>,
60 pub power_on_seed: Option<i64>,
63 pub start_line: i64,
65 pub start_offset: i64,
66 pub vblank_dots: Option<i64>,
68 pub vertical_at_line_start: bool,
69 pub dma_resumes: bool,
71 pub psg: PsgSwitches,
73 pub timer_underflow_window_mclk: i64,
75}
76
77impl Default for BoardOptions {
78 fn default() -> Self {
79 BoardOptions {
80 machine: PC_ENGINE,
81 card: None,
82 port: None,
83 pad: None,
84 pixel_path: None,
85 power_on_seed: None,
86 start_line: 0,
87 start_offset: 0,
88 vblank_dots: Some(-8),
89 vertical_at_line_start: false,
90 dma_resumes: true,
91 psg: PsgSwitches::default(),
92 timer_underflow_window_mclk: 15,
93 }
94 }
95}
96
97pub struct Board {
98 pub machine: Machine,
99 pub mclk: i64,
100 pub(crate) held: i64,
101 pub(crate) lines: (bool, bool, bool),
102 pub(crate) row_end: Option<i64>,
104 pub(crate) row_timing: Option<VideoTiming>,
106 pub irq2: IrqLine,
107 pub vce: Vce,
108 pub vdcs: Vec<Vdc>,
112 pub(crate) vdc_access: VdcAccess,
114 pub psg: Psg,
115 pub cpu_io: CpuIo,
116 pub ram: Ram,
117 pub slot: CardSlot,
118 pub port: Option<Box<dyn PortDevice>>,
119 pub audio_sources: Vec<Box<dyn AudioSource>>,
121 pub mixer: Mixer,
122 pub timeline: Timeline,
123 pub capture: Capture,
124 pub pixel_path: Box<dyn PixelPath>,
125 pub pages: PageTable,
126 pub(crate) opcode: u8,
128 pub bus_log: Option<Vec<u64>>,
131 pub bus_detail: Option<Vec<(u8, u32, u8, i64)>>,
134}
135
136impl Board {
137 pub fn new(options: BoardOptions) -> Result<Board, String> {
138 let machine = options.machine;
139 let mut rng = options.power_on_seed.map(PythonRandom::new);
140
141 let vce = Vce::new(rng.as_mut());
142 let vdcs: Vec<Vdc> = (0..machine.vdc_count)
143 .map(|_| {
144 let mut vdc = Vdc::new(
145 rng.as_mut(),
146 options.vblank_dots,
147 options.vertical_at_line_start,
148 options.dma_resumes,
149 );
150 vdc.serve = true; vdc
152 })
153 .collect();
154 if vdcs.is_empty() {
155 return Err("a machine has at least one VDC".to_string());
156 }
157 let psg = Psg::new(44100.0, options.psg);
158 let mut cpu_io = CpuIo::new(machine.country_pc_engine, options.pad);
159 cpu_io.timer.underflow_window_mclk = options.timer_underflow_window_mclk;
160 let mut ram = Ram::new(machine.work_ram_bytes);
161 if let Some(rng) = rng.as_mut() {
162 for byte in ram.data.iter_mut() {
163 *byte = rng.getrandbits(8) as u8;
164 }
165 }
166 let timeline = Timeline::new(&machine, &vce, options.start_line, options.start_offset)?;
167 let capture = Capture::new(&vce);
168
169 let mut pages = PageTable::new();
170 pages.set_base(0x1F00, 0x1F7F, Handler::Ram);
172 map_hardware_page(&mut pages);
173 if let Some(card) = options.card.as_ref() {
174 for (first, last) in card.claims() {
175 pages.claim(first, last, Handler::Card)?;
176 }
177 }
178 if let Some(port) = options.port.as_ref() {
179 for (first, last) in port.claims() {
180 pages.claim(first, last, Handler::Port)?;
181 }
182 }
183 let pixel_path = options.pixel_path.unwrap_or_else(|| Box::new(DirectPath));
184 for (first, last) in pixel_path.claims() {
185 pages.claim(first, last, Handler::PixelPath)?;
186 }
187
188 let mut board = Board {
189 machine,
190 mclk: 0,
191 held: 0,
192 lines: (false, false, false),
193 row_end: None,
194 row_timing: None,
195 irq2: IrqLine::new("IRQ2"),
196 vce,
197 vdcs,
198 vdc_access: VdcAccess::default(),
199 psg,
200 cpu_io,
201 ram,
202 slot: CardSlot::new(options.card),
203 port: options.port,
204 audio_sources: Vec::new(),
205 mixer: Mixer::default(),
206 timeline,
207 capture,
208 pixel_path,
209 pages,
210 opcode: 0,
211 bus_log: None,
212 bus_detail: None,
213 };
214 let divider = board.vce.dot_divider();
215 for vdc in board.vdcs.iter_mut() {
216 vdc.hsync(board.timeline.line_start, divider);
217 if board.timeline.line >= board.timeline.frame_lines - 3 {
218 vdc.vsync();
219 }
220 }
221 Ok(board)
222 }
223
224 pub fn vdc(&mut self) -> &mut Vdc {
226 &mut self.vdcs[0]
227 }
228
229 pub fn take_audio(&mut self) -> Vec<(i16, i16)> {
231 let mut sources: Vec<&mut dyn AudioSource> = vec![&mut self.psg];
232 if let Some(port) = self.port.as_mut() {
233 sources.extend(port.audio_sources());
234 }
235 for source in self.audio_sources.iter_mut() {
236 sources.push(source.as_mut());
237 }
238 self.mixer.take(self.mclk, sources)
239 }
240
241 pub fn set_pressed(&mut self, port: usize, pressed: u16) {
244 if let Some(device) = self.cpu_io.port.device.as_mut() {
245 device.set_pressed(port, pressed);
246 }
247 }
248
249 fn cd_attached(&self) -> bool {
252 self.port.as_ref().is_some_and(|port| port.present())
253 }
254
255 pub fn page_read(&mut self, address: u32, mclk: i64) -> u8 {
258 self.vdc_access.begin();
259 loop {
260 let value = self.decode_read(address, mclk);
261 match self.vdc_waiting() {
262 None => return value,
263 Some(index) => self.serve_access(index, mclk),
264 }
265 }
266 }
267
268 pub fn page_write(&mut self, address: u32, value: u8, mclk: i64) {
270 self.vdc_access.begin();
271 loop {
272 self.decode_write(address, value, mclk);
273 match self.vdc_waiting() {
274 None => return,
275 Some(index) => self.serve_access(index, mclk),
276 }
277 }
278 }
279
280 #[inline]
284 fn vdc_waiting(&self) -> Option<usize> {
285 self.vdc_access
286 .stopped()
287 .or_else(|| self.vdcs.iter().position(|vdc| vdc.serve_wanted))
288 }
289
290 fn serve_access(&mut self, index: usize, mclk: i64) {
294 self.vdcs[index].serve_wanted = false;
295 let served = self.serve_vram(index);
296 if served > mclk {
297 self.hold(served - mclk);
298 }
299 self.vdc_access.again(index, served.max(mclk));
300 }
301
302 fn decode_read(&mut self, address: u32, mclk: i64) -> u8 {
303 let address = address & ADDRESS_MASK;
304 match self.pages.handler(address) {
305 Handler::Unmapped => 0xFF,
306 Handler::Ram => self.ram.read(address),
307 Handler::Vdc => self.vdc_access.read(&mut self.vdcs, 0, address & 3, mclk),
308 Handler::Vce => self.vce.read(address & 7, mclk),
309 Handler::CpuIo => {
310 let cd_attached = self.cd_attached();
311 self.cpu_io.read(address & 0x1FFF, mclk, cd_attached)
312 }
313 Handler::Card => {
314 let Board {
315 slot,
316 irq2,
317 held,
318 vdcs,
319 vdc_access,
320 opcode,
321 ..
322 } = self;
323 let mut pins = BoardPins {
324 irq2,
325 held,
326 vdcs,
327 access: vdc_access,
328 opcode: *opcode,
329 card: None,
330 };
331 match slot.card.as_mut() {
332 Some(card) => card.read(address, mclk, &mut pins),
333 None => 0xFF,
334 }
335 }
336 Handler::Port => {
337 let Board {
338 slot,
339 port,
340 irq2,
341 held,
342 vdcs,
343 vdc_access,
344 opcode,
345 ..
346 } = self;
347 let mut pins = BoardPins {
348 irq2,
349 held,
350 vdcs,
351 access: vdc_access,
352 opcode: *opcode,
353 card: slot.card.as_deref_mut(),
354 };
355 match port.as_mut() {
356 Some(port) => port.read(address, mclk, &mut pins),
357 None => 0xFF,
358 }
359 }
360 Handler::PixelPath => {
361 let Board {
362 slot,
363 pixel_path,
364 irq2,
365 held,
366 vdcs,
367 vdc_access,
368 opcode,
369 ..
370 } = self;
371 let mut pins = BoardPins {
372 irq2,
373 held,
374 vdcs,
375 access: vdc_access,
376 opcode: *opcode,
377 card: slot.card.as_deref_mut(),
378 };
379 pixel_path.read(address, mclk, &mut pins)
380 }
381 }
382 }
383
384 fn decode_write(&mut self, address: u32, value: u8, mclk: i64) {
385 let address = address & ADDRESS_MASK;
386 match self.pages.handler(address) {
387 Handler::Unmapped => {}
388 Handler::Ram => self.ram.write(address, value),
389 Handler::Vdc => self
390 .vdc_access
391 .write(&mut self.vdcs, 0, address & 3, value, mclk),
392 Handler::Vce => self.vce.write(address & 7, value, mclk),
393 Handler::CpuIo => self
394 .cpu_io
395 .write(address & 0x1FFF, value, mclk, &mut self.psg),
396 Handler::Card => {
397 let Board {
398 slot,
399 irq2,
400 held,
401 vdcs,
402 vdc_access,
403 opcode,
404 ..
405 } = self;
406 let mut pins = BoardPins {
407 irq2,
408 held,
409 vdcs,
410 access: vdc_access,
411 opcode: *opcode,
412 card: None,
413 };
414 if let Some(card) = slot.card.as_mut() {
415 card.write(address, value, mclk, &mut pins);
416 }
417 }
418 Handler::Port => {
419 let Board {
420 slot,
421 port,
422 irq2,
423 held,
424 vdcs,
425 vdc_access,
426 opcode,
427 ..
428 } = self;
429 let mut pins = BoardPins {
430 irq2,
431 held,
432 vdcs,
433 access: vdc_access,
434 opcode: *opcode,
435 card: slot.card.as_deref_mut(),
436 };
437 if let Some(port) = port.as_mut() {
438 port.write(address, value, mclk, &mut pins);
439 }
440 }
441 Handler::PixelPath => {
442 let Board {
443 slot,
444 pixel_path,
445 irq2,
446 held,
447 vdcs,
448 vdc_access,
449 opcode,
450 ..
451 } = self;
452 let mut pins = BoardPins {
453 irq2,
454 held,
455 vdcs,
456 access: vdc_access,
457 opcode: *opcode,
458 card: slot.card.as_deref_mut(),
459 };
460 pixel_path.write(address, value, mclk, &mut pins);
461 }
462 }
463 }
464
465 #[inline]
468 fn cycle_clocks(pins: &Pins) -> i64 {
469 if pins.high_speed {
470 CPU_CLOCKS_HIGH
471 } else {
472 CPU_CLOCKS_LOW
473 }
474 }
475
476 fn finish_access(&mut self, address: u32, cycle: i64, pins: &mut Pins) {
477 if self.cpu_io.irq.mask_changed {
480 self.cpu_io.irq.mask_changed = false;
481 pins.set_irq_disable(self.cpu_io.irq.disable);
482 }
483 let page = (address >> PAGE_BITS) as usize;
487 if (HARDWARE_FIRST_PAGE..HARDWARE_FIRST_PAGE + 8).contains(&page) {
488 self.held += cycle;
489 }
490 for vdc in self.vdcs.iter_mut() {
491 self.held += vdc.take_hold();
492 }
493 if self.held != 0 {
494 let held = std::mem::take(&mut self.held);
495 self.advance_with(held, Some(&mut *pins));
496 }
497 self.deliver_lines(Some(pins), false);
499 }
500
501 pub fn hold(&mut self, clocks: i64) {
503 self.held += clocks;
504 }
505
506 pub fn advance(&mut self, clocks: i64) {
511 self.advance_with(clocks, None);
512 }
513
514 fn advance_with(&mut self, clocks: i64, pins: Option<&mut Pins>) {
515 self.mclk += clocks;
516 self.run_to(self.mclk);
517 self.deliver_lines(pins, false);
518 }
519
520 fn run_to(&mut self, target: i64) {
521 while self.step(target).is_some() {}
522 self.settle(target);
523 }
524
525 fn step(&mut self, target: i64) -> Option<i64> {
528 let line_at = self.timeline.next_line_start();
529 let row_at = self.row_end;
530 let mut vdc_at = self.vdcs[0].next_event();
531 for other in &self.vdcs[1..] {
532 if let Some(at) = other.next_event() {
533 if vdc_at.is_none_or(|first| at < first) {
534 vdc_at = Some(at);
535 }
536 }
537 }
538 let timer_at = self.cpu_io.next_event();
539 if let Some(row_at) = row_at
540 .filter(|&at| at <= target && at <= line_at && vdc_at.is_none_or(|vdc_at| at <= vdc_at))
541 {
542 self.end_row(row_at);
543 return Some(row_at);
544 }
545 if line_at <= target && vdc_at.is_none_or(|at| line_at <= at) {
546 self.new_line(line_at);
547 return Some(line_at);
548 }
549 if let Some(vdc_at) = vdc_at.filter(|&at| at <= target) {
550 for chip in self.vdcs.iter_mut() {
551 chip.catch_up(vdc_at);
552 }
553 return Some(vdc_at);
554 }
555 if let Some(timer_at) = timer_at.filter(|&at| at <= target) {
556 self.cpu_io.catch_up(timer_at);
557 return Some(timer_at);
558 }
559 None
560 }
561
562 pub(crate) fn serve_vram(&mut self, index: usize) -> i64 {
566 let mut now = self.mclk;
567 while self.vdcs[index].bsy() {
568 if let Some(at) = self.step(1 << 62) {
570 now = now.max(at);
571 }
572 }
573 self.settle(now);
574 now
575 }
576
577 fn settle(&mut self, target: i64) {
578 for chip in self.vdcs.iter_mut() {
579 chip.catch_up(target);
580 }
581 self.cpu_io.catch_up(target);
582 let Board {
584 slot,
585 port,
586 irq2,
587 held,
588 vdcs,
589 vdc_access,
590 opcode,
591 ..
592 } = self;
593 if let Some(port) = port.as_mut() {
594 let mut pins = BoardPins {
595 irq2,
596 held,
597 vdcs,
598 access: vdc_access,
599 opcode: *opcode,
600 card: slot.card.as_deref_mut(),
601 };
602 port.catch_up(target, &mut pins);
603 }
604 }
605
606 fn new_line(&mut self, at: i64) {
607 for vdc in self.vdcs.iter_mut() {
608 vdc.catch_up(at);
609 }
610 self.row_timing = Some(self.timeline.timing(&self.vce));
612 self.row_end = Some(at + HSYNC_CLOCKS);
613 self.timeline.advance(&self.vce);
614 let divider = self.vce.dot_divider();
615 let vsync = self.timeline.line == self.timeline.frame_lines - 3;
616 for vdc in self.vdcs.iter_mut() {
617 vdc.hsync(at, divider);
618 if vsync {
619 vdc.vsync(); }
621 }
622 }
623
624 fn end_row(&mut self, at: i64) {
627 for vdc in self.vdcs.iter_mut() {
628 vdc.catch_up(at - 1);
629 }
630 let timing = self.row_timing.expect("a row ends after a line began");
631 let dots = (LINE_CLOCKS / timing.dot_divider) as usize;
632 let rows: Vec<Vec<u16>> = self.vdcs.iter().map(|vdc| vdc.pixel_row(dots)).collect();
633 let row = self.pixel_path.mix(&timing, rows);
634 self.capture.finish_line(&timing, &row, &mut self.vce);
635 self.row_end = None;
636 }
637
638 pub fn lines(&self) -> (bool, bool, bool) {
642 (
644 self.vdcs.iter().any(|vdc| vdc.irq1()),
645 self.irq2.level(),
646 self.cpu_io.tiq(),
647 )
648 }
649
650 pub(crate) fn deliver_lines(&mut self, pins: Option<&mut Pins>, force: bool) {
651 let lines = self.lines();
652 self.cpu_io.irq.irq1 = lines.0;
653 self.cpu_io.irq.irq2 = lines.1;
654 if lines != self.lines || force {
655 if let Some(pins) = pins {
656 pins.set_irq_lines(lines.0, lines.1, lines.2);
657 }
658 }
659 self.lines = lines;
660 }
661
662 pub fn reset(&mut self, kind: ResetKind) {
674 let Board {
675 slot,
676 port,
677 pixel_path,
678 irq2,
679 held,
680 vdcs,
681 vdc_access,
682 opcode,
683 ..
684 } = self;
685 if let Some(card) = slot.card.as_mut() {
686 let mut pins = BoardPins {
687 irq2,
688 held,
689 vdcs,
690 access: vdc_access,
691 opcode: *opcode,
692 card: None,
693 };
694 card.reset(kind, &mut pins);
695 }
696 if let Some(port) = port.as_mut() {
697 let mut pins = BoardPins {
698 irq2,
699 held,
700 vdcs,
701 access: vdc_access,
702 opcode: *opcode,
703 card: slot.card.as_deref_mut(),
704 };
705 port.reset(kind, &mut pins);
706 }
707 let mut pins = BoardPins {
708 irq2,
709 held,
710 vdcs,
711 access: vdc_access,
712 opcode: *opcode,
713 card: slot.card.as_deref_mut(),
714 };
715 pixel_path.reset(kind, &mut pins);
716 if kind == ResetKind::PowerOn {
717 self.cpu_io.reset();
718 }
719 }
720}
721
722impl Bus for Board {
723 fn read(&mut self, address: u32, pins: &mut Pins) -> u8 {
724 self.opcode = pins.opcode();
725 let cycle = Board::cycle_clocks(pins);
726 self.advance_with(cycle, Some(pins));
727 let value = self.page_read(address, self.mclk);
728 self.finish_access(address, cycle, pins);
729 if let Some(log) = self.bus_log.as_mut() {
730 log.push((address as u64) << 8 | value as u64);
731 log.push((self.mclk as u64) << 2);
732 }
733 if let Some(detail) = self.bus_detail.as_mut() {
734 detail.push((0, address, value, self.mclk));
735 }
736 value
737 }
738
739 fn write(&mut self, address: u32, value: u8, pins: &mut Pins) {
740 self.opcode = pins.opcode();
741 let cycle = Board::cycle_clocks(pins);
742 self.advance_with(cycle, Some(pins));
743 self.page_write(address, value, self.mclk);
744 self.finish_access(address, cycle, pins);
745 if let Some(log) = self.bus_log.as_mut() {
746 log.push((address as u64) << 8 | value as u64);
747 log.push((self.mclk as u64) << 2 | 1);
748 }
749 if let Some(detail) = self.bus_detail.as_mut() {
750 detail.push((1, address, value, self.mclk));
751 }
752 }
753
754 fn idle(&mut self, _address: Option<u32>, pins: &mut Pins) {
756 self.opcode = pins.opcode();
757 let cycle = Board::cycle_clocks(pins);
758 self.advance_with(cycle, Some(pins));
759 if let Some(log) = self.bus_log.as_mut() {
760 log.push((self.mclk as u64) << 2 | 2);
761 }
762 if let Some(detail) = self.bus_detail.as_mut() {
763 detail.push((2, 0, 0, self.mclk));
764 }
765 }
766}