-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcontroller.c
More file actions
110 lines (89 loc) · 2.5 KB
/
controller.c
File metadata and controls
110 lines (89 loc) · 2.5 KB
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
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
#include "controller.h"
#include "common.h"
#include <stdio.h>
typedef struct{
byte state;
byte cur_bit_mask;
bool is_polled;
}joypad_state_t;
static joypad_state_t jp[2] = {{0, 1, false}, {0, 1, false}};
#define JOYPAD_COUNT (sizeof(jp)/sizeof(joypad_state_t))
static inline void check_for_valid_jp(JOYPAD_t joypad_index){
if(joypad_index >= JOYPAD_COUNT){
fprintf(stderr, "ERR: Tried to read from joypad %d which does not exist!\n", joypad_index);
abort();
}
}
byte joypad_read_bit(JOYPAD_t joypad_index){
check_for_valid_jp(joypad_index);
if(jp[joypad_index].is_polled == false) return 0; //Dont do anything with the controller if we never recived a poll command
bool read_bit = !!(jp[joypad_index].state & jp[joypad_index].cur_bit_mask);
jp[joypad_index].cur_bit_mask <<= 1;
//Check if wrap around happens
if(jp[joypad_index].cur_bit_mask == 0){
jp[joypad_index].cur_bit_mask = 1;
jp[joypad_index].is_polled = false;
}
//Idk why but emulators always have 0x40 as well as the bit read
return 0x40 | (byte)read_bit;
}
void joypad_zero_out(JOYPAD_t joypad_index){
check_for_valid_jp(joypad_index);
jp[joypad_index].state = 0;
jp[joypad_index].cur_bit_mask = 1;
}
void joypad_prepare_read(void){
for(int i = 0; i < JOYPAD_COUNT; i++){
jp[i].cur_bit_mask = 0b1;
}
}
//Fills the shift register and publishes the button states
void joypad_publish_state(void){
for(int i = 0; i < JOYPAD_COUNT; i++){
jp[i].is_polled = true;
}
}
void joypad_set_button(JOYPAD_t joypad_index, BUTTON_t bit_index, bool button_state){
check_for_valid_jp(joypad_index);
if(bit_index >= 8){
fprintf(stderr, "ERR: jpad bit index of %d is too high!\n", bit_index);
abort();
}
#ifdef DEBUG
if(button_state == true){
fprintf(stderr, "Pressed ");
}else{
fprintf(stderr, "Released ");
}
switch(bit_index){
case BUTTON_A:
fprintf(stderr, "A Button\n");
break;
case BUTTON_B:
fprintf(stderr, "B Button\n");
break;
case BUTTON_SELECT:
fprintf(stderr, "Select Button\n");
break;
case BUTTON_START:
fprintf(stderr, "Start Button\n");
break;
case BUTTON_UP:
fprintf(stderr, "Up Button\n");
break;
case BUTTON_DOWN:
fprintf(stderr, "Down Button\n");
break;
case BUTTON_LEFT:
fprintf(stderr, "Left Button\n");
break;
case BUTTON_RIGHT:
fprintf(stderr, "Right Button\n");
break;
}
#endif
byte bval = ((byte)button_state) << bit_index;
byte bmask = 1 << bit_index;
jp[joypad_index].state &= ~bmask;
jp[joypad_index].state |= bval;
}