Planet
navi homePPSaboutscreenshotsdownloaddevelopmentforum

source: code/trunk/src/core/input/InputManager.cc @ 1770

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

Bug fix in InputManager destructor.

  • Property svn:eol-style set to native
File size: 44.8 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 "util/Exception.h"
45#include "core/CoreIncludes.h"
46#include "core/ConfigValueIncludes.h"
47#include "core/CommandExecutor.h"
48#include "core/ConsoleCommand.h"
49#include "util/Debug.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<double> coeffPos;
363            std::vector<double> coeffNeg;
364            std::vector<int> 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, this);
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, this);
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, this);
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        singletonRef_s = 0;
459    }
460
461    /**
462    @brief
463        Destroys the keyboard and sets it to 0.
464    */
465    void InputManager::_destroyKeyboard()
466    {
467        assert(inputSystem_);
468        if (keyboard_)
469            inputSystem_->destroyInputObject(keyboard_);
470        keyboard_ = 0;
471        CCOUT(4) << "Keyboard destroyed." << std::endl;
472    }
473
474    /**
475    @brief
476        Destroys the mouse and sets it to 0.
477    */
478    void InputManager::_destroyMouse()
479    {
480        assert(inputSystem_);
481        if (mouse_)
482            inputSystem_->destroyInputObject(mouse_);
483        mouse_ = 0;
484        CCOUT(4) << "Mouse destroyed." << std::endl;
485    }
486
487    /**
488    @brief
489        Destroys all the joy sticks and resizes the lists to 0.
490    */
491    void InputManager::_destroyJoySticks()
492    {
493        if (joySticksSize_ > 0)
494        {
495            assert(inputSystem_);
496            for (unsigned int i = 0; i < joySticksSize_; i++)
497                if (joySticks_[i] != 0)
498                    inputSystem_->destroyInputObject(joySticks_[i]);
499
500            joySticks_.clear();
501            // don't use _redimensionLists(), might mess with registered handler if
502            // downgrading from 2 to 1 joystick
503            //_redimensionLists();
504            joySticksSize_ = 0;
505        }
506        CCOUT(4) << "Joy sticks destroyed." << std::endl;
507    }
508
509    /**
510    @brief
511        Removes and destroys an InputState.
512    @return
513        True if state was removed immediately, false if postponed.
514    */
515    void InputManager::_destroyState(InputState* state)
516    {
517        assert(state && !(this->internalState_ & Ticking));
518        std::map<int, InputState*>::iterator it = this->activeStates_.find(state->getPriority());
519        if (it != this->activeStates_.end())
520        {
521            this->activeStates_.erase(it);
522            _updateActiveStates();
523        }
524        inputStatesByPriority_.erase(state->getPriority());
525        inputStatesByName_.erase(state->getName());
526        delete state;
527    }
528
529    void InputManager::_clearBuffers()
530    {
531        keysDown_.clear();
532        keyboardModifiers_ = 0;
533        mouseButtonsDown_.clear();
534        for (unsigned int i = 0; i < joySticksSize_; ++i)
535        {
536            joyStickButtonsDown_[i].clear();
537            for (int j = 0; j < 4; ++j)
538            {
539                sliderStates_[i].sliderStates[j].x = 0;
540                sliderStates_[i].sliderStates[j].y = 0;
541                povStates_[i][j] = 0;
542            }
543        }
544    }
545
546
547    // ############################################################
548    // #####                     Reloading                    #####
549    // ##########                                        ##########
550    // ############################################################
551
552    /**
553    @brief
554        Public interface. Only reloads immediately if the call stack doesn't
555        include the tick() method.
556    @param joyStickSupport
557        Whether or not to initialise joy sticks as well.
558    */
559    void InputManager::reloadInputSystem(bool joyStickSupport)
560    {
561        if (internalState_ & Ticking)
562        {
563            // We cannot destroy OIS right now, because reload was probably
564            // caused by a user clicking on a GUI item. The backtrace would then
565            // include an OIS method. So it would be a very bad thing to destroy it..
566            internalState_ |= ReloadRequest;
567            // Misuse of internalState_: We can easily store the joyStickSupport bool.
568            // use Uninitialised as 0 value in order to make use of the overloaded |= operator
569            internalState_ |= joyStickSupport ? JoyStickSupport : Uninitialised;
570        }
571        else if (internalState_ & OISReady)
572        {
573            _reload(joyStickSupport);
574        }
575        else
576        {
577            CCOUT(2) << "Warning: Cannot reload OIS. May not yet be initialised or"
578                     << "joy sticks are currently calibrating." << std::endl;
579        }
580    }
581
582    /**
583    @brief
584        Internal reload method. Destroys the OIS devices and loads them again.
585    */
586    void InputManager::_reload(bool joyStickSupport)
587    {
588        try
589        {
590            CCOUT(3) << "Reloading ..." << std::endl;
591
592            // Save mouse clipping size
593            int mouseWidth  = mouse_->getMouseState().width;
594            int mouseHeight = mouse_->getMouseState().height;
595
596            internalState_ &= ~OISReady;
597
598            // destroy the devices
599            _destroyKeyboard();
600            _destroyMouse();
601            _destroyJoySticks();
602
603            OIS::InputManager::destroyInputSystem(inputSystem_);
604            inputSystem_ = 0;
605
606            // clear all buffers containing input information
607            _clearBuffers();
608
609            initialise(windowHnd_, mouseWidth, mouseHeight, joyStickSupport);
610
611            CCOUT(3) << "Reloading done." << std::endl;
612        }
613        catch (OIS::Exception& ex)
614        {
615            CCOUT(1) << "An exception has occured while reloading:\n" << ex.what() << std::endl;
616        }
617    }
618
619    // ############################################################
620    // #####                  Runtime Methods                 #####
621    // ##########                                        ##########
622    // ############################################################
623
624    /**
625    @brief
626        Updates the InputManager. Tick is called by the Core class.
627    @param dt
628        Delta time
629    */
630    void InputManager::tick(float dt)
631    {
632        if (internalState_ == Uninitialised)
633            return;
634        else if (internalState_ & ReloadRequest)
635        {
636            _reload(internalState_ & JoyStickSupport);
637            internalState_ &= ~ReloadRequest;
638            internalState_ &= ~JoyStickSupport;
639        }
640
641        // check for states to leave
642        for (std::set<InputState*>::reverse_iterator rit = stateLeaveRequests_.rbegin();
643            rit != stateLeaveRequests_.rend(); ++rit)
644        {
645            (*rit)->onLeave();
646            // just to be sure that the state actually is registered
647            assert(inputStatesByName_.find((*rit)->getName()) != inputStatesByName_.end());
648
649            activeStates_.erase((*rit)->getPriority());
650            _updateActiveStates();
651        }
652        stateLeaveRequests_.clear();
653
654        // check for states to enter
655        for (std::set<InputState*>::reverse_iterator rit = stateEnterRequests_.rbegin();
656            rit != stateEnterRequests_.rend(); ++rit)
657        {
658            // just to be sure that the state actually is registered
659            assert(inputStatesByName_.find((*rit)->getName()) != inputStatesByName_.end());
660
661            activeStates_[(*rit)->getPriority()] = (*rit);
662            _updateActiveStates();
663            (*rit)->onEnter();
664        }
665        stateEnterRequests_.clear();
666
667        // check for states to destroy
668        for (std::set<InputState*>::reverse_iterator rit = stateDestroyRequests_.rbegin();
669            rit != stateDestroyRequests_.rend(); ++rit)
670        {
671            _destroyState((*rit));
672        }
673        stateDestroyRequests_.clear();
674
675        // mark that we capture and distribute input
676        internalState_ |= Ticking;
677
678        // Capture all the input. This calls the event handlers in InputManager.
679        if (keyboard_)
680            keyboard_->capture();
681        if (mouse_)
682            mouse_->capture();
683        for (unsigned  int i = 0; i < joySticksSize_; i++)
684            joySticks_[i]->capture();
685
686        if (!bCalibrating_)
687        {
688            // call all the handlers for the held key events
689            for (unsigned int iKey = 0; iKey < keysDown_.size(); iKey++)
690                activeStatesTop_[Keyboard]->keyHeld(KeyEvent(keysDown_[iKey], keyboardModifiers_));
691
692            // call all the handlers for the held mouse button events
693            for (unsigned int iButton = 0; iButton < mouseButtonsDown_.size(); iButton++)
694                activeStatesTop_[Mouse]->mouseButtonHeld(mouseButtonsDown_[iButton]);
695
696            // call all the handlers for the held joy stick button events
697            for (unsigned int iJoyStick  = 0; iJoyStick < joySticksSize_; iJoyStick++)
698                for (unsigned int iButton   = 0; iButton   < joyStickButtonsDown_[iJoyStick].size(); iButton++)
699                    activeStatesTop_[JoyStick0 + iJoyStick]
700                        ->joyStickButtonHeld(iJoyStick, joyStickButtonsDown_[iJoyStick][iButton]);
701
702            // tick the handlers for each active handler
703            for (unsigned int i = 0; i < devicesNum_; ++i)
704                activeStatesTop_[i]->tickInput(dt, i);
705
706            // tick the handler with a general tick afterwards
707            for (unsigned int i = 0; i < activeStatesTicked_.size(); ++i)
708                activeStatesTicked_[i]->tickInput(dt);
709        }
710
711        internalState_ &= ~Ticking;
712    }
713
714    /**
715    @brief
716        Updates the currently active states (according to activeStates_) for each device.
717        Also, a list of all active states (no duplicates!) is compiled for the general tick.
718    */
719    void InputManager::_updateActiveStates()
720    {
721        for (std::map<int, InputState*>::const_iterator it = activeStates_.begin(); it != activeStates_.end(); ++it)
722            for (unsigned int i = 0; i < devicesNum_; ++i)
723                if (it->second->isInputDeviceEnabled(i))
724                    activeStatesTop_[i] = it->second;
725
726        // update tickables (every state will only appear once)
727        // Using a std::set to avoid duplicates
728        std::set<InputState*> tempSet;
729        for (unsigned int i = 0; i < devicesNum_; ++i)
730            tempSet.insert(activeStatesTop_[i]);
731
732        // copy the content of the set back to the actual vector
733        activeStatesTicked_.clear();
734        for (std::set<InputState*>::const_iterator it = tempSet.begin();it != tempSet.end(); ++it)
735            activeStatesTicked_.push_back(*it);
736
737        this->mouseButtonsDown_.clear();
738    }
739
740    /**
741    @brief
742        Processes the accumultated data for the joy stick calibration.
743    */
744    void InputManager::_completeCalibration()
745    {
746        for (unsigned int i = 0; i < 24; i++)
747        {
748            // positive coefficient
749            if (marginalsMax_[i] == INT_MIN)
750                marginalsMax_[i] =  32767;
751            // coefficients
752            if (marginalsMax_[i] - joySticksCalibration_[0].zeroStates[i])
753            {
754                joySticksCalibration_[0].positiveCoeff[i]
755                    = 1.0f/(marginalsMax_[i] - joySticksCalibration_[0].zeroStates[i]);
756            }
757            else
758                joySticksCalibration_[0].positiveCoeff[i] =  1.0f;
759
760            // config value
761            ConfigValueContainer* cont = getIdentifier()->getConfigValueContainer("CoeffPos");
762            assert(cont);
763            cont->set(i, joySticksCalibration_[0].positiveCoeff[i]);
764
765            // negative coefficient
766            if (marginalsMin_[i] == INT_MAX)
767                marginalsMin_[i] = -32768;
768            // coefficients
769            if (marginalsMin_[i] - joySticksCalibration_[0].zeroStates[i])
770            {
771                joySticksCalibration_[0].negativeCoeff[i] = -1.0f
772                    / (marginalsMin_[i] - joySticksCalibration_[0].zeroStates[i]);
773            }
774            else
775                joySticksCalibration_[0].negativeCoeff[i] =  1.0f;
776            // config value
777            cont = getIdentifier()->getConfigValueContainer("CoeffNeg");
778            assert(cont);
779            cont->set(i, joySticksCalibration_[0].negativeCoeff[i]);
780
781            // zero states
782            if (i < 8)
783            {
784                if (!(i & 1))
785                    joySticksCalibration_[0].zeroStates[i] = joySticks_[0]->getJoyStickState().mSliders[i/2].abX;
786                else
787                    joySticksCalibration_[0].zeroStates[i] = joySticks_[0]->getJoyStickState().mSliders[i/2].abY;
788            }
789            else
790            {
791                if (i - 8 < joySticks_[0]->getJoyStickState().mAxes.size())
792                    joySticksCalibration_[0].zeroStates[i] = joySticks_[0]->getJoyStickState().mAxes[i - 8].abs;
793                else
794                    joySticksCalibration_[0].zeroStates[i] = 0;
795            }
796            // config value
797            cont = getIdentifier()->getConfigValueContainer("Zero");
798            assert(cont);
799            cont->set(i, joySticksCalibration_[0].zeroStates[i]);
800        }
801
802        // restore old input state
803        requestLeaveState("calibrator");
804        bCalibrating_ = false;
805    }
806
807
808    // ############################################################
809    // #####                    OIS events                    #####
810    // ##########                                        ##########
811    // ############################################################
812
813    // ###### Key Events ######
814
815    /**
816    @brief
817        Event handler for the keyPressed Event.
818    @param e
819        Event information
820    */
821    bool InputManager::keyPressed(const OIS::KeyEvent &e)
822    {
823        // check whether the key already is in the list (can happen when focus was lost)
824        unsigned int iKey = 0;
825        while (iKey < keysDown_.size() && keysDown_[iKey].key != (KeyCode::Enum)e.key)
826            iKey++;
827        if (iKey == keysDown_.size())
828            keysDown_.push_back(Key(e));
829        else
830            return true;
831
832        // update modifiers
833        if(e.key == OIS::KC_RMENU    || e.key == OIS::KC_LMENU)
834            keyboardModifiers_ |= KeyboardModifier::Alt;   // alt key
835        if(e.key == OIS::KC_RCONTROL || e.key == OIS::KC_LCONTROL)
836            keyboardModifiers_ |= KeyboardModifier::Ctrl;  // ctrl key
837        if(e.key == OIS::KC_RSHIFT   || e.key == OIS::KC_LSHIFT)
838            keyboardModifiers_ |= KeyboardModifier::Shift; // shift key
839
840        activeStatesTop_[Keyboard]->keyPressed(KeyEvent(e, keyboardModifiers_));
841
842        return true;
843    }
844
845    /**
846    @brief
847        Event handler for the keyReleased Event.
848    @param e
849        Event information
850    */
851    bool InputManager::keyReleased(const OIS::KeyEvent &e)
852    {
853        // remove the key from the keysDown_ list
854        for (unsigned int iKey = 0; iKey < keysDown_.size(); iKey++)
855        {
856            if (keysDown_[iKey].key == (KeyCode::Enum)e.key)
857            {
858                keysDown_.erase(keysDown_.begin() + iKey);
859                break;
860            }
861        }
862
863        // update modifiers
864        if(e.key == OIS::KC_RMENU    || e.key == OIS::KC_LMENU)
865            keyboardModifiers_ &= ~KeyboardModifier::Alt;   // alt key
866        if(e.key == OIS::KC_RCONTROL || e.key == OIS::KC_LCONTROL)
867            keyboardModifiers_ &= ~KeyboardModifier::Ctrl;  // ctrl key
868        if(e.key == OIS::KC_RSHIFT   || e.key == OIS::KC_LSHIFT)
869            keyboardModifiers_ &= ~KeyboardModifier::Shift; // shift key
870
871        activeStatesTop_[Keyboard]->keyReleased(KeyEvent(e, keyboardModifiers_));
872
873        return true;
874    }
875
876
877    // ###### Mouse Events ######
878
879    /**
880    @brief
881        Event handler for the mouseMoved Event.
882    @param e
883        Event information
884    */
885    bool InputManager::mouseMoved(const OIS::MouseEvent &e)
886    {
887        // check for actual moved event
888        if (e.state.X.rel != 0 || e.state.Y.rel != 0)
889        {
890            activeStatesTop_[Mouse]->mouseMoved(IntVector2(e.state.X.abs, e.state.Y.abs),
891                    IntVector2(e.state.X.rel, e.state.Y.rel), IntVector2(e.state.width, e.state.height));
892        }
893
894        // check for mouse scrolled event
895        if (e.state.Z.rel != 0)
896        {
897            activeStatesTop_[Mouse]->mouseScrolled(e.state.Z.abs, e.state.Z.rel);
898        }
899
900        return true;
901    }
902
903    /**
904    @brief
905        Event handler for the mousePressed Event.
906    @param e
907        Event information
908    @param id
909        The ID of the mouse button
910    */
911    bool InputManager::mousePressed(const OIS::MouseEvent &e, OIS::MouseButtonID id)
912    {
913        // check whether the button already is in the list (can happen when focus was lost)
914        unsigned int iButton = 0;
915        while (iButton < mouseButtonsDown_.size() && mouseButtonsDown_[iButton] != (MouseButton::Enum)id)
916            iButton++;
917        if (iButton == mouseButtonsDown_.size())
918            mouseButtonsDown_.push_back((MouseButton::Enum)id);
919
920        activeStatesTop_[Mouse]->mouseButtonPressed((MouseButton::Enum)id);
921
922        return true;
923    }
924
925    /**
926    @brief
927        Event handler for the mouseReleased Event.
928    @param e
929        Event information
930    @param id
931        The ID of the mouse button
932    */
933    bool InputManager::mouseReleased(const OIS::MouseEvent &e, OIS::MouseButtonID id)
934    {
935        // remove the button from the keysDown_ list
936        for (unsigned int iButton = 0; iButton < mouseButtonsDown_.size(); iButton++)
937        {
938            if (mouseButtonsDown_[iButton] == (MouseButton::Enum)id)
939            {
940                mouseButtonsDown_.erase(mouseButtonsDown_.begin() + iButton);
941                break;
942            }
943        }
944
945        activeStatesTop_[Mouse]->mouseButtonReleased((MouseButton::Enum)id);
946
947        return true;
948    }
949
950
951    // ###### Joy Stick Events ######
952
953    /**
954    @brief
955        Returns the joy stick ID (orxonox) according to a OIS::JoyStickEvent
956    */
957    inline unsigned int InputManager::_getJoystick(const OIS::JoyStickEvent& arg)
958    {
959        // use the device to identify which one called the method
960        OIS::JoyStick* joyStick = (OIS::JoyStick*)arg.device;
961        unsigned int iJoyStick = 0;
962        while (joySticks_[iJoyStick] != joyStick)
963            iJoyStick++;
964        // assert: Unknown joystick fired an event.
965        assert(iJoyStick != joySticksSize_);
966        return iJoyStick;
967    }
968
969    bool InputManager::buttonPressed(const OIS::JoyStickEvent &arg, int button)
970    {
971        unsigned int iJoyStick = _getJoystick(arg);
972
973        // check whether the button already is in the list (can happen when focus was lost)
974        std::vector<JoyStickButton::Enum>& buttonsDown = joyStickButtonsDown_[iJoyStick];
975        unsigned int iButton = 0;
976        while (iButton < buttonsDown.size() && buttonsDown[iButton] != button)
977            iButton++;
978        if (iButton == buttonsDown.size())
979            buttonsDown.push_back((JoyStickButton::Enum)button);
980
981        activeStatesTop_[2 + iJoyStick]->joyStickButtonPressed(iJoyStick, (JoyStickButton::Enum)button);
982
983        return true;
984    }
985
986    bool InputManager::buttonReleased(const OIS::JoyStickEvent &arg, int button)
987    {
988        unsigned int iJoyStick = _getJoystick(arg);
989
990        // remove the button from the joyStickButtonsDown_ list
991        std::vector<JoyStickButton::Enum>& buttonsDown = joyStickButtonsDown_[iJoyStick];
992        for (unsigned int iButton = 0; iButton < buttonsDown.size(); iButton++)
993        {
994            if (buttonsDown[iButton] == button)
995            {
996                buttonsDown.erase(buttonsDown.begin() + iButton);
997                break;
998            }
999        }
1000
1001        activeStatesTop_[2 + iJoyStick]->joyStickButtonReleased(iJoyStick, (JoyStickButton::Enum)button);
1002
1003        return true;
1004    }
1005
1006    /**
1007    @brief
1008        Calls the states for a particular axis with our enumeration.
1009        Used by OIS sliders and OIS axes.
1010    */
1011    void InputManager::_fireAxis(unsigned int iJoyStick, int axis, int value)
1012    {
1013        if (bCalibrating_)
1014        {
1015            if (value > marginalsMax_[axis])
1016                marginalsMax_[axis] = value;
1017            if (value < marginalsMin_[axis])
1018                marginalsMin_[axis] = value;
1019        }
1020        else
1021        {
1022            float fValue = value - joySticksCalibration_[iJoyStick].zeroStates[axis];
1023            if (fValue > 0.0f)
1024                fValue *= joySticksCalibration_[iJoyStick].positiveCoeff[axis];
1025            else
1026                fValue *= joySticksCalibration_[iJoyStick].negativeCoeff[axis];
1027
1028            activeStatesTop_[2 + iJoyStick]->joyStickAxisMoved(iJoyStick, axis, fValue);
1029        }
1030    }
1031
1032    bool InputManager::axisMoved(const OIS::JoyStickEvent &arg, int axis)
1033    {
1034        unsigned int iJoyStick = _getJoystick(arg);
1035
1036        // keep in mind that the first 8 axes are reserved for the sliders
1037        _fireAxis(iJoyStick, axis + 8, arg.state.mAxes[axis].abs);
1038
1039        return true;
1040    }
1041
1042    bool InputManager::sliderMoved(const OIS::JoyStickEvent &arg, int id)
1043    {
1044        unsigned int iJoyStick = _getJoystick(arg);
1045
1046        if (sliderStates_[iJoyStick].sliderStates[id].x != arg.state.mSliders[id].abX)
1047            _fireAxis(iJoyStick, id * 2, arg.state.mSliders[id].abX);
1048        else if (sliderStates_[iJoyStick].sliderStates[id].y != arg.state.mSliders[id].abY)
1049            _fireAxis(iJoyStick, id * 2 + 1, arg.state.mSliders[id].abY);
1050
1051        return true;
1052    }
1053
1054    bool InputManager::povMoved(const OIS::JoyStickEvent &arg, int id)
1055    {
1056        unsigned int iJoyStick = _getJoystick(arg);
1057
1058        // translate the POV into 8 simple buttons
1059
1060        int lastState = povStates_[iJoyStick][id];
1061        if (lastState & OIS::Pov::North)
1062            buttonReleased(arg, 32 + id * 4 + 0);
1063        if (lastState & OIS::Pov::South)
1064            buttonReleased(arg, 32 + id * 4 + 1);
1065        if (lastState & OIS::Pov::East)
1066            buttonReleased(arg, 32 + id * 4 + 2);
1067        if (lastState & OIS::Pov::West)
1068            buttonReleased(arg, 32 + id * 4 + 3);
1069
1070        povStates_[iJoyStick].povStates[id] = arg.state.mPOV[id].direction;
1071
1072        int currentState = povStates_[iJoyStick][id];
1073        if (currentState & OIS::Pov::North)
1074            buttonPressed(arg, 32 + id * 4 + 0);
1075        if (currentState & OIS::Pov::South)
1076            buttonPressed(arg, 32 + id * 4 + 1);
1077        if (currentState & OIS::Pov::East)
1078            buttonPressed(arg, 32 + id * 4 + 2);
1079        if (currentState & OIS::Pov::West)
1080            buttonPressed(arg, 32 + id * 4 + 3);
1081
1082        return true;
1083    }
1084
1085
1086    // ############################################################
1087    // #####         Other Public Interface Methods           #####
1088    // ##########                                        ##########
1089    // ############################################################
1090
1091    /**
1092    @brief
1093        Adjusts the mouse window metrics.
1094        This method has to be called every time the size of the window changes.
1095    @param width
1096        The new width of the render window
1097    @param^height
1098        The new height of the render window
1099    */
1100    void InputManager::setWindowExtents(const int width, const int height)
1101    {
1102        if (mouse_)
1103        {
1104            // Set mouse region (if window resizes, we should alter this to reflect as well)
1105            mouse_->getMouseState().width  = width;
1106            mouse_->getMouseState().height = height;
1107        }
1108    }
1109
1110
1111    // ###### InputStates ######
1112
1113    /**
1114    @brief
1115        Adds a new key handler.
1116    @param handler
1117        Pointer to the handler object.
1118    @param name
1119        Unique name of the handler.
1120    @param priority
1121        Unique integer number. Higher means more prioritised.
1122    @return
1123        True if added, false if name or priority already existed.
1124    */
1125    bool InputManager::_configureInputState(InputState* state, const std::string& name, int priority)
1126    {
1127        if (name == "")
1128            return false;
1129        if (!state)
1130            return false;
1131        if (inputStatesByName_.find(name) == inputStatesByName_.end())
1132        {
1133            if (inputStatesByPriority_.find(priority)
1134                == inputStatesByPriority_.end())
1135            {
1136                inputStatesByName_[name] = state;
1137                inputStatesByPriority_[priority] = state;
1138                state->setNumOfJoySticks(numberOfJoySticks());
1139                state->setName(name);
1140                state->setPriority(priority);
1141                return true;
1142            }
1143            else
1144            {
1145                COUT(2) << "Warning: Could not add an InputState with the same priority '"
1146                    << priority << "'." << std::endl;
1147                return false;
1148            }
1149        }
1150        else
1151        {
1152            COUT(2) << "Warning: Could not add an InputState with the same name '" << name << "'." << std::endl;
1153            return false;
1154        }
1155    }
1156
1157    /**
1158    @brief
1159        Removes and destroys an input state internally.
1160    @param name
1161        Name of the handler.
1162    @return
1163        True if removal was successful, false if name was not found.
1164    @remarks
1165        You can't remove the internal states "empty", "calibrator" and "detector".
1166        The removal process is being postponed if InputManager::tick() is currently running.
1167    */
1168    bool InputManager::requestDestroyState(const std::string& name)
1169    {
1170        if (name == "empty" || name == "calibrator" || name == "detector")
1171        {
1172            COUT(2) << "InputManager: Removing the '" << name << "' state is not allowed!" << std::endl;
1173            return false;
1174        }
1175        std::map<std::string, InputState*>::iterator it = inputStatesByName_.find(name);
1176        if (it != inputStatesByName_.end())
1177        {
1178            if (activeStates_.find(it->second->getPriority()) != activeStates_.end())
1179            {
1180                // The state is still active. We have to postpone
1181                stateLeaveRequests_.insert(it->second);
1182                stateDestroyRequests_.insert(it->second);
1183            }
1184            else if (this->internalState_ & Ticking)
1185            {
1186                // cannot remove state while ticking
1187                stateDestroyRequests_.insert(it->second);
1188            }
1189            else
1190                _destroyState(it->second);
1191
1192            return true;
1193        }
1194        return false;
1195    }
1196
1197    /**
1198    @brief
1199        Returns the pointer to the requested InputState.
1200    @param name
1201        Unique name of the state.
1202    @return
1203        Pointer to the instance, 0 if name was not found.
1204    */
1205    InputState* InputManager::getState(const std::string& name)
1206    {
1207        std::map<std::string, InputState*>::iterator it = inputStatesByName_.find(name);
1208        if (it != inputStatesByName_.end())
1209            return it->second;
1210        else
1211            return 0;
1212    }
1213
1214    /**
1215    @brief
1216        Returns the current input state (there might be others active too!)
1217    @return
1218        The current highest prioritised active input state.
1219    */
1220    InputState* InputManager::getCurrentState()
1221    {
1222        return (*activeStates_.rbegin()).second;
1223    }
1224
1225    /**
1226    @brief
1227        Activates a specific input state.
1228        It might not be really activated if the priority is too low!
1229    @param name
1230        Unique name of the state.
1231    @return
1232        False if name was not found, true otherwise.
1233    */
1234    bool InputManager::requestEnterState(const std::string& name)
1235    {
1236        // get pointer from the map with all stored handlers
1237        std::map<std::string, InputState*>::const_iterator it = inputStatesByName_.find(name);
1238        if (it != inputStatesByName_.end())
1239        {
1240            // exists
1241            if (activeStates_.find(it->second->getPriority()) == activeStates_.end())
1242            {
1243                // not active
1244                if (stateDestroyRequests_.find(it->second) == stateDestroyRequests_.end())
1245                {
1246                    // not scheduled for destruction
1247                    // set prevents a state being added multiple times
1248                    stateEnterRequests_.insert(it->second);
1249                    return true;
1250                }
1251            }
1252        }
1253        return false;
1254    }
1255
1256    /**
1257    @brief
1258        Deactivates a specific input state.
1259    @param name
1260        Unique name of the state.
1261    @return
1262        False if name was not found, true otherwise.
1263    */
1264    bool InputManager::requestLeaveState(const std::string& name)
1265    {
1266        // get pointer from the map with all stored handlers
1267        std::map<std::string, InputState*>::const_iterator it = inputStatesByName_.find(name);
1268        if (it != inputStatesByName_.end())
1269        {
1270            // exists
1271            if (activeStates_.find(it->second->getPriority()) != activeStates_.end())
1272            {
1273                // active
1274                stateLeaveRequests_.insert(it->second);
1275                return true;
1276            }
1277        }
1278        return false;
1279    }
1280
1281
1282    // ############################################################
1283    // #####                Console Commands                  #####
1284    // ##########                                        ##########
1285    // ############################################################
1286
1287    /**
1288    @brief
1289        Method for easily storing a string with the command executor. It is used by the
1290        KeyDetector to get assign commands. The KeyDetector simply executes
1291        the command 'storeKeyStroke myName' for each button/axis.
1292    @remarks
1293        This is only a temporary hack until we thourouhgly support multiple KeyBinders.
1294    @param name
1295        The name of the button/axis.
1296    */
1297    void InputManager::storeKeyStroke(const std::string& name)
1298    {
1299        getInstance().requestLeaveState("detector");
1300        COUT(0) << "Binding string \"" << bindingCommmandString_s << "\" on key '" << name << "'" << std::endl;
1301        CommandExecutor::execute("config KeyBinder " + name + " " + bindingCommmandString_s, false);
1302    }
1303
1304    /**
1305    @brief
1306        Assigns a command string to a key/button/axis. The name is determined via KeyDetector
1307        and InputManager::storeKeyStroke(.).
1308    @param command
1309        Command string that can be executed by the CommandExecutor
1310    */
1311    void InputManager::keyBind(const std::string& command)
1312    {
1313        bindingCommmandString_s = command;
1314        getInstance().requestEnterState("detector");
1315        COUT(0) << "Press any button/key or move a mouse/joystick axis" << std::endl;
1316    }
1317
1318    /**
1319    @brief
1320        Starts joy stick calibration.
1321    */
1322    void InputManager::calibrate()
1323    {
1324        getInstance().bCalibrating_ = true;
1325        getInstance().requestEnterState("calibrator");
1326    }
1327
1328    /**
1329    @brief
1330        Reloads the input system
1331    */
1332    void InputManager::reload(bool joyStickSupport)
1333    {
1334        getInstance().reloadInputSystem(joyStickSupport);
1335    }
1336}
Note: See TracBrowser for help on using the repository browser.