GCC Code Coverage Report
Directory: src/ Exec Total Coverage
File: src/input/joystick.cpp Lines: 4 170 2.4 %
Date: 2017-11-29 Branches: 1 196 0.5 %

Line Branch Exec Source
1
/*
2
 *  The ManaPlus Client
3
 *  Copyright (C) 2004-2009  The Mana World Development Team
4
 *  Copyright (C) 2009-2010  The Mana Developers
5
 *  Copyright (C) 2011-2017  The ManaPlus Developers
6
 *
7
 *  This file is part of The ManaPlus Client.
8
 *
9
 *  This program is free software; you can redistribute it and/or modify
10
 *  it under the terms of the GNU General Public License as published by
11
 *  the Free Software Foundation; either version 2 of the License, or
12
 *  any later version.
13
 *
14
 *  This program is distributed in the hope that it will be useful,
15
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
16
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
17
 *  GNU General Public License for more details.
18
 *
19
 *  You should have received a copy of the GNU General Public License
20
 *  along with this program.  If not, see <http://www.gnu.org/licenses/>.
21
 */
22
23
#include "input/joystick.h"
24
25
#include "configuration.h"
26
#include "logger.h"
27
#include "settings.h"
28
#include "sdlshared.h"
29
30
#include "input/inputmanager.h"
31
32
#include "utils/foreach.h"
33
#include "utils/timer.h"
34
35
PRAGMA48(GCC diagnostic push)
36
PRAGMA48(GCC diagnostic ignored "-Wshadow")
37
#include <SDL.h>
38
PRAGMA48(GCC diagnostic pop)
39
40
#include "debug.h"
41
42
Joystick *joystick = nullptr;
43
int Joystick::joystickCount = 0;
44
bool Joystick::mEnabled = false;
45
46
Joystick::Joystick(const int no) :
47
    mDirection(0),
48
    mJoystick(nullptr),
49
    mUpTolerance(0),
50
    mDownTolerance(0),
51
    mLeftTolerance(0),
52
    mRightTolerance(0),
53
    mCalibrating(false),
54
    mNumber(no >= joystickCount ? joystickCount : no),
55
    mCalibrated(false),
56
    mButtonsNumber(MAX_BUTTONS),
57
    mUseInactive(false),
58
    mHaveHats(false),
59
    mKeyToAction(),
60
    mKeyToId(),
61
    mKeyTimeMap()
62
{
63
    for (int i = 0; i < MAX_BUTTONS; i++)
64
        mActiveButtons[i] = false;
65
}
66
67
Joystick::~Joystick()
68
{
69
    close();
70
}
71
72
void Joystick::init()
73
{
74
    SDL_InitSubSystem(SDL_INIT_JOYSTICK);
75
    // +++ possible to use SDL_EventState with different joystick features.
76
    SDL_JoystickEventState(SDL_ENABLE);
77
    joystickCount = SDL_NumJoysticks();
78
    logger->log("%i joysticks/gamepads found", joystickCount);
79
    for (int i = 0; i < joystickCount; i++)
80
        logger->log("- %s", SDL_JoystickNameForIndex(i));
81
82
    mEnabled = config.getBoolValue("joystickEnabled");
83
84
    if (joystickCount > 0)
85
    {
86
        joystick = new Joystick(config.getIntValue("selectedJoystick"));
87
        if (mEnabled)
88
            joystick->open();
89
    }
90
}
91
92
bool Joystick::open()
93
{
94
    if (mNumber >= joystickCount)
95
        mNumber = joystickCount - 1;
96
    if (mNumber < 0)
97
    {
98
        logger->log1("error: incorrect joystick selection");
99
        return false;
100
    }
101
    logger->log("open joystick %d", mNumber);
102
103
    mJoystick = SDL_JoystickOpen(mNumber);
104
105
    if (mJoystick == nullptr)
106
    {
107
        logger->log("Couldn't open joystick: %s", SDL_GetError());
108
        return false;
109
    }
110
111
    mButtonsNumber = SDL_JoystickNumButtons(mJoystick);
112
    logger->log("Joystick: %i ", mNumber);
113
#ifdef USE_SDL2
114
    logger->log("Name: %s", SDL_JoystickName(mJoystick));
115
    SDL_JoystickGUID guid = SDL_JoystickGetGUID(mJoystick);
116
    std::string guidStr;
117
    for (int f = 0; f < 16; f ++)
118
        guidStr.append(strprintf("%02x", CAST_U32(guid.data[f])));
119
    logger->log("Guid: %s", guidStr.c_str());
120
#if SDL_VERSION_ATLEAST(2, 0, 6)
121
    logger->log("Device id: %u:%u.%u",
122
        CAST_U32(SDL_JoystickGetVendor(mJoystick)),
123
        CAST_U32(SDL_JoystickGetProduct(mJoystick)),
124
        CAST_U32(SDL_JoystickGetProductVersion(mJoystick)));
125
126
    SDL_JoystickType type = SDL_JoystickGetType(mJoystick);
127
    std::string typeStr;
128
    switch (type)
129
    {
130
        default:
131
        case SDL_JOYSTICK_TYPE_UNKNOWN:
132
            typeStr = "unknown";
133
            break;
134
        case SDL_JOYSTICK_TYPE_GAMECONTROLLER:
135
            typeStr = "game controller";
136
            break;
137
        case SDL_JOYSTICK_TYPE_WHEEL:
138
            typeStr = "wheel";
139
            break;
140
        case SDL_JOYSTICK_TYPE_ARCADE_STICK:
141
            typeStr = "arcade stick";
142
            break;
143
        case SDL_JOYSTICK_TYPE_FLIGHT_STICK:
144
            typeStr = "flight stick";
145
            break;
146
        case SDL_JOYSTICK_TYPE_DANCE_PAD:
147
            typeStr = "dance pad";
148
            break;
149
        case SDL_JOYSTICK_TYPE_GUITAR:
150
            typeStr = "guitar";
151
            break;
152
        case SDL_JOYSTICK_TYPE_DRUM_KIT:
153
            typeStr = "drum kit";
154
            break;
155
        case SDL_JOYSTICK_TYPE_ARCADE_PAD:
156
            typeStr = "arcade pad";
157
            break;
158
        case SDL_JOYSTICK_TYPE_THROTTLE:
159
            typeStr = "throttle";
160
            break;
161
    }
162
    logger->log("Type: " + typeStr);
163
#endif  // SDL_VERSION_ATLEAST(2, 0, 6)
164
    // probably need aslo dump SDL_JoystickCurrentPowerLevel
165
#else  // USE_SDL2
166
167
    logger->log("Name: %s", SDL_JoystickName(mNumber));
168
#endif  // USE_SDL2
169
170
    logger->log("Axes: %i ", SDL_JoystickNumAxes(mJoystick));
171
    logger->log("Balls: %i", SDL_JoystickNumBalls(mJoystick));
172
    logger->log("Hats: %i", SDL_JoystickNumHats(mJoystick));
173
    logger->log("Buttons: %i", mButtonsNumber);
174
175
    mHaveHats = (SDL_JoystickNumHats(mJoystick) > 0);
176
177
    if (mButtonsNumber > MAX_BUTTONS)
178
        mButtonsNumber = MAX_BUTTONS;
179
180
    mCalibrated = config.getValueBool("joystick"
181
        + toString(mNumber) + "calibrated", false);
182
    mUpTolerance = config.getIntValue("upTolerance" + toString(mNumber));
183
    mDownTolerance = config.getIntValue("downTolerance" + toString(mNumber));
184
    mLeftTolerance = config.getIntValue("leftTolerance" + toString(mNumber));
185
    mRightTolerance = config.getIntValue("rightTolerance" + toString(mNumber));
186
    mUseInactive = config.getBoolValue("useInactiveJoystick");
187
188
    return true;
189
}
190
191
void Joystick::close()
192
{
193
    logger->log("close joystick %d", mNumber);
194
    if (mJoystick != nullptr)
195
    {
196
        SDL_JoystickClose(mJoystick);
197
        mJoystick = nullptr;
198
    }
199
}
200
201
void Joystick::reload()
202
{
203
    joystickCount = SDL_NumJoysticks();
204
    setNumber(mNumber);
205
}
206
207
void Joystick::setNumber(const int n)
208
{
209
    if (mJoystick != nullptr)
210
    {
211
        SDL_JoystickClose(mJoystick);
212
        mNumber = n;
213
        open();
214
    }
215
    else
216
    {
217
        mNumber = n;
218
    }
219
}
220
221
void Joystick::logic()
222
{
223
    BLOCK_START("Joystick::logic")
224
    // When calibrating, don't bother the outside with our state
225
    if (mCalibrating)
226
    {
227
        doCalibration();
228
        BLOCK_END("Joystick::logic")
229
        return;
230
    };
231
232
    if (!mEnabled || !mCalibrated)
233
    {
234
        BLOCK_END("Joystick::logic")
235
        return;
236
    }
237
238
    mDirection = 0;
239
240
    if (mUseInactive ||
241
        settings.inputFocused != KeyboardFocus::Unfocused)
242
    {
243
        // X-Axis
244
        int position = SDL_JoystickGetAxis(mJoystick, 0);
245
        if (position >= mRightTolerance)
246
            mDirection |= RIGHT;
247
        else if (position <= mLeftTolerance)
248
            mDirection |= LEFT;
249
250
        // Y-Axis
251
        position = SDL_JoystickGetAxis(mJoystick, 1);
252
        if (position <= mUpTolerance)
253
            mDirection |= UP;
254
        else if (position >= mDownTolerance)
255
            mDirection |= DOWN;
256
257
#ifdef DEBUG_JOYSTICK
258
        if (SDL_JoystickGetAxis(mJoystick, 2))
259
            logger->log("axis 2 pos: %d", SDL_JoystickGetAxis(mJoystick, 2));
260
        if (SDL_JoystickGetAxis(mJoystick, 3))
261
            logger->log("axis 3 pos: %d", SDL_JoystickGetAxis(mJoystick, 3));
262
        if (SDL_JoystickGetAxis(mJoystick, 4))
263
            logger->log("axis 4 pos: %d", SDL_JoystickGetAxis(mJoystick, 4));
264
#endif  // DEBUG_JOYSTICK
265
266
        if ((mDirection == 0u) && mHaveHats)
267
        {
268
            // reading only hat 0
269
            const uint8_t hat = SDL_JoystickGetHat(mJoystick, 0);
270
            if ((hat & SDL_HAT_RIGHT) != 0)
271
                mDirection |= RIGHT;
272
            else if ((hat & SDL_HAT_LEFT) != 0)
273
                mDirection |= LEFT;
274
            if ((hat & SDL_HAT_UP) != 0)
275
                mDirection |= UP;
276
            else if ((hat & SDL_HAT_DOWN) != 0)
277
                mDirection |= DOWN;
278
        }
279
280
        // Buttons
281
        for (int i = 0; i < mButtonsNumber; i++)
282
        {
283
            const bool state = (SDL_JoystickGetButton(mJoystick, i) == 1);
284
            mActiveButtons[i] = state;
285
            if (!state)
286
                resetRepeat(i);
287
#ifdef DEBUG_JOYSTICK
288
            if (mActiveButtons[i])
289
                logger->log("button: %d", i);
290
#endif  // DEBUG_JOYSTICK
291
        }
292
    }
293
    else
294
    {
295
        for (int i = 0; i < mButtonsNumber; i++)
296
            mActiveButtons[i] = false;
297
    }
298
    BLOCK_END("Joystick::logic")
299
}
300
301
void Joystick::startCalibration()
302
{
303
    mUpTolerance = 0;
304
    mDownTolerance = 0;
305
    mLeftTolerance = 0;
306
    mRightTolerance = 0;
307
    mCalibrating = true;
308
}
309
310
void Joystick::doCalibration()
311
{
312
    // X-Axis
313
    int position = SDL_JoystickGetAxis(mJoystick, 0);
314
    if (position > mRightTolerance)
315
        mRightTolerance = position;
316
    else if (position < mLeftTolerance)
317
        mLeftTolerance = position;
318
319
    // Y-Axis
320
    position = SDL_JoystickGetAxis(mJoystick, 1);
321
    if (position > mDownTolerance)
322
        mDownTolerance = position;
323
    else if (position < mUpTolerance)
324
        mUpTolerance = position;
325
}
326
327
void Joystick::finishCalibration()
328
{
329
    mCalibrated = true;
330
    mCalibrating = false;
331
    config.setValue("joystick" + toString(mNumber) + "calibrated", true);
332
    config.setValue("leftTolerance" + toString(mNumber), mLeftTolerance);
333
    config.setValue("rightTolerance" + toString(mNumber), mRightTolerance);
334
    config.setValue("upTolerance" + toString(mNumber), mUpTolerance);
335
    config.setValue("downTolerance" + toString(mNumber), mDownTolerance);
336
}
337
338
bool Joystick::buttonPressed(const unsigned char no) const
339
{
340
    return (mEnabled && no < MAX_BUTTONS) ? mActiveButtons[no] : false;
341
}
342
343
4
void Joystick::getNames(STD_VECTOR <std::string> &names)
344
{
345
4
    names.clear();
346
4
    for (int i = 0; i < joystickCount; i++)
347
        names.push_back(SDL_JoystickNameForIndex(i));
348
4
}
349
350
void Joystick::update()
351
{
352
    inputManager.updateKeyActionMap(mKeyToAction, mKeyToId,
353
        mKeyTimeMap, InputType::JOYSTICK);
354
}
355
356
KeysVector *Joystick::getActionVector(const SDL_Event &event)
357
{
358
    const int i = getButtonFromEvent(event);
359
360
    if (i < 0 || i >= mButtonsNumber)
361
        return nullptr;
362
//    logger->log("button triggerAction: %d", i);
363
    if (mKeyToAction.find(i) != mKeyToAction.end())
364
        return &mKeyToAction[i];
365
    return nullptr;
366
}
367
368
KeysVector *Joystick::getActionVectorByKey(const int i)
369
{
370
    if (i < 0 || i >= mButtonsNumber)
371
        return nullptr;
372
//    logger->log("button triggerAction: %d", i);
373
    if (mKeyToAction.find(i) != mKeyToAction.end())
374
        return &mKeyToAction[i];
375
    return nullptr;
376
}
377
378
int Joystick::getButtonFromEvent(const SDL_Event &event) const
379
{
380
    if (event.jbutton.which != mNumber)
381
        return -1;
382
    return event.jbutton.button;
383
}
384
385
bool Joystick::isActionActive(const InputActionT index) const
386
{
387
    if (!validate())
388
        return false;
389
390
    const InputFunction &key = inputManager.getKey(index);
391
    for (size_t i = 0; i < inputFunctionSize; i ++)
392
    {
393
        const InputItem &val = key.values[i];
394
        if (val.type != InputType::JOYSTICK)
395
            continue;
396
        const int value = val.value;
397
        if (value >= 0 && value < mButtonsNumber)
398
        {
399
            if (mActiveButtons[value])
400
                return true;
401
        }
402
    }
403
    return false;
404
}
405
406
bool Joystick::validate() const
407
{
408
    if (mCalibrating || !mEnabled || !mCalibrated)
409
        return false;
410
411
    return mUseInactive ||
412
        settings.inputFocused != KeyboardFocus::Unfocused;
413
}
414
415
void Joystick::handleRepeat(const int time)
416
{
417
    BLOCK_START("Joystick::handleRepeat")
418
    FOR_EACH (KeyTimeMapIter, it, mKeyTimeMap)
419
    {
420
        bool repeat(false);
421
        const int key = (*it).first;
422
        if (key >= 0 && key < mButtonsNumber)
423
        {
424
            if (mActiveButtons[key])
425
                repeat = true;
426
        }
427
        if (repeat)
428
        {
429
            int &keyTime = (*it).second;
430
            if (time > keyTime && abs(time - keyTime)
431
                > SDL_DEFAULT_REPEAT_DELAY * 10)
432
            {
433
                keyTime = time;
434
                inputManager.triggerAction(getActionVectorByKey(key));
435
            }
436
        }
437
    }
438
    BLOCK_END("Joystick::handleRepeat")
439
}
440
441
void Joystick::resetRepeat(const int key)
442
{
443
    const KeyTimeMapIter it = mKeyTimeMap.find(key);
444
    if (it != mKeyTimeMap.end())
445
        (*it).second = tick_time;
446
}