Planet
navi homePPSaboutscreenshotsdownloaddevelopmentforum

source: code/branches/network/src/core/InputManager.cc @ 1446

Last change on this file since 1446 was 1446, checked in by landauf, 16 years ago

merged console branch into network branch

after several heavy troubles it compiles, but there is still a bug I couldn't fix: orxonox crashes as soon as one presses a key after opening the console… maybe someone else sees the problem?

File size: 49.1 KB
Line 
1/*
2 *   ORXONOX - the hottest 3D action shooter ever to exist
3 *                    > www.orxonox.net <
4 *
5 *
6 *   License notice:
7 *
8 *   This program is free software; you can redistribute it and/or
9 *   modify it under the terms of the GNU General Public License
10 *   as published by the Free Software Foundation; either version 2
11 *   of the License, or (at your option) any later version.
12 *
13 *   This program is distributed in the hope that it will be useful,
14 *   but WITHOUT ANY WARRANTY; without even the implied warranty of
15 *   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
16 *   GNU General Public License for more details.
17 *
18 *   You should have received a copy of the GNU General Public License
19 *   along with this program; if not, write to the Free Software
20 *   Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.
21 *
22 *   Author:
23 *      Reto Grieder
24 *   Co-authors:
25 *      ...
26 *
27 */
28
29/**
30  @file
31  @brief Implementation of the InputManager that captures all the input from OIS
32         and redirects it to handlers.
33 */
34
35#include "InputManager.h"
36#include "util/Convert.h"
37#include "CoreIncludes.h"
38#include "ConfigValueIncludes.h"
39#include "Debug.h"
40#include "InputBuffer.h"
41#include "KeyBinder.h"
42#include "CommandExecutor.h"
43#include "ConsoleCommand.h"
44#include "Shell.h"
45
46namespace orxonox
47{
48  SetConsoleCommandShortcut(InputManager, keyBind);
49  SetConsoleCommandShortcut(InputManager, storeKeyStroke);
50  SetConsoleCommandShortcut(InputManager, calibrate);
51
52  // ###############################
53  // ###    Internal Methods     ###
54  // ###############################
55  // ###############################
56
57  /**
58    @brief Constructor only sets member fields to initial zero values
59           and registers the class in the class hierarchy.
60  */
61  InputManager::InputManager() :
62      inputSystem_(0), keyboard_(0), mouse_(0),
63      joySticksSize_(0),
64      keyBinder_(0), keyDetector_(0), buffer_(0), calibratorCallback_(0),
65      state_(IS_UNINIT), stateRequest_(IS_UNINIT), savedState_(IS_UNINIT),
66      keyboardModifiers_(0)
67  {
68    RegisterObject(InputManager);
69  }
70
71  /**
72    @brief The one instance of the InputManager is stored in this function.
73    @return A reference to the only instance of the InputManager
74  */
75  InputManager& InputManager::_getSingleton()
76  {
77    static InputManager theOnlyInstance;
78    return theOnlyInstance;
79  }
80
81  /**
82    @brief Destructor only called at the end of the program, after main.
83  */
84  InputManager::~InputManager()
85  {
86    _destroy();
87  }
88
89  /**
90    @brief Creates the OIS::InputMananger, the keyboard, the mouse and
91           the joysticks and assigns the key bindings.
92    @param windowHnd The window handle of the render window
93    @param windowWidth The width of the render window
94    @param windowHeight The height of the render window
95  */
96  bool InputManager::_initialise(const size_t windowHnd, int windowWidth, int windowHeight,
97        bool createKeyboard, bool createMouse, bool createJoySticks)
98  {
99    if (state_ == IS_UNINIT)
100    {
101      CCOUT(3) << "Initialising Input System..." << std::endl;
102      CCOUT(ORX_DEBUG) << "Initialising OIS components..." << std::endl;
103
104      OIS::ParamList paramList;
105      std::ostringstream windowHndStr;
106
107      // Fill parameter list
108      windowHndStr << (unsigned int)windowHnd;
109      paramList.insert(std::make_pair(std::string("WINDOW"), windowHndStr.str()));
110      //paramList.insert(std::make_pair(std::string("w32_mouse"), std::string("DISCL_NONEXCLUSIVE")));
111      //paramList.insert(std::make_pair(std::string("w32_mouse"), std::string("DISCL_FOREGROUND")));
112//#if defined OIS_LINUX_PLATFORM
113//      paramList.insert(std::make_pair(std::string("XAutoRepeatOn"), std::string("true")));
114//#endif
115
116      try
117      {
118        inputSystem_ = OIS::InputManager::createInputSystem(paramList);
119        CCOUT(ORX_DEBUG) << "Created OIS input system" << std::endl;
120      }
121      catch (OIS::Exception ex)
122      {
123        CCOUT(ORX_ERROR) << "Error: Failed creating an OIS input system."
124            << "OIS message: \"" << ex.eText << "\"" << std::endl;
125        inputSystem_ = 0;
126        return false;
127      }
128
129      if (createKeyboard)
130        _initialiseKeyboard();
131
132      if (createMouse)
133        _initialiseMouse();
134
135      if (createJoySticks)
136        _initialiseJoySticks();
137
138      // Set mouse/joystick region
139      if (mouse_)
140      {
141        //// hack the mouse position
142        //((OIS::MouseState&)mouse_->getMouseState()).X.abs = windowWidth/2;
143        //((OIS::MouseState&)mouse_->getMouseState()).Y.abs = windowHeight/2;
144        setWindowExtents(windowWidth, windowHeight);
145      }
146
147      state_ = IS_NONE;
148      CCOUT(ORX_DEBUG) << "Initialising OIS components done." << std::endl;
149
150      // InputManager holds the input buffer --> create one and add it.
151      buffer_ = new InputBuffer();
152      addKeyHandler(buffer_, "buffer");
153      Shell::getInstance().setInputBuffer(buffer_);
154
155      keyBinder_ = new KeyBinder();
156      keyBinder_->loadBindings();
157      addKeyHandler(keyBinder_, "keybinder");
158      addMouseHandler(keyBinder_, "keybinder");
159      addJoyStickHandler(keyBinder_, "keybinder");
160
161      keyDetector_ = new KeyDetector();
162      keyDetector_->loadBindings();
163      addKeyHandler(keyDetector_, "keydetector");
164      addMouseHandler(keyDetector_, "keydetector");
165      addJoyStickHandler(keyDetector_, "keydetector");
166
167      calibratorCallback_ = new CalibratorCallback();
168      addKeyHandler(calibratorCallback_, "calibratorcallback");
169
170      setConfigValues();
171
172      CCOUT(ORX_DEBUG) << "Initialising complete." << std::endl;
173    }
174    else
175    {
176      CCOUT(ORX_WARNING) << "Warning: OIS compoments already initialised, skipping" << std::endl;
177    }
178    return true;
179  }
180
181  /**
182    @brief Creates a keyboard and sets the event handler.
183    @return False if keyboard stays uninitialised, true otherwise.
184  */
185  bool InputManager::_initialiseKeyboard()
186  {
187    if (keyboard_ != 0)
188    {
189      CCOUT(2) << "Warning: Keyboard already initialised, skipping." << std::endl;
190      return true;
191    }
192    try
193    {
194      if (inputSystem_->getNumberOfDevices(OIS::OISKeyboard) > 0)
195      {
196        keyboard_ = (OIS::Keyboard*)inputSystem_->createInputObject(OIS::OISKeyboard, true);
197        // register our listener in OIS.
198        keyboard_->setEventCallback(this);
199        // note: OIS will not detect keys that have already been down when the keyboard was created.
200        CCOUT(ORX_DEBUG) << "Created OIS keyboard" << std::endl;
201        return true;
202      }
203      else
204      {
205        CCOUT(ORX_WARNING) << "Warning: No keyboard found!" << std::endl;
206        return false;
207      }
208    }
209    catch (OIS::Exception ex)
210    {
211      // TODO: Test this output regarding formatting
212      CCOUT(ORX_WARNING) << "Warning: Failed to create an OIS keyboard\n"
213          << "OIS error message: \"" << ex.eText << "\"" << std::endl;
214      keyboard_ = 0;
215      return false;
216    }
217  }
218
219  /**
220    @brief Creates a mouse and sets the event handler.
221    @return False if mouse stays uninitialised, true otherwise.
222  */
223  bool InputManager::_initialiseMouse()
224  {
225    if (mouse_ != 0)
226    {
227      CCOUT(2) << "Warning: Mouse already initialised, skipping." << std::endl;
228      return true;
229    }
230    try
231    {
232      if (inputSystem_->getNumberOfDevices(OIS::OISMouse) > 0)
233      {
234        mouse_ = static_cast<OIS::Mouse*>(inputSystem_->createInputObject(OIS::OISMouse, true));
235        // register our listener in OIS.
236        mouse_->setEventCallback(this);
237        CCOUT(ORX_DEBUG) << "Created OIS mouse" << std::endl;
238        return true;
239      }
240      else
241      {
242        CCOUT(ORX_WARNING) << "Warning: No mouse found!" << std::endl;
243        return false;
244      }
245    }
246    catch (OIS::Exception ex)
247    {
248      CCOUT(ORX_WARNING) << "Warning: Failed to create an OIS mouse\n"
249          << "OIS error message: \"" << ex.eText << "\"" << std::endl;
250      mouse_ = 0;
251      return false;
252    }
253  }
254
255  /**
256    @brief Creates all joy sticks and sets the event handler.
257    @return False joy stick stay uninitialised, true otherwise.
258  */
259  bool InputManager::_initialiseJoySticks()
260  {
261    if (joySticksSize_ > 0)
262    {
263      CCOUT(2) << "Warning: Joy sticks already initialised, skipping." << std::endl;
264      return true;
265    }
266    bool success = false;
267    if (inputSystem_->getNumberOfDevices(OIS::OISJoyStick) > 0)
268    {
269      for (int i = 0; i < inputSystem_->getNumberOfDevices(OIS::OISJoyStick); i++)
270      {
271        try
272        {
273          OIS::JoyStick* stig = static_cast<OIS::JoyStick*>(inputSystem_->createInputObject(OIS::OISJoyStick, true));
274          joySticks_.push_back(stig);
275          // register our listener in OIS.
276          stig->setEventCallback(this);
277          CCOUT(ORX_DEBUG) << "Created OIS joy stick with ID " << stig->getID() << std::endl;
278          success = true;
279        }
280        catch (OIS::Exception ex)
281        {
282          CCOUT(ORX_WARNING) << "Warning: Failed to create OIS joy number" << i << "\n"
283              << "OIS error message: \"" << ex.eText << "\"" << std::endl;
284        }
285      }
286    }
287    else
288    {
289      CCOUT(ORX_WARNING) << "Warning: Joy stick support requested, but no joy stick was found" << std::endl;
290      return false;
291    }
292    joySticksSize_ = joySticks_.size();
293    activeJoyStickHandlers_.resize(joySticksSize_);
294    joyStickButtonsDown_.resize(joySticksSize_);
295    povStates_.resize(joySticksSize_);
296    sliderStates_.resize(joySticksSize_);
297    joySticksCalibration_.resize(joySticksSize_);
298    for (unsigned int iJoyStick = 0; iJoyStick < joySticksSize_; iJoyStick++)
299    {
300      // reset the calibration with default values
301      for (unsigned int i = 0; i < 24; i++)
302      {
303        joySticksCalibration_[iJoyStick].negativeCoeff[i] = 1.0f/32767.0f;
304        joySticksCalibration_[iJoyStick].positiveCoeff[i] = 1.0f/32768.0f;
305        joySticksCalibration_[iJoyStick].zeroStates[i] = 0;
306      }
307    }
308    return success;
309  }
310
311  /**
312    @brief Sets the configurable values. Use keybindings.ini as file..
313  */
314  void InputManager::setConfigValues()
315  {
316    if (joySticksSize_)
317    {
318      std::vector<MultiTypeMath> coeffPos;
319      std::vector<MultiTypeMath> coeffNeg;
320      std::vector<MultiTypeMath> zero;
321      coeffPos.resize(24);
322      coeffNeg.resize(24);
323      zero.resize(24);
324      for (unsigned int i = 0; i < 24; i++)
325      {
326        coeffPos[i] =  1.0f/32767.0f;
327        coeffNeg[i] =  1.0f/32768.0f;
328        zero[i]     =  0;
329      }
330
331      ConfigValueContainer* cont = getIdentifier()->getConfigValueContainer("CoeffPos");
332      if (!cont)
333      {
334          cont = new ConfigValueContainer(CFT_Keybindings, getIdentifier(), "CoeffPos", coeffPos);
335          getIdentifier()->addConfigValueContainer("CoeffPos", cont);
336      }
337      cont->getValue(&coeffPos);
338
339      cont = getIdentifier()->getConfigValueContainer("CoeffNeg");
340      if (!cont)
341      {
342          cont = new ConfigValueContainer(CFT_Keybindings, getIdentifier(), "CoeffNeg", coeffNeg);
343          getIdentifier()->addConfigValueContainer("CoeffNeg", cont);
344      }
345      cont->getValue(&coeffNeg);
346
347      cont = getIdentifier()->getConfigValueContainer("Zero");
348      if (!cont)
349      {
350          cont = new ConfigValueContainer(CFT_Keybindings, getIdentifier(), "Zero", zero);
351          getIdentifier()->addConfigValueContainer("Zero", cont);
352      }
353      cont->getValue(&zero);
354
355      // copy values to our own variables
356      for (unsigned int i = 0; i < 24; i++)
357      {
358        joySticksCalibration_[0].positiveCoeff[i] = coeffPos[i];
359        joySticksCalibration_[0].negativeCoeff[i] = coeffNeg[i];
360        joySticksCalibration_[0].zeroStates[i]    = zero[i];
361      }
362    }
363  }
364
365  /**
366    @brief Destroys all the created input devices and sets the InputManager to construction state.
367  */
368  void InputManager::_destroy()
369  {
370    if (state_ != IS_UNINIT)
371    {
372      CCOUT(ORX_DEBUG) << "Destroying ..." << std::endl;
373
374      if (buffer_)
375        delete buffer_;
376
377      if (keyBinder_)
378        delete keyBinder_;
379
380      if (keyDetector_)
381        delete keyDetector_;
382
383      if (calibratorCallback_)
384        delete calibratorCallback_;
385
386      keyHandlers_.clear();
387      mouseHandlers_.clear();
388      joyStickHandlers_.clear();
389
390      _destroyKeyboard();
391      _destroyMouse();
392      _destroyJoySticks();
393
394      activeHandlers_.clear();
395
396      // inputSystem_ can never be 0, or else the code is mistaken
397      OIS::InputManager::destroyInputSystem(inputSystem_);
398      inputSystem_ = 0;
399
400      state_ = IS_UNINIT;
401      CCOUT(ORX_DEBUG) << "Destroying done." << std::endl;
402    }
403  }
404
405  /**
406    @brief Destroys the keyboard and sets it to 0.
407  */
408  void InputManager::_destroyKeyboard()
409  {
410    if (keyboard_)
411      // inputSystem_ can never be 0, or else the code is mistaken
412      inputSystem_->destroyInputObject(keyboard_);
413    keyboard_ = 0;
414    activeKeyHandlers_.clear();
415    keysDown_.clear();
416    CCOUT(ORX_DEBUG) << "Keyboard destroyed." << std::endl;
417  }
418
419  /**
420    @brief Destroys the mouse and sets it to 0.
421  */
422  void InputManager::_destroyMouse()
423  {
424    if (mouse_)
425      // inputSystem_ can never be 0, or else the code is mistaken
426      inputSystem_->destroyInputObject(mouse_);
427    mouse_ = 0;
428    activeMouseHandlers_.clear();
429    mouseButtonsDown_.clear();
430    CCOUT(ORX_DEBUG) << "Mouse destroyed." << std::endl;
431  }
432
433  /**
434    @brief Destroys all the joy sticks and resizes the lists to 0.
435  */
436  void InputManager::_destroyJoySticks()
437  {
438    if (joySticksSize_ > 0)
439    {
440      // note: inputSystem_ can never be 0, or else the code is mistaken
441      for (unsigned int i = 0; i < joySticksSize_; i++)
442        if (joySticks_[i] != 0)
443          inputSystem_->destroyInputObject(joySticks_[i]);
444
445      joySticks_.clear();
446      joySticksSize_ = 0;
447      activeJoyStickHandlers_.clear();
448      joyStickButtonsDown_.clear();
449      povStates_.clear();
450      sliderStates_.clear();
451      joySticksCalibration_.clear();
452    }
453    CCOUT(ORX_DEBUG) << "Joy sticks destroyed." << std::endl;
454  }
455
456  void InputManager::_saveState()
457  {
458    savedHandlers_.activeHandlers_ = activeHandlers_;
459    savedHandlers_.activeJoyStickHandlers_ = activeJoyStickHandlers_;
460    savedHandlers_.activeKeyHandlers_ = activeKeyHandlers_;
461    savedHandlers_.activeMouseHandlers_ = activeMouseHandlers_;
462  }
463
464  void InputManager::_restoreState()
465  {
466    activeHandlers_ = savedHandlers_.activeHandlers_;
467    activeJoyStickHandlers_ = savedHandlers_.activeJoyStickHandlers_;
468    activeKeyHandlers_ = savedHandlers_.activeKeyHandlers_;
469    activeMouseHandlers_ = savedHandlers_.activeMouseHandlers_;
470  }
471
472  void InputManager::_updateTickables()
473  {
474    // we can use a map to have a list of unique pointers (an object can implement all 3 handlers)
475    std::map<InputTickable*, HandlerState> tempSet;
476    for (unsigned int iHandler = 0; iHandler < activeKeyHandlers_.size(); iHandler++)
477      tempSet[activeKeyHandlers_[iHandler]].joyStick = true;
478    for (unsigned int iHandler = 0; iHandler < activeMouseHandlers_.size(); iHandler++)
479      tempSet[activeMouseHandlers_[iHandler]].mouse = true;
480    for (unsigned int iJoyStick  = 0; iJoyStick < joySticksSize_; iJoyStick++)
481      for (unsigned int iHandler = 0; iHandler  < activeJoyStickHandlers_[iJoyStick].size(); iHandler++)
482        tempSet[activeJoyStickHandlers_[iJoyStick][iHandler]].joyStick = true;
483
484    // copy the content of the map back to the actual vector
485    activeHandlers_.clear();
486    for (std::map<InputTickable*, HandlerState>::const_iterator itHandler = tempSet.begin();
487        itHandler != tempSet.end(); itHandler++)
488      activeHandlers_.push_back(std::pair<InputTickable*, HandlerState>((*itHandler).first, (*itHandler).second));
489  }
490
491
492  // #################################
493  // ### Private Interface Methods ###
494  // #################################
495  // #################################
496
497  /**
498    @brief Updates the InputManager. Tick is called by Orxonox.
499    @param dt Delta time
500  */
501  void InputManager::tick(float dt)
502  {
503    if (state_ == IS_UNINIT)
504      return;
505
506    if (state_ != stateRequest_)
507    {
508      InputState sr = stateRequest_;
509      switch (sr)
510      {
511      case IS_NORMAL:
512        activeKeyHandlers_.clear();
513        activeMouseHandlers_.clear();
514        for (unsigned int i = 0; i < joySticksSize_; i++)
515          activeJoyStickHandlers_[i].clear();
516
517        // normal play mode
518        // note: we assume that the handlers exist since otherwise, something's wrong anyway.
519        enableKeyHandler("keybinder");
520        enableMouseHandler("keybinder");
521        enableJoyStickHandler("keybinder", 0);
522        stateRequest_ = IS_NORMAL;
523        state_ = IS_NORMAL;
524        break;
525
526      case IS_GUI:
527        state_ = IS_GUI;
528        break;
529
530      case IS_CONSOLE:
531        activeKeyHandlers_.clear();
532        activeMouseHandlers_.clear();
533        for (unsigned int i = 0; i < joySticksSize_; i++)
534          activeJoyStickHandlers_[i].clear();
535
536        enableMouseHandler("keybinder");
537        enableJoyStickHandler("keybinder", 0);
538        enableKeyHandler("buffer");
539        stateRequest_ = IS_CONSOLE;
540        state_ = IS_CONSOLE;
541        break;
542
543      case IS_DETECT:
544        savedState_ = state_;
545        _saveState();
546
547        activeKeyHandlers_.clear();
548        activeMouseHandlers_.clear();
549        for (unsigned int i = 0; i < joySticksSize_; i++)
550          activeJoyStickHandlers_[i].clear();
551
552        enableKeyHandler("keydetector");
553        enableMouseHandler("keydetector");
554        enableJoyStickHandler("keydetector", 0);
555
556        stateRequest_ = IS_DETECT;
557        state_ = IS_DETECT;
558        break;
559
560      case IS_NODETECT:
561        _restoreState();
562        state_ = IS_NODETECT;
563        stateRequest_ = savedState_;
564        break;
565
566      case IS_CALIBRATE:
567        if (joySticksSize_)
568        {
569          savedState_ = _getSingleton().state_;
570          for (unsigned int i = 0; i < 24; i++)
571          {
572            marginalsMax_[i] = INT_MIN;
573            marginalsMin_[i] = INT_MAX;
574          }
575          COUT(3) << "Move all joy stick axes in all directions a few times. "
576            << "Then put all axes in zero state and hit enter." << std::endl;
577
578          savedState_ = state_;
579          _saveState();
580
581          activeKeyHandlers_.clear();
582          activeMouseHandlers_.clear();
583          for (unsigned int i = 0; i < joySticksSize_; i++)
584            activeJoyStickHandlers_[i].clear();
585
586          enableKeyHandler("calibratorcallback");
587          stateRequest_ = IS_CALIBRATE;
588          state_ = IS_CALIBRATE;
589        }
590        else
591        {
592          COUT(3) << "Connot calibrate, no joy stick found!" << std::endl;
593          stateRequest_ = state_;
594        }
595        break;
596
597      case IS_NOCALIBRATE:
598        _completeCalibration();
599        _restoreState();
600        state_ = IS_NOCALIBRATE;
601        stateRequest_ = savedState_;
602        break;
603
604      case IS_NONE:
605        activeKeyHandlers_.clear();
606        activeMouseHandlers_.clear();
607        for (unsigned int i = 0; i < joySticksSize_; i++)
608          activeJoyStickHandlers_[i].clear();
609        state_ = IS_NONE;
610
611      default:
612        break;
613      }
614    }
615
616    // Capture all the input. This calls the event handlers in InputManager.
617    if (mouse_)
618      mouse_->capture();
619    if (keyboard_)
620      keyboard_->capture();
621    for (unsigned  int i = 0; i < joySticksSize_; i++)
622      joySticks_[i]->capture();
623
624    if (state_ != IS_CALIBRATE)
625    {
626      // call all the handlers for the held key events
627      for (unsigned int iKey = 0; iKey < keysDown_.size(); iKey++)
628        for (unsigned int iHandler = 0; iHandler < activeKeyHandlers_.size(); iHandler++)
629          activeKeyHandlers_[iHandler]->keyHeld(KeyEvent(keysDown_[iKey], keyboardModifiers_));
630
631      // call all the handlers for the held mouse button events
632      for (unsigned int iButton = 0; iButton < mouseButtonsDown_.size(); iButton++)
633        for (unsigned int iHandler = 0; iHandler < activeMouseHandlers_.size(); iHandler++)
634          activeMouseHandlers_[iHandler]->mouseButtonHeld(mouseButtonsDown_[iButton]);
635
636      // call all the handlers for the held joy stick button events
637      for (unsigned int iJoyStick  = 0; iJoyStick < joySticksSize_; iJoyStick++)
638        for (unsigned int iButton   = 0; iButton   < joyStickButtonsDown_[iJoyStick].size(); iButton++)
639          for (unsigned int iHandler = 0; iHandler  < activeJoyStickHandlers_[iJoyStick].size(); iHandler++)
640            activeJoyStickHandlers_[iJoyStick][iHandler]->joyStickButtonHeld(iJoyStick, joyStickButtonsDown_[iJoyStick][iButton]);
641    }
642
643    // call the ticks for the handlers (need to be treated specially)
644    for (unsigned int iHandler = 0; iHandler < activeHandlers_.size(); iHandler++)
645      activeHandlers_[iHandler].first->tickInput(dt, activeHandlers_[iHandler].second);
646  }
647
648  void InputManager::_completeCalibration()
649  {
650    for (unsigned int i = 0; i < 24; i++)
651    {
652      // positive coefficient
653      if (marginalsMax_[i] == INT_MIN)
654        marginalsMax_[i] =  32767;
655      // coefficients
656      if (marginalsMax_[i] - joySticksCalibration_[0].zeroStates[i])
657        joySticksCalibration_[0].positiveCoeff[i] =  1.0f/(marginalsMax_[i] - joySticksCalibration_[0].zeroStates[i]);
658      else
659        joySticksCalibration_[0].positiveCoeff[i] =  1.0f;
660
661      // config value
662      ConfigValueContainer* cont = getIdentifier()->getConfigValueContainer("CoeffPos");
663      assert(cont);
664      cont->set(getConvertedValue<int, std::string>(i) + " "
665        + getConvertedValue<float, std::string>(joySticksCalibration_[0].positiveCoeff[i]));
666
667      // negative coefficient
668      if (marginalsMin_[i] == INT_MAX)
669        marginalsMin_[i] = -32768;
670      // coefficients
671      if (marginalsMin_[i] - joySticksCalibration_[0].zeroStates[i])
672        joySticksCalibration_[0].negativeCoeff[i] = -1.0f/(marginalsMin_[i] - joySticksCalibration_[0].zeroStates[i]);
673      else
674        joySticksCalibration_[0].negativeCoeff[i] =  1.0f;
675      // config value
676      cont = getIdentifier()->getConfigValueContainer("CoeffNeg");
677      assert(cont);
678      cont->set(getConvertedValue<int, std::string>(i) + " "
679        + getConvertedValue<float, std::string>(joySticksCalibration_[0].negativeCoeff[i]));
680
681      // zero states
682      if (i < 8)
683      {
684        if (!(i & 1))
685          joySticksCalibration_[0].zeroStates[i] = joySticks_[0]->getJoyStickState().mSliders[i/2].abX;
686        else
687          joySticksCalibration_[0].zeroStates[i] = joySticks_[0]->getJoyStickState().mSliders[i/2].abY;
688      }
689      else
690      {
691        if (i - 8 < joySticks_[0]->getJoyStickState().mAxes.size())
692          joySticksCalibration_[0].zeroStates[i] = joySticks_[0]->getJoyStickState().mAxes[i - 8].abs;
693        else
694          joySticksCalibration_[0].zeroStates[i] = 0;
695      }
696      // config value
697      cont = getIdentifier()->getConfigValueContainer("Zero");
698      assert(cont);
699      cont->set(getConvertedValue<int, std::string>(i) + " "
700        + getConvertedValue<int, std::string>(joySticksCalibration_[0].zeroStates[i]));
701    }
702  }
703
704  // ###### Key Events ######
705
706  /**
707    @brief Event handler for the keyPressed Event.
708    @param e Event information
709  */
710  bool InputManager::keyPressed(const OIS::KeyEvent &e)
711  {
712    // check whether the key already is in the list (can happen when focus was lost)
713    unsigned int iKey = 0;
714    while (iKey < keysDown_.size() && keysDown_[iKey].key != (KeyCode::Enum)e.key)
715      iKey++;
716    if (iKey == keysDown_.size())
717      keysDown_.push_back(Key(e));
718
719    // update modifiers
720    if(e.key == OIS::KC_RMENU    || e.key == OIS::KC_LMENU)
721      keyboardModifiers_ |= KeyboardModifier::Alt;   // alt key
722    if(e.key == OIS::KC_RCONTROL || e.key == OIS::KC_LCONTROL)
723      keyboardModifiers_ |= KeyboardModifier::Ctrl;  // ctrl key
724    if(e.key == OIS::KC_RSHIFT   || e.key == OIS::KC_LSHIFT)
725      keyboardModifiers_ |= KeyboardModifier::Shift; // shift key
726
727    for (unsigned int i = 0; i < activeKeyHandlers_.size(); i++)
728      activeKeyHandlers_[i]->keyPressed(KeyEvent(e, keyboardModifiers_));
729
730    return true;
731  }
732
733  /**
734    @brief Event handler for the keyReleased Event.
735    @param e Event information
736  */
737  bool InputManager::keyReleased(const OIS::KeyEvent &e)
738  {
739    // remove the key from the keysDown_ list
740    for (unsigned int iKey = 0; iKey < keysDown_.size(); iKey++)
741    {
742      if (keysDown_[iKey].key == (KeyCode::Enum)e.key)
743      {
744        keysDown_.erase(keysDown_.begin() + iKey);
745        break;
746      }
747    }
748
749    // update modifiers
750    if(e.key == OIS::KC_RMENU    || e.key == OIS::KC_LMENU)
751      keyboardModifiers_ &= ~KeyboardModifier::Alt;   // alt key
752    if(e.key == OIS::KC_RCONTROL || e.key == OIS::KC_LCONTROL)
753      keyboardModifiers_ &= ~KeyboardModifier::Ctrl;  // ctrl key
754    if(e.key == OIS::KC_RSHIFT   || e.key == OIS::KC_LSHIFT)
755      keyboardModifiers_ &= ~KeyboardModifier::Shift; // shift key
756
757    for (unsigned int i = 0; i < activeKeyHandlers_.size(); i++)
758      activeKeyHandlers_[i]->keyReleased(KeyEvent(e, keyboardModifiers_));
759
760    return true;
761  }
762
763
764  // ###### Mouse Events ######
765
766  /**
767    @brief Event handler for the mouseMoved Event.
768    @param e Event information
769  */
770  bool InputManager::mouseMoved(const OIS::MouseEvent &e)
771  {
772    // check for actual moved event
773    if (e.state.X.rel != 0 || e.state.Y.rel != 0)
774    {
775      for (unsigned int i = 0; i < activeMouseHandlers_.size(); i++)
776        activeMouseHandlers_[i]->mouseMoved(IntVector2(e.state.X.abs, e.state.Y.abs),
777            IntVector2(e.state.X.rel, e.state.Y.rel), IntVector2(e.state.width, e.state.height));
778    }
779
780    // check for mouse scrolled event
781    if (e.state.Z.rel != 0)
782    {
783      for (unsigned int i = 0; i < activeMouseHandlers_.size(); i++)
784        activeMouseHandlers_[i]->mouseScrolled(e.state.Z.abs, e.state.Z.rel);
785    }
786
787    return true;
788  }
789
790  /**
791    @brief Event handler for the mousePressed Event.
792    @param e Event information
793    @param id The ID of the mouse button
794  */
795  bool InputManager::mousePressed(const OIS::MouseEvent &e, OIS::MouseButtonID id)
796  {
797    // check whether the button already is in the list (can happen when focus was lost)
798    unsigned int iButton = 0;
799    while (iButton < mouseButtonsDown_.size() && mouseButtonsDown_[iButton] != (MouseButton::Enum)id)
800      iButton++;
801    if (iButton == mouseButtonsDown_.size())
802      mouseButtonsDown_.push_back((MouseButton::Enum)id);
803
804    for (unsigned int i = 0; i < activeMouseHandlers_.size(); i++)
805      activeMouseHandlers_[i]->mouseButtonPressed((MouseButton::Enum)id);
806
807    return true;
808  }
809
810  /**
811    @brief Event handler for the mouseReleased Event.
812    @param e Event information
813    @param id The ID of the mouse button
814  */
815  bool InputManager::mouseReleased(const OIS::MouseEvent &e, OIS::MouseButtonID id)
816  {
817    // remove the button from the keysDown_ list
818    for (unsigned int iButton = 0; iButton < mouseButtonsDown_.size(); iButton++)
819    {
820      if (mouseButtonsDown_[iButton] == (MouseButton::Enum)id)
821      {
822        mouseButtonsDown_.erase(mouseButtonsDown_.begin() + iButton);
823        break;
824      }
825    }
826
827    for (unsigned int i = 0; i < activeMouseHandlers_.size(); i++)
828      activeMouseHandlers_[i]->mouseButtonReleased((MouseButton::Enum)id);
829
830    return true;
831  }
832
833
834  // ###### Joy Stick Events ######
835
836  inline unsigned int InputManager::_getJoystick(const OIS::JoyStickEvent& arg)
837  {
838    // use the device to identify which one called the method
839    OIS::JoyStick* joyStick = (OIS::JoyStick*)arg.device;
840    unsigned int iJoyStick = 0;
841    while (joySticks_[iJoyStick] != joyStick)
842    {
843      iJoyStick++;
844      if (iJoyStick == joySticksSize_)
845      {
846        CCOUT(3) << "Unknown joystick fired an event. This means there is a bug somewhere! Aborting." << std::endl;
847        abort();
848      }
849    }
850    return iJoyStick;
851  }
852
853  bool InputManager::buttonPressed(const OIS::JoyStickEvent &arg, int button)
854  {
855    unsigned int iJoyStick = _getJoystick(arg);
856
857    // check whether the button already is in the list (can happen when focus was lost)
858    std::vector<int>& buttonsDown = joyStickButtonsDown_[iJoyStick];
859    unsigned int iButton = 0;
860    while (iButton < buttonsDown.size() && buttonsDown[iButton] != button)
861      iButton++;
862    if (iButton == buttonsDown.size())
863      buttonsDown.push_back(button);
864
865    for (unsigned int iHandler = 0; iHandler < activeJoyStickHandlers_[iJoyStick].size(); iHandler++)
866      activeJoyStickHandlers_[iJoyStick][iHandler]->joyStickButtonPressed(iJoyStick, button);
867
868    return true;
869  }
870
871  bool InputManager::buttonReleased(const OIS::JoyStickEvent &arg, int button)
872  {
873    unsigned int iJoyStick = _getJoystick(arg);
874
875    // remove the button from the joyStickButtonsDown_ list
876    std::vector<int>& buttonsDown = joyStickButtonsDown_[iJoyStick];
877    for (unsigned int iButton = 0; iButton < buttonsDown.size(); iButton++)
878    {
879      if (buttonsDown[iButton] == button)
880      {
881        buttonsDown.erase(buttonsDown.begin() + iButton);
882        break;
883      }
884    }
885
886    for (unsigned int iHandler = 0; iHandler < activeJoyStickHandlers_[iJoyStick].size(); iHandler++)
887      activeJoyStickHandlers_[iJoyStick][iHandler]->joyStickButtonReleased(iJoyStick, button);
888
889    return true;
890  }
891
892  void InputManager::_fireAxis(unsigned int iJoyStick, int axis, int value)
893  {
894    if (state_ == IS_CALIBRATE)
895    {
896      if (value > marginalsMax_[axis])
897        marginalsMax_[axis] = value;
898      if (value < marginalsMin_[axis])
899        marginalsMin_[axis] = value;
900    }
901    else
902    {
903      float fValue = value - joySticksCalibration_[iJoyStick].zeroStates[axis];
904      if (fValue > 0.0f)
905        fValue *= joySticksCalibration_[iJoyStick].positiveCoeff[axis];
906      else
907        fValue *= joySticksCalibration_[iJoyStick].negativeCoeff[axis];
908
909      for (unsigned int iHandler = 0; iHandler < activeJoyStickHandlers_[iJoyStick].size(); iHandler++)
910        activeJoyStickHandlers_[iJoyStick][iHandler]->joyStickAxisMoved(iJoyStick, axis, fValue);
911    }
912  }
913
914  bool InputManager::axisMoved(const OIS::JoyStickEvent &arg, int axis)
915  {
916    //if (arg.state.mAxes[axis].abs > 10000 || arg.state.mAxes[axis].abs < -10000)
917    //{ CCOUT(3) << "axis " << axis << " moved" << arg.state.mAxes[axis].abs << std::endl;}
918
919    unsigned int iJoyStick = _getJoystick(arg);
920
921    // keep in mind that the first 8 axes are reserved for the sliders
922    _fireAxis(iJoyStick, axis + 8, arg.state.mAxes[axis].abs);
923
924    return true;
925  }
926
927  bool InputManager::sliderMoved(const OIS::JoyStickEvent &arg, int id)
928  {
929    //if (arg.state.mSliders[id].abX > 10000 || arg.state.mSliders[id].abX < -10000)
930    //{CCOUT(3) << "slider " << id << " moved" << arg.state.mSliders[id].abX << std::endl;}
931    //CCOUT(3) << arg.state.mSliders[id].abX << "\t |" << arg.state.mSliders[id].abY << std::endl;
932
933    unsigned int iJoyStick = _getJoystick(arg);
934
935    if (sliderStates_[iJoyStick].sliderStates[id].x != arg.state.mSliders[id].abX)
936      _fireAxis(iJoyStick, id * 2, arg.state.mSliders[id].abX);
937    else if (sliderStates_[iJoyStick].sliderStates[id].y != arg.state.mSliders[id].abY)
938      _fireAxis(iJoyStick, id * 2 + 1, arg.state.mSliders[id].abY);
939
940    return true;
941  }
942
943  bool InputManager::povMoved(const OIS::JoyStickEvent &arg, int id)
944  {
945    unsigned int iJoyStick = _getJoystick(arg);
946
947    // translate the POV into 8 simple buttons
948    int lastState = povStates_[iJoyStick][id];
949    if (lastState & OIS::Pov::North)
950      buttonReleased(arg, 32 + id * 4 + 0);
951    if (lastState & OIS::Pov::South)
952      buttonReleased(arg, 32 + id * 4 + 1);
953    if (lastState & OIS::Pov::East)
954      buttonReleased(arg, 32 + id * 4 + 2);
955    if (lastState & OIS::Pov::West)
956      buttonReleased(arg, 32 + id * 4 + 3);
957
958    povStates_[iJoyStick].povStates[id] = arg.state.mPOV[id].direction;
959
960    int currentState = povStates_[iJoyStick][id];
961    if (currentState & OIS::Pov::North)
962      buttonPressed(arg, 32 + id * 4 + 0);
963    if (currentState & OIS::Pov::South)
964      buttonPressed(arg, 32 + id * 4 + 1);
965    if (currentState & OIS::Pov::East)
966      buttonPressed(arg, 32 + id * 4 + 2);
967    if (currentState & OIS::Pov::West)
968      buttonPressed(arg, 32 + id * 4 + 3);
969
970    return true;
971  }
972
973  /*bool InputManager::vector3Moved(const OIS::JoyStickEvent &arg, int id)
974  {
975    unsigned int iJoyStick = _getJoystick(arg);
976
977    for (unsigned int iHandler = 0; iHandler < activeJoyStickHandlers_[iJoyStick].size(); iHandler++)
978      activeJoyStickHandlers_[iJoyStick][iHandler]->joyStickVector3Moved(JoyStickState(arg.state, iJoyStick), id);
979
980    return true;
981  }*/
982
983
984  // ################################
985  // ### Static Interface Methods ###
986  // ################################
987  // ################################
988
989  std::string InputManager::bindingCommmandString_s = "";
990
991  bool InputManager::initialise(const size_t windowHnd, int windowWidth, int windowHeight,
992    bool createKeyboard, bool createMouse, bool createJoySticks)
993  {
994    return _getSingleton()._initialise(windowHnd, windowWidth, windowHeight,
995          createKeyboard, createMouse, createJoySticks);
996  }
997
998  bool InputManager::initialiseKeyboard()
999  {
1000    return _getSingleton()._initialiseKeyboard();
1001  }
1002
1003  bool InputManager::initialiseMouse()
1004  {
1005    return _getSingleton()._initialiseMouse();
1006  }
1007
1008  bool InputManager::initialiseJoySticks()
1009  {
1010    return _getSingleton()._initialiseJoySticks();
1011  }
1012
1013  int InputManager::numberOfKeyboards()
1014  {
1015    if (_getSingleton().keyboard_ != 0)
1016      return 1;
1017    else
1018      return 0;
1019  }
1020
1021  int InputManager::numberOfMice()
1022  {
1023    if (_getSingleton().mouse_ != 0)
1024      return 1;
1025    else
1026      return 0;
1027  }
1028
1029  int InputManager::numberOfJoySticks()
1030  {
1031    return _getSingleton().joySticksSize_;
1032  }
1033
1034  /*bool InputManager::isKeyDown(KeyCode::Enum key)
1035  {
1036    if (_getSingleton().keyboard_)
1037      return _getSingleton().keyboard_->isKeyDown((OIS::KeyCode)key);
1038    else
1039      return false;
1040  }*/
1041
1042  /*bool InputManager::isModifierDown(KeyboardModifier::Enum modifier)
1043  {
1044    if (_getSingleton().keyboard_)
1045      return isModifierDown(modifier);
1046    else
1047      return false;
1048  }*/
1049
1050  /*const MouseState InputManager::getMouseState()
1051  {
1052    if (_getSingleton().mouse_)
1053      return _getSingleton().mouse_->getMouseState();
1054    else
1055      return MouseState();
1056  }*/
1057
1058  /*const JoyStickState InputManager::getJoyStickState(unsigned int ID)
1059  {
1060    if (ID < _getSingleton().joySticksSize_)
1061      return JoyStickState(_getSingleton().joySticks_[ID]->getJoyStickState(), ID);
1062    else
1063      return JoyStickState();
1064  }*/
1065
1066  void InputManager::destroy()
1067  {
1068    _getSingleton()._destroy();
1069  }
1070
1071  void InputManager::destroyKeyboard()
1072  {
1073    return _getSingleton()._destroyKeyboard();
1074  }
1075
1076  void InputManager::destroyMouse()
1077  {
1078    return _getSingleton()._destroyMouse();
1079  }
1080
1081  void InputManager::destroyJoySticks()
1082  {
1083    return _getSingleton()._destroyJoySticks();
1084  }
1085
1086
1087  /**
1088    @brief Adjusts the mouse window metrics.
1089    This method has to be called every time the size of the window changes.
1090    @param width The new width of the render window
1091    @param height the new height of the render window
1092  */
1093  void InputManager::setWindowExtents(const int width, const int height)
1094  {
1095    if (_getSingleton().mouse_)
1096    {
1097      // Set mouse region (if window resizes, we should alter this to reflect as well)
1098      const OIS::MouseState &mouseState = _getSingleton().mouse_->getMouseState();
1099      mouseState.width  = width;
1100      mouseState.height = height;
1101    }
1102  }
1103
1104  /**
1105    @brief Sets the input mode to either GUI, inGame or Buffer
1106    @param mode The new input mode
1107    @remark Only has an affect if the mode actually changes
1108  */
1109  void InputManager::setInputState(const InputState state)
1110  {
1111    _getSingleton().stateRequest_ = state;
1112  }
1113
1114  /**
1115    @brief Returns the current input handling method
1116    @return The current input mode.
1117  */
1118  InputManager::InputState InputManager::getInputState()
1119  {
1120    return _getSingleton().state_;
1121  }
1122
1123  void InputManager::storeKeyStroke(const std::string& name)
1124  {
1125    setInputState(IS_NODETECT);
1126    COUT(3) << "Binding string \"" << bindingCommmandString_s << "\" on key '" << name << "'" << std::endl;
1127    CommandExecutor::execute("set KeyBinder " + name + " " + bindingCommmandString_s, false);
1128  }
1129
1130  void InputManager::keyBind(const std::string& command)
1131  {
1132    bindingCommmandString_s = command;
1133    setInputState(IS_DETECT);
1134    COUT(3) << "Press any button/key or move a mouse/joystick axis" << std::endl;
1135  }
1136
1137  void InputManager::calibrate()
1138  {
1139    _getSingleton().setInputState(IS_CALIBRATE);
1140  }
1141
1142  // ###### KeyHandler ######
1143
1144  /**
1145    @brief Adds a new key handler.
1146    @param handler Pointer to the handler object.
1147    @param name Unique name of the handler.
1148    @return True if added, false if name already existed.
1149  */
1150  bool InputManager::addKeyHandler(KeyHandler* handler, const std::string& name)
1151  {
1152    if (!handler)
1153      return false;
1154    if (_getSingleton().keyHandlers_.find(name) == _getSingleton().keyHandlers_.end())
1155    {
1156      _getSingleton().keyHandlers_[name] = handler;
1157      return true;
1158    }
1159    else
1160      return false;
1161  }
1162
1163  /**
1164    @brief Removes a Key handler from the list.
1165    @param name Unique name of the handler.
1166    @return True if removal was successful, false if name was not found.
1167  */
1168  bool InputManager::removeKeyHandler(const std::string &name)
1169  {
1170    disableKeyHandler(name);
1171    std::map<std::string, KeyHandler*>::iterator it = _getSingleton().keyHandlers_.find(name);
1172    if (it != _getSingleton().keyHandlers_.end())
1173    {
1174      _getSingleton().keyHandlers_.erase(it);
1175      return true;
1176    }
1177    else
1178      return false;
1179  }
1180
1181  /**
1182    @brief Returns the pointer to a handler.
1183    @param name Unique name of the handler.
1184    @return Pointer to the instance, 0 if name was not found.
1185  */
1186  KeyHandler* InputManager::getKeyHandler(const std::string& name)
1187  {
1188    std::map<std::string, KeyHandler*>::iterator it = _getSingleton().keyHandlers_.find(name);
1189    if (it != _getSingleton().keyHandlers_.end())
1190    {
1191      return (*it).second;
1192    }
1193    else
1194      return 0;
1195  }
1196
1197  /**
1198    @brief Enables a specific key handler that has already been added.
1199    @param name Unique name of the handler.
1200    @return False if name was not found, true otherwise.
1201  */
1202  bool InputManager::enableKeyHandler(const std::string& name)
1203  {
1204    // get pointer from the map with all stored handlers
1205    std::map<std::string, KeyHandler*>::const_iterator mapIt = _getSingleton().keyHandlers_.find(name);
1206    if (mapIt == _getSingleton().keyHandlers_.end())
1207      return false;
1208    // see whether the handler already is in the list
1209    for (std::vector<KeyHandler*>::iterator it = _getSingleton().activeKeyHandlers_.begin();
1210          it != _getSingleton().activeKeyHandlers_.end(); it++)
1211    {
1212      if ((*it) == (*mapIt).second)
1213      {
1214        return true;
1215      }
1216    }
1217    _getSingleton().activeKeyHandlers_.push_back((*mapIt).second);
1218    _getSingleton().stateRequest_ = IS_CUSTOM;
1219    _getSingleton()._updateTickables();
1220    return true;
1221  }
1222
1223  /**
1224    @brief Disables a specific key handler.
1225    @param name Unique name of the handler.
1226    @return False if name was not found, true otherwise.
1227  */
1228  bool InputManager::disableKeyHandler(const std::string &name)
1229  {
1230    // get pointer from the map with all stored handlers
1231    std::map<std::string, KeyHandler*>::const_iterator mapIt = _getSingleton().keyHandlers_.find(name);
1232    if (mapIt == _getSingleton().keyHandlers_.end())
1233      return false;
1234    // look for the handler in the list
1235    for (std::vector<KeyHandler*>::iterator it = _getSingleton().activeKeyHandlers_.begin();
1236          it != _getSingleton().activeKeyHandlers_.end(); it++)
1237    {
1238      if ((*it) == (*mapIt).second)
1239      {
1240        _getSingleton().activeKeyHandlers_.erase(it);
1241        _getSingleton().stateRequest_ = IS_CUSTOM;
1242        _getSingleton()._updateTickables();
1243        return true;
1244      }
1245    }
1246    return true;
1247  }
1248
1249  /**
1250    @brief Checks whether a key handler is active
1251    @param name Unique name of the handler.
1252    @return False if key handler is not active or doesn't exist, true otherwise.
1253  */
1254  bool InputManager::isKeyHandlerActive(const std::string& name)
1255  {
1256    // get pointer from the map with all stored handlers
1257    std::map<std::string, KeyHandler*>::const_iterator mapIt = _getSingleton().keyHandlers_.find(name);
1258    if (mapIt == _getSingleton().keyHandlers_.end())
1259      return false;
1260    // see whether the handler already is in the list
1261    for (std::vector<KeyHandler*>::iterator it = _getSingleton().activeKeyHandlers_.begin();
1262          it != _getSingleton().activeKeyHandlers_.end(); it++)
1263    {
1264      if ((*it) == (*mapIt).second)
1265        return true;
1266    }
1267    return false;
1268  }
1269
1270
1271  // ###### MouseHandler ######
1272  /**
1273    @brief Adds a new mouse handler.
1274    @param handler Pointer to the handler object.
1275    @param name Unique name of the handler.
1276    @return True if added, false if name already existed.
1277  */
1278  bool InputManager::addMouseHandler(MouseHandler* handler, const std::string& name)
1279  {
1280    if (!handler)
1281      return false;
1282    if (_getSingleton().mouseHandlers_.find(name) == _getSingleton().mouseHandlers_.end())
1283    {
1284      _getSingleton().mouseHandlers_[name] = handler;
1285      return true;
1286    }
1287    else
1288      return false;
1289  }
1290
1291  /**
1292    @brief Removes a Mouse handler from the list.
1293    @param name Unique name of the handler.
1294    @return True if removal was successful, false if name was not found.
1295  */
1296  bool InputManager::removeMouseHandler(const std::string &name)
1297  {
1298    disableMouseHandler(name);
1299    std::map<std::string, MouseHandler*>::iterator it = _getSingleton().mouseHandlers_.find(name);
1300    if (it != _getSingleton().mouseHandlers_.end())
1301    {
1302      _getSingleton().mouseHandlers_.erase(it);
1303      return true;
1304    }
1305    else
1306      return false;
1307  }
1308
1309  /**
1310    @brief Returns the pointer to a handler.
1311    @param name Unique name of the handler.
1312    @return Pointer to the instance, 0 if name was not found.
1313  */
1314  MouseHandler* InputManager::getMouseHandler(const std::string& name)
1315  {
1316    std::map<std::string, MouseHandler*>::iterator it = _getSingleton().mouseHandlers_.find(name);
1317    if (it != _getSingleton().mouseHandlers_.end())
1318    {
1319      return (*it).second;
1320    }
1321    else
1322      return 0;
1323  }
1324
1325  /**
1326    @brief Enables a specific mouse handler that has already been added.
1327    @param name Unique name of the handler.
1328    @return False if name was not found, true otherwise.
1329  */
1330  bool InputManager::enableMouseHandler(const std::string& name)
1331  {
1332    // get pointer from the map with all stored handlers
1333    std::map<std::string, MouseHandler*>::const_iterator mapIt = _getSingleton().mouseHandlers_.find(name);
1334    if (mapIt == _getSingleton().mouseHandlers_.end())
1335      return false;
1336    // see whether the handler already is in the list
1337    for (std::vector<MouseHandler*>::iterator it = _getSingleton().activeMouseHandlers_.begin();
1338          it != _getSingleton().activeMouseHandlers_.end(); it++)
1339    {
1340      if ((*it) == (*mapIt).second)
1341      {
1342        return true;
1343      }
1344    }
1345    _getSingleton().activeMouseHandlers_.push_back((*mapIt).second);
1346    _getSingleton().stateRequest_ = IS_CUSTOM;
1347    _getSingleton()._updateTickables();
1348    return true;
1349  }
1350
1351  /**
1352    @brief Disables a specific mouse handler.
1353    @param name Unique name of the handler.
1354    @return False if name was not found, true otherwise.
1355  */
1356  bool InputManager::disableMouseHandler(const std::string &name)
1357  {
1358    // get pointer from the map with all stored handlers
1359    std::map<std::string, MouseHandler*>::const_iterator mapIt = _getSingleton().mouseHandlers_.find(name);
1360    if (mapIt == _getSingleton().mouseHandlers_.end())
1361      return false;
1362    // look for the handler in the list
1363    for (std::vector<MouseHandler*>::iterator it = _getSingleton().activeMouseHandlers_.begin();
1364          it != _getSingleton().activeMouseHandlers_.end(); it++)
1365    {
1366      if ((*it) == (*mapIt).second)
1367      {
1368        _getSingleton().activeMouseHandlers_.erase(it);
1369        _getSingleton().stateRequest_ = IS_CUSTOM;
1370        _getSingleton()._updateTickables();
1371        return true;
1372      }
1373    }
1374    return true;
1375  }
1376
1377  /**
1378    @brief Checks whether a mouse handler is active
1379    @param name Unique name of the handler.
1380    @return False if key handler is not active or doesn't exist, true otherwise.
1381  */
1382  bool InputManager::isMouseHandlerActive(const std::string& name)
1383  {
1384    // get pointer from the map with all stored handlers
1385    std::map<std::string, MouseHandler*>::const_iterator mapIt = _getSingleton().mouseHandlers_.find(name);
1386    if (mapIt == _getSingleton().mouseHandlers_.end())
1387      return false;
1388    // see whether the handler already is in the list
1389    for (std::vector<MouseHandler*>::iterator it = _getSingleton().activeMouseHandlers_.begin();
1390          it != _getSingleton().activeMouseHandlers_.end(); it++)
1391    {
1392      if ((*it) == (*mapIt).second)
1393        return true;
1394    }
1395    return false;
1396  }
1397
1398
1399  // ###### JoyStickHandler ######
1400
1401  /**
1402    @brief Adds a new joy stick handler.
1403    @param handler Pointer to the handler object.
1404    @param name Unique name of the handler.
1405    @return True if added, false if name already existed.
1406  */
1407  bool InputManager::addJoyStickHandler(JoyStickHandler* handler, const std::string& name)
1408  {
1409    if (!handler)
1410      return false;
1411    if (_getSingleton().joyStickHandlers_.find(name) == _getSingleton().joyStickHandlers_.end())
1412    {
1413      _getSingleton().joyStickHandlers_[name] = handler;
1414      return true;
1415    }
1416    else
1417      return false;
1418  }
1419
1420  /**
1421    @brief Removes a JoyStick handler from the list.
1422    @param name Unique name of the handler.
1423    @return True if removal was successful, false if name was not found.
1424  */
1425  bool InputManager::removeJoyStickHandler(const std::string &name)
1426  {
1427    for (std::vector<OIS::JoyStick*>::iterator itstick = _getSingleton().joySticks_.begin();
1428          itstick != _getSingleton().joySticks_.end(); itstick++)
1429      disableJoyStickHandler(name, itstick - _getSingleton().joySticks_.begin());
1430
1431    std::map<std::string, JoyStickHandler*>::iterator it = _getSingleton().joyStickHandlers_.find(name);
1432    if (it != _getSingleton().joyStickHandlers_.end())
1433    {
1434      _getSingleton().joyStickHandlers_.erase(it);
1435      return true;
1436    }
1437    else
1438      return false;
1439  }
1440
1441  /**
1442    @brief Returns the pointer to a handler.
1443    @param name Unique name of the handler.
1444    @return Pointer to the instance, 0 if name was not found.
1445  */
1446  JoyStickHandler* InputManager::getJoyStickHandler(const std::string& name)
1447  {
1448    std::map<std::string, JoyStickHandler*>::iterator it = _getSingleton().joyStickHandlers_.find(name);
1449    if (it != _getSingleton().joyStickHandlers_.end())
1450    {
1451      return (*it).second;
1452    }
1453    else
1454      return 0;
1455  }
1456
1457  /**
1458    @brief Enables a specific joy stick handler that has already been added.
1459    @param name Unique name of the handler.
1460    @return False if name or id was not found, true otherwise.
1461  */
1462  bool InputManager::enableJoyStickHandler(const std::string& name, unsigned int ID)
1463  {
1464    // get handler pointer from the map with all stored handlers
1465    std::map<std::string, JoyStickHandler*>::const_iterator handlerIt = _getSingleton().joyStickHandlers_.find(name);
1466    if (handlerIt == _getSingleton().joyStickHandlers_.end())
1467      return false;
1468
1469    // check for existence of the ID
1470    if (ID >= _getSingleton().joySticksSize_)
1471      return false;
1472
1473    // see whether the handler already is in the list
1474    for (std::vector<JoyStickHandler*>::iterator it = _getSingleton().activeJoyStickHandlers_[ID].begin();
1475          it != _getSingleton().activeJoyStickHandlers_[ID].end(); it++)
1476    {
1477      if ((*it) == (*handlerIt).second)
1478      {
1479        return true;
1480      }
1481    }
1482    _getSingleton().activeJoyStickHandlers_[ID].push_back((*handlerIt).second);
1483    _getSingleton().stateRequest_ = IS_CUSTOM;
1484    _getSingleton()._updateTickables();
1485    return true;
1486  }
1487
1488  /**
1489    @brief Disables a specific joy stick handler.
1490    @param name Unique name of the handler.
1491    @return False if name or id was not found, true otherwise.
1492  */
1493  bool InputManager::disableJoyStickHandler(const std::string &name, unsigned int ID)
1494  {
1495    // get handler pointer from the map with all stored handlers
1496    std::map<std::string, JoyStickHandler*>::const_iterator handlerIt = _getSingleton().joyStickHandlers_.find(name);
1497    if (handlerIt == _getSingleton().joyStickHandlers_.end())
1498      return false;
1499
1500    // check for existence of the ID
1501    if (ID >= _getSingleton().joySticksSize_)
1502      return false;
1503
1504    // look for the handler in the list
1505    for (std::vector<JoyStickHandler*>::iterator it = _getSingleton().activeJoyStickHandlers_[ID].begin();
1506          it != _getSingleton().activeJoyStickHandlers_[ID].end(); it++)
1507    {
1508      if ((*it) == (*handlerIt).second)
1509      {
1510        _getSingleton().activeJoyStickHandlers_[ID].erase(it);
1511        _getSingleton().stateRequest_ = IS_CUSTOM;
1512        _getSingleton()._updateTickables();
1513        return true;
1514      }
1515    }
1516    return true;
1517  }
1518
1519  /**
1520    @brief Checks whether a joy stick handler is active
1521    @param name Unique name of the handler.
1522    @return False if key handler is not active or doesn't exist, true otherwise.
1523  */
1524  bool InputManager::isJoyStickHandlerActive(const std::string& name, unsigned int ID)
1525  {
1526    // get handler pointer from the map with all stored handlers
1527    std::map<std::string, JoyStickHandler*>::const_iterator handlerIt = _getSingleton().joyStickHandlers_.find(name);
1528    if (handlerIt == _getSingleton().joyStickHandlers_.end())
1529      return false;
1530
1531    // check for existence of the ID
1532    if (ID >= _getSingleton().joySticksSize_)
1533      return false;
1534
1535    // see whether the handler already is in the list
1536    for (std::vector<JoyStickHandler*>::iterator it = _getSingleton().activeJoyStickHandlers_[ID].begin();
1537          it != _getSingleton().activeJoyStickHandlers_[ID].end(); it++)
1538    {
1539      if ((*it) == (*handlerIt).second)
1540        return true;
1541    }
1542    return false;
1543  }
1544
1545}
Note: See TracBrowser for help on using the repository browser.