main.cpp 9.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313
  1. /** Example 019 Mouse and Joystick
  2. This tutorial builds on example 04.Movement which showed how to
  3. handle keyboard events in Irrlicht. Here we'll handle mouse events
  4. and joystick events, if you have a joystick connected and a device
  5. that supports joysticks. These are currently Windows, Linux and SDL
  6. devices.
  7. */
  8. #ifdef _MSC_VER
  9. #pragma comment(lib, "Irrlicht.lib")
  10. #endif
  11. #include <irrlicht.h>
  12. #include "driverChoice.h"
  13. using namespace irr;
  14. /*
  15. Just as we did in example 04.Movement with keys, we'll store the latest state of the
  16. mouse and the first joystick, updating them as we receive events.
  17. Note that instead of working with events we could work with CursorControl, aka
  18. device->getCursorControl(), to get the current mouse state.
  19. With events you get every mouse movement since the last device->run(),
  20. while CursorControl will always return the current state at the moment you check it.
  21. CursorControl will be able to get cursor positions even if the mouse is outside the
  22. active Window, while the behavior of mouse-events for this is a bit system dependent
  23. and also can be influenced by system calls for mouse-grabbing.
  24. Events tend to work on more devices (especially mobile devices) where CursorControl might
  25. not be available. Also on some systems (X11) checking the mouse position with CursorControl
  26. can be rather slow compared to events.
  27. Often it depends a bit on the type of game which solution is preferable, just be aware
  28. that you have some choice for this.
  29. */
  30. class MyEventReceiver : public IEventReceiver
  31. {
  32. public:
  33. // We'll create a struct to record info on the mouse state
  34. struct SMouseState
  35. {
  36. core::position2di Position;
  37. bool LeftButtonDown;
  38. bool WasMouseMoved;
  39. SMouseState() : LeftButtonDown(false), WasMouseMoved(false) { }
  40. } MouseState;
  41. // This is the one method that we have to implement
  42. virtual bool OnEvent(const SEvent& event)
  43. {
  44. // Remember the mouse state
  45. if (event.EventType == irr::EET_MOUSE_INPUT_EVENT)
  46. {
  47. switch(event.MouseInput.Event)
  48. {
  49. case EMIE_LMOUSE_PRESSED_DOWN:
  50. MouseState.LeftButtonDown = true;
  51. break;
  52. case EMIE_LMOUSE_LEFT_UP:
  53. MouseState.LeftButtonDown = false;
  54. break;
  55. case EMIE_MOUSE_MOVED:
  56. MouseState.Position.X = event.MouseInput.X;
  57. MouseState.Position.Y = event.MouseInput.Y;
  58. MouseState.WasMouseMoved = true;
  59. break;
  60. default:
  61. // We won't use the wheel
  62. break;
  63. }
  64. }
  65. // The state of each connected joystick is sent to us
  66. // once every run() of the Irrlicht device. Store the
  67. // state of the first joystick, ignoring other joysticks.
  68. if (event.EventType == irr::EET_JOYSTICK_INPUT_EVENT
  69. && event.JoystickEvent.Joystick == 0)
  70. {
  71. JoystickState = event.JoystickEvent;
  72. }
  73. return false;
  74. }
  75. const SEvent::SJoystickEvent & GetJoystickState(void) const
  76. {
  77. return JoystickState;
  78. }
  79. const SMouseState & GetMouseState(void) const
  80. {
  81. return MouseState;
  82. }
  83. void ResetMouseMoved()
  84. {
  85. MouseState.WasMouseMoved = false;
  86. }
  87. private:
  88. SEvent::SJoystickEvent JoystickState;
  89. };
  90. /*
  91. The event receiver for remembering the events is ready, the actual responses
  92. will be made inside the render loop, right before drawing the scene. So lets
  93. just create an irr::IrrlichtDevice and the scene node we want to move.
  94. */
  95. int main()
  96. {
  97. // ask user for driver
  98. video::E_DRIVER_TYPE driverType=driverChoiceConsole();
  99. if (driverType==video::EDT_COUNT)
  100. return 1;
  101. // create device
  102. MyEventReceiver receiver;
  103. IrrlichtDevice* device = createDevice(driverType,
  104. core::dimension2d<u32>(640, 480), 16, false, false, false, &receiver);
  105. if (device == 0)
  106. return 1; // could not create selected driver.
  107. /*
  108. Joysticks have to be activated to generate events.
  109. So lets's do that and also print out some info to the console
  110. about all the joysticks we found and can use.
  111. */
  112. core::array<SJoystickInfo> joystickInfo;
  113. if(device->activateJoysticks(joystickInfo))
  114. {
  115. std::cout << "Joystick support is enabled and " << joystickInfo.size() << " joystick(s) are present." << std::endl;
  116. for(u32 joystick = 0; joystick < joystickInfo.size(); ++joystick)
  117. {
  118. std::cout << "Joystick " << joystick << ":" << std::endl;
  119. std::cout << "\tName: '" << joystickInfo[joystick].Name.c_str() << "'" << std::endl;
  120. std::cout << "\tAxes: " << joystickInfo[joystick].Axes << std::endl;
  121. std::cout << "\tButtons: " << joystickInfo[joystick].Buttons << std::endl;
  122. std::cout << "\tHat is: ";
  123. switch(joystickInfo[joystick].PovHat)
  124. {
  125. case SJoystickInfo::POV_HAT_PRESENT:
  126. std::cout << "present" << std::endl;
  127. break;
  128. case SJoystickInfo::POV_HAT_ABSENT:
  129. std::cout << "absent" << std::endl;
  130. break;
  131. case SJoystickInfo::POV_HAT_UNKNOWN:
  132. default:
  133. std::cout << "unknown" << std::endl;
  134. break;
  135. }
  136. }
  137. }
  138. else
  139. {
  140. std::cout << "Joystick support is not enabled." << std::endl;
  141. }
  142. // Set some window caption text
  143. core::stringw tmp = L"Irrlicht Joystick Example (";
  144. tmp += joystickInfo.size();
  145. tmp += " joysticks)";
  146. device->setWindowCaption(tmp.c_str());
  147. video::IVideoDriver* driver = device->getVideoDriver();
  148. scene::ISceneManager* smgr = device->getSceneManager();
  149. /*
  150. We'll create an arrow mesh and move it around either with the joystick axis/hat,
  151. or make it follow the mouse pointer. */
  152. scene::ISceneNode * node = smgr->addMeshSceneNode(
  153. smgr->addArrowMesh( "Arrow",
  154. video::SColor(255, 255, 0, 0),
  155. video::SColor(255, 0, 255, 0),
  156. 16,16,
  157. 2.f, 1.3f,
  158. 0.1f, 0.6f
  159. )
  160. );
  161. node->setMaterialFlag(video::EMF_LIGHTING, false);
  162. scene::ICameraSceneNode * camera = smgr->addCameraSceneNode();
  163. camera->setPosition(core::vector3df(0, 0, -10));
  164. // As in example 04, we'll use framerate independent movement.
  165. u32 then = device->getTimer()->getRealTime();
  166. const f32 MOVEMENT_SPEED = 5.f;
  167. // Ignore all events which happened until now.
  168. // Like mouse events triggered while we chose our driver.
  169. device->clearSystemMessages();
  170. while(device->run())
  171. {
  172. // Work out a frame delta time.
  173. const u32 now = device->getTimer()->getRealTime();
  174. const f32 frameDeltaTime = (f32)(now - then) / 1000.f; // Time in seconds
  175. then = now;
  176. bool movedWithJoystick = false;
  177. core::vector3df nodePosition = node->getPosition();
  178. if(joystickInfo.size() > 0) // if we have at least one joystick
  179. {
  180. f32 moveHorizontal = 0.f; // Range is -1.f for full left to +1.f for full right
  181. f32 moveVertical = 0.f; // -1.f for full down to +1.f for full up.
  182. const SEvent::SJoystickEvent & joystickData = receiver.GetJoystickState();
  183. // We receive the full analog range of the axes, and so have to implement our
  184. // own dead zone. This is an empirical value, since some joysticks have more
  185. // jitter or creep around the center point than others. We'll use 5% of the
  186. // range as the dead zone, but generally you would want to give the user the
  187. // option to change this.
  188. const f32 DEAD_ZONE = 0.05f;
  189. moveHorizontal =
  190. (f32)joystickData.Axis[SEvent::SJoystickEvent::AXIS_X] / 32767.f;
  191. if(fabs(moveHorizontal) < DEAD_ZONE)
  192. moveHorizontal = 0.f;
  193. moveVertical =
  194. (f32)joystickData.Axis[SEvent::SJoystickEvent::AXIS_Y] / -32767.f;
  195. if(fabs(moveVertical) < DEAD_ZONE)
  196. moveVertical = 0.f;
  197. // POV hat info is only currently supported on Windows, but the value is
  198. // guaranteed to be 65535 if it's not supported, so we can check its range.
  199. const u16 povDegrees = joystickData.POV / 100;
  200. if(povDegrees < 360)
  201. {
  202. if(povDegrees > 0 && povDegrees < 180)
  203. moveHorizontal = 1.f;
  204. else if(povDegrees > 180)
  205. moveHorizontal = -1.f;
  206. if(povDegrees > 90 && povDegrees < 270)
  207. moveVertical = -1.f;
  208. else if(povDegrees > 270 || povDegrees < 90)
  209. moveVertical = +1.f;
  210. }
  211. if(!core::equals(moveHorizontal, 0.f) || !core::equals(moveVertical, 0.f))
  212. {
  213. nodePosition.X += MOVEMENT_SPEED * frameDeltaTime * moveHorizontal;
  214. nodePosition.Y += MOVEMENT_SPEED * frameDeltaTime * moveVertical;
  215. movedWithJoystick = true;
  216. // We only go back to following mouse when it moves again
  217. receiver.ResetMouseMoved();
  218. }
  219. }
  220. // If the arrow node isn't being moved with the joystick, then have it follow the mouse cursor.
  221. if (!movedWithJoystick && receiver.GetMouseState().WasMouseMoved)
  222. {
  223. // Create a ray through the mouse cursor.
  224. core::line3df ray = smgr->getSceneCollisionManager()->getRayFromScreenCoordinates(
  225. receiver.GetMouseState().Position, camera);
  226. // And intersect the ray with a plane around the node facing towards the camera.
  227. core::plane3df plane(nodePosition, core::vector3df(0, 0, -1));
  228. core::vector3df mousePosition;
  229. if(plane.getIntersectionWithLine(ray.start, ray.getVector(), mousePosition))
  230. {
  231. // We now have a mouse position in 3d space; move towards it.
  232. core::vector3df toMousePosition(mousePosition - nodePosition);
  233. const f32 availableMovement = MOVEMENT_SPEED * frameDeltaTime;
  234. if(toMousePosition.getLength() <= availableMovement)
  235. {
  236. nodePosition = mousePosition; // Jump to the final position
  237. }
  238. else
  239. {
  240. nodePosition += toMousePosition.normalize() * availableMovement; // Move towards it
  241. }
  242. }
  243. }
  244. node->setPosition(nodePosition);
  245. // Turn lighting on and off depending on whether the left mouse button is down.
  246. node->setMaterialFlag(video::EMF_LIGHTING, receiver.GetMouseState().LeftButtonDown);
  247. driver->beginScene(video::ECBF_COLOR | video::ECBF_DEPTH, video::SColor(255,113,113,133));
  248. smgr->drawAll(); // draw the 3d scene
  249. driver->endScene();
  250. }
  251. /*
  252. In the end, delete the Irrlicht device.
  253. */
  254. device->drop();
  255. return 0;
  256. }
  257. /*
  258. **/