Planet
navi homePPSaboutscreenshotsdownloaddevelopmentforum

source: code/trunk/src/core/input/KeyBinder.cc @ 3021

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

Merged gui branch back to trunk.

I did 2 small changes in IngameManager.cc on line 777 and 888 (yes, really), because const_reverse_iterator strangely doesn't work on MinGW.

  • Property svn:eol-style set to native
File size: 18.5 KB
RevLine 
[971]1/*
2 *   ORXONOX - the hottest 3D action shooter ever to exist
[1349]3 *                    > www.orxonox.net <
[971]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 */
[973]28
[971]29/**
30 @file
[973]31 @brief Implementation of the different input handlers.
[971]32 */
33
[1413]34#include "KeyBinder.h"
[2662]35
[1413]36#include <fstream>
[1520]37#include <string>
[2662]38
[1293]39#include "util/Convert.h"
[1747]40#include "util/Debug.h"
[1519]41#include "core/ConfigValueIncludes.h"
42#include "core/CoreIncludes.h"
[1795]43#include "core/ConfigFileManager.h"
[1520]44#include "InputCommands.h"
[1887]45#include "InputManager.h"
[971]46
47namespace orxonox
48{
[1755]49    /**
50    @brief
51        Constructor that does as little as necessary.
52    */
53    KeyBinder::KeyBinder()
[1887]54        : numberOfJoySticks_(0)
55        , deriveTime_(0.0f)
[1755]56    {
57        mouseRelative_[0] = 0;
58        mouseRelative_[1] = 0;
59        mousePosition_[0] = 0;
60        mousePosition_[1] = 0;
[1391]61
[1755]62        RegisterRootObject(KeyBinder);
[1293]63
[1887]64        // intialise all buttons and half axes to avoid creating everything with 'new'
[1755]65        // keys
[1887]66        for (unsigned int i = 0; i < KeyCode::numberOfKeys; i++)
[1755]67        {
[1887]68            std::string keyname = KeyCode::ByString[i];
69            if (!keyname.empty())
70                keys_[i].name_ = std::string("Key") + keyname;
71            else
[2662]72                keys_[i].name_ = "";
[1887]73            keys_[i].paramCommandBuffer_ = &paramCommandBuffer_;
74            keys_[i].groupName_ = "Keys";
[1755]75        }
[1887]76        // mouse buttons plus 4 mouse wheel buttons only 'generated' by KeyBinder
77        const char* const mouseWheelNames[] = { "Wheel1Down", "Wheel1Up", "Wheel2Down", "Wheel2Up" };
78        for (unsigned int i = 0; i < numberOfMouseButtons_; i++)
[1755]79        {
[1887]80            std::string nameSuffix;
81            if (i < MouseButtonCode::numberOfButtons)
82                nameSuffix = MouseButtonCode::ByString[i];
83            else
84                nameSuffix = mouseWheelNames[i - MouseButtonCode::numberOfButtons];
85            mouseButtons_[i].name_ = std::string("Mouse") + nameSuffix;
86            mouseButtons_[i].paramCommandBuffer_ = &paramCommandBuffer_;
87            mouseButtons_[i].groupName_ = "MouseButtons";
[1755]88        }
[1887]89        // mouse axes
90        for (unsigned int i = 0; i < MouseAxisCode::numberOfAxes * 2; i++)
91        {
[2662]92            mouseAxes_[i].name_ = std::string("Mouse") + MouseAxisCode::ByString[i / 2];
[1887]93            if (i & 1)
94                mouseAxes_[i].name_ += "Pos";
95            else
96                mouseAxes_[i].name_ += "Neg";
97            mouseAxes_[i].paramCommandBuffer_ = &paramCommandBuffer_;
98            mouseAxes_[i].groupName_ = "MouseAxes";
99        }
[1755]100
[2103]101        // Get a new ConfigFileType from the ConfigFileManager
102        this->configFile_ = ConfigFileManager::getInstance().getNewConfigFileType();
103
[1887]104        // initialise joy sticks separatly to allow for reloading
105        numberOfJoySticks_ = InputManager::getInstance().numberOfJoySticks();
106        initialiseJoyStickBindings();
107
108        // collect all Buttons and HalfAxes
109        compilePointerLists();
110
111        // set them here to use allHalfAxes_
112        setConfigValues();
[1413]113    }
114
[1755]115    /**
116    @brief
117        Destructor
118    */
119    KeyBinder::~KeyBinder()
[1413]120    {
[1755]121        // almost no destructors required because most of the arrays are static.
122        clearBindings(); // does some destruction work
[1413]123    }
124
[1755]125    /**
126    @brief
127        Loader for the key bindings, managed by config values.
128    */
129    void KeyBinder::setConfigValues()
130    {
131        SetConfigValue(analogThreshold_, 0.05f)
132            .description("Threshold for analog axes until which the state is 0.");
[2087]133        SetConfigValue(bFilterAnalogNoise_, false)
134            .description("Specifies whether to filter small analog values like joy stick fluctuations.");
[1755]135        SetConfigValue(mouseSensitivity_, 1.0f)
136            .description("Mouse sensitivity.");
137        SetConfigValue(bDeriveMouseInput_, false)
138            .description("Whether or not to derive moues movement for the absolute value.");
139        SetConfigValue(derivePeriod_, 0.05f)
140            .description("Accuracy of the mouse input deriver. The higher the more precise, but laggier.");
141        SetConfigValue(mouseSensitivityDerived_, 1.0f)
142            .description("Mouse sensitivity if mouse input is derived.");
[2087]143        SetConfigValue(mouseWheelStepSize_, 120)
[1887]144            .description("Equals one step of the mousewheel.");
[1755]145        SetConfigValue(buttonThreshold_, 0.80f)
[1887]146            .description("Threshold for analog axes until which the button is not pressed.")
147            .callback(this, &KeyBinder::buttonThresholdChanged);
148    }
[973]149
[1887]150    void KeyBinder::buttonThresholdChanged()
151    {
152        for (unsigned int i = 0; i < allHalfAxes_.size(); i++)
153            if (!allHalfAxes_[i]->bButtonThresholdUser_)
154                allHalfAxes_[i]->buttonThreshold_ = this->buttonThreshold_;
[1755]155    }
[1293]156
[1887]157    void KeyBinder::JoyStickDeviceNumberChanged(unsigned int value)
[1755]158    {
[1887]159        unsigned int oldValue = numberOfJoySticks_;
160        numberOfJoySticks_ = value;
161
162        // initialise joy stick bindings
163        initialiseJoyStickBindings();
164
165        // collect all Buttons and HalfAxes again
166        compilePointerLists();
167
168        // load the bindings if required
[2103]169        if (configFile_ != ConfigFileType::NoType)
[1755]170        {
[1887]171            for (unsigned int iDev = oldValue; iDev < numberOfJoySticks_; ++iDev)
172            {
173                for (unsigned int i = 0; i < JoyStickButtonCode::numberOfButtons; ++i)
[2103]174                    joyStickButtons_[iDev][i].readConfigValue(this->configFile_);
[1887]175                for (unsigned int i = 0; i < JoyStickAxisCode::numberOfAxes * 2; ++i)
[2103]176                    joyStickAxes_[iDev][i].readConfigValue(this->configFile_);
[1887]177            }
[1755]178        }
[1293]179
[1887]180        // Set the button threshold for potential new axes
181        buttonThresholdChanged();
182    }
183
184    void KeyBinder::initialiseJoyStickBindings()
185    {
186        this->joyStickAxes_.resize(numberOfJoySticks_);
187        this->joyStickButtons_.resize(numberOfJoySticks_);
188
189        // reinitialise all joy stick binings (doesn't overwrite the old ones)
190        for (unsigned int iDev = 0; iDev < numberOfJoySticks_; iDev++)
[1755]191        {
[1887]192            std::string deviceNumber = convertToString(iDev);
193            // joy stick buttons
194            for (unsigned int i = 0; i < JoyStickButtonCode::numberOfButtons; i++)
195            {
196                joyStickButtons_[iDev][i].name_ = std::string("JoyStick") + deviceNumber + JoyStickButtonCode::ByString[i];
197                joyStickButtons_[iDev][i].paramCommandBuffer_ = &paramCommandBuffer_;
198                joyStickButtons_[iDev][i].groupName_ = std::string("JoyStick") + deviceNumber + "Buttons";
199            }
200            // joy stick axes
201            for (unsigned int i = 0; i < JoyStickAxisCode::numberOfAxes * 2; i++)
202            {
203                joyStickAxes_[iDev][i].name_ = std::string("JoyStick") + deviceNumber + JoyStickAxisCode::ByString[i >> 1];
204                if (i & 1)
205                    joyStickAxes_[iDev][i].name_ += "Pos";
206                else
207                    joyStickAxes_[iDev][i].name_ += "Neg";
208                joyStickAxes_[iDev][i].paramCommandBuffer_ = &paramCommandBuffer_;
209                joyStickAxes_[iDev][i].groupName_ = std::string("JoyStick") + deviceNumber + "Axes";
210            }
211        }
212    }
[973]213
[1887]214    void KeyBinder::compilePointerLists()
215    {
216        allButtons_.clear();
217        allHalfAxes_.clear();
218
[2662]219        // Note: Don't include the dummy keys which don't actually exist in OIS but have a number
[1887]220        for (unsigned int i = 0; i < KeyCode::numberOfKeys; i++)
[2662]221            if (!keys_[i].name_.empty())
222                allButtons_[keys_[i].name_] = keys_ + i;
[1887]223        for (unsigned int i = 0; i < numberOfMouseButtons_; i++)
224            allButtons_[mouseButtons_[i].name_] = mouseButtons_ + i;
225        for (unsigned int i = 0; i < MouseAxisCode::numberOfAxes * 2; i++)
226        {
227            allButtons_[mouseAxes_[i].name_] = mouseAxes_ + i;
228            allHalfAxes_.push_back(mouseAxes_ + i);
[1755]229        }
[1887]230        for (unsigned int iDev = 0; iDev < numberOfJoySticks_; iDev++)
231        {
232            for (unsigned int i = 0; i < JoyStickButtonCode::numberOfButtons; i++)
233                allButtons_[joyStickButtons_[iDev][i].name_] = &(joyStickButtons_[iDev][i]);
234            for (unsigned int i = 0; i < JoyStickAxisCode::numberOfAxes * 2; i++)
235            {
236                allButtons_[joyStickAxes_[iDev][i].name_] = &(joyStickAxes_[iDev][i]);
237                allHalfAxes_.push_back(&(joyStickAxes_[iDev][i]));
238            }
239        }
[1349]240    }
241
[1755]242    /**
243    @brief
[1887]244        Loads the key and button bindings.
245    @return
246        True if loading succeeded.
[1755]247    */
[2710]248    void KeyBinder::loadBindings(const std::string& filename)
[1349]249    {
[1887]250        COUT(3) << "KeyBinder: Loading key bindings..." << std::endl;
[1428]251
[2103]252        if (filename.empty())
[1887]253            return;
[1293]254
[2103]255        ConfigFileManager::getInstance().setFilename(this->configFile_, filename);
[1219]256
[1887]257        // Parse bindings and create the ConfigValueContainers if necessary
258        clearBindings();
259        for (std::map<std::string, Button*>::const_iterator it = allButtons_.begin(); it != allButtons_.end(); ++it)
[2103]260            it->second->readConfigValue(this->configFile_);
[1349]261
[1887]262        COUT(3) << "KeyBinder: Loading key bindings done." << std::endl;
263    }
264
265    bool KeyBinder::setBinding(const std::string& binding, const std::string& name, bool bTemporary)
266    {
267        std::map<std::string, Button*>::iterator it = allButtons_.find(name);
268        if (it != allButtons_.end())
269        {
270            if (bTemporary)
271                it->second->configContainer_->tset(binding);
272            else
273                it->second->configContainer_->set(binding);
274            it->second->configContainer_->getValue(&(it->second->bindingString_), it->second);
275            return true;
276        }
277        else
278        {
279            COUT(2) << "Could not find key/button/axis with name '" << name << "'." << std::endl;
280            return false;
281        }
282    }
283
284    /**
285    @brief
286        Overwrites all bindings with ""
287    */
288    void KeyBinder::clearBindings()
289    {
290        for (std::map<std::string, Button*>::const_iterator it = allButtons_.begin(); it != allButtons_.end(); ++it)
291            it->second->clear();
292
[1755]293        for (unsigned int i = 0; i < paramCommandBuffer_.size(); i++)
294            delete paramCommandBuffer_[i];
295        paramCommandBuffer_.clear();
296    }
[1349]297
[1755]298    void KeyBinder::resetJoyStickAxes()
[1461]299    {
[1887]300        for (unsigned int iDev = 0; iDev < numberOfJoySticks_; ++iDev)
[1755]301        {
[1887]302            for (unsigned int i = 0; i < JoyStickAxisCode::numberOfAxes * 2; i++)
303            {
304                joyStickAxes_[iDev][i].absVal_ = 0.0f;
305                joyStickAxes_[iDev][i].relVal_ = 0.0f;
306            }
[1755]307        }
[1461]308    }
309
[2896]310    void KeyBinder::updateMouse(float dt)
[1349]311    {
[1755]312        if (bDeriveMouseInput_)
[1349]313        {
[2662]314            // only update when derivation dt has passed
[1755]315            if (deriveTime_ > derivePeriod_)
316            {
317                for (int i = 0; i < 2; i++)
318                {
[2662]319                    if (mouseRelative_[i] < 0)
[1755]320                    {
[1887]321                        mouseAxes_[2*i + 0].absVal_
[2662]322                            = -mouseRelative_[i] / deriveTime_ * 0.0005 * mouseSensitivityDerived_;
[1887]323                        mouseAxes_[2*i + 1].absVal_ = 0.0f;
[1755]324                    }
[2662]325                    else if (mouseRelative_[i] > 0)
[1755]326                    {
[1887]327                        mouseAxes_[2*i + 0].absVal_ = 0.0f;
328                        mouseAxes_[2*i + 1].absVal_
[2662]329                            =  mouseRelative_[i] / deriveTime_ * 0.0005 * mouseSensitivityDerived_;
[1755]330                    }
331                    else
332                    {
[1887]333                        mouseAxes_[2*i + 0].absVal_ = 0.0f;
334                        mouseAxes_[2*i + 1].absVal_ = 0.0f;
[1755]335                    }
336                    mouseRelative_[i] = 0;
[1887]337                    mouseAxes_[2*i + 0].hasChanged_ = true;
338                    mouseAxes_[2*i + 1].hasChanged_ = true;
[1755]339                }
340                deriveTime_ = 0.0f;
341            }
342            else
343                deriveTime_ += dt;
[1349]344        }
[1219]345
[2087]346        for (unsigned int i = 0; i < MouseAxisCode::numberOfAxes * 2; i++)
[1349]347        {
[2087]348            // Why dividing relative value by dt? The reason lies in the simple fact, that when you
349            // press a button that has relative movement, that value has to be multiplied by dt to be
[2896]350            // frame rate independent. This can easily (and only) be done in updateInput(float).
[2087]351            // Hence we need to divide by dt here for the mouse to compensate, because the relative
352            // move movements have nothing to do with dt.
353            if (dt != 0.0f)
[1755]354            {
[2087]355                // just ignore if dt == 0.0 because we have multiplied by 0.0 anyway..
356                mouseAxes_[i].relVal_ /= dt;
[1755]357            }
358
[2087]359            tickHalfAxis(mouseAxes_[i]);
360        }
361    }
362
[2896]363    void KeyBinder::updateJoyStick(float dt, unsigned int joyStick)
[2087]364    {
365        for (unsigned int i = 0; i < JoyStickAxisCode::numberOfAxes * 2; i++)
366        {
367            tickHalfAxis(joyStickAxes_[joyStick][i]);
368        }
369    }
370
371    void KeyBinder::tickHalfAxis(HalfAxis& halfAxis)
372    {
373        // button mode
374        // TODO: optimize out all the half axes that don't act as a button at the moment
375        if (halfAxis.hasChanged_)
376        {
377            if (!halfAxis.pressed_ && halfAxis.absVal_ > halfAxis.buttonThreshold_)
[1755]378            {
[2087]379                // key pressed event
380                halfAxis.pressed_ = true;
381                if (halfAxis.nCommands_[KeybindMode::OnPress])
382                    halfAxis.execute(KeybindMode::OnPress);
[1755]383            }
[2087]384            else if (halfAxis.pressed_ && halfAxis.absVal_ < halfAxis.buttonThreshold_)
[1755]385            {
[2087]386                // key released event
387                halfAxis.pressed_ = false;
388                if (halfAxis.nCommands_[KeybindMode::OnRelease])
389                    halfAxis.execute(KeybindMode::OnRelease);
[1755]390            }
[2087]391            halfAxis.hasChanged_ = false;
[1349]392        }
[2087]393
394        if (halfAxis.pressed_)
395        {
396            // key held event
397            if (halfAxis.nCommands_[KeybindMode::OnHold])
398                halfAxis.execute(KeybindMode::OnHold);
399        }
400
401        // these are the actually useful axis bindings for analog input
402        if (!bFilterAnalogNoise_ || halfAxis.relVal_ > analogThreshold_ || halfAxis.absVal_ > analogThreshold_)
403        {
404            halfAxis.execute();
405        }
[1349]406    }
407
[1755]408    /**
409    @brief
410        Event handler for the mouseMoved Event.
411    @param e
412        Mouse state information
413    */
414    void KeyBinder::mouseMoved(IntVector2 abs_, IntVector2 rel_, IntVector2 clippingSize)
415    {
416        // y axis of mouse input is inverted
417        int rel[] = { rel_.x, -rel_.y };
[1349]418
[2087]419        if (bDeriveMouseInput_)
[1755]420        {
[2087]421            mouseRelative_[0] += rel[0];
422            mouseRelative_[1] += rel[1];
423        }
424        else
425        {
[1755]426            for (int i = 0; i < 2; i++)
427            {
[2662]428                if (rel[i]) // performance opt. for the case that rel[i] == 0
[1755]429                {
[1887]430                    // write absolute values
431                    mouseAxes_[2*i + 0].hasChanged_ = true;
432                    mouseAxes_[2*i + 1].hasChanged_ = true;
[1755]433                    mousePosition_[i] += rel[i];
[1349]434
[1887]435                    // clip absolute position
436                    if (mousePosition_[i] > mouseClippingSize_)
437                        mousePosition_[i] =  mouseClippingSize_;
438                    if (mousePosition_[i] < -mouseClippingSize_)
439                        mousePosition_[i] = -mouseClippingSize_;
[1428]440
[2662]441                    if (mousePosition_[i] < 0)
[1755]442                    {
[2662]443                        mouseAxes_[2*i + 0].absVal_ =  -mousePosition_[i]/(float)mouseClippingSize_ * mouseSensitivity_;
[1887]444                        mouseAxes_[2*i + 1].absVal_ =  0.0f;
[1755]445                    }
446                    else
447                    {
[1887]448                        mouseAxes_[2*i + 0].absVal_ =  0.0f;
[2662]449                        mouseAxes_[2*i + 1].absVal_ =   mousePosition_[i]/(float)mouseClippingSize_ * mouseSensitivity_;
[1755]450                    }
451                }
452            }
453        }
[1428]454
[1755]455        // relative
456        for (int i = 0; i < 2; i++)
457        {
[2662]458            if (rel[i] < 0)
459                mouseAxes_[0 + 2*i].relVal_ = -((float)rel[i])/(float)mouseClippingSize_ * mouseSensitivity_;
[1755]460            else
[2662]461                mouseAxes_[1 + 2*i].relVal_ =  ((float)rel[i])/(float)mouseClippingSize_ * mouseSensitivity_;
[1349]462        }
463    }
[1428]464
[1755]465    /**
[1349]466    @brief Event handler for the mouseScrolled Event.
467    @param e Mouse state information
[1755]468    */
469    void KeyBinder::mouseScrolled(int abs, int rel)
[1349]470    {
[2662]471        if (rel < 0)
472            for (int i = 0; i < -rel/mouseWheelStepSize_; i++)
[1887]473                mouseButtons_[8].execute(KeybindMode::OnPress, ((float)abs)/mouseWheelStepSize_);
[1755]474        else
[2662]475            for (int i = 0; i < rel/mouseWheelStepSize_; i++)
[1887]476                mouseButtons_[9].execute(KeybindMode::OnPress, ((float)abs)/mouseWheelStepSize_);
[1349]477    }
[1755]478
479    void KeyBinder::joyStickAxisMoved(unsigned int joyStickID, unsigned int axis, float value)
[1349]480    {
[1887]481        int i = axis * 2;
[2662]482        if (value < 0)
[1755]483        {
[2662]484            joyStickAxes_[joyStickID][i].absVal_ = -value;
485            joyStickAxes_[joyStickID][i].relVal_ = -value;
[1887]486            joyStickAxes_[joyStickID][i].hasChanged_ = true;
487            if (joyStickAxes_[joyStickID][i + 1].absVal_ > 0.0f)
[1755]488            {
[1887]489                joyStickAxes_[joyStickID][i + 1].absVal_ = -0.0f;
490                joyStickAxes_[joyStickID][i + 1].relVal_ = -0.0f;
491                joyStickAxes_[joyStickID][i + 1].hasChanged_ = true;
[1755]492            }
493        }
494        else
495        {
[2662]496            joyStickAxes_[joyStickID][i + 1].absVal_ = value;
497            joyStickAxes_[joyStickID][i + 1].relVal_ = value;
[1887]498            joyStickAxes_[joyStickID][i + 1].hasChanged_ = true;
499            if (joyStickAxes_[joyStickID][i].absVal_ > 0.0f)
[1755]500            {
[1887]501                joyStickAxes_[joyStickID][i].absVal_ = -0.0f;
502                joyStickAxes_[joyStickID][i].relVal_ = -0.0f;
503                joyStickAxes_[joyStickID][i].hasChanged_ = true;
[1755]504            }
505        }
[1349]506    }
[971]507}
Note: See TracBrowser for help on using the repository browser.