1 #ifdef WITH_JOYSTICK
2 
3 #include <stddef.h>
4 #include <SDL.h>
5 #include <SDL_joystick.h>
6 #include "md.h"
7 
8 static SDL_Joystick *(*handles)[];
9 static unsigned int handles_n;
10 
init_joysticks()11 void md::init_joysticks()
12 {
13 	int n;
14 	unsigned int i;
15 	SDL_Joystick *(*tmp)[];
16 
17 	deinit_joysticks();
18   // Initialize the joystick support
19   // Thanks to Cameron Moore <cameron@unbeatenpath.net>
20   if(SDL_InitSubSystem(SDL_INIT_JOYSTICK) < 0)
21     {
22       fprintf(stderr, "joystick: Unable to initialize joystick system\n");
23       return;
24     }
25 	n = SDL_NumJoysticks();
26 	if (n <= 0) {
27 		fprintf(stderr, "joystick: no joystick found\n");
28 		return;
29 	}
30 	fprintf(stderr, "joystick: %d joystick(s) found\n", n);
31 	i = (sizeof((*tmp)[0]) * n); // Separate, otherwise Clang complains.
32 	tmp = (SDL_Joystick *(*)[])malloc(i);
33 	if (tmp == NULL) {
34 		fprintf(stderr, "joystick: unable to allocate memory\n");
35 		return;
36 	}
37 	// Open all of them.
38 	for (i = 0; (i != (unsigned int)n); ++i) {
39 		SDL_Joystick *handle = SDL_JoystickOpen(i);
40 
41 		if (handle == NULL)
42 			fprintf(stderr, "joystick: can't open joystick %u: %s",
43 				i, SDL_GetError());
44 		else
45 			fprintf(stderr,
46 				"joystick #%u:, %d %s, %d button(s),"
47 				" %d hat(s), name: \"%s\"\n",
48 				i,
49 				SDL_JoystickNumAxes(handle),
50 				((SDL_JoystickNumAxes(handle) == 1) ?
51 				 "axis" : "axes"),
52 				SDL_JoystickNumButtons(handle),
53 				SDL_JoystickNumHats(handle),
54 				SDL_JoystickName(i));
55 		(*tmp)[i] = handle;
56 	}
57 	handles = tmp;
58 	handles_n = i;
59   // Enable joystick events
60   SDL_JoystickEventState(SDL_ENABLE);
61 }
62 
deinit_joysticks()63 void md::deinit_joysticks()
64 {
65 	unsigned int n = handles_n;
66 	SDL_Joystick *(*tmp)[] = handles;
67 
68 	handles_n = 0;
69 	handles = NULL;
70 	if (tmp == NULL)
71 		return;
72 	while (n != 0) {
73 		--n;
74 		if ((*tmp)[n] == NULL)
75 			continue;
76 		SDL_JoystickClose((*tmp)[n]);
77 		(*tmp)[n] = NULL;
78 	}
79 	free(tmp);
80 	SDL_QuitSubSystem(SDL_INIT_JOYSTICK);
81 }
82 
83 #else // WITH_JOYSTICK
84 
85 // Avoid empty translation unit.
86 typedef int md_phil;
87 
88 #endif // WITH_JOYSTICK
89