Planet
navi homePPSaboutscreenshotsdownloaddevelopmentforum

source: code/branches/gui/src/core/input/InputManager.cc @ 1646

Last change on this file since 1646 was 1646, checked in by rgrieder, 16 years ago
  • privatised InputState c'tors
  • added destruction code for GUIManager
  • fixed some issues and bugs
  • found 2400 memory leaks ;)
  • haven't done anything about it
  • converted GUIManager to Ogre Singleton
  • added NULL checkers in Loader
  • Property svn:eol-style set to native
File size: 41.0 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
32    Implementation of the InputManager that captures all the input from OIS
33    and redirects it to handlers.
34 */
35
36#include "InputManager.h"
37
38#include <climits>
39#include <cassert>
40
41#include "ois/OISException.h"
42#include "ois/OISInputManager.h"
43
44#include "core/CoreIncludes.h"
45#include "core/ConfigValueIncludes.h"
46#include "core/Debug.h"
47#include "core/CommandExecutor.h"
48#include "core/ConsoleCommand.h"
49
50#include "InputBuffer.h"
51#include "KeyBinder.h"
52#include "KeyDetector.h"
53#include "CalibratorCallback.h"
54#include "InputState.h"
55#include "SimpleInputState.h"
56#include "ExtendedInputState.h"
57
58namespace orxonox
59{
60    SetConsoleCommandShortcut(InputManager, keyBind);
61    SetConsoleCommandShortcut(InputManager, storeKeyStroke);
62    SetConsoleCommandShortcut(InputManager, calibrate);
63
64    std::string InputManager::bindingCommmandString_s = "";
65    InputManager* InputManager::singletonRef_s = 0;
66
67    using namespace InputDevice;
68
69    // ############################################################
70    // #####                  Initialisation                  #####
71    // ##########                                        ##########
72    // ############################################################
73
74    /**
75    @brief
76        Constructor only sets member fields to initial zero values
77        and registers the class in the class hierarchy.
78    */
79    InputManager::InputManager()
80        : inputSystem_(0)
81        , keyboard_(0)
82        , mouse_(0)
83        , joySticksSize_(0)
84        , devicesNum_(0)
85        , stateDetector_(0)
86        , stateCalibrator_(0)
87        , stateEmpty_(0)
88        , bCalibrating_(false)
89        , keyboardModifiers_(0)
90    {
91        RegisterRootObject(InputManager);
92
93        assert(singletonRef_s == 0);
94        singletonRef_s = this;
95    }
96
97    /**
98    @brief
99        Creates the OIS::InputMananger, the keyboard, the mouse and
100        the joysticks and assigns the key bindings.
101    @param windowHnd
102        The window handle of the render window
103    @param windowWidth
104        The width of the render window
105    @param windowHeight
106        The height of the render window
107    */
108    bool InputManager::initialise(const size_t windowHnd, int windowWidth, int windowHeight,
109                                   bool createKeyboard, bool createMouse, bool createJoySticks)
110    {
111        if (inputSystem_ == 0)
112        {
113            CCOUT(3) << "Initialising Input System..." << std::endl;
114            CCOUT(4) << "Initialising OIS components..." << std::endl;
115
116            OIS::ParamList paramList;
117            std::ostringstream windowHndStr;
118
119            // Fill parameter list
120            windowHndStr << (unsigned int)windowHnd;
121            paramList.insert(std::make_pair(std::string("WINDOW"), windowHndStr.str()));
122            //paramList.insert(std::make_pair(std::string("w32_mouse"), std::string("DISCL_NONEXCLUSIVE")));
123            //paramList.insert(std::make_pair(std::string("w32_mouse"), std::string("DISCL_FOREGROUND")));
124//#if defined OIS_LINUX_PLATFORM
125            //paramList.insert(std::make_pair(std::string("XAutoRepeatOn"), std::string("true")));
126//#endif
127
128            try
129            {
130                inputSystem_ = OIS::InputManager::createInputSystem(paramList);
131                CCOUT(ORX_DEBUG) << "Created OIS input system" << std::endl;
132            }
133            catch (OIS::Exception ex)
134            {
135                CCOUT(ORX_ERROR) << "Error: Failed creating an OIS input system."
136                    << "OIS message: \"" << ex.eText << "\"" << std::endl;
137                inputSystem_ = 0;
138                return false;
139            }
140
141            if (createKeyboard)
142                _initialiseKeyboard();
143
144            if (createMouse)
145                _initialiseMouse();
146
147            if (createJoySticks)
148                _initialiseJoySticks();
149
150            // set all the std::vector list sizes now that the devices have been created
151            _redimensionLists();
152
153            // Set mouse/joystick region
154            if (mouse_)
155            {
156                setWindowExtents(windowWidth, windowHeight);
157            }
158
159            CCOUT(ORX_DEBUG) << "Initialising OIS components done." << std::endl;
160
161            setConfigValues();
162
163            stateEmpty_ = createSimpleInputState("empty", -1);
164            stateEmpty_->setHandler(new EmptyHandler());
165            activeStates_[stateEmpty_->getPriority()] = stateEmpty_;
166
167            stateDetector_ = createSimpleInputState("detector", 101);
168            KeyDetector* temp = new KeyDetector();
169            temp->loadBindings("storeKeyStroke");
170            stateDetector_->setHandler(temp);
171
172            stateCalibrator_ = createSimpleInputState("calibrator", 100);
173            stateCalibrator_->setHandler(new EmptyHandler());
174            InputBuffer* buffer = new InputBuffer();
175            buffer->registerListener(this, &InputManager::_completeCalibration, '\r', true);
176            stateCalibrator_->setKeyHandler(buffer);
177
178            _updateActiveStates();
179
180            CCOUT(3) << "Initialising complete." << std::endl;
181        }
182        else
183        {
184            CCOUT(2) << "Warning: OIS compoments already initialised, skipping" << std::endl;
185        }
186        return true;
187    }
188
189    /**
190    @brief
191        Creates a keyboard and sets the event handler.
192    @return
193        False if keyboard stays uninitialised, true otherwise.
194    */
195    bool InputManager::_initialiseKeyboard()
196    {
197        if (keyboard_ != 0)
198        {
199            CCOUT(2) << "Warning: Keyboard already initialised, skipping." << std::endl;
200            return true;
201        }
202        try
203        {
204            if (inputSystem_->getNumberOfDevices(OIS::OISKeyboard) > 0)
205            {
206                keyboard_ = (OIS::Keyboard*)inputSystem_->createInputObject(OIS::OISKeyboard, true);
207                // register our listener in OIS.
208                keyboard_->setEventCallback(this);
209                // note: OIS will not detect keys that have already been down when the keyboard was created.
210                CCOUT(ORX_DEBUG) << "Created OIS keyboard" << std::endl;
211                return true;
212            }
213            else
214            {
215                CCOUT(ORX_WARNING) << "Warning: No keyboard found!" << std::endl;
216                return false;
217            }
218        }
219        catch (OIS::Exception ex)
220        {
221            CCOUT(ORX_WARNING) << "Warning: Failed to create an OIS keyboard\n"
222                << "OIS error message: \"" << ex.eText << "\"" << std::endl;
223            keyboard_ = 0;
224            return false;
225        }
226    }
227
228    /**
229    @brief
230        Creates a mouse and sets the event handler.
231    @return
232        False if mouse stays uninitialised, true otherwise.
233    */
234    bool InputManager::_initialiseMouse()
235    {
236        if (mouse_ != 0)
237        {
238            CCOUT(2) << "Warning: Mouse already initialised, skipping." << std::endl;
239            return true;
240        }
241        try
242        {
243            if (inputSystem_->getNumberOfDevices(OIS::OISMouse) > 0)
244            {
245                mouse_ = static_cast<OIS::Mouse*>(inputSystem_->createInputObject(OIS::OISMouse, true));
246                // register our listener in OIS.
247                mouse_->setEventCallback(this);
248                CCOUT(ORX_DEBUG) << "Created OIS mouse" << std::endl;
249                return true;
250            }
251            else
252            {
253                CCOUT(ORX_WARNING) << "Warning: No mouse found!" << std::endl;
254                return false;
255            }
256        }
257        catch (OIS::Exception ex)
258        {
259            CCOUT(ORX_WARNING) << "Warning: Failed to create an OIS mouse\n"
260                << "OIS error message: \"" << ex.eText << "\"" << std::endl;
261            mouse_ = 0;
262            return false;
263        }
264    }
265
266    /**
267    @brief
268        Creates all joy sticks and sets the event handler.
269    @return
270        False joy stick stay uninitialised, true otherwise.
271    */
272    bool InputManager::_initialiseJoySticks()
273    {
274        if (joySticksSize_ > 0)
275        {
276            CCOUT(2) << "Warning: Joy sticks already initialised, skipping." << std::endl;
277            return true;
278        }
279        bool success = false;
280        if (inputSystem_->getNumberOfDevices(OIS::OISJoyStick) > 0)
281        {
282            for (int i = 0; i < inputSystem_->getNumberOfDevices(OIS::OISJoyStick); i++)
283            {
284                try
285                {
286                    OIS::JoyStick* stig = static_cast<OIS::JoyStick*>
287                        (inputSystem_->createInputObject(OIS::OISJoyStick, true));
288                    CCOUT(ORX_DEBUG) << "Created OIS joy stick with ID " << stig->getID() << std::endl;
289                    joySticks_.push_back(stig);
290                    // register our listener in OIS.
291                    stig->setEventCallback(this);
292                    success = true;
293                }
294                catch (OIS::Exception ex)
295                {
296                    CCOUT(ORX_WARNING) << "Warning: Failed to create OIS joy number" << i << "\n"
297                        << "OIS error message: \"" << ex.eText << "\"" << std::endl;
298                }
299            }
300        }
301        else
302        {
303            CCOUT(ORX_WARNING) << "Warning: Joy stick support requested, but no joy stick was found" << std::endl;
304            return false;
305        }
306        return success;
307    }
308
309    /**
310    @brief
311        Sets the size of all the different lists that are dependent on the number
312        of joy stick devices created.
313    @remarks
314        No matter whether there are a mouse and/or keyboard, they will always
315        occupy 2 places in the device number dependent lists.
316    */
317    void InputManager::_redimensionLists()
318    {
319        joySticksSize_ = joySticks_.size();
320        devicesNum_ = 2 + joySticksSize_;
321        joyStickButtonsDown_ .resize(joySticksSize_);
322        povStates_           .resize(joySticksSize_);
323        sliderStates_        .resize(joySticksSize_);
324        joySticksCalibration_.resize(joySticksSize_);
325
326        for (unsigned int iJoyStick = 0; iJoyStick < joySticksSize_; iJoyStick++)
327        {
328            // reset the calibration with default values
329            for (unsigned int i = 0; i < 24; i++)
330            {
331                joySticksCalibration_[iJoyStick].negativeCoeff[i] = 1.0f/32767.0f;
332                joySticksCalibration_[iJoyStick].positiveCoeff[i] = 1.0f/32768.0f;
333                joySticksCalibration_[iJoyStick].zeroStates[i] = 0;
334            }
335        }
336
337        // state management
338        activeStatesTop_.resize(devicesNum_);
339
340        // inform all states
341        for (std::map<int, InputState*>::const_iterator it = inputStatesByPriority_.begin();
342            it != inputStatesByPriority_.end(); ++it)
343            (*it).second->setNumOfJoySticks(joySticksSize_);
344    }
345
346    /**
347    @brief
348        Sets the configurable values.
349        This mainly concerns joy stick calibrations.
350    */
351    void InputManager::setConfigValues()
352    {
353        if (joySticksSize_ > 0)
354        {
355            std::vector<MultiTypeMath> coeffPos;
356            std::vector<MultiTypeMath> coeffNeg;
357            std::vector<MultiTypeMath> zero;
358            coeffPos.resize(24);
359            coeffNeg.resize(24);
360            zero.resize(24);
361            for (unsigned int i = 0; i < 24; i++)
362            {
363                coeffPos[i] =  1.0f/32767.0f;
364                coeffNeg[i] =  1.0f/32768.0f;
365                zero[i]     =  0;
366            }
367
368            ConfigValueContainer* cont = getIdentifier()->getConfigValueContainer("CoeffPos");
369            if (!cont)
370            {
371                cont = new ConfigValueContainer(CFT_Settings, getIdentifier(), "CoeffPos", coeffPos);
372                getIdentifier()->addConfigValueContainer("CoeffPos", cont);
373            }
374            cont->getValue(&coeffPos);
375
376            cont = getIdentifier()->getConfigValueContainer("CoeffNeg");
377            if (!cont)
378            {
379                cont = new ConfigValueContainer(CFT_Settings, getIdentifier(), "CoeffNeg", coeffNeg);
380                getIdentifier()->addConfigValueContainer("CoeffNeg", cont);
381            }
382            cont->getValue(&coeffNeg);
383
384            cont = getIdentifier()->getConfigValueContainer("Zero");
385            if (!cont)
386            {
387                cont = new ConfigValueContainer(CFT_Settings, getIdentifier(), "Zero", zero);
388                getIdentifier()->addConfigValueContainer("Zero", cont);
389            }
390            cont->getValue(&zero);
391
392            // copy values to our own variables
393            for (unsigned int i = 0; i < 24; i++)
394            {
395                joySticksCalibration_[0].positiveCoeff[i] = coeffPos[i];
396                joySticksCalibration_[0].negativeCoeff[i] = coeffNeg[i];
397                joySticksCalibration_[0].zeroStates[i]    = zero[i];
398            }
399        }
400    }
401
402
403    // ############################################################
404    // #####                    Destruction                   #####
405    // ##########                                        ##########
406    // ############################################################
407
408    /**
409    @brief
410        Destroys all the created input devices and states.
411    */
412    InputManager::~InputManager()
413    {
414        if (inputSystem_)
415        {
416            try
417            {
418                CCOUT(3) << "Destroying ..." << std::endl;
419
420                // clear our own states
421                stateEmpty_->removeAndDestroyAllHandlers();
422                stateCalibrator_->removeAndDestroyAllHandlers();
423                stateDetector_->removeAndDestroyAllHandlers();
424
425                // kick all active states 'nicely'
426                for (std::map<int, InputState*>::reverse_iterator rit = activeStates_.rbegin();
427                    rit != activeStates_.rend(); ++rit)
428                {
429                    (*rit).second->onLeave();
430                }
431                //activeStates_.clear();
432                //_updateActiveStates();
433
434                // destroy all input states
435                while (inputStatesByPriority_.size() > 0)
436                {
437                    _destroyState((*inputStatesByPriority_.rbegin()).second);
438                }
439
440                //stateEmpty_ = 0;
441                //stateCalibrator_ = 0;
442                //stateDetector_ = 0;
443
444                // destroy the devices
445                _destroyKeyboard();
446                _destroyMouse();
447                _destroyJoySticks();
448
449                // 0 joy sticks now
450                //_redimensionLists();
451
452                OIS::InputManager::destroyInputSystem(inputSystem_);
453                //inputSystem_ = 0;
454
455                CCOUT(3) << "Destroying done." << std::endl;
456            }
457            catch (OIS::Exception& ex)
458            {
459                CCOUT(1) << "An exception has occured while destroying:\n" << ex.what() << std::endl;
460            }
461        }
462    }
463
464    /**
465    @brief
466        Destroys the keyboard and sets it to 0.
467    */
468    void InputManager::_destroyKeyboard()
469    {
470        if (keyboard_)
471            inputSystem_->destroyInputObject(keyboard_);
472        keyboard_ = 0;
473        keysDown_.clear();
474        CCOUT(4) << "Keyboard destroyed." << std::endl;
475    }
476
477    /**
478    @brief
479        Destroys the mouse and sets it to 0.
480    */
481    void InputManager::_destroyMouse()
482    {
483        if (mouse_)
484            inputSystem_->destroyInputObject(mouse_);
485        mouse_ = 0;
486        mouseButtonsDown_.clear();
487        CCOUT(4) << "Mouse destroyed." << std::endl;
488    }
489
490    /**
491    @brief
492        Destroys all the joy sticks and resizes the lists to 0.
493    */
494    void InputManager::_destroyJoySticks()
495    {
496        if (joySticksSize_ > 0)
497        {
498            // note: inputSystem_ can never be 0, or else the code is mistaken
499            for (unsigned int i = 0; i < joySticksSize_; i++)
500                if (joySticks_[i] != 0)
501                    inputSystem_->destroyInputObject(joySticks_[i]);
502
503            joySticks_.clear();
504        }
505        CCOUT(4) << "Joy sticks destroyed." << std::endl;
506    }
507
508    void InputManager::_destroyState(InputState* state)
509    {
510        assert(state);
511        std::map<int, InputState*>::iterator it = this->activeStates_.find(state->getPriority());
512        if (it != this->activeStates_.end())
513        {
514            this->activeStates_.erase(it);
515            _updateActiveStates();
516        }
517        inputStatesByPriority_.erase(state->getPriority());
518        inputStatesByName_.erase(state->getName());
519        delete state;
520    }
521
522
523    // ############################################################
524    // #####                  Runtime Methods                 #####
525    // ##########                                        ##########
526    // ############################################################
527
528    /**
529    @brief
530        Updates the InputManager. Tick is called by the Core class.
531    @param dt
532        Delta time
533    */
534    void InputManager::tick(float dt)
535    {
536        if (inputSystem_ == 0)
537            return;
538
539        // check for states to leave (don't use unsigned int!)
540        for (int i = stateLeaveRequests_.size() - 1; i >= 0; --i)
541        {
542            stateLeaveRequests_[i]->onLeave();
543            // just to be sure that the state actually is registered
544            assert(inputStatesByName_.find(stateLeaveRequests_[i]->getName()) != inputStatesByName_.end());
545           
546            activeStates_.erase(stateLeaveRequests_[i]->getPriority());
547            _updateActiveStates();
548            stateLeaveRequests_.pop_back();
549        }
550
551
552        // check for states to enter (don't use unsigned int!)
553        for (int i = stateEnterRequests_.size() - 1; i >= 0; --i)
554        {
555            // just to be sure that the state actually is registered
556            assert(inputStatesByName_.find(stateEnterRequests_[i]->getName()) != inputStatesByName_.end());
557           
558            activeStates_[stateEnterRequests_[i]->getPriority()] = stateEnterRequests_[i];
559            _updateActiveStates();
560            stateEnterRequests_[i]->onEnter();
561            stateEnterRequests_.pop_back();
562        }
563
564        // Capture all the input. This calls the event handlers in InputManager.
565        if (keyboard_)
566            keyboard_->capture();
567        if (mouse_)
568            mouse_->capture();
569        for (unsigned  int i = 0; i < joySticksSize_; i++)
570            joySticks_[i]->capture();
571
572        if (!bCalibrating_)
573        {
574            // call all the handlers for the held key events
575            for (unsigned int iKey = 0; iKey < keysDown_.size(); iKey++)
576                activeStatesTop_[Keyboard]->keyHeld(KeyEvent(keysDown_[iKey], keyboardModifiers_));
577
578            // call all the handlers for the held mouse button events
579            for (unsigned int iButton = 0; iButton < mouseButtonsDown_.size(); iButton++)
580                activeStatesTop_[Mouse]->mouseButtonHeld(mouseButtonsDown_[iButton]);
581
582            // call all the handlers for the held joy stick button events
583            for (unsigned int iJoyStick  = 0; iJoyStick < joySticksSize_; iJoyStick++)
584                for (unsigned int iButton   = 0; iButton   < joyStickButtonsDown_[iJoyStick].size(); iButton++)
585                    activeStatesTop_[JoyStick0 + iJoyStick]
586                        ->joyStickButtonHeld(iJoyStick, joyStickButtonsDown_[iJoyStick][iButton]);
587
588            // tick the handlers for each active handler
589            for (unsigned int i = 0; i < devicesNum_; ++i)
590                activeStatesTop_[i]->tickInput(dt, i);
591
592            // tick the handler with a general tick afterwards
593            for (unsigned int i = 0; i < activeStatesTicked_.size(); ++i)
594                activeStatesTicked_[i]->tickInput(dt);
595        }
596    }
597
598    /**
599    @brief
600        Updates the currently active states (according to activeStates_) for each device.
601        Also, a list of all active states (no duplicates!) is compiled for the general tick.
602    */
603    void InputManager::_updateActiveStates()
604    {
605        for (std::map<int, InputState*>::const_iterator it = activeStates_.begin(); it != activeStates_.end(); ++it)
606            for (unsigned int i = 0; i < devicesNum_; ++i)
607                if ((*it).second->isInputDeviceEnabled(i))
608                    activeStatesTop_[i] = (*it).second;
609
610        // update tickables (every state will only appear once)
611        // Using a std::set to avoid duplicates
612        std::set<InputState*> tempSet;
613        for (unsigned int i = 0; i < devicesNum_; ++i)
614            tempSet.insert(activeStatesTop_[i]);
615
616        // copy the content of the set back to the actual vector
617        activeStatesTicked_.clear();
618        for (std::set<InputState*>::const_iterator it = tempSet.begin();it != tempSet.end(); ++it)
619            activeStatesTicked_.push_back(*it);
620    }
621
622    /**
623    @brief
624        Processes the accumultated data for the joy stick calibration.
625    */
626    void InputManager::_completeCalibration()
627    {
628        for (unsigned int i = 0; i < 24; i++)
629        {
630            // positive coefficient
631            if (marginalsMax_[i] == INT_MIN)
632                marginalsMax_[i] =  32767;
633            // coefficients
634            if (marginalsMax_[i] - joySticksCalibration_[0].zeroStates[i])
635            {
636                joySticksCalibration_[0].positiveCoeff[i]
637                    = 1.0f/(marginalsMax_[i] - joySticksCalibration_[0].zeroStates[i]);
638            }
639            else
640                joySticksCalibration_[0].positiveCoeff[i] =  1.0f;
641
642            // config value
643            ConfigValueContainer* cont = getIdentifier()->getConfigValueContainer("CoeffPos");
644            assert(cont);
645            cont->set(i, joySticksCalibration_[0].positiveCoeff[i]);
646
647            // negative coefficient
648            if (marginalsMin_[i] == INT_MAX)
649                marginalsMin_[i] = -32768;
650            // coefficients
651            if (marginalsMin_[i] - joySticksCalibration_[0].zeroStates[i])
652            {
653                joySticksCalibration_[0].negativeCoeff[i] = -1.0f
654                    / (marginalsMin_[i] - joySticksCalibration_[0].zeroStates[i]);
655            }
656            else
657                joySticksCalibration_[0].negativeCoeff[i] =  1.0f;
658            // config value
659            cont = getIdentifier()->getConfigValueContainer("CoeffNeg");
660            assert(cont);
661            cont->set(i, joySticksCalibration_[0].negativeCoeff[i]);
662
663            // zero states
664            if (i < 8)
665            {
666                if (!(i & 1))
667                    joySticksCalibration_[0].zeroStates[i] = joySticks_[0]->getJoyStickState().mSliders[i/2].abX;
668                else
669                    joySticksCalibration_[0].zeroStates[i] = joySticks_[0]->getJoyStickState().mSliders[i/2].abY;
670            }
671            else
672            {
673                if (i - 8 < joySticks_[0]->getJoyStickState().mAxes.size())
674                    joySticksCalibration_[0].zeroStates[i] = joySticks_[0]->getJoyStickState().mAxes[i - 8].abs;
675                else
676                    joySticksCalibration_[0].zeroStates[i] = 0;
677            }
678            // config value
679            cont = getIdentifier()->getConfigValueContainer("Zero");
680            assert(cont);
681            cont->set(i, joySticksCalibration_[0].zeroStates[i]);
682        }
683
684        // restore old input state
685        requestLeaveState("calibrator");
686        bCalibrating_ = false;
687    }
688
689
690    // ############################################################
691    // #####                    OIS events                    #####
692    // ##########                                        ##########
693    // ############################################################
694
695    // ###### Key Events ######
696
697    /**
698    @brief
699        Event handler for the keyPressed Event.
700    @param e
701        Event information
702    */
703    bool InputManager::keyPressed(const OIS::KeyEvent &e)
704    {
705        // check whether the key already is in the list (can happen when focus was lost)
706        unsigned int iKey = 0;
707        while (iKey < keysDown_.size() && keysDown_[iKey].key != (KeyCode::Enum)e.key)
708            iKey++;
709        if (iKey == keysDown_.size())
710            keysDown_.push_back(Key(e));
711
712        // update modifiers
713        if(e.key == OIS::KC_RMENU    || e.key == OIS::KC_LMENU)
714            keyboardModifiers_ |= KeyboardModifier::Alt;   // alt key
715        if(e.key == OIS::KC_RCONTROL || e.key == OIS::KC_LCONTROL)
716            keyboardModifiers_ |= KeyboardModifier::Ctrl;  // ctrl key
717        if(e.key == OIS::KC_RSHIFT   || e.key == OIS::KC_LSHIFT)
718            keyboardModifiers_ |= KeyboardModifier::Shift; // shift key
719
720        activeStatesTop_[Keyboard]->keyPressed(KeyEvent(e, keyboardModifiers_));
721
722        return true;
723    }
724
725    /**
726    @brief
727        Event handler for the keyReleased Event.
728    @param e
729        Event information
730    */
731    bool InputManager::keyReleased(const OIS::KeyEvent &e)
732    {
733        // remove the key from the keysDown_ list
734        for (unsigned int iKey = 0; iKey < keysDown_.size(); iKey++)
735        {
736            if (keysDown_[iKey].key == (KeyCode::Enum)e.key)
737            {
738                keysDown_.erase(keysDown_.begin() + iKey);
739                break;
740            }
741        }
742
743        // update modifiers
744        if(e.key == OIS::KC_RMENU    || e.key == OIS::KC_LMENU)
745            keyboardModifiers_ &= ~KeyboardModifier::Alt;   // alt key
746        if(e.key == OIS::KC_RCONTROL || e.key == OIS::KC_LCONTROL)
747            keyboardModifiers_ &= ~KeyboardModifier::Ctrl;  // ctrl key
748        if(e.key == OIS::KC_RSHIFT   || e.key == OIS::KC_LSHIFT)
749            keyboardModifiers_ &= ~KeyboardModifier::Shift; // shift key
750
751        activeStatesTop_[Keyboard]->keyReleased(KeyEvent(e, keyboardModifiers_));
752
753        return true;
754    }
755
756
757    // ###### Mouse Events ######
758
759    /**
760    @brief
761        Event handler for the mouseMoved Event.
762    @param e
763        Event information
764    */
765    bool InputManager::mouseMoved(const OIS::MouseEvent &e)
766    {
767        // check for actual moved event
768        if (e.state.X.rel != 0 || e.state.Y.rel != 0)
769        {
770            activeStatesTop_[Mouse]->mouseMoved(IntVector2(e.state.X.abs, e.state.Y.abs),
771                    IntVector2(e.state.X.rel, e.state.Y.rel), IntVector2(e.state.width, e.state.height));
772        }
773
774        // check for mouse scrolled event
775        if (e.state.Z.rel != 0)
776        {
777            activeStatesTop_[Mouse]->mouseScrolled(e.state.Z.abs, e.state.Z.rel);
778        }
779
780        return true;
781    }
782
783    /**
784    @brief
785        Event handler for the mousePressed Event.
786    @param e
787        Event information
788    @param id
789        The ID of the mouse button
790    */
791    bool InputManager::mousePressed(const OIS::MouseEvent &e, OIS::MouseButtonID id)
792    {
793        // check whether the button already is in the list (can happen when focus was lost)
794        unsigned int iButton = 0;
795        while (iButton < mouseButtonsDown_.size() && mouseButtonsDown_[iButton] != (MouseButton::Enum)id)
796            iButton++;
797        if (iButton == mouseButtonsDown_.size())
798            mouseButtonsDown_.push_back((MouseButton::Enum)id);
799
800        activeStatesTop_[Mouse]->mouseButtonPressed((MouseButton::Enum)id);
801
802        return true;
803    }
804
805    /**
806    @brief
807        Event handler for the mouseReleased Event.
808    @param e
809        Event information
810    @param id
811        The ID of the mouse button
812    */
813    bool InputManager::mouseReleased(const OIS::MouseEvent &e, OIS::MouseButtonID id)
814    {
815        // remove the button from the keysDown_ list
816        for (unsigned int iButton = 0; iButton < mouseButtonsDown_.size(); iButton++)
817        {
818            if (mouseButtonsDown_[iButton] == (MouseButton::Enum)id)
819            {
820                mouseButtonsDown_.erase(mouseButtonsDown_.begin() + iButton);
821                break;
822            }
823        }
824
825        activeStatesTop_[Mouse]->mouseButtonReleased((MouseButton::Enum)id);
826
827        return true;
828    }
829
830
831    // ###### Joy Stick Events ######
832
833    /**
834    @brief
835        Returns the joy stick ID (orxonox) according to a OIS::JoyStickEvent
836    */
837    inline unsigned int InputManager::_getJoystick(const OIS::JoyStickEvent& arg)
838    {
839        // use the device to identify which one called the method
840        OIS::JoyStick* joyStick = (OIS::JoyStick*)arg.device;
841        unsigned int iJoyStick = 0;
842        while (joySticks_[iJoyStick] != joyStick)
843            iJoyStick++;
844        // assert: Unknown joystick fired an event.
845        assert(iJoyStick != joySticksSize_);
846        return iJoyStick;
847    }
848
849    bool InputManager::buttonPressed(const OIS::JoyStickEvent &arg, int button)
850    {
851        unsigned int iJoyStick = _getJoystick(arg);
852
853        // check whether the button already is in the list (can happen when focus was lost)
854        std::vector<JoyStickButton::Enum>& buttonsDown = joyStickButtonsDown_[iJoyStick];
855        unsigned int iButton = 0;
856        while (iButton < buttonsDown.size() && buttonsDown[iButton] != button)
857            iButton++;
858        if (iButton == buttonsDown.size())
859            buttonsDown.push_back((JoyStickButton::Enum)button);
860
861        activeStatesTop_[2 + iJoyStick]->joyStickButtonPressed(iJoyStick, (JoyStickButton::Enum)button);
862
863        return true;
864    }
865
866    bool InputManager::buttonReleased(const OIS::JoyStickEvent &arg, int button)
867    {
868        unsigned int iJoyStick = _getJoystick(arg);
869
870        // remove the button from the joyStickButtonsDown_ list
871        std::vector<JoyStickButton::Enum>& buttonsDown = joyStickButtonsDown_[iJoyStick];
872        for (unsigned int iButton = 0; iButton < buttonsDown.size(); iButton++)
873        {
874            if (buttonsDown[iButton] == button)
875            {
876                buttonsDown.erase(buttonsDown.begin() + iButton);
877                break;
878            }
879        }
880
881        activeStatesTop_[2 + iJoyStick]->joyStickButtonReleased(iJoyStick, (JoyStickButton::Enum)button);
882
883        return true;
884    }
885
886    /**
887    @brief
888        Calls the states for a particular axis with our enumeration.
889        Used by OIS sliders and OIS axes.
890    */
891    void InputManager::_fireAxis(unsigned int iJoyStick, int axis, int value)
892    {
893        if (bCalibrating_)
894        {
895            if (value > marginalsMax_[axis])
896                marginalsMax_[axis] = value;
897            if (value < marginalsMin_[axis])
898                marginalsMin_[axis] = value;
899        }
900        else
901        {
902            float fValue = value - joySticksCalibration_[iJoyStick].zeroStates[axis];
903            if (fValue > 0.0f)
904                fValue *= joySticksCalibration_[iJoyStick].positiveCoeff[axis];
905            else
906                fValue *= joySticksCalibration_[iJoyStick].negativeCoeff[axis];
907
908            activeStatesTop_[2 + iJoyStick]->joyStickAxisMoved(iJoyStick, axis, fValue);
909        }
910    }
911
912    bool InputManager::axisMoved(const OIS::JoyStickEvent &arg, int axis)
913    {
914        unsigned int iJoyStick = _getJoystick(arg);
915
916        // keep in mind that the first 8 axes are reserved for the sliders
917        _fireAxis(iJoyStick, axis + 8, arg.state.mAxes[axis].abs);
918
919        return true;
920    }
921
922    bool InputManager::sliderMoved(const OIS::JoyStickEvent &arg, int id)
923    {
924        unsigned int iJoyStick = _getJoystick(arg);
925
926        if (sliderStates_[iJoyStick].sliderStates[id].x != arg.state.mSliders[id].abX)
927            _fireAxis(iJoyStick, id * 2, arg.state.mSliders[id].abX);
928        else if (sliderStates_[iJoyStick].sliderStates[id].y != arg.state.mSliders[id].abY)
929            _fireAxis(iJoyStick, id * 2 + 1, arg.state.mSliders[id].abY);
930
931        return true;
932    }
933
934    bool InputManager::povMoved(const OIS::JoyStickEvent &arg, int id)
935    {
936        unsigned int iJoyStick = _getJoystick(arg);
937
938        // translate the POV into 8 simple buttons
939
940        int lastState = povStates_[iJoyStick][id];
941        if (lastState & OIS::Pov::North)
942            buttonReleased(arg, 32 + id * 4 + 0);
943        if (lastState & OIS::Pov::South)
944            buttonReleased(arg, 32 + id * 4 + 1);
945        if (lastState & OIS::Pov::East)
946            buttonReleased(arg, 32 + id * 4 + 2);
947        if (lastState & OIS::Pov::West)
948            buttonReleased(arg, 32 + id * 4 + 3);
949
950        povStates_[iJoyStick].povStates[id] = arg.state.mPOV[id].direction;
951
952        int currentState = povStates_[iJoyStick][id];
953        if (currentState & OIS::Pov::North)
954            buttonPressed(arg, 32 + id * 4 + 0);
955        if (currentState & OIS::Pov::South)
956            buttonPressed(arg, 32 + id * 4 + 1);
957        if (currentState & OIS::Pov::East)
958            buttonPressed(arg, 32 + id * 4 + 2);
959        if (currentState & OIS::Pov::West)
960            buttonPressed(arg, 32 + id * 4 + 3);
961
962        return true;
963    }
964
965
966    // ############################################################
967    // #####         Other Public Interface Methods           #####
968    // ##########                                        ##########
969    // ############################################################
970
971    /**
972    @brief
973        Adjusts the mouse window metrics.
974        This method has to be called every time the size of the window changes.
975    @param width
976        The new width of the render window
977    @param^height
978        The new height of the render window
979    */
980    void InputManager::setWindowExtents(const int width, const int height)
981    {
982        if (mouse_)
983        {
984            // Set mouse region (if window resizes, we should alter this to reflect as well)
985            mouse_->getMouseState().width  = width;
986            mouse_->getMouseState().height = height;
987        }
988    }
989
990
991    // ###### InputStates ######
992
993    /**
994    @brief
995        Adds a new key handler.
996    @param handler
997        Pointer to the handler object.
998    @param name
999        Unique name of the handler.
1000    @param priority
1001        Unique integer number. Higher means more prioritised.
1002    @return
1003        True if added, false if name or priority already existed.
1004    */
1005    bool InputManager::_configureInputState(InputState* state, const std::string& name, int priority)
1006    {
1007        if (name == "")
1008            return false;
1009        if (!state)
1010            return false;
1011        if (inputStatesByName_.find(name) == inputStatesByName_.end())
1012        {
1013            if (inputStatesByPriority_.find(priority)
1014                == inputStatesByPriority_.end())
1015            {
1016                inputStatesByName_[name] = state;
1017                inputStatesByPriority_[priority] = state;
1018                state->setNumOfJoySticks(numberOfJoySticks());
1019                state->setName(name);
1020                state->setPriority(priority);
1021                return true;
1022            }
1023            else
1024            {
1025                COUT(2) << "Warning: Could not add an InputState with the same priority '"
1026                    << priority << "'." << std::endl;
1027                return false;
1028            }
1029        }
1030        else
1031        {
1032            COUT(2) << "Warning: Could not add an InputState with the same name '" << name << "'." << std::endl;
1033            return false;
1034        }
1035    }
1036
1037    /**
1038    @brief
1039        Returns a new SimpleInputState and configures it first.
1040    */
1041    SimpleInputState* InputManager::createSimpleInputState(const std::string &name, int priority)
1042    {
1043        SimpleInputState* state = new SimpleInputState();
1044        if (_configureInputState(state, name, priority))
1045            return state;
1046        else
1047        {
1048            delete state;
1049            return 0;
1050        }
1051    }
1052
1053    /**
1054    @brief
1055        Returns a new ExtendedInputState and configures it first.
1056    */
1057    ExtendedInputState* InputManager::createExtendedInputState(const std::string &name, int priority)
1058    {
1059        ExtendedInputState* state = new ExtendedInputState();
1060        if (_configureInputState(state, name, priority))
1061            return state;
1062        else
1063        {
1064            delete state;
1065            return 0;
1066        }
1067    }
1068
1069    /**
1070    @brief
1071        Returns a new InputState of type 'type' and configures it first.
1072    @param type
1073        String name of the class (used by the factory)
1074    */
1075    InputState* InputManager::createInputState(const std::string& type, const std::string &name, int priority)
1076    {
1077        InputState* state = dynamic_cast<InputState*>(Factory::getIdentifier(type)->fabricate());
1078        if (_configureInputState(state, name, priority))
1079            return state;
1080        else
1081        {
1082            delete state;
1083            return 0;
1084        }
1085    }
1086
1087    /**
1088    @brief
1089        Removes an input state internally.
1090    @param name
1091        Name of the handler.
1092    @return
1093        True if removal was successful, false if name was not found.
1094    @remarks
1095        You can't remove the internal states "empty", "calibrator" and "detector".
1096    */
1097    bool InputManager::destroyState(const std::string& name)
1098    {
1099        if (name == "empty" || name == "calibrator" || name == "detector")
1100        {
1101            COUT(2) << "InputManager: Removing the '" << name << "' state is not allowed!" << std::endl;
1102            return false;
1103        }
1104        std::map<std::string, InputState*>::iterator it = inputStatesByName_.find(name);
1105        if (it != inputStatesByName_.end())
1106        {
1107            _destroyState((*it).second);
1108            return true;
1109        }
1110        return false;
1111    }
1112
1113    /**
1114    @brief
1115        Returns the pointer to the requested InputState.
1116    @param name
1117        Unique name of the state.
1118    @return
1119        Pointer to the instance, 0 if name was not found.
1120    */
1121    InputState* InputManager::getState(const std::string& name)
1122    {
1123        std::map<std::string, InputState*>::iterator it = inputStatesByName_.find(name);
1124        if (it != inputStatesByName_.end())
1125            return (*it).second;
1126        else
1127            return 0;
1128    }
1129
1130    /**
1131    @brief
1132        Returns the current input state (there might be others active too!)
1133    @return
1134        The current highest prioritised active input state.
1135    */
1136    InputState* InputManager::getCurrentState()
1137    {
1138        return (*activeStates_.rbegin()).second;
1139    }
1140
1141    /**
1142    @brief
1143        Activates a specific input state.
1144        It might not be really activated if the priority is too low!
1145    @param name
1146        Unique name of the state.
1147    @return
1148        False if name was not found, true otherwise.
1149    */
1150    bool InputManager::requestEnterState(const std::string& name)
1151    {
1152        // get pointer from the map with all stored handlers
1153        std::map<std::string, InputState*>::const_iterator it = inputStatesByName_.find(name);
1154        if (it != inputStatesByName_.end())
1155        {
1156            stateEnterRequests_.push_back((*it).second);
1157            return true;
1158        }
1159        return false;
1160    }
1161
1162    /**
1163    @brief
1164        Deactivates a specific input state.
1165    @param name
1166        Unique name of the state.
1167    @return
1168        False if name was not found, true otherwise.
1169    */
1170    bool InputManager::requestLeaveState(const std::string& name)
1171    {
1172        // get pointer from the map with all stored handlers
1173        std::map<std::string, InputState*>::const_iterator it = inputStatesByName_.find(name);
1174        if (it != inputStatesByName_.end())
1175        {
1176            stateLeaveRequests_.push_back((*it).second);
1177            return true;
1178        }
1179        return false;
1180    }
1181
1182
1183    // ############################################################
1184    // #####                Console Commands                  #####
1185    // ##########                                        ##########
1186    // ############################################################
1187
1188    /**
1189    @brief
1190        Method for easily storing a string with the command executor. It is used by the
1191        KeyDetector to get assign commands. The KeyDetector simply executes
1192        the command 'storeKeyStroke myName' for each button/axis.
1193    @remarks
1194        This is only a temporary hack until we thourouhgly support multiple KeyBinders.
1195    @param name
1196        The name of the button/axis.
1197    */
1198    void InputManager::storeKeyStroke(const std::string& name)
1199    {
1200        getInstance().requestLeaveState("detector");
1201        COUT(0) << "Binding string \"" << bindingCommmandString_s << "\" on key '" << name << "'" << std::endl;
1202        CommandExecutor::execute("config KeyBinder " + name + " " + bindingCommmandString_s, false);
1203    }
1204
1205    /**
1206    @brief
1207        Assigns a command string to a key/button/axis. The name is determined via KeyDetector
1208        and InputManager::storeKeyStroke(.).
1209    @param command
1210        Command string that can be executed by the CommandExecutor
1211    */
1212    void InputManager::keyBind(const std::string& command)
1213    {
1214        bindingCommmandString_s = command;
1215        getInstance().requestEnterState("detector");
1216        COUT(0) << "Press any button/key or move a mouse/joystick axis" << std::endl;
1217    }
1218
1219    /**
1220    @brief
1221        Starts joy stick calibration.
1222    */
1223    void InputManager::calibrate()
1224    {
1225        getInstance().bCalibrating_ = true;
1226        getInstance().requestEnterState("calibrator");
1227    }
1228}
Note: See TracBrowser for help on using the repository browser.