Input.cpp 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674
  1. //
  2. // Urho3D Engine
  3. // Copyright (c) 2008-2012 Lasse Öörni
  4. //
  5. // Permission is hereby granted, free of charge, to any person obtaining a copy
  6. // of this software and associated documentation files (the "Software"), to deal
  7. // in the Software without restriction, including without limitation the rights
  8. // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  9. // copies of the Software, and to permit persons to whom the Software is
  10. // furnished to do so, subject to the following conditions:
  11. //
  12. // The above copyright notice and this permission notice shall be included in
  13. // all copies or substantial portions of the Software.
  14. //
  15. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  16. // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  17. // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  18. // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  19. // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  20. // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
  21. // THE SOFTWARE.
  22. //
  23. #include "Context.h"
  24. #include "CoreEvents.h"
  25. #include "Graphics.h"
  26. #include "GraphicsEvents.h"
  27. #include "GraphicsImpl.h"
  28. #include "Input.h"
  29. #include "Log.h"
  30. #include "Mutex.h"
  31. #include "ProcessUtils.h"
  32. #include "Profiler.h"
  33. #include "StringUtils.h"
  34. #include <cstring>
  35. #include <SDL.h>
  36. #include "DebugNew.h"
  37. static HashMap<unsigned, Input*> inputInstances;
  38. /// Return the Input subsystem instance corresponding to an SDL window ID.
  39. Input* GetInputInstance(unsigned windowID)
  40. {
  41. #ifndef ANDROID
  42. return windowID ? inputInstances[windowID] : 0;
  43. #else
  44. // On Android we support only a single instance of Urho3D in the process, and the window ID can not be relied on.
  45. return inputInstances.Size() ? inputInstances.Begin()->second_ : 0;
  46. #endif
  47. }
  48. /// Convert SDL keycode if necessary
  49. int ConvertSDLKeyCode(int keySym, int scanCode)
  50. {
  51. if (scanCode == SDL_SCANCODE_AC_BACK)
  52. return KEY_ESC;
  53. else
  54. return SDL_toupper(keySym);
  55. }
  56. OBJECTTYPESTATIC(Input);
  57. Input::Input(Context* context) :
  58. Object(context),
  59. windowID_(0),
  60. toggleFullscreen_(true),
  61. active_(false),
  62. minimized_(false),
  63. activated_(false),
  64. suppressNextMouseMove_(false),
  65. initialized_(false)
  66. {
  67. // Zero the initial state
  68. mouseButtonDown_ = 0;
  69. ResetState();
  70. SubscribeToEvent(E_SCREENMODE, HANDLER(Input, HandleScreenMode));
  71. SubscribeToEvent(E_BEGINFRAME, HANDLER(Input, HandleBeginFrame));
  72. // Try to initialize right now, but skip if screen mode is not yet set
  73. Initialize();
  74. }
  75. Input::~Input()
  76. {
  77. // Remove input instance mapping
  78. if (initialized_)
  79. {
  80. MutexLock lock(GetStaticMutex());
  81. inputInstances.Erase(windowID_);
  82. }
  83. }
  84. void Input::Update()
  85. {
  86. PROFILE(UpdateInput);
  87. if (!graphics_ || !graphics_->IsInitialized())
  88. return;
  89. // Reset input accumulation for this frame
  90. keyPress_.Clear();
  91. mouseButtonPress_ = 0;
  92. mouseMove_ = IntVector2::ZERO;
  93. mouseMoveWheel_ = 0;
  94. // Reset touch delta movement
  95. for (Map<int, TouchState>::Iterator i = touches_.Begin(); i != touches_.End(); ++i)
  96. {
  97. TouchState& state = i->second_;
  98. state.lastPosition_ = state.position_;
  99. state.delta_ = IntVector2::ZERO;
  100. }
  101. {
  102. MutexLock lock(GetStaticMutex());
  103. // Pump SDL events
  104. SDL_Event evt;
  105. SDL_PumpEvents();
  106. while (SDL_PollEvent(&evt))
  107. {
  108. // Dispatch event to the appropriate Input instance. However SDL_QUIT can not at the moment be handled for multiple
  109. // instances properly (other threads' graphics devices can not be closed from this thread), so we handle it only
  110. // for own instance
  111. if (evt.type != SDL_QUIT)
  112. HandleSDLEvent(&evt);
  113. else
  114. graphics_->Close();
  115. }
  116. }
  117. // Check for activation and inactivation from SDL window flags. Must nullcheck the window pointer because it may have
  118. // been closed due to input events
  119. SDL_Window* window = graphics_->GetImpl()->GetWindow();
  120. if (window)
  121. {
  122. unsigned flags = SDL_GetWindowFlags(window) & (SDL_WINDOW_INPUT_FOCUS | SDL_WINDOW_MOUSE_FOCUS);
  123. if (!active_ && flags == (SDL_WINDOW_INPUT_FOCUS | SDL_WINDOW_MOUSE_FOCUS))
  124. activated_ = true;
  125. else if (active_ && (flags & SDL_WINDOW_INPUT_FOCUS) == 0)
  126. MakeInactive();
  127. }
  128. else
  129. return;
  130. // Activate input now if necessary
  131. if (activated_)
  132. MakeActive();
  133. // Check for mouse move
  134. if (active_)
  135. {
  136. IntVector2 mousePos = GetCursorPosition();
  137. mouseMove_ = mousePos - lastCursorPosition_;
  138. if (mouseMove_ != IntVector2::ZERO && suppressNextMouseMove_)
  139. {
  140. mouseMove_ = IntVector2::ZERO;
  141. suppressNextMouseMove_ = false;
  142. }
  143. if (!suppressNextMouseMove_)
  144. {
  145. // Recenter the mouse cursor manually
  146. IntVector2 center(graphics_->GetWidth() / 2, graphics_->GetHeight() / 2);
  147. SetCursorPosition(center);
  148. lastCursorPosition_ = center;
  149. }
  150. if (mouseMove_ != IntVector2::ZERO)
  151. {
  152. using namespace MouseMove;
  153. VariantMap eventData;
  154. eventData[P_DX] = mouseMove_.x_;
  155. eventData[P_DY] = mouseMove_.y_;
  156. eventData[P_BUTTONS] = mouseButtonDown_;
  157. eventData[P_QUALIFIERS] = GetQualifiers();
  158. SendEvent(E_MOUSEMOVE, eventData);
  159. }
  160. }
  161. }
  162. void Input::SetToggleFullscreen(bool enable)
  163. {
  164. toggleFullscreen_ = enable;
  165. }
  166. bool Input::GetKeyDown(int key) const
  167. {
  168. return keyDown_.Contains(key);
  169. }
  170. bool Input::GetKeyPress(int key) const
  171. {
  172. return keyPress_.Contains(key);
  173. }
  174. bool Input::GetMouseButtonDown(int button) const
  175. {
  176. return (mouseButtonDown_ & button) != 0;
  177. }
  178. bool Input::GetMouseButtonPress(int button) const
  179. {
  180. return (mouseButtonPress_ & button) != 0;
  181. }
  182. bool Input::GetQualifierDown(int qualifier) const
  183. {
  184. if (qualifier == QUAL_SHIFT)
  185. return GetKeyDown(KEY_LSHIFT) || GetKeyDown(KEY_RSHIFT);
  186. if (qualifier == QUAL_CTRL)
  187. return GetKeyDown(KEY_LCTRL) || GetKeyDown(KEY_RCTRL);
  188. if (qualifier == QUAL_ALT)
  189. return GetKeyDown(KEY_LALT) || GetKeyDown(KEY_RALT);
  190. return false;
  191. }
  192. bool Input::GetQualifierPress(int qualifier) const
  193. {
  194. if (qualifier == QUAL_SHIFT)
  195. return GetKeyPress(KEY_LSHIFT) || GetKeyPress(KEY_RSHIFT);
  196. if (qualifier == QUAL_CTRL)
  197. return GetKeyPress(KEY_LCTRL) || GetKeyPress(KEY_RCTRL);
  198. if (qualifier == QUAL_ALT)
  199. return GetKeyPress(KEY_LALT) || GetKeyPress(KEY_RALT);
  200. return false;
  201. }
  202. int Input::GetQualifiers() const
  203. {
  204. int ret = 0;
  205. if (GetQualifierDown(QUAL_SHIFT))
  206. ret |= QUAL_SHIFT;
  207. if (GetQualifierDown(QUAL_CTRL))
  208. ret |= QUAL_CTRL;
  209. if (GetQualifierDown(QUAL_ALT))
  210. ret |= QUAL_ALT;
  211. return ret;
  212. }
  213. TouchState Input::GetTouch(unsigned index) const
  214. {
  215. unsigned cmpIndex = 0;
  216. for (Map<int, TouchState>::ConstIterator i = touches_.Begin(); i != touches_.End(); ++i)
  217. {
  218. /// \todo Do not make a value copy
  219. if (cmpIndex == index)
  220. return i->second_;
  221. else
  222. ++cmpIndex;
  223. }
  224. return TouchState();
  225. }
  226. bool Input::IsMinimized() const
  227. {
  228. // Return minimized state also when inactive in fullscreen
  229. if (!active_ && graphics_ && graphics_->GetFullscreen())
  230. return true;
  231. else
  232. return minimized_;
  233. }
  234. void Input::Initialize()
  235. {
  236. Graphics* graphics = GetSubsystem<Graphics>();
  237. if (!graphics || !graphics->IsInitialized())
  238. return;
  239. graphics_ = graphics;
  240. // Set the initial activation
  241. activated_ = true;
  242. initialized_ = true;
  243. {
  244. MutexLock lock(GetStaticMutex());
  245. // Store window ID to direct SDL events to the correct instance
  246. windowID_ = SDL_GetWindowID(graphics_->GetImpl()->GetWindow());
  247. inputInstances[windowID_] = this;
  248. }
  249. LOGINFO("Initialized input");
  250. }
  251. void Input::MakeActive()
  252. {
  253. if (!graphics_ || !graphics_->IsInitialized())
  254. return;
  255. ResetState();
  256. active_ = true;
  257. activated_ = false;
  258. // Re-establish mouse cursor hiding as necessary
  259. SDL_ShowCursor(SDL_FALSE);
  260. suppressNextMouseMove_ = true;
  261. using namespace Activation;
  262. VariantMap eventData;
  263. eventData[P_ACTIVE] = active_;
  264. eventData[P_MINIMIZED] = minimized_;
  265. SendEvent(E_ACTIVATION, eventData);
  266. }
  267. void Input::MakeInactive()
  268. {
  269. if (!graphics_ || !graphics_->IsInitialized())
  270. return;
  271. ResetState();
  272. active_ = false;
  273. activated_ = false;
  274. // Show the mouse cursor when inactive
  275. SDL_ShowCursor(SDL_TRUE);
  276. using namespace Activation;
  277. VariantMap eventData;
  278. eventData[P_ACTIVE] = active_;
  279. eventData[P_MINIMIZED] = minimized_;
  280. SendEvent(E_ACTIVATION, eventData);
  281. }
  282. void Input::ResetState()
  283. {
  284. keyDown_.Clear();
  285. keyPress_.Clear();
  286. // When clearing touch states, send the corresponding touch end events
  287. for (Map<int, TouchState>::Iterator i = touches_.Begin(); i != touches_.End(); ++i)
  288. {
  289. TouchState& state = i->second_;
  290. using namespace TouchEnd;
  291. VariantMap eventData;
  292. eventData[P_TOUCHID] = state.touchID_;
  293. eventData[P_X] = state.position_.x_;
  294. eventData[P_Y] = state.position_.y_;
  295. SendEvent(E_TOUCHEND, eventData);
  296. }
  297. // Use SetMouseButton() to reset the state so that mouse events will be sent properly
  298. SetMouseButton(MOUSEB_LEFT, false);
  299. SetMouseButton(MOUSEB_RIGHT, false);
  300. SetMouseButton(MOUSEB_MIDDLE, false);
  301. mouseMove_ = IntVector2::ZERO;
  302. mouseMoveWheel_ = 0;
  303. mouseButtonPress_ = 0;
  304. }
  305. void Input::SetMouseButton(int button, bool newState)
  306. {
  307. // If we are not active yet, do not react to the mouse button down
  308. if (newState && !active_)
  309. return;
  310. if (newState)
  311. {
  312. if (!(mouseButtonDown_ & button))
  313. mouseButtonPress_ |= button;
  314. mouseButtonDown_ |= button;
  315. }
  316. else
  317. {
  318. if (!(mouseButtonDown_ & button))
  319. return;
  320. mouseButtonDown_ &= ~button;
  321. }
  322. using namespace MouseButtonDown;
  323. VariantMap eventData;
  324. eventData[P_BUTTON] = button;
  325. eventData[P_BUTTONS] = mouseButtonDown_;
  326. eventData[P_QUALIFIERS] = GetQualifiers();
  327. SendEvent(newState ? E_MOUSEBUTTONDOWN : E_MOUSEBUTTONUP, eventData);
  328. }
  329. void Input::SetKey(int key, bool newState)
  330. {
  331. // If we are not active yet, do not react to the key down
  332. if (newState && !active_)
  333. return;
  334. bool repeat = false;
  335. if (newState)
  336. {
  337. if (!keyDown_.Contains(key))
  338. {
  339. keyDown_.Insert(key);
  340. keyPress_.Insert(key);
  341. }
  342. else
  343. repeat = true;
  344. }
  345. else
  346. {
  347. if (!keyDown_.Erase(key))
  348. return;
  349. }
  350. using namespace KeyDown;
  351. VariantMap eventData;
  352. eventData[P_KEY] = key;
  353. eventData[P_BUTTONS] = mouseButtonDown_;
  354. eventData[P_QUALIFIERS] = GetQualifiers();
  355. if (newState)
  356. eventData[P_REPEAT] = repeat;
  357. SendEvent(newState ? E_KEYDOWN : E_KEYUP, eventData);
  358. if (key == KEY_RETURN && newState && !repeat && toggleFullscreen_ && (GetKeyDown(KEY_LALT) || GetKeyDown(KEY_RALT)))
  359. graphics_->ToggleFullscreen();
  360. }
  361. void Input::SetMouseWheel(int delta)
  362. {
  363. // If we are not active yet, do not react to the wheel
  364. if (!active_)
  365. return;
  366. if (delta)
  367. {
  368. mouseMoveWheel_ += delta;
  369. using namespace MouseWheel;
  370. VariantMap eventData;
  371. eventData[P_WHEEL] = delta;
  372. eventData[P_BUTTONS] = mouseButtonDown_;
  373. eventData[P_QUALIFIERS] = GetQualifiers();
  374. SendEvent(E_MOUSEWHEEL, eventData);
  375. }
  376. }
  377. void Input::SetCursorPosition(const IntVector2& position)
  378. {
  379. if (!graphics_)
  380. return;
  381. SDL_WarpMouseInWindow(graphics_->GetImpl()->GetWindow(), position.x_, position.y_);
  382. }
  383. IntVector2 Input::GetCursorPosition() const
  384. {
  385. IntVector2 ret = lastCursorPosition_;
  386. if (!graphics_ || !graphics_->IsInitialized())
  387. return ret;
  388. SDL_GetMouseState(&ret.x_, &ret.y_);
  389. return ret;
  390. }
  391. void Input::HandleSDLEvent(void* sdlEvent)
  392. {
  393. SDL_Event& evt = *static_cast<SDL_Event*>(sdlEvent);
  394. Input* input = 0;
  395. switch (evt.type)
  396. {
  397. case SDL_KEYDOWN:
  398. // Convert to uppercase to match Win32 virtual key codes
  399. input = GetInputInstance(evt.key.windowID);
  400. if (input)
  401. input->SetKey(ConvertSDLKeyCode(evt.key.keysym.sym, evt.key.keysym.scancode), true);
  402. break;
  403. case SDL_KEYUP:
  404. input = GetInputInstance(evt.key.windowID);
  405. if (input)
  406. input->SetKey(ConvertSDLKeyCode(evt.key.keysym.sym, evt.key.keysym.scancode), false);
  407. break;
  408. case SDL_TEXTINPUT:
  409. input = GetInputInstance(evt.text.windowID);
  410. if (input && evt.text.text[0])
  411. {
  412. String text(&evt.text.text[0]);
  413. unsigned unicode = text.AtUTF8(0);
  414. if (unicode)
  415. {
  416. using namespace Char;
  417. VariantMap keyEventData;
  418. keyEventData[P_CHAR] = unicode;
  419. keyEventData[P_BUTTONS] = input->mouseButtonDown_;
  420. keyEventData[P_QUALIFIERS] = input->GetQualifiers();
  421. input->SendEvent(E_CHAR, keyEventData);
  422. }
  423. }
  424. break;
  425. case SDL_MOUSEBUTTONDOWN:
  426. input = GetInputInstance(evt.button.windowID);
  427. if (input)
  428. input->SetMouseButton(1 << (evt.button.button - 1), true);
  429. break;
  430. case SDL_MOUSEBUTTONUP:
  431. input = GetInputInstance(evt.button.windowID);
  432. if (input)
  433. input->SetMouseButton(1 << (evt.button.button - 1), false);
  434. break;
  435. case SDL_MOUSEWHEEL:
  436. input = GetInputInstance(evt.wheel.windowID);
  437. if (input)
  438. input->SetMouseWheel(evt.wheel.y);
  439. break;
  440. case SDL_FINGERDOWN:
  441. input = GetInputInstance(evt.tfinger.windowID);
  442. if (input)
  443. {
  444. int touchID = evt.tfinger.fingerId & 0x7ffffff;
  445. TouchState& state = input->touches_[touchID];
  446. state.touchID_ = touchID;
  447. state.lastPosition_ = state.position_ = IntVector2(evt.tfinger.x * input->graphics_->GetWidth() / 32768,
  448. evt.tfinger.y * input->graphics_->GetHeight() / 32768);
  449. state.delta_ = IntVector2::ZERO;
  450. state.pressure_ = evt.tfinger.pressure;
  451. using namespace TouchBegin;
  452. VariantMap eventData;
  453. eventData[P_TOUCHID] = touchID;
  454. eventData[P_X] = state.position_.x_;
  455. eventData[P_Y] = state.position_.y_;
  456. eventData[P_PRESSURE] = state.pressure_;
  457. input->SendEvent(E_TOUCHBEGIN, eventData);
  458. }
  459. break;
  460. case SDL_FINGERUP:
  461. input = GetInputInstance(evt.tfinger.windowID);
  462. if (input)
  463. {
  464. int touchID = evt.tfinger.fingerId & 0x7ffffff;
  465. input->touches_.Erase(touchID);
  466. using namespace TouchEnd;
  467. VariantMap eventData;
  468. eventData[P_TOUCHID] = touchID;
  469. eventData[P_X] = evt.tfinger.x * input->graphics_->GetWidth() / 32768;
  470. eventData[P_Y] = evt.tfinger.y * input->graphics_->GetHeight() / 32768;
  471. input->SendEvent(E_TOUCHEND, eventData);
  472. }
  473. break;
  474. case SDL_FINGERMOTION:
  475. input = GetInputInstance(evt.tfinger.windowID);
  476. if (input)
  477. {
  478. int touchID = evt.tfinger.fingerId & 0x7ffffff;
  479. TouchState& state = input->touches_[touchID];
  480. state.touchID_ = touchID;
  481. state.position_ = IntVector2(evt.tfinger.x * input->graphics_->GetWidth() / 32768,
  482. evt.tfinger.y * input->graphics_->GetHeight() / 32768);
  483. state.delta_ = state.position_ - state.lastPosition_;
  484. state.pressure_ = evt.tfinger.pressure;
  485. using namespace TouchMove;
  486. VariantMap eventData;
  487. eventData[P_TOUCHID] = touchID;
  488. eventData[P_X] = state.position_.x_;
  489. eventData[P_Y] = state.position_.y_;
  490. eventData[P_DX] = evt.tfinger.dx * input->graphics_->GetWidth() / 32768;
  491. eventData[P_DY] = evt.tfinger.dy * input->graphics_->GetHeight() / 32768;
  492. eventData[P_PRESSURE] = state.pressure_;
  493. input->SendEvent(E_TOUCHMOVE, eventData);
  494. }
  495. break;
  496. case SDL_WINDOWEVENT:
  497. input = GetInputInstance(evt.window.windowID);
  498. if (input)
  499. {
  500. switch (evt.window.event)
  501. {
  502. case SDL_WINDOWEVENT_CLOSE:
  503. input->GetSubsystem<Graphics>()->Close();
  504. break;
  505. case SDL_WINDOWEVENT_MINIMIZED:
  506. input->minimized_ = true;
  507. break;
  508. case SDL_WINDOWEVENT_RESTORED:
  509. input->minimized_ = false;
  510. break;
  511. #ifdef ANDROID
  512. case SDL_WINDOWEVENT_SURFACE_LOST:
  513. // Mark GPU objects lost
  514. input->graphics_->Release(false, false);
  515. break;
  516. case SDL_WINDOWEVENT_SURFACE_CREATED:
  517. // Restore GPU objects
  518. input->graphics_->Restore();
  519. break;
  520. #endif
  521. }
  522. }
  523. break;
  524. }
  525. }
  526. void Input::HandleScreenMode(StringHash eventType, VariantMap& eventData)
  527. {
  528. // Reset input state on subsequent initializations
  529. if (!initialized_)
  530. Initialize();
  531. else
  532. ResetState();
  533. // Re-enable cursor clipping, and re-center the cursor (if needed) to the new screen size, so that there is no erroneous
  534. // mouse move event. Also get the new window ID in case it changed
  535. unsigned newWindowID = SDL_GetWindowID(graphics_->GetImpl()->GetWindow());
  536. if (newWindowID != windowID_)
  537. {
  538. MutexLock lock(GetStaticMutex());
  539. inputInstances.Erase(windowID_);
  540. inputInstances[newWindowID] = this;
  541. windowID_ = newWindowID;
  542. }
  543. IntVector2 center(graphics_->GetWidth() / 2, graphics_->GetHeight() / 2);
  544. SetCursorPosition(center);
  545. lastCursorPosition_ = center;
  546. activated_ = true;
  547. // After setting new screen mode we never should be minimized
  548. minimized_ = false;
  549. }
  550. void Input::HandleBeginFrame(StringHash eventType, VariantMap& eventData)
  551. {
  552. // Update input right at the beginning of the frame
  553. if (initialized_)
  554. Update();
  555. }