Planet
navi homePPSaboutscreenshotsdownloaddevelopmentforum

source: code/branches/chat/src/libraries/core/input/KeyBinder.cc @ 7078

Last change on this file since 7078 was 6428, checked in by rgrieder, 15 years ago

Changed config value handling in the KeyBinder. Doesn't change the interface though.

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