Planet
navi homePPSaboutscreenshotsdownloaddevelopmentforum

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

Last change on this file since 10741 was 10624, checked in by landauf, 9 years ago

merged branch core7 back to trunk

  • Property svn:eol-style set to native
File size: 24.9 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 and a static variable from the InputHandler.
33*/
34
35#include "InputManager.h"
36
37#include <cassert>
38#include <climits>
39#include <ois/OISException.h>
40#include <ois/OISInputManager.h>
41#include <boost/foreach.hpp>
42#include <loki/ScopeGuard.h>
43
44#include "util/Clock.h"
45#include "util/Convert.h"
46#include "util/Exception.h"
47#include "core/CoreIncludes.h"
48#include "core/GraphicsManager.h"
49#include "core/config/ConfigValueIncludes.h"
50#include "core/commandline/CommandLineIncludes.h"
51#include "core/command/ConsoleCommandIncludes.h"
52#include "core/command/Functor.h"
53
54#include "InputBuffer.h"
55#include "JoyStick.h"
56#include "JoyStickQuantityListener.h"
57#include "Mouse.h"
58#include "Keyboard.h"
59
60namespace orxonox
61{
62    SetCommandLineSwitch(keyboard_no_grab).information("Whether not to exclusively grab the keyboard");
63
64    static const std::string __CC_InputManager_name = "InputManager";
65    static const std::string __CC_calibrate_name = "calibrate";
66    static const std::string __CC_reload_name = "reload";
67
68    SetConsoleCommand(__CC_InputManager_name, __CC_calibrate_name, &InputManager::calibrate).addShortcut();
69    SetConsoleCommand(__CC_InputManager_name, __CC_reload_name,    &InputManager::reload   );
70
71    // Abuse of this source file for the InputHandler
72    InputHandler InputHandler::EMPTY;
73
74    InputManager* InputManager::singletonPtr_s = 0;
75
76    //! Defines the |= operator for easier use.
77    inline InputManager::State operator|=(InputManager::State& lval, InputManager::State rval)
78    {
79        return (lval = (InputManager::State)(lval | rval));
80    }
81
82    //! Defines the &= operator for easier use.
83    inline InputManager::State operator&=(InputManager::State& lval, int rval)
84    {
85        return (lval = (InputManager::State)(lval & rval));
86    }
87
88    RegisterAbstractClass(InputManager).inheritsFrom<WindowEventListener>();
89
90    // ############################################################
91    // #####                  Initialisation                  #####
92    // ##########                                        ##########
93    // ############################################################
94    InputManager::InputManager()
95        : internalState_(Bad)
96        , oisInputManager_(0)
97        , devices_(2)
98        , exclusiveMouse_(false)
99        , emptyState_(0)
100        , calibratorCallbackHandler_(0)
101    {
102        RegisterObject(InputManager);
103
104        orxout(internal_status, context::input) << "InputManager: Constructing..." << endl;
105
106        // Allocate space for the function call buffer
107        this->callBuffer_.reserve(16);
108
109        this->setConfigValues();
110
111        if (GraphicsManager::getInstance().isFullScreen())
112            exclusiveMouse_ = true;
113        this->loadDevices();
114
115        // Lowest priority empty InputState
116        emptyState_ = createInputState("empty", false, false, InputStatePriority::Empty);
117        emptyState_->setHandler(&InputHandler::EMPTY);
118        activeStates_[emptyState_->getPriority()] = emptyState_;
119
120        // Joy stick calibration helper callback
121        InputState* calibrator = createInputState("calibrator", false, false, InputStatePriority::Calibrator);
122        calibrator->setHandler(&InputHandler::EMPTY);
123        calibratorCallbackHandler_ = new InputBuffer();
124        calibratorCallbackHandler_->registerListener(this, &InputManager::stopCalibration, '\r', true);
125        calibrator->setKeyHandler(calibratorCallbackHandler_);
126
127        this->updateActiveStates();
128
129        ModifyConsoleCommand(__CC_InputManager_name, __CC_calibrate_name).setObject(this);
130        ModifyConsoleCommand(__CC_InputManager_name, __CC_reload_name).setObject(this);
131
132        orxout(internal_status, context::input) << "InputManager: Construction complete." << endl;
133        internalState_ = Nothing;
134    }
135
136    void InputManager::setConfigValues()
137    {
138    }
139
140    /**
141    @brief
142        Creates the OIS::InputMananger, the keyboard, the mouse and
143        the joys ticks. If either of the first two fail, this method throws an exception.
144    */
145    void InputManager::loadDevices()
146    {
147        orxout(verbose, context::input) << "InputManager: Loading input devices..." << endl;
148
149        // When loading the devices they should not already be loaded
150        assert(internalState_ & Bad);
151        assert(devices_[InputDeviceEnumerator::Mouse] == 0);
152        assert(devices_[InputDeviceEnumerator::Keyboard] == 0);
153        assert(devices_.size() == InputDeviceEnumerator::FirstJoyStick);
154
155        typedef std::pair<std::string, std::string> StringPair;
156
157        // Fill parameter list
158        OIS::ParamList paramList;
159        size_t windowHnd = GraphicsManager::getInstance().getRenderWindowHandle();
160        paramList.insert(StringPair("WINDOW", multi_cast<std::string>(windowHnd)));
161#if defined(ORXONOX_PLATFORM_WINDOWS)
162        paramList.insert(StringPair("w32_keyboard", "DISCL_NONEXCLUSIVE"));
163        paramList.insert(StringPair("w32_keyboard", "DISCL_FOREGROUND"));
164        paramList.insert(StringPair("w32_mouse", "DISCL_FOREGROUND"));
165        if (exclusiveMouse_ || GraphicsManager::getInstance().isFullScreen())
166        {
167            // Disable Windows key plus special keys (like play, stop, next, etc.)
168            paramList.insert(StringPair("w32_keyboard", "DISCL_NOWINKEY"));
169            paramList.insert(StringPair("w32_mouse", "DISCL_EXCLUSIVE"));
170        }
171        else
172            paramList.insert(StringPair("w32_mouse", "DISCL_NONEXCLUSIVE"));
173#elif defined(ORXONOX_PLATFORM_LINUX)
174        // Enabling this is probably a bad idea, but whenever orxonox crashes, the setting stays on
175        // Trouble might be that the Pressed event occurs a bit too often...
176        paramList.insert(StringPair("XAutoRepeatOn", "true"));
177
178        if (exclusiveMouse_ || GraphicsManager::getInstance().isFullScreen())
179        {
180            if (CommandLineParser::getValue("keyboard_no_grab").get<bool>())
181                paramList.insert(StringPair("x11_keyboard_grab", "false"));
182            else
183                paramList.insert(StringPair("x11_keyboard_grab", "true"));
184            paramList.insert(StringPair("x11_mouse_grab",  "true"));
185            paramList.insert(StringPair("x11_mouse_hide", "true"));
186        }
187        else
188        {
189            paramList.insert(StringPair("x11_keyboard_grab", "false"));
190            paramList.insert(StringPair("x11_mouse_grab",  "false"));
191            paramList.insert(StringPair("x11_mouse_hide", "false"));
192        }
193#endif
194
195        try
196        {
197            oisInputManager_ = OIS::InputManager::createInputSystem(paramList);
198            // Exception-safety
199            Loki::ScopeGuard guard = Loki::MakeGuard(OIS::InputManager::destroyInputSystem, oisInputManager_);
200            orxout(verbose, context::input) << "Created OIS input manager." << endl;
201
202            if (oisInputManager_->getNumberOfDevices(OIS::OISKeyboard) > 0)
203                devices_[InputDeviceEnumerator::Keyboard] = new Keyboard(InputDeviceEnumerator::Keyboard, oisInputManager_);
204            else
205                ThrowException(InitialisationFailed, "InputManager: No keyboard found, cannot proceed!");
206
207            // Successful initialisation
208            guard.Dismiss();
209        }
210        catch (const std::exception& ex)
211        {
212            oisInputManager_ = NULL;
213            internalState_ |= Bad;
214            ThrowException(InitialisationFailed, "Could not initialise the input system: " << ex.what());
215        }
216
217        this->loadMouse();
218        this->loadJoySticks();
219
220        // Reorder states in case some joy sticks were added/removed
221        this->updateActiveStates();
222
223        orxout(verbose, context::input) << "Input devices loaded." << endl;
224    }
225
226    //! Creates a new orxonox::Mouse
227    void InputManager::loadMouse()
228    {
229        if (oisInputManager_->getNumberOfDevices(OIS::OISMouse) > 0)
230        {
231            try
232            {
233                devices_[InputDeviceEnumerator::Mouse] = new Mouse(InputDeviceEnumerator::Mouse, oisInputManager_);
234            }
235            catch (const std::exception& ex)
236            {
237                orxout(user_warning, context::input) << "Failed to create Mouse:" << ex.what() << '\n'
238                                                     << "Proceeding without mouse support." << endl;
239            }
240        }
241        else
242            orxout(user_warning, context::input) << "No mouse found! Proceeding without mouse support." << endl;
243    }
244
245    //! Creates as many joy sticks as are available.
246    void InputManager::loadJoySticks()
247    {
248        for (int i = 0; i < oisInputManager_->getNumberOfDevices(OIS::OISJoyStick); i++)
249        {
250            try
251            {
252                devices_.push_back(new JoyStick(InputDeviceEnumerator::FirstJoyStick + i, oisInputManager_));
253            }
254            catch (const std::exception& ex)
255            {
256                orxout(user_warning, context::input) << "Failed to create joy stick: " << ex.what() << endl;
257            }
258        }
259
260        // inform all JoyStick Device Number Listeners
261        std::vector<JoyStick*> joyStickList;
262        for (unsigned int i = InputDeviceEnumerator::FirstJoyStick; i < devices_.size(); ++i)
263            joyStickList.push_back(static_cast<JoyStick*>(devices_[i]));
264        JoyStickQuantityListener::changeJoyStickQuantity(joyStickList);
265    }
266
267    // ############################################################
268    // #####                    Destruction                   #####
269    // ##########                                        ##########
270    // ############################################################
271
272    InputManager::~InputManager()
273    {
274        orxout(internal_status, context::input) << "InputManager: Destroying..." << endl;
275
276        // Leave all active InputStates (except "empty")
277        while (this->activeStates_.size() > 1)
278            this->leaveState(this->activeStates_.rbegin()->second->getName());
279        this->activeStates_.clear();
280
281        // Destroy calibrator helper handler and state
282        this->destroyState("calibrator");
283        // Destroy KeyDetector and state
284        delete calibratorCallbackHandler_;
285        // Destroy the empty InputState
286        this->destroyStateInternal(this->emptyState_);
287
288        // Destroy all user InputStates
289        while (statesByName_.size() > 0)
290            this->destroyStateInternal(statesByName_.rbegin()->second);
291
292        if (!(internalState_ & Bad))
293            this->destroyDevices();
294
295        // Reset console commands
296        ModifyConsoleCommand(__CC_InputManager_name, __CC_calibrate_name).setObject(0);
297        ModifyConsoleCommand(__CC_InputManager_name, __CC_reload_name).setObject(0);
298
299        orxout(internal_status, context::input) << "InputManager: Destruction complete." << endl;
300    }
301
302    /**
303    @brief
304        Destoys all input devices (joy sticks, mouse, keyboard and OIS::InputManager)
305    @throw
306        Method does not throw
307    */
308    void InputManager::destroyDevices()
309    {
310        orxout(verbose, context::input) << "InputManager: Destroying devices..." << endl;
311
312        BOOST_FOREACH(InputDevice*& device, devices_)
313        {
314            if (device == NULL)
315                continue;
316            const std::string& className = device->getClassName();
317            delete device;
318            device = 0;
319            orxout(verbose, context::input) << className << " destroyed." << endl;
320        }
321        devices_.resize(InputDeviceEnumerator::FirstJoyStick);
322
323        assert(oisInputManager_ != NULL);
324        try
325        {
326            OIS::InputManager::destroyInputSystem(oisInputManager_);
327        }
328        catch (const OIS::Exception& ex)
329        {
330            orxout(internal_error, context::input) << "OIS::InputManager destruction failed" << ex.eText << '\n'
331                                                   << "Potential resource leak!" << endl;
332        }
333        oisInputManager_ = NULL;
334
335        internalState_ |= Bad;
336        orxout(verbose, context::input) << "Destroyed devices." << endl;
337    }
338
339    // ############################################################
340    // #####                     Reloading                    #####
341    // ##########                                        ##########
342    // ############################################################
343
344    void InputManager::reload()
345    {
346        if (internalState_ & Calibrating)
347            orxout(internal_warning, context::input) << "Cannot reload input system. Joy sticks are currently being calibrated." << endl;
348        else
349            reloadInternal();
350    }
351
352    //! Internal reload method. Destroys the OIS devices and loads them again.
353    void InputManager::reloadInternal()
354    {
355        orxout(verbose, context::input) << "InputManager: Reloading ..." << endl;
356
357        this->destroyDevices();
358        this->loadDevices();
359
360        internalState_ &= ~Bad;
361        orxout(verbose, context::input) << "InputManager: Reloading complete." << endl;
362    }
363
364    // ############################################################
365    // #####                  Runtime Methods                 #####
366    // ##########                                        ##########
367    // ############################################################
368
369    void InputManager::preUpdate(const Clock& time)
370    {
371        if (internalState_ & Bad)
372            ThrowException(General, "InputManager was not correctly reloaded.");
373
374        // check whether a state has changed its EMPTY situation
375        bool bUpdateRequired = false;
376        for (std::map<int, InputState*>::iterator it = activeStates_.begin(); it != activeStates_.end(); ++it)
377        {
378            if (it->second->hasExpired())
379            {
380                it->second->resetExpiration();
381                bUpdateRequired = true;
382            }
383        }
384        if (bUpdateRequired)
385            updateActiveStates();
386
387        // Capture all the input and collect the function calls
388        // No event gets triggered here yet!
389        BOOST_FOREACH(InputDevice* device, devices_)
390            if (device != NULL)
391                device->update(time);
392
393        // Collect function calls for the update
394        for (unsigned int i = 0; i < activeStatesTicked_.size(); ++i)
395            activeStatesTicked_[i]->update(time.getDeltaTime());
396
397        // Execute all cached function calls in order
398        // Why so complicated? The problem is that an InputHandler could trigger
399        // a reload that would destroy the OIS devices or it could even leave and
400        // then destroy its own InputState. That would of course lead to access
401        // violations.
402        // If we delay the calls, then OIS and and the InputStates are not anymore
403        // in the call stack and can therefore be edited.
404        for (size_t i = 0; i < this->callBuffer_.size(); ++i)
405            this->callBuffer_[i]();
406
407        this->callBuffer_.clear();
408    }
409
410    /**
411    @brief
412        Updates the currently active states (according to activeStates_) for each device.
413        Also, a list of all active states (no duplicates!) is compiled for the general preUpdate().
414    */
415    void InputManager::updateActiveStates()
416    {
417        // Calculate the stack of input states
418        // and assign it to the corresponding device
419        for (unsigned int i = 0; i < devices_.size(); ++i)
420        {
421            if (devices_[i] == NULL)
422                continue;
423            std::vector<InputState*>& states = devices_[i]->getStateListRef();
424            bool occupied = false;
425            states.clear();
426            for (std::map<int, InputState*>::reverse_iterator rit = activeStates_.rbegin(); rit != activeStates_.rend(); ++rit)
427            {
428                if (rit->second->isInputDeviceEnabled(i) && (!occupied || rit->second->bAlwaysGetsInput_))
429                {
430                    states.push_back(rit->second);
431                    if (!rit->second->bTransparent_)
432                        occupied = true;
433                }
434            }
435        }
436
437        // See that we only update each InputState once for each device
438        // Using an std::set to avoid duplicates
439        std::set<InputState*> tempSet;
440        for (unsigned int i = 0; i < devices_.size(); ++i)
441            if (devices_[i] != NULL)
442                for (unsigned int iState = 0; iState < devices_[i]->getStateListRef().size(); ++iState)
443                    tempSet.insert(devices_[i]->getStateListRef()[iState]);
444
445        // Copy the content of the std::set back to the actual vector
446        activeStatesTicked_.clear();
447        for (std::set<InputState*>::const_iterator it = tempSet.begin();it != tempSet.end(); ++it)
448            activeStatesTicked_.push_back(*it);
449
450        // Check whether we have to change the mouse mode
451        tribool requestedMode = dontcare;
452        std::vector<InputState*>& mouseStates = devices_[InputDeviceEnumerator::Mouse]->getStateListRef();
453        if (mouseStates.empty())
454            requestedMode = false;
455        else
456            requestedMode = mouseStates.front()->getMouseExclusive();
457        if (requestedMode != dontcare && exclusiveMouse_ != requestedMode)
458        {
459            assert(requestedMode != dontcare);
460            exclusiveMouse_ = (requestedMode == true);
461            if (!GraphicsManager::getInstance().isFullScreen())
462                this->reloadInternal();
463        }
464    }
465
466    void InputManager::clearBuffers()
467    {
468        BOOST_FOREACH(InputDevice* device, devices_)
469            if (device != NULL)
470                device->clearBuffers();
471    }
472
473    void InputManager::calibrate()
474    {
475        orxout(message) << "Move all joy stick axes fully in all directions." << '\n'
476                        << "When done, put the axex in the middle position and press enter." << endl;
477
478        BOOST_FOREACH(InputDevice* device, devices_)
479            if (device != NULL)
480                device->startCalibration();
481
482        internalState_ |= Calibrating;
483        enterState("calibrator");
484    }
485
486    //! Tells all devices to stop the calibration and evaluate it. Buffers are being cleared as well!
487    void InputManager::stopCalibration()
488    {
489        BOOST_FOREACH(InputDevice* device, devices_)
490            if (device != NULL)
491                device->stopCalibration();
492
493        // restore old input state
494        leaveState("calibrator");
495        internalState_ &= ~Calibrating;
496        // Clear buffers to prevent button hold events
497        this->clearBuffers();
498
499        orxout(message) << "Calibration has been stored." << endl;
500    }
501
502    //! Gets called by WindowEventListener upon focus change --> clear buffers
503    void InputManager::windowFocusChanged(bool bFocus)
504    {
505        this->clearBuffers();
506    }
507
508    std::pair<int, int> InputManager::getMousePosition() const
509    {
510        Mouse* mouse = static_cast<Mouse*>(devices_[InputDeviceEnumerator::Mouse]);
511        if (mouse != NULL)
512        {
513            const OIS::MouseState state = mouse->getOISDevice()->getMouseState();
514            return std::make_pair(state.X.abs, state.Y.abs);
515        }
516        else
517            return std::make_pair(0, 0);
518    }
519
520    // ############################################################
521    // #####                    Input States                  #####
522    // ##########                                        ##########
523    // ############################################################
524
525    InputState* InputManager::createInputState(const std::string& name, bool bAlwaysGetsInput, bool bTransparent, InputStatePriority priority)
526    {
527        if (name.empty())
528            return 0;
529        if (statesByName_.find(name) == statesByName_.end())
530        {
531            if (priority >= InputStatePriority::HighPriority || priority == InputStatePriority::Empty)
532            {
533                // Make sure we don't add two high priority states with the same priority
534                for (std::map<std::string, InputState*>::const_iterator it = this->statesByName_.begin();
535                    it != this->statesByName_.end(); ++it)
536                {
537                    if (it->second->getPriority() == priority)
538                    {
539                        orxout(internal_warning, context::input) << "Could not add an InputState with the same priority '"
540                            << static_cast<int>(priority) << "' != 0." << endl;
541                        return 0;
542                    }
543                }
544            }
545            InputState* state = new InputState(name, bAlwaysGetsInput, bTransparent, priority);
546            statesByName_[name] = state;
547
548            return state;
549        }
550        else
551        {
552            orxout(internal_warning, context::input) << "Could not add an InputState with the same name '" << name << "'." << endl;
553            return 0;
554        }
555    }
556
557    InputState* InputManager::getState(const std::string& name)
558    {
559        std::map<std::string, InputState*>::iterator it = statesByName_.find(name);
560        if (it != statesByName_.end())
561            return it->second;
562        else
563            return 0;
564    }
565
566    bool InputManager::enterState(const std::string& name)
567    {
568        // get pointer from the map with all stored handlers
569        std::map<std::string, InputState*>::const_iterator it = statesByName_.find(name);
570        if (it != statesByName_.end() && activeStates_.find(it->second->getPriority()) == activeStates_.end())
571        {
572            // exists and not active
573            if (it->second->getPriority() == 0)
574            {
575                // Get smallest possible priority between 1 and maxStateStackSize_s
576                for (std::map<int, InputState*>::reverse_iterator rit = activeStates_.rbegin();
577                    rit != activeStates_.rend(); ++rit)
578                {
579                    if (rit->first < InputStatePriority::HighPriority)
580                    {
581                        it->second->setPriority(rit->first + 1);
582                        break;
583                    }
584                }
585                // In case no normal handler was on the stack
586                if (it->second->getPriority() == 0)
587                    it->second->setPriority(1);
588            }
589            activeStates_[it->second->getPriority()] = it->second;
590            updateActiveStates();
591            it->second->entered();
592
593            return true;
594        }
595        return false;
596    }
597
598    bool InputManager::leaveState(const std::string& name)
599    {
600        if (name == "empty")
601        {
602            orxout(internal_warning, context::input) << "InputManager: Leaving the empty state is not allowed!" << endl;
603            return false;
604        }
605        // get pointer from the map with all stored handlers
606        std::map<std::string, InputState*>::const_iterator it = statesByName_.find(name);
607        if (it != statesByName_.end() && activeStates_.find(it->second->getPriority()) != activeStates_.end())
608        {
609            // exists and active
610
611            it->second->left();
612
613            activeStates_.erase(it->second->getPriority());
614            if (it->second->getPriority() < InputStatePriority::HighPriority)
615                it->second->setPriority(0);
616            updateActiveStates();
617
618            return true;
619        }
620        return false;
621    }
622
623    bool InputManager::destroyState(const std::string& name)
624    {
625        if (name == "empty")
626        {
627            orxout(internal_warning, context::input) << "InputManager: Removing the empty state is not allowed!" << endl;
628            return false;
629        }
630        std::map<std::string, InputState*>::iterator it = statesByName_.find(name);
631        if (it != statesByName_.end())
632        {
633            this->leaveState(name);
634            destroyStateInternal(it->second);
635
636            return true;
637        }
638        return false;
639    }
640
641    //! Destroys an InputState internally.
642    void InputManager::destroyStateInternal(InputState* state)
643    {
644        assert(state && this->activeStates_.find(state->getPriority()) == this->activeStates_.end());
645        statesByName_.erase(state->getName());
646        delete state;
647    }
648
649    bool InputManager::setMouseExclusive(const std::string& name, tribool value)
650    {
651        if (name == "empty")
652        {
653            orxout(internal_warning, context::input) << "InputManager: Changing the empty state is not allowed!" << endl;
654            return false;
655        }
656        std::map<std::string, InputState*>::iterator it = statesByName_.find(name);
657        if (it != statesByName_.end())
658        {
659            it->second->setMouseExclusive(value);
660            return true;
661        }
662        return false;
663    }
664}
Note: See TracBrowser for help on using the repository browser.