Planet
navi homePPSaboutscreenshotsdownloaddevelopmentforum

source: code/trunk/src/libraries/core/input/Button.cc @ 9978

Last change on this file since 9978 was 9978, checked in by landauf, 10 years ago

added new keybind mode 'OnPressAndRelease' which triggers both when a button is pressed and when it's released.
pressed buttons send the value '1' to the bound console command, while released buttons send the value '0'.

  • Property svn:eol-style set to native
File size: 10.0 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 different input handlers.
33*/
34
35#include "Button.h"
36
37#include "util/Convert.h"
38#include "util/SubString.h"
39#include "util/StringUtils.h"
40#include "util/Output.h"
41#include "core/command/ConsoleCommand.h"
42#include "core/command/CommandEvaluation.h"
43#include "core/command/CommandExecutor.h"
44#include "core/config/ConfigFile.h"
45
46namespace orxonox
47{
48    /**
49    @note
50        bButtonThresholdUser_: We set it to true so that setConfigValues in KeyBinder sets the value
51        correctly the first time. It is then set to false first and changed later in Button::parse().
52    */
53    Button::Button()
54        : bButtonThresholdUser_(false)
55        , paramCommandBuffer_(0)
56    {
57        nCommands_[0]=0;
58        nCommands_[1]=0;
59        nCommands_[2]=0;
60    }
61
62    Button::~Button()
63    {
64        this->clear();
65    }
66
67    void Button::clear()
68    {
69        for (unsigned int j = 0; j < 3; j++)
70        {
71            if (nCommands_[j])
72            {
73                // delete all commands and the command pointer array
74                for (unsigned int i = 0; i < nCommands_[j]; i++)
75                    delete commands_[j][i];
76                delete[] commands_[j];
77                commands_[j] = 0;
78                nCommands_[j] = 0;
79            }
80        }
81        this->bindingString_.clear();
82    }
83
84    void Button::readBinding(ConfigFile* configFile, ConfigFile* fallbackFile)
85    {
86        std::string binding = configFile->getOrCreateValue(groupName_, name_, "", true);
87        if (binding.empty() && fallbackFile)
88            binding = fallbackFile->getValue(groupName_, name_, true);
89        this->parse(binding);
90    }
91
92    void Button::setBinding(ConfigFile* configFile, ConfigFile* fallbackFile, const std::string& binding, bool bTemporary)
93    {
94        if (!bTemporary)
95            configFile->setValue(groupName_, name_, binding, true);
96        this->parse(binding);
97    }
98
99    void Button::parse(const std::string& binding)
100    {
101        if (binding == this->bindingString_)
102            return;
103
104        // delete all commands
105        clear();
106        this->bindingString_ = binding;
107
108        if (isEmpty(bindingString_) || removeTrailingWhitespaces(getLowercase(binding)) == "nobinding")
109            return;
110
111        // reset this to false first when parsing (was true before when parsing for the first time)
112        bButtonThresholdUser_ = false;
113
114        // use std::vector for a temporary dynamic array
115        std::vector<BaseCommand*> commands[3];
116
117        // separate the commands
118        SubString commandStrings(bindingString_, "|", SubString::WhiteSpaces, false,
119            '\\', false, '"', false, '{', '}', false, '\0');
120
121        for (unsigned int iCommand = 0; iCommand < commandStrings.size(); iCommand++)
122        {
123            if (!commandStrings[iCommand].empty())
124            {
125                SubString tokens(commandStrings[iCommand], " ", SubString::WhiteSpaces, false,
126                    '\\', false, '"', false, '{', '}', false, '\0');
127
128                KeybindMode::Value mode = KeybindMode::None;
129                float paramModifier = 1.0f;
130                std::string commandStr;
131
132                for (unsigned int iToken = 0; iToken < tokens.size(); ++iToken)
133                {
134                    const std::string& token = getLowercase(tokens[iToken]);
135
136                    if (token == "onpress")
137                        mode = KeybindMode::OnPress;
138                    else if (token == "onrelease")
139                        mode = KeybindMode::OnRelease;
140                    else if (token == "onpressandrelease")
141                        mode = KeybindMode::OnPressAndRelease;
142                    else if (token == "onhold")
143                        mode = KeybindMode::OnHold;
144                    else if (token == "buttonthreshold")
145                    {
146                        // for real axes, we can feed a ButtonThreshold argument
147                        ++iToken;
148                        if (iToken == tokens.size())
149                            continue;
150                        // may fail, but doesn't matter (default value already set)
151                        if (!convertValue(&buttonThreshold_, tokens[iToken + 1]))
152                            parseError("Could not parse 'ButtonThreshold' argument. \
153                                Switching to default value.", true);
154                        else
155                            this->bButtonThresholdUser_ = true;
156                    }
157                    else if (token == "scale")
158                    {
159                        ++iToken;
160                        if (iToken == tokens.size() || !convertValue(&paramModifier, tokens[iToken]))
161                            parseError("Could not parse 'scale' argument. Switching to default value.", true);
162                    }
163                    else
164                    {
165                        // no input related argument
166                        // we interpret everything from here as a command string
167                        while (iToken != tokens.size())
168                            commandStr += tokens[iToken++] + ' ';
169                    }
170                }
171
172                if (commandStr.empty())
173                {
174                    parseError("No command string given.", false);
175                    continue;
176                }
177
178                // evaluate the command
179                CommandEvaluation eval = CommandExecutor::evaluate(commandStr);
180                if (!eval.isValid() || eval.evaluateArguments(true))
181                {
182                    parseError("Command evaluation of \"" + commandStr + "\"failed.", true);
183                    continue;
184                }
185
186                // check for param command
187                int paramIndex = eval.getConsoleCommand()->getInputConfiguredParam_();
188                if (paramIndex >= 0)
189                {
190                    // parameter supported command
191                    ParamCommand* cmd = new ParamCommand();
192                    cmd->scale_ = paramModifier;
193
194                    // add command to the buffer if not yet existing
195                    for (unsigned int iParamCmd = 0; iParamCmd < paramCommandBuffer_->size(); iParamCmd++)
196                    {
197                        if ((*paramCommandBuffer_)[iParamCmd]->evaluation_.getConsoleCommand()
198                            == eval.getConsoleCommand())
199                        {
200                            // already in list
201                            cmd->paramCommand_ = (*paramCommandBuffer_)[iParamCmd];
202                            break;
203                        }
204                    }
205                    if (cmd->paramCommand_ == 0)
206                    {
207                        cmd->paramCommand_ = new BufferedParamCommand();
208                        paramCommandBuffer_->push_back(cmd->paramCommand_);
209                        cmd->paramCommand_->evaluation_ = eval;
210                        cmd->paramCommand_->paramIndex_ = paramIndex;
211                    }
212
213
214                    // we don't know whether this is an actual axis or just a button
215                    if (mode == KeybindMode::None)
216                    {
217                        if (!addParamCommand(cmd))
218                        {
219                            mode = eval.getConsoleCommand()->getKeybindMode();
220                            this->addCommand(cmd, mode, commands);
221                        }
222                    }
223                    else
224                        cmd->setFixedKeybindMode(true);
225                }
226                else
227                {
228                    SimpleCommand* cmd = new SimpleCommand();
229                    cmd->evaluation_ = eval;
230
231                    if (mode == KeybindMode::None)
232                        mode = eval.getConsoleCommand()->getKeybindMode();
233                    else
234                        cmd->setFixedKeybindMode(true);
235
236                    this->addCommand(cmd, mode, commands);
237                }
238            }
239        }
240
241        for (unsigned int j = 0; j < 3; j++)
242        {
243            nCommands_[j] = commands[j].size();
244            if (nCommands_[j])
245            {
246                commands_[j] = new BaseCommand*[nCommands_[j]];
247                for (unsigned int i = 0; i < commands[j].size(); i++)
248                    commands_[j][i] = commands[j][i];
249            }
250            else
251                commands_[j] = 0;
252        }
253    }
254
255    inline void Button::addCommand(BaseCommand* cmd, KeybindMode::Value mode, std::vector<BaseCommand*> commands[3])
256    {
257        if (mode == KeybindMode::OnPressAndRelease)
258        {
259            BaseCommand* cmd2 = cmd->clone();
260
261            commands[KeybindMode::OnPress].push_back(cmd);
262            commands[KeybindMode::OnRelease].push_back(cmd2); // clone
263        }
264        else
265            commands[mode].push_back(cmd);
266    }
267
268    inline void Button::parseError(const std::string& message, bool serious)
269    {
270        if (serious)
271        {
272            orxout(internal_error, context::input) << "Error while parsing binding for button/axis " << this->name_ << ". "
273                << message << endl;
274        }
275        else
276        {
277            orxout(internal_warning, context::input) << "Warning while parsing binding for button/axis " << this->name_ << ". "
278                << message << endl;
279        }
280    }
281}
Note: See TracBrowser for help on using the repository browser.