summaryrefslogtreecommitdiffhomepage
path: root/dinput/dinput.cpp
blob: 8a3d0f4aee591f746a5275bbf98c58d00107cc18 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
#include "dinput.hpp"
#include <QDebug>

std::atomic<int> di_t::refcnt;
std::atomic_flag di_t::init_lock = ATOMIC_FLAG_INIT;
diptr di_t::handle;

diptr di_t::init_di_()
{
    CoInitialize(nullptr);

    diptr di = nullptr;
    if (HRESULT hr = DirectInput8Create(GetModuleHandle(nullptr),
                                        DIRECTINPUT_VERSION,
                                        IID_IDirectInput8,
                                        (void**)&di,
                                        nullptr);
        !SUCCEEDED(hr))
    {
        qDebug() << "can't make dinput:" << (void*)(LONG_PTR)hr;
        qDebug() << "crashing!";
        std::abort();
    }

    return di;
}

di_t::di_t()
{
    ref_di();
}

void di_t::ref_di()
{
    while (init_lock.test_and_set()) { /* busy loop */ }

    if (!handle)
        handle = init_di_();

    ++refcnt;

    init_lock.clear();
}

void di_t::unref_di()
{
    const int refcnt_ = --refcnt;

    if (refcnt_ == 0)
    {
        while (init_lock.test_and_set()) { /* busy loop */ }

        qDebug() << "exit: di handle";
        handle->Release();

        init_lock.clear();
    }
}

di_t::~di_t()
{
    unref_di();
}