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
use crate::gbi::GBICommandParams;
use log::trace;

use super::{
    gbi::{defines::Gfx, GBICommandRegistry, GBIResult},
    output::RCPOutput,
    rdp::RDP,
    rsp::RSP,
};

pub struct RCP {
    gbi: GBICommandRegistry,
    pub rdp: RDP,
    pub rsp: RSP,
}

impl Default for RCP {
    fn default() -> Self {
        Self::new()
    }
}

impl RCP {
    pub fn new() -> Self {
        let mut gbi = GBICommandRegistry::default();
        let mut rsp = RSP::default();
        gbi.setup(&mut rsp);

        RCP {
            gbi,
            rdp: RDP::default(),
            rsp,
        }
    }

    pub fn reset(&mut self) {
        self.rdp.reset();
        self.rsp.reset();
    }

    /// This function is called to process a work buffer.
    /// It takes in a pointer to the start of the work buffer and will
    /// process until it hits a `G_ENDDL` indicating the end.
    pub fn run(&mut self, output: &mut RCPOutput, commands: usize) {
        self.reset();
        self.run_dl(output, commands);
        self.rdp.flush(output);
    }

    fn run_dl(&mut self, output: &mut RCPOutput, commands: usize) {
        let mut command = commands as *mut Gfx;

        loop {
            let opcode = unsafe { (*command).words.w0 } >> 24;
            if let Some(handler) = self.gbi.handler(&opcode) {
                let handler_input = &mut GBICommandParams {
                    rdp: &mut self.rdp,
                    rsp: &mut self.rsp,
                    output,
                    command: &mut command,
                };
                match handler.process(handler_input) {
                    GBIResult::Recurse(new_command) => self.run_dl(output, new_command),
                    GBIResult::Return => return,
                    GBIResult::Continue => {}
                }
            } else {
                trace!("Unknown GBI command: {:#x}", opcode);
            }

            unsafe { command = command.add(1) };
        }
    }
}