Planet
navi homePPSaboutscreenshotsdownloaddevelopmentforum

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

Last change on this file since 1660 was 1660, checked in by rgrieder, 16 years ago

GameState class added. Tested and working, but now comes the hard part: Implementing the actual states…

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