Planet
navi homePPSaboutscreenshotsdownloaddevelopmentforum

source: code/branches/core4/src/core/input/KeyBinder.cc @ 3288

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

Finally found a satisfying way to deal with interfaces that deliver information, but only upon virtual call.
The solution involves a static variable but any other (and uglier/hackier) solution will do so too.
I applied the method the the JoyStickQuantityListener so that the KeyBinder is now independent on the InputManager.

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