aboutsummaryrefslogtreecommitdiff
path: root/src/controller.rs
blob: bb78769e4af4a21559a206ad83248185d090e2ec (plain) (blame)
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
#![allow(dead_code)]
use utils::{Read, Write};

pub trait Controller {
    fn read(&self) -> u8;
    fn write(&self, data: u8);
    fn load(&mut self, reader: &mut Read) -> bool;
    fn save(&self, writer: &mut Write) -> bool;
}

pub mod stdctl {
    use utils::{Read, Write, load_prefix, save_prefix};
    use core::cell::Cell;
    use controller::Controller;
    pub const A: u8 = 1 << 0;
    pub const B: u8 = 1 << 1;
    pub const SELECT: u8 = 1 << 2;
    pub const START: u8 = 1 << 3;
    pub const UP: u8 = 1 << 4;
    pub const DOWN: u8 = 1 << 5;
    pub const LEFT: u8 = 1 << 6;
    pub const RIGHT: u8 = 1 << 7;
    pub const NULL: u8 = 0;
    
    #[repr(C)]
    pub struct Joystick {
        strobe: Cell<bool>,
        reg: Cell<u8>,
        back_reg: Cell<u8>
    }

    impl Joystick {
        pub fn new() -> Self {
            Joystick{reg: Cell::new(0), strobe: Cell::new(false), back_reg: Cell::new(0)}
        }

        pub fn set(&self, buttons: u8) {
            self.reg.set(buttons);
            self.back_reg.set(buttons);
        }
    }

    impl Controller for Joystick {
        fn read(&self) -> u8 {
            let res = self.reg.get() & 1;
            if !self.strobe.get() {
                self.reg.set(self.reg.get() >> 1);
            }
            res
        }
        
        fn write(&self, data: u8) {
            self.strobe.set(data & 1 == 1);
            self.reg.set(self.back_reg.get());
        }

        fn load(&mut self, reader: &mut Read) -> bool {
            load_prefix(self, 0, reader)
        }

        fn save(&self, writer: &mut Write) -> bool {
            save_prefix(self, 0, writer)
        }
    }
}