From 1cfafd9df6e334ac436cc4ffd78de6341b9caa42 Mon Sep 17 00:00:00 2001 From: Stanislaw Halik Date: Tue, 26 Jun 2018 22:26:07 +0200 Subject: dinput: simplify di_t --- dinput/dinput.cpp | 80 +++++++++++++++++++------------------------------------ 1 file changed, 28 insertions(+), 52 deletions(-) (limited to 'dinput/dinput.cpp') diff --git a/dinput/dinput.cpp b/dinput/dinput.cpp index 226d3277..c3509dd6 100644 --- a/dinput/dinput.cpp +++ b/dinput/dinput.cpp @@ -1,88 +1,64 @@ #include "dinput.hpp" #include -std::atomic dinput_handle::refcnt; -std::atomic_flag dinput_handle::init_lock = ATOMIC_FLAG_INIT; +std::atomic di_t::refcnt; +std::atomic_flag di_t::init_lock = ATOMIC_FLAG_INIT; +diptr di_t::handle; -LPDIRECTINPUT8& dinput_handle::init_di() +diptr di_t::init_di_() { CoInitialize(nullptr); - static LPDIRECTINPUT8 di_ = nullptr; - if (di_ == nullptr) + diptr di = nullptr; + if (HRESULT hr = DirectInput8Create(GetModuleHandle(nullptr), + DIRECTINPUT_VERSION, + IID_IDirectInput8, + (void**)&di, + nullptr); + !SUCCEEDED(hr)) { - if (!SUCCEEDED(DirectInput8Create(GetModuleHandle(NULL), DIRECTINPUT_VERSION, IID_IDirectInput8, (void**)&di_, NULL))) - { - di_ = nullptr; - } + qDebug() << "can't make dinput:" << (void*)hr; + qDebug() << "crashing!"; + std::abort(); } - return di_; -} - -dinput_handle::di_t dinput_handle::make_di() -{ - while (init_lock.test_and_set()) { /* busy loop */ } - - LPDIRECTINPUT8& ret = init_di(); - init_lock.clear(); - - return di_t(ret); + return di; } -void dinput_handle::di_t::free_di() +di_t::di_t() { - if (handle && *handle) - { - (*handle)->Release(); - *handle = nullptr; - } - handle = nullptr; -} - -void dinput_handle::di_t::ref_di() -{ - //const int refcnt_ = refcnt.fetch_add(1) + 1; - (void) refcnt.fetch_add(1); + ref_di(); } -dinput_handle::di_t& dinput_handle::di_t::operator=(const di_t& new_di) +void di_t::ref_di() { - if (handle) - unref_di(); + while (init_lock.test_and_set()) { /* busy loop */ } - handle = new_di.handle; + if (!handle) + handle = init_di_(); - if (handle) - ref_di(); + ++refcnt; - return *this; + init_lock.clear(); } -void dinput_handle::di_t::unref_di() +void di_t::unref_di() { - const int refcnt_ = refcnt.fetch_sub(1) - 1; + const int refcnt_ = --refcnt; if (refcnt_ == 0) { while (init_lock.test_and_set()) { /* busy loop */ } qDebug() << "exit: di handle"; - free_di(); + handle->Release(); init_lock.clear(); } } -dinput_handle::di_t::di_t(LPDIRECTINPUT8& handle) : handle(&handle) +di_t::~di_t() { - ref_di(); + unref_di(); } -dinput_handle::di_t::di_t() : handle(nullptr) {} - -dinput_handle::di_t::~di_t() -{ - if (handle) - unref_di(); -} -- cgit v1.2.3