12abea5c60951a8ff03e4576e1f679dce0af8b98
[mercenary-reloaded.git] / src / libjoystick / joystick.c
1 /* joystick emulation
2  *
3  * (C) 2018 by Andreas Eversberg <jolly@eversberg.eu>
4  * All Rights Reserved
5  *
6  * This program is free software: you can redistribute it and/or modify
7  * it under the terms of the GNU General Public License as published by
8  * the Free Software Foundation, either version 3 of the License, or
9  * (at your option) any later version.
10  *
11  * This program is distributed in the hope that it will be useful,
12  * but WITHOUT ANY WARRANTY; without even the implied warranty of
13  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
14  * GNU General Public License for more details.
15  *
16  * You should have received a copy of the GNU General Public License
17  * along with this program.  If not, see <http://www.gnu.org/licenses/>.
18  */
19
20 #include <stdio.h>
21 #include <stdint.h>
22 #include <string.h>
23 #include "joystick.h"
24
25 static int joystick_left = 0;
26 static int joystick_right = 0;
27 static int joystick_up = 0;
28 static int joystick_down = 0;
29 static int joystick_fire = 0;
30
31 #define CIAAPRA         0xbfe000
32 #define JOYDAT1         0xdff00c
33
34 uint16_t emulate_joystick_read(uint32_t address)
35 {
36         if (address == CIAAPRA) {
37                 if (joystick_fire)
38                         return 0xff7f;
39                 return 0xffff;
40         }
41
42         if (address == JOYDAT1) {
43                 uint16_t joydat = 0x0000;
44                 if (joystick_right) {
45                         joydat |= 0x0002;
46                         /* make bit 0 and 1 equal */
47                         if (!joystick_down)
48                                 joydat |= 0x0001;
49                 } else {
50                         /* make bit 0 and 1 odd */
51                         if (joystick_down)
52                                 joydat |= 0x0001;
53                 }
54                 if (joystick_left) {
55                         joydat |= 0x0200;
56                         /* make bit 8 and 9 equal */
57                         if (!joystick_up)
58                                 joydat |= 0x0100;
59                 } else {
60                         /* make bit 8 and 9 odd */
61                         if (joystick_up)
62                                 joydat |= 0x0100;
63                 }
64                 return joydat;
65         }
66
67         return 0xffff;
68 }
69
70 /* use -1 to keep state unchanged */
71 void set_joystick(int left, int right, int up, int down, int fire)
72 {
73         if (left >= 0)
74                 joystick_left = left;
75         if (right >= 0)
76                 joystick_right = right;
77         if (up >= 0)
78                 joystick_up = up;
79         if (down >= 0)
80                 joystick_down = down;
81         if (fire >= 0)
82                 joystick_fire = fire;
83 }
84
85