1 #include "JoystickPool.h"
2 
3 #include <iostream>
4 #include <cstdio>
5 #include <cstring>
6 #include <sstream>
7 
8 #include <SDL2/SDL.h>
9 
10 // Joystick Pool
11 JoystickPool* JoystickPool::mSingleton = 0; //static
12 
getSingleton()13 JoystickPool& JoystickPool::getSingleton()
14 {
15 	if (mSingleton == 0)
16 		mSingleton = new JoystickPool();
17 
18 	return *mSingleton;
19 }
20 
getJoystick(int id)21 SDL_Joystick* JoystickPool::getJoystick(int id)
22 {
23 	SDL_Joystick* joy =  mJoyMap[id];
24 
25 	if (!joy)
26 		std::cerr << "Warning: could not find joystick number "
27 			<< id << "!" << std::endl;
28 
29 	return joy;
30 }
31 
probeJoysticks()32 void JoystickPool::probeJoysticks()
33 {
34 	int numJoysticks = SDL_NumJoysticks();
35 	SDL_Joystick* lastjoy;
36 	for(int i = 0; i < numJoysticks; i++)
37 	{
38 		lastjoy = SDL_JoystickOpen(i);
39 
40 		if (lastjoy == NULL)
41 			continue;
42 
43 		mJoyMap[SDL_JoystickInstanceID(lastjoy)] = lastjoy;
44 	}
45 }
46 
closeJoysticks()47 void JoystickPool::closeJoysticks()
48 {
49 	for (JoyMap::iterator iter = mJoyMap.begin();
50 		iter != mJoyMap.end(); ++iter)
51 	{
52 		SDL_JoystickClose((*iter).second);
53 	}
54 }
55 
56 // Joystick Action
57 
JoystickAction(std::string string)58 JoystickAction::JoystickAction(std::string string)
59 {
60 	type = AXIS;
61 	number = 0;
62 	joy = 0;
63 	joyid = 0;
64 	try
65 	{
66 		const char* str = string.c_str();
67 		if (std::strstr(str, "button"))
68 		{
69 			type = BUTTON;
70 			if (sscanf(str, "joy_%d_button_%d", &joyid, &number) < 2)
71 				throw string;
72 		}
73 		else if (std::strstr(str, "axis"))
74 		{
75 			if (sscanf(str, "joy_%d_axis_%d", &joyid, &number) < 2)
76 				throw string;
77 		}
78 
79 		joy = JoystickPool::getSingleton().getJoystick(joyid);
80 	}
81 	catch (const std::string& e)
82 	{
83 		std::cerr << "Parse error in joystick config: " << e << std::endl;
84 	}
85 }
86 
JoystickAction(const JoystickAction & action)87 JoystickAction::JoystickAction(const JoystickAction& action)
88 {
89 	type = action.type;
90 	joy = JoystickPool::getSingleton().getJoystick(action.joyid);
91 	joyid = action.joyid;
92 	number = action.number;
93 }
94 
~JoystickAction()95 JoystickAction::~JoystickAction()
96 {
97 }
98 
toString()99 std::string JoystickAction::toString()
100 {
101 	const char* typestr = "unknown";
102 	if (type == AXIS)
103 		typestr = "axis";
104 
105 	if (type == BUTTON)
106 		typestr = "button";
107 
108 	std::stringstream buf;
109 	buf << "joy_" << joyid << "_" << typestr << "_" << number;
110 	return buf.str();
111 }
112 
113