diff --git a/projects/kiwano-physics/kiwano-physics.vcxproj b/projects/kiwano-physics/kiwano-physics.vcxproj index dac0da27..cc69700c 100644 --- a/projects/kiwano-physics/kiwano-physics.vcxproj +++ b/projects/kiwano-physics/kiwano-physics.vcxproj @@ -13,7 +13,7 @@ - + @@ -24,7 +24,7 @@ - + diff --git a/projects/kiwano-physics/kiwano-physics.vcxproj.filters b/projects/kiwano-physics/kiwano-physics.vcxproj.filters index 2a808fb3..a927a9b3 100644 --- a/projects/kiwano-physics/kiwano-physics.vcxproj.filters +++ b/projects/kiwano-physics/kiwano-physics.vcxproj.filters @@ -9,7 +9,7 @@ - + @@ -18,6 +18,6 @@ - + \ No newline at end of file diff --git a/projects/kiwano/kiwano.vcxproj b/projects/kiwano/kiwano.vcxproj index 57b8f114..4ec7a3d1 100644 --- a/projects/kiwano/kiwano.vcxproj +++ b/projects/kiwano/kiwano.vcxproj @@ -11,19 +11,21 @@ - - - - - - - - - - - - - + + + + + + + + + + + + + + + @@ -40,22 +42,19 @@ - - - - - - - - - - - - - - - - + + + + + + + + + + + + + @@ -65,7 +64,10 @@ + + + @@ -88,7 +90,6 @@ - @@ -113,21 +114,24 @@ - - - - - - - - - - - - - + + + + + + + + + + + + + + + + @@ -148,7 +152,6 @@ - diff --git a/projects/kiwano/kiwano.vcxproj.filters b/projects/kiwano/kiwano.vcxproj.filters index 24b70a35..2f48b1a4 100644 --- a/projects/kiwano/kiwano.vcxproj.filters +++ b/projects/kiwano/kiwano.vcxproj.filters @@ -16,7 +16,7 @@ {896bdedf-6e82-449b-9b6e-0bc69f3699b1} - + {2e18d99a-e906-499a-9e29-4e0783202644} @@ -25,13 +25,13 @@ {9314f30d-5742-48b6-94e5-e3b4284106f6} - + {86e2d0f2-a9d0-4456-b6a5-d480228bbf82} {30333461-e9bc-4709-84bd-ce6e0e1a3079} - + {192a47a9-9df6-4f40-a7d3-888eb00c53ac} @@ -63,29 +63,23 @@ 2d - - base + + core - - base + + core - - base + + core - - base + + core - - base + + core - - base - - - base - - - base + + core math @@ -107,27 +101,24 @@ math - - base - - - base + + core - - base + + core - - base + + core - - base + + core 2d - - base + + core 2d @@ -162,32 +153,32 @@ 2d - - core + + common - - core + + common - - core + + common - - core + + common - - core + + common - - core + + common - - core + + common - - core + + common - - core + + common 2d @@ -201,17 +192,14 @@ 2d\action - - base - - - base + + core math - - base + + core renderer @@ -282,24 +270,39 @@ math - - base\win32 + + core\win32 - - base\win32 + + core\win32 utils - - utils - - - core + + common utils + + core + + + core + + + platform + + + core + + + platform + + + platform + @@ -323,17 +326,17 @@ 2d - - base + + core - - base + + core - - base + + core - - base + + core platform @@ -341,23 +344,20 @@ platform - - base + + core - - base + + core - - base - - - base + + core 2d - - base + + core 2d @@ -401,14 +401,11 @@ 2d\action - - base + + core - - base - - - base + + core renderer @@ -464,17 +461,29 @@ renderer - - base + + core utils - - utils - utils + + core + + + core + + + platform + + + platform + + + platform + \ No newline at end of file diff --git a/src/kiwano-audio/AudioEngine.cpp b/src/kiwano-audio/AudioEngine.cpp index 53f2d05b..194b180d 100644 --- a/src/kiwano-audio/AudioEngine.cpp +++ b/src/kiwano-audio/AudioEngine.cpp @@ -18,7 +18,7 @@ // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. -#include +#include #include #include diff --git a/src/kiwano-audio/AudioEngine.h b/src/kiwano-audio/AudioEngine.h index ecc4548b..11187a2a 100644 --- a/src/kiwano-audio/AudioEngine.h +++ b/src/kiwano-audio/AudioEngine.h @@ -19,10 +19,11 @@ // THE SOFTWARE. #pragma once -#include -#include -#include +#include +#include +#include #include +#include namespace kiwano { diff --git a/src/kiwano-audio/Sound.cpp b/src/kiwano-audio/Sound.cpp index d0bda67f..622391fb 100644 --- a/src/kiwano-audio/Sound.cpp +++ b/src/kiwano-audio/Sound.cpp @@ -18,8 +18,8 @@ // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. -#include -#include +#include +#include #include #include diff --git a/src/kiwano-audio/Sound.h b/src/kiwano-audio/Sound.h index 42ca5650..e94171a4 100644 --- a/src/kiwano-audio/Sound.h +++ b/src/kiwano-audio/Sound.h @@ -19,11 +19,11 @@ // THE SOFTWARE. #pragma once -#include -#include -#include -#include +#include +#include +#include #include +#include namespace kiwano { diff --git a/src/kiwano-audio/SoundPlayer.h b/src/kiwano-audio/SoundPlayer.h index f3659a5d..913fe04f 100644 --- a/src/kiwano-audio/SoundPlayer.h +++ b/src/kiwano-audio/SoundPlayer.h @@ -19,8 +19,8 @@ // THE SOFTWARE. #pragma once -#include -#include +#include +#include #include namespace kiwano diff --git a/src/kiwano-audio/Transcoder.cpp b/src/kiwano-audio/Transcoder.cpp index 23552f8b..256ebe83 100644 --- a/src/kiwano-audio/Transcoder.cpp +++ b/src/kiwano-audio/Transcoder.cpp @@ -23,10 +23,10 @@ #endif #include -#include -#include -#include -#include +#include +#include +#include +#include #include #include #include diff --git a/src/kiwano-audio/Transcoder.h b/src/kiwano-audio/Transcoder.h index 7d6d0d78..1ee99cf3 100644 --- a/src/kiwano-audio/Transcoder.h +++ b/src/kiwano-audio/Transcoder.h @@ -19,7 +19,7 @@ // THE SOFTWARE. #pragma once -#include +#include #include #include #include diff --git a/src/kiwano-audio/audio-modules.cpp b/src/kiwano-audio/audio-modules.cpp index fe4403e9..f140f00d 100644 --- a/src/kiwano-audio/audio-modules.cpp +++ b/src/kiwano-audio/audio-modules.cpp @@ -18,7 +18,7 @@ // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. -#include +#include #include namespace kiwano @@ -28,7 +28,7 @@ namespace kiwano namespace modules { XAudio2::XAudio2() - : xaudio2(nullptr) + : xaudio2() , XAudio2Create(nullptr) { const auto xaudio2_dll_names = @@ -40,16 +40,17 @@ namespace kiwano for (const auto& name : xaudio2_dll_names) { - xaudio2 = LoadLibraryW(name); - if (xaudio2) + if (xaudio2.Load(name)) { - XAudio2Create = (PFN_XAudio2Create) - GetProcAddress(xaudio2, "XAudio2Create"); break; } } - if (!xaudio2) + if (xaudio2.IsValid()) + { + XAudio2Create = xaudio2.GetProcess(L"XAudio2Create"); + } + else { KGE_ERROR_LOG(L"Load xaudio2.dll failed"); throw std::runtime_error("Load xaudio2.dll failed"); @@ -57,8 +58,8 @@ namespace kiwano } MediaFoundation::MediaFoundation() - : mfplat(nullptr) - , mfreadwrite(nullptr) + : mfplat() + , mfreadwrite() , MFStartup(nullptr) , MFShutdown(nullptr) , MFCreateMediaType(nullptr) @@ -67,23 +68,13 @@ namespace kiwano , MFCreateSourceReaderFromByteStream(nullptr) , MFCreateMFByteStreamOnStream(nullptr) { - mfplat = LoadLibraryW(L"Mfplat.dll"); - if (mfplat) + if (mfplat.Load(L"Mfplat.dll")) { - MFStartup = (PFN_MFStartup) - GetProcAddress(mfplat, "MFStartup"); - - MFShutdown = (PFN_MFShutdown) - GetProcAddress(mfplat, "MFShutdown"); - - MFCreateMediaType = (PFN_MFCreateMediaType) - GetProcAddress(mfplat, "MFCreateMediaType"); - - MFCreateWaveFormatExFromMFMediaType = (PFN_MFCreateWaveFormatExFromMFMediaType) - GetProcAddress(mfplat, "MFCreateWaveFormatExFromMFMediaType"); - - MFCreateMFByteStreamOnStream = (PFN_MFCreateMFByteStreamOnStream) - GetProcAddress(mfplat, "MFCreateMFByteStreamOnStream"); + MFStartup = mfplat.GetProcess(L"MFStartup"); + MFShutdown = mfplat.GetProcess(L"MFShutdown"); + MFCreateMediaType = mfplat.GetProcess(L"MFCreateMediaType"); + MFCreateWaveFormatExFromMFMediaType = mfplat.GetProcess(L"MFCreateWaveFormatExFromMFMediaType"); + MFCreateMFByteStreamOnStream = mfplat.GetProcess(L"MFCreateMFByteStreamOnStream"); } else { @@ -91,14 +82,10 @@ namespace kiwano throw std::runtime_error("Load Mfplat.dll failed"); } - mfreadwrite = LoadLibraryW(L"Mfreadwrite.dll"); - if (mfreadwrite) + if (mfreadwrite.Load(L"Mfreadwrite.dll")) { - MFCreateSourceReaderFromURL = (PFN_MFCreateSourceReaderFromURL) - GetProcAddress(mfreadwrite, "MFCreateSourceReaderFromURL"); - - MFCreateSourceReaderFromByteStream = (PFN_MFCreateSourceReaderFromByteStream) - GetProcAddress(mfreadwrite, "MFCreateSourceReaderFromByteStream"); + MFCreateSourceReaderFromURL = mfreadwrite.GetProcess(L"MFCreateSourceReaderFromURL"); + MFCreateSourceReaderFromByteStream = mfreadwrite.GetProcess(L"MFCreateSourceReaderFromByteStream"); } else { diff --git a/src/kiwano-audio/audio-modules.h b/src/kiwano-audio/audio-modules.h index 689ba0dd..299beb34 100644 --- a/src/kiwano-audio/audio-modules.h +++ b/src/kiwano-audio/audio-modules.h @@ -19,6 +19,7 @@ // THE SOFTWARE. #pragma once +#include #include #include #include @@ -32,13 +33,6 @@ namespace kiwano { class KGE_API XAudio2 { - XAudio2(); - - HMODULE xaudio2; - - // XAudio2 functions - typedef HRESULT(WINAPI* PFN_XAudio2Create)(IXAudio2**, UINT32, XAUDIO2_PROCESSOR); - public: static inline XAudio2& Get() { @@ -46,16 +40,29 @@ namespace kiwano return instance; } + // XAudio2 functions + typedef HRESULT(WINAPI* PFN_XAudio2Create)(IXAudio2**, UINT32, XAUDIO2_PROCESSOR); + PFN_XAudio2Create XAudio2Create; + + private: + XAudio2(); + + XAudio2(const XAudio2&) = delete; + XAudio2& operator=(const XAudio2&) = delete; + + Library xaudio2; }; class KGE_API MediaFoundation { - MediaFoundation(); - - HMODULE mfplat; - HMODULE mfreadwrite; + public: + static inline MediaFoundation& Get() + { + static MediaFoundation instance; + return instance; + } // MediaFoundation functions typedef HRESULT(WINAPI* PFN_MFStartup)(ULONG, DWORD); @@ -66,13 +73,6 @@ namespace kiwano typedef HRESULT(WINAPI* PFN_MFCreateSourceReaderFromByteStream)(IMFByteStream*, IMFAttributes*, IMFSourceReader**); typedef HRESULT(WINAPI* PFN_MFCreateMFByteStreamOnStream)(IStream*, IMFByteStream**); - public: - static inline MediaFoundation& Get() - { - static MediaFoundation instance; - return instance; - } - PFN_MFStartup MFStartup; PFN_MFShutdown MFShutdown; PFN_MFCreateMediaType MFCreateMediaType; @@ -80,6 +80,15 @@ namespace kiwano PFN_MFCreateSourceReaderFromURL MFCreateSourceReaderFromURL; PFN_MFCreateSourceReaderFromByteStream MFCreateSourceReaderFromByteStream; PFN_MFCreateMFByteStreamOnStream MFCreateMFByteStreamOnStream; + + private: + MediaFoundation(); + + MediaFoundation(const MediaFoundation&) = delete; + MediaFoundation& operator=(const MediaFoundation&) = delete; + + Library mfplat; + Library mfreadwrite; }; } } diff --git a/src/kiwano-imgui/ImGuiModule.cpp b/src/kiwano-imgui/ImGuiModule.cpp index 5ed0034f..f164f2bd 100644 --- a/src/kiwano-imgui/ImGuiModule.cpp +++ b/src/kiwano-imgui/ImGuiModule.cpp @@ -1,10 +1,10 @@ // Copyright (C) 2019 Nomango -#include -#include -#include -#include -#include +#include +#include +#include +#include +#include #include #include #include diff --git a/src/kiwano-imgui/ImGuiModule.h b/src/kiwano-imgui/ImGuiModule.h index a047da68..c9069a40 100644 --- a/src/kiwano-imgui/ImGuiModule.h +++ b/src/kiwano-imgui/ImGuiModule.h @@ -19,8 +19,8 @@ // THE SOFTWARE. #pragma once -#include -#include +#include +#include namespace kiwano { diff --git a/src/kiwano-imgui/imgui_impl_dx11.cpp b/src/kiwano-imgui/imgui_impl_dx11.cpp index a8f20a45..a8dc29eb 100644 --- a/src/kiwano-imgui/imgui_impl_dx11.cpp +++ b/src/kiwano-imgui/imgui_impl_dx11.cpp @@ -1,6 +1,6 @@ // dear imgui: Renderer for Kiwano (DirectX11) -#include +#include #include // DirectX diff --git a/src/kiwano-network/HttpClient.cpp b/src/kiwano-network/HttpClient.cpp index 4822be25..7e7d97cc 100644 --- a/src/kiwano-network/HttpClient.cpp +++ b/src/kiwano-network/HttpClient.cpp @@ -25,7 +25,7 @@ #include #include -#include +#include #include #include <3rd-party/curl/curl.h> // CURL @@ -36,7 +36,7 @@ namespace uint32_t write_data(void* buffer, uint32_t size, uint32_t nmemb, void* userp) { - core::string* recv_buffer = (core::string*)userp; + common::string* recv_buffer = (common::string*)userp; uint32_t total = size * nmemb; // add data to the end of recv_buffer @@ -46,10 +46,10 @@ namespace return total; } - core::string convert_to_utf8(core::wstring const& str) + common::string convert_to_utf8(common::wstring const& str) { std::wstring_convert> utf8_conv; - core::string result; + common::string result; try { @@ -63,10 +63,10 @@ namespace return result; } - core::wstring convert_from_utf8(core::string const& str) + common::wstring convert_from_utf8(common::string const& str) { kiwano::string_convert> utf8_conv; - core::wstring result; + common::wstring result; try { @@ -104,7 +104,7 @@ namespace } } - bool Init(HttpClient* client, Vector const& headers, core::string const& url, core::string* response_data, core::string* response_header, char* error_buffer) + bool Init(HttpClient* client, Vector const& headers, common::string const& url, common::string* response_data, common::string* response_header, char* error_buffer) { if (!SetOption(CURLOPT_ERRORBUFFER, error_buffer)) return false; @@ -170,11 +170,11 @@ namespace public: static inline bool GetRequest( HttpClient* client, - Vector const& headers, - core::string const& url, + Vector const& headers, + common::string const& url, long* response_code, - core::string* response_data, - core::string* response_header, + common::string* response_data, + common::string* response_header, char* error_buffer) { Curl curl; @@ -185,12 +185,12 @@ namespace static inline bool PostRequest( HttpClient* client, - Vector const& headers, - core::string const& url, - core::string const& request_data, + Vector const& headers, + common::string const& url, + common::string const& request_data, long* response_code, - core::string* response_data, - core::string* response_header, + common::string* response_data, + common::string* response_header, char* error_buffer) { Curl curl; @@ -203,12 +203,12 @@ namespace static inline bool PutRequest( HttpClient* client, - Vector const& headers, - core::string const& url, - core::string const& request_data, + Vector const& headers, + common::string const& url, + common::string const& request_data, long* response_code, - core::string* response_data, - core::string* response_header, + common::string* response_data, + common::string* response_header, char* error_buffer) { Curl curl; @@ -221,11 +221,11 @@ namespace static inline bool DeleteRequest( HttpClient* client, - Vector const& headers, - core::string const& url, + Vector const& headers, + common::string const& url, long* response_code, - core::string* response_data, - core::string* response_header, + common::string* response_data, + common::string* response_header, char* error_buffer) { Curl curl; @@ -307,13 +307,13 @@ namespace kiwano bool ok = false; long response_code = 0; char error_message[256] = { 0 }; - core::string response_header; - core::string response_data; + common::string response_header; + common::string response_data; - core::string url = convert_to_utf8(request->GetUrl()); - core::string data = convert_to_utf8(request->GetData()); + common::string url = convert_to_utf8(request->GetUrl()); + common::string data = convert_to_utf8(request->GetData()); - Vector headers; + Vector headers; headers.reserve(request->GetHeaders().size()); for (const auto& pair : request->GetHeaders()) { diff --git a/src/kiwano-network/HttpClient.h b/src/kiwano-network/HttpClient.h index 73b52f7a..31e7bf1f 100644 --- a/src/kiwano-network/HttpClient.h +++ b/src/kiwano-network/HttpClient.h @@ -19,9 +19,9 @@ // THE SOFTWARE. #pragma once -#include -#include -#include +#include +#include +#include #include #include @@ -36,39 +36,19 @@ namespace kiwano KGE_DECLARE_SINGLETON(HttpClient); public: - void Send( - HttpRequestPtr request - ); + void Send(HttpRequestPtr request); - inline void SetTimeoutForConnect(Duration timeout) - { - timeout_for_connect_ = timeout; - } + void SetTimeoutForConnect(Duration timeout); - inline Duration GetTimeoutForConnect() const - { - return timeout_for_connect_; - } + Duration GetTimeoutForConnect() const; - inline void SetTimeoutForRead(Duration timeout) - { - timeout_for_read_ = timeout; - } + void SetTimeoutForRead(Duration timeout); - inline Duration GetTimeoutForRead() const - { - return timeout_for_read_; - } + Duration GetTimeoutForRead() const; - inline void SetSSLVerification(String const& root_certificate_path) - { - ssl_verification_ = root_certificate_path; - } + void SetSSLVerification(String const& root_certificate_path); - inline String const& GetSSLVerification() const - { - return ssl_verification_; - } + String const& GetSSLVerification() const; public: virtual void SetupComponent() override; @@ -101,5 +81,37 @@ namespace kiwano std::condition_variable_any sleep_condition_; }; + + + inline void HttpClient::SetTimeoutForConnect(Duration timeout) + { + timeout_for_connect_ = timeout; + } + + inline Duration HttpClient::GetTimeoutForConnect() const + { + return timeout_for_connect_; + } + + inline void HttpClient::SetTimeoutForRead(Duration timeout) + { + timeout_for_read_ = timeout; + } + + inline Duration HttpClient::GetTimeoutForRead() const + { + return timeout_for_read_; + } + + inline void HttpClient::SetSSLVerification(String const& root_certificate_path) + { + ssl_verification_ = root_certificate_path; + } + + inline String const& HttpClient::GetSSLVerification() const + { + return ssl_verification_; + } + } } diff --git a/src/kiwano-network/HttpRequest.cpp b/src/kiwano-network/HttpRequest.cpp index 0a52f3b4..610df352 100644 --- a/src/kiwano-network/HttpRequest.cpp +++ b/src/kiwano-network/HttpRequest.cpp @@ -30,19 +30,5 @@ namespace kiwano SetHeader(L"Content-Type", L"application/json;charset=UTF-8"); data_ = json.dump(); } - - void HttpRequest::SetHeader(String const& field, String const& content) - { - auto iter = headers_.find(field); - if (iter != headers_.end()) - { - headers_[field] = content; - } - else - { - headers_.insert(std::make_pair(field, content)); - } - } - } } diff --git a/src/kiwano-network/HttpRequest.h b/src/kiwano-network/HttpRequest.h index 942376fe..716f8240 100644 --- a/src/kiwano-network/HttpRequest.h +++ b/src/kiwano-network/HttpRequest.h @@ -19,10 +19,10 @@ // THE SOFTWARE. #pragma once -#include -#include -#include -#include +#include +#include +#include +#include namespace kiwano { @@ -47,35 +47,32 @@ namespace kiwano Delete }; - inline HttpRequest() : type_(Type::Unknown) {} + HttpRequest(); - inline HttpRequest(Type type) : type_(type) {} + HttpRequest(Type type); - inline void SetUrl(String const& url) { url_ = url; } + // 请求地址 + void SetUrl(String const& url); + String const& GetUrl() const; - inline String const& GetUrl() const { return url_; } + // 请求类型 + void SetType(Type type); + Type GetType() const; - inline void SetType(Type type) { type_ = type; } + // 请求数据 + void SetData(String const& data); + void SetJsonData(Json const& json); + String const& GetData() const; - inline Type GetType() const { return type_; } + // 请求头 + void SetHeaders(Map const& headers); + void SetHeader(String const& field, String const& content); + Map& GetHeaders(); + String const& GetHeader(String const& header) const; - inline void SetData(String const& data) { data_ = data; } - - void SetJsonData(Json const& json); - - inline String const& GetData() const { return data_; } - - inline void SetHeaders(Map const& headers) { headers_ = headers; } - - void SetHeader(String const& field, String const& content); - - inline Map& GetHeaders() { return headers_; } - - inline String const& GetHeader(String const& header) const { return headers_.at(header); } - - inline void SetResponseCallback(ResponseCallback const& callback) { response_cb_ = callback; } - - inline ResponseCallback const& GetResponseCallback() const { return response_cb_; } + // 响应回调 + void SetResponseCallback(ResponseCallback const& callback); + ResponseCallback const& GetResponseCallback() const; protected: Type type_; @@ -84,5 +81,33 @@ namespace kiwano Map headers_; ResponseCallback response_cb_; }; + + inline HttpRequest::HttpRequest() : type_(Type::Unknown) {} + + inline HttpRequest::HttpRequest(Type type) : type_(type) {} + + inline void HttpRequest::SetUrl(String const& url) { url_ = url; } + + inline String const& HttpRequest::GetUrl() const { return url_; } + + inline void HttpRequest::SetType(Type type) { type_ = type; } + + inline HttpRequest::Type HttpRequest::GetType() const { return type_; } + + inline void HttpRequest::SetData(String const& data) { data_ = data; } + + inline String const& HttpRequest::GetData() const { return data_; } + + inline void HttpRequest::SetHeaders(Map const& headers) { headers_ = headers; } + + inline void HttpRequest::SetHeader(String const& field, String const& content) { headers_[field] = content; } + + inline Map& HttpRequest::GetHeaders() { return headers_; } + + inline String const& HttpRequest::GetHeader(String const& header) const { return headers_.at(header); } + + inline void HttpRequest::SetResponseCallback(ResponseCallback const& callback) { response_cb_ = callback; } + + inline HttpRequest::ResponseCallback const& HttpRequest::GetResponseCallback() const { return response_cb_; } } } diff --git a/src/kiwano-network/HttpResponse.hpp b/src/kiwano-network/HttpResponse.hpp index 24874db9..a2d043b0 100644 --- a/src/kiwano-network/HttpResponse.hpp +++ b/src/kiwano-network/HttpResponse.hpp @@ -31,29 +31,30 @@ namespace kiwano : public ObjectBase { public: - inline HttpResponse(HttpRequestPtr request) : request_(request), succeed_(false), response_code_(0) {} + HttpResponse(HttpRequestPtr request); - inline HttpRequestPtr GetRequest() const { return request_; } + // 获取请求 + HttpRequestPtr GetRequest() const; - inline void SetSucceed(bool succeed) { succeed_ = succeed; } + // 响应状态 + bool IsSucceed() const; + void SetSucceed(bool succeed); - inline bool IsSucceed() const { return succeed_; } + // 响应状态码 + long GetResponseCode() const; + void SetResponseCode(long response_code); - inline void SetResponseCode(long response_code) { response_code_ = response_code; } + // 响应头 + String GetHeader() const; + void SetHeader(String const& response_header); - inline long GetResponseCode() const { return response_code_; } + // 响应数据 + String const& GetData() const; + void SetData(String const& response_data); - inline void SetHeader(String const& response_header) { response_header_ = response_header; } - - inline String GetHeader() const { return response_header_; } - - inline void SetData(String const& response_data) { response_data_ = response_data; } - - inline String const& GetData() const { return response_data_; } - - inline void SetError(String const& error_buffer) { error_buffer_ = error_buffer; } - - inline String const& GetError() const { return error_buffer_; } + // 错误信息 + String const& GetError() const; + void SetError(String const& error_buffer); protected: bool succeed_; @@ -64,5 +65,29 @@ namespace kiwano String response_data_; String error_buffer_; }; + + inline HttpResponse::HttpResponse(HttpRequestPtr request) : request_(request), succeed_(false), response_code_(0) {} + + inline HttpRequestPtr HttpResponse::GetRequest() const { return request_; } + + inline void HttpResponse::SetSucceed(bool succeed) { succeed_ = succeed; } + + inline bool HttpResponse::IsSucceed() const { return succeed_; } + + inline void HttpResponse::SetResponseCode(long response_code) { response_code_ = response_code; } + + inline long HttpResponse::GetResponseCode() const { return response_code_; } + + inline void HttpResponse::SetHeader(String const& response_header) { response_header_ = response_header; } + + inline String HttpResponse::GetHeader() const { return response_header_; } + + inline void HttpResponse::SetData(String const& response_data) { response_data_ = response_data; } + + inline String const& HttpResponse::GetData() const { return response_data_; } + + inline void HttpResponse::SetError(String const& error_buffer) { error_buffer_ = error_buffer; } + + inline String const& HttpResponse::GetError() const { return error_buffer_; } } } diff --git a/src/kiwano-physics/Body.cpp b/src/kiwano-physics/Body.cpp index 18feed30..379b40f1 100644 --- a/src/kiwano-physics/Body.cpp +++ b/src/kiwano-physics/Body.cpp @@ -26,7 +26,7 @@ namespace kiwano namespace physics { - PhysicBody::PhysicBody() + Body::Body() : body_(nullptr) , actor_(nullptr) , world_(nullptr) @@ -36,25 +36,25 @@ namespace kiwano { } - PhysicBody::PhysicBody(b2Body* body, Actor* actor) - : PhysicBody() + Body::Body(b2Body* body, Actor* actor) + : Body() { SetB2Body(body); SetActor(actor); } - PhysicBody::PhysicBody(PhysicWorld* world, Actor* actor) - : PhysicBody() + Body::Body(World* world, Actor* actor) + : Body() { Init(world, actor); } - PhysicBody::~PhysicBody() + Body::~Body() { Destroy(); } - void PhysicBody::Init(PhysicWorld* world, Actor* actor) + void Body::Init(World* world, Actor* actor) { KGE_ASSERT(world); @@ -69,38 +69,38 @@ namespace kiwano UpdateFromActor(); } - PhysicFixture PhysicBody::AddFixture(PhysicShape* shape, const PhysicFixture::Param& param) + Fixture Body::AddFixture(Shape* shape, const Fixture::Param& param) { KGE_ASSERT(body_ && world_); - return PhysicFixture(this, shape, param); + return Fixture(this, shape, param); } - PhysicFixture PhysicBody::AddCircleShape(float radius, float density) + Fixture Body::AddCircleShape(float radius, float density) { - return AddFixture(&PhysicCircleShape(radius), PhysicFixture::Param(density)); + return AddFixture(&CircleShape(radius), Fixture::Param(density)); } - PhysicFixture PhysicBody::AddBoxShape(Vec2 const& size, float density) + Fixture Body::AddBoxShape(Vec2 const& size, float density) { - return AddFixture(&PhysicBoxShape(size), PhysicFixture::Param(density)); + return AddFixture(&BoxShape(size), Fixture::Param(density)); } - PhysicFixture PhysicBody::AddPolygonShape(Vector const& vertexs, float density) + Fixture Body::AddPolygonShape(Vector const& vertexs, float density) { - return AddFixture(&PhysicPolygonShape(vertexs), PhysicFixture::Param(density)); + return AddFixture(&PolygonShape(vertexs), Fixture::Param(density)); } - PhysicFixture PhysicBody::AddEdgeShape(Point const& p1, Point const& p2, float density) + Fixture Body::AddEdgeShape(Point const& p1, Point const& p2, float density) { - return AddFixture(&PhysicEdgeShape(p1, p2), PhysicFixture::Param(density)); + return AddFixture(&EdgeShape(p1, p2), Fixture::Param(density)); } - PhysicFixture PhysicBody::AddChainShape(Vector const& vertexs, bool loop, float density) + Fixture Body::AddChainShape(Vector const& vertexs, bool loop, float density) { - return AddFixture(&PhysicChainShape(vertexs, loop), PhysicFixture::Param(density)); + return AddFixture(&ChainShape(vertexs, loop), Fixture::Param(density)); } - void PhysicBody::RemoveFixture(PhysicFixture const& fixture) + void Body::RemoveFixture(Fixture const& fixture) { if (fixture.GetB2Fixture()) { @@ -109,7 +109,7 @@ namespace kiwano } } - void PhysicBody::SetCategoryBits(uint16_t category_bits) + void Body::SetCategoryBits(uint16_t category_bits) { KGE_ASSERT(body_); @@ -126,7 +126,7 @@ namespace kiwano } } - void PhysicBody::SetMaskBits(uint16_t mask_bits) + void Body::SetMaskBits(uint16_t mask_bits) { KGE_ASSERT(body_); @@ -143,7 +143,7 @@ namespace kiwano } } - void PhysicBody::SetGroupIndex(int16_t index) + void Body::SetGroupIndex(int16_t index) { KGE_ASSERT(body_); @@ -160,7 +160,7 @@ namespace kiwano } } - void PhysicBody::GetMassData(float* mass, Point* center, float* inertia) const + void Body::GetMassData(float* mass, Point* center, float* inertia) const { KGE_ASSERT(body_ && world_); @@ -172,7 +172,7 @@ namespace kiwano if (inertia) *inertia = data.I; } - void PhysicBody::SetMassData(float mass, Point const& center, float inertia) + void Body::SetMassData(float mass, Point const& center, float inertia) { KGE_ASSERT(body_ && world_); @@ -183,67 +183,67 @@ namespace kiwano body_->SetMassData(&data); } - void PhysicBody::ResetMassData() + void Body::ResetMassData() { KGE_ASSERT(body_); body_->ResetMassData(); } - Point PhysicBody::GetBodyPosition() const + Point Body::GetBodyPosition() const { KGE_ASSERT(body_ && world_); return world_->World2Stage(body_->GetPosition()); } - void PhysicBody::SetBodyTransform(Point const& pos, float angle) + void Body::SetBodyTransform(Point const& pos, float angle) { KGE_ASSERT(body_ && world_); body_->SetTransform(world_->Stage2World(pos), math::Degree2Radian(angle)); } - Point PhysicBody::GetLocalPoint(Point const& world) const + Point Body::GetLocalPoint(Point const& world) const { KGE_ASSERT(body_ && world_); return world_->World2Stage(body_->GetLocalPoint(world_->Stage2World(world))); } - Point PhysicBody::GetWorldPoint(Point const& local) const + Point Body::GetWorldPoint(Point const& local) const { KGE_ASSERT(body_ && world_); return world_->World2Stage(body_->GetWorldPoint(world_->Stage2World(local))); } - Point PhysicBody::GetLocalCenter() const + Point Body::GetLocalCenter() const { KGE_ASSERT(body_ && world_); return world_->World2Stage(body_->GetLocalCenter()); } - Point PhysicBody::GetWorldCenter() const + Point Body::GetWorldCenter() const { KGE_ASSERT(body_ && world_); return world_->World2Stage(body_->GetWorldCenter()); } - void PhysicBody::ApplyForce(Vec2 const& force, Point const& point, bool wake) + void Body::ApplyForce(Vec2 const& force, Point const& point, bool wake) { KGE_ASSERT(body_ && world_); body_->ApplyForce(b2Vec2(force.x, force.y), world_->Stage2World(point), wake); } - void PhysicBody::ApplyForceToCenter(Vec2 const& force, bool wake) + void Body::ApplyForceToCenter(Vec2 const& force, bool wake) { KGE_ASSERT(body_ && world_); body_->ApplyForceToCenter(b2Vec2(force.x, force.y), wake); } - void PhysicBody::ApplyTorque(float torque, bool wake) + void Body::ApplyTorque(float torque, bool wake) { KGE_ASSERT(body_ && world_); body_->ApplyTorque(torque, wake); } - void PhysicBody::SetB2Body(b2Body* body) + void Body::SetB2Body(b2Body* body) { body_ = body; if (body_) @@ -252,7 +252,7 @@ namespace kiwano } } - void PhysicBody::Destroy() + void Body::Destroy() { if (world_) { @@ -264,7 +264,7 @@ namespace kiwano actor_ = nullptr; } - void PhysicBody::UpdateActor() + void Body::UpdateActor() { if (actor_ && body_) { @@ -280,7 +280,7 @@ namespace kiwano } } - void PhysicBody::UpdateFromActor() + void Body::UpdateFromActor() { if (actor_ && body_) { @@ -301,7 +301,7 @@ namespace kiwano } } - void PhysicBody::UpdateFixtureFilter(b2Fixture* fixture) + void Body::UpdateFixtureFilter(b2Fixture* fixture) { b2Filter filter; filter.categoryBits = category_bits_; diff --git a/src/kiwano-physics/Body.h b/src/kiwano-physics/Body.h index 8647eddf..e9f25989 100644 --- a/src/kiwano-physics/Body.h +++ b/src/kiwano-physics/Body.h @@ -28,11 +28,11 @@ namespace kiwano { namespace physics { - class PhysicWorld; + class World; // 物体 - KGE_DECLARE_SMART_PTR(PhysicBody); - class KGE_API PhysicBody + KGE_DECLARE_SMART_PTR(Body); + class KGE_API Body : public virtual RefCounter { public: @@ -43,33 +43,33 @@ namespace kiwano Dynamic, }; - PhysicBody(); - PhysicBody(b2Body* body, Actor* actor); - PhysicBody(PhysicWorld* world, Actor* actor); - PhysicBody(PhysicWorld* world, ActorPtr actor) : PhysicBody(world, actor.get()) {} - virtual ~PhysicBody(); + Body(); + Body(b2Body* body, Actor* actor); + Body(World* world, Actor* actor); + Body(World* world, ActorPtr actor) : Body(world, actor.get()) {} + virtual ~Body(); // 初始化 - void Init(PhysicWorld* world, Actor* actor); + void Init(World* world, Actor* actor); // 添加夹具 - PhysicFixture AddFixture(PhysicShape* shape, const PhysicFixture::Param& param); + Fixture AddFixture(Shape* shape, const Fixture::Param& param); // 添加形状 - PhysicFixture AddCircleShape(float radius, float density = 0.f); - PhysicFixture AddBoxShape(Vec2 const& size, float density = 0.f); - PhysicFixture AddPolygonShape(Vector const& vertexs, float density = 0.f); - PhysicFixture AddEdgeShape(Point const& p1, Point const& p2, float density = 0.f); - PhysicFixture AddChainShape(Vector const& vertexs, bool loop, float density = 0.f); + Fixture AddCircleShape(float radius, float density = 0.f); + Fixture AddBoxShape(Vec2 const& size, float density = 0.f); + Fixture AddPolygonShape(Vector const& vertexs, float density = 0.f); + Fixture AddEdgeShape(Point const& p1, Point const& p2, float density = 0.f); + Fixture AddChainShape(Vector const& vertexs, bool loop, float density = 0.f); // 获取夹具 - PhysicFixture GetFixtureList() const { KGE_ASSERT(body_); return PhysicFixture(body_->GetFixtureList()); } + Fixture GetFixtureList() const { KGE_ASSERT(body_); return Fixture(body_->GetFixtureList()); } // 移除夹具 - void RemoveFixture(PhysicFixture const& fixture); + void RemoveFixture(Fixture const& fixture); // 获取接触边 - PhysicContactEdge GetContactList() const { KGE_ASSERT(body_); PhysicContactEdge(body_->GetContactList()); } + ContactEdge GetContactList() const { KGE_ASSERT(body_); ContactEdge(body_->GetContactList()); } // 类别码 uint16_t GetCategoryBits() const { return category_bits_; } @@ -153,8 +153,8 @@ namespace kiwano const b2Body* GetB2Body() const { return body_; } void SetB2Body(b2Body* body); - PhysicWorld* GetWorld() { return world_; } - const PhysicWorld* GetWorld() const { return world_; } + World* GetWorld() { return world_; } + const World* GetWorld() const { return world_; } void Destroy(); @@ -166,7 +166,7 @@ namespace kiwano protected: Actor* actor_; - PhysicWorld* world_; + World* world_; b2Body* body_; uint16_t category_bits_; diff --git a/src/kiwano-physics/Contact.cpp b/src/kiwano-physics/Contact.cpp index 8b5bcf41..b46698ce 100644 --- a/src/kiwano-physics/Contact.cpp +++ b/src/kiwano-physics/Contact.cpp @@ -27,87 +27,87 @@ namespace kiwano namespace physics { - PhysicContact::PhysicContact() + Contact::Contact() : contact_(nullptr) { } - PhysicContact::PhysicContact(b2Contact* contact) - : PhysicContact() + Contact::Contact(b2Contact* contact) + : Contact() { SetB2Contact(contact); } - PhysicContact PhysicContact::GetNext() + Contact Contact::GetNext() { KGE_ASSERT(contact_); - return PhysicContact(contact_->GetNext()); + return Contact(contact_->GetNext()); } - const PhysicContact PhysicContact::GetNext() const + const Contact Contact::GetNext() const { KGE_ASSERT(contact_); - return PhysicContact(contact_->GetNext()); + return Contact(contact_->GetNext()); } - PhysicFixture PhysicContact::GetFixtureA() + Fixture Contact::GetFixtureA() { KGE_ASSERT(contact_); - return PhysicFixture(contact_->GetFixtureA()); + return Fixture(contact_->GetFixtureA()); } - const PhysicFixture PhysicContact::GetFixtureA() const + const Fixture Contact::GetFixtureA() const { KGE_ASSERT(contact_); - return PhysicFixture(contact_->GetFixtureA()); + return Fixture(contact_->GetFixtureA()); } - PhysicFixture PhysicContact::GetFixtureB() + Fixture Contact::GetFixtureB() { KGE_ASSERT(contact_); - return PhysicFixture(contact_->GetFixtureB()); + return Fixture(contact_->GetFixtureB()); } - const PhysicFixture PhysicContact::GetFixtureB() const + const Fixture Contact::GetFixtureB() const { KGE_ASSERT(contact_); - return PhysicFixture(contact_->GetFixtureB()); + return Fixture(contact_->GetFixtureB()); } - void PhysicContact::SetTangentSpeed(float speed) + void Contact::SetTangentSpeed(float speed) { KGE_ASSERT(contact_); - PhysicBody* body = GetFixtureA().GetBody(); + Body* body = GetFixtureA().GetBody(); KGE_ASSERT(body); - PhysicWorld* world = body->GetWorld(); + World* world = body->GetWorld(); KGE_ASSERT(world); contact_->SetTangentSpeed(world->Stage2World(speed)); } - float PhysicContact::GetTangentSpeed() const + float Contact::GetTangentSpeed() const { KGE_ASSERT(contact_); - const PhysicBody* body = GetFixtureA().GetBody(); + const Body* body = GetFixtureA().GetBody(); KGE_ASSERT(body); - const PhysicWorld* world = body->GetWorld(); + const World* world = body->GetWorld(); KGE_ASSERT(world); return world->World2Stage(contact_->GetTangentSpeed()); } - PhysicContactEdge::PhysicContactEdge() + ContactEdge::ContactEdge() : edge_(nullptr) { } - PhysicContactEdge::PhysicContactEdge(b2ContactEdge* edge) - : PhysicContactEdge() + ContactEdge::ContactEdge(b2ContactEdge* edge) + : ContactEdge() { SetB2ContactEdge(edge); } diff --git a/src/kiwano-physics/Contact.h b/src/kiwano-physics/Contact.h index b32b8db4..0f0ee915 100644 --- a/src/kiwano-physics/Contact.h +++ b/src/kiwano-physics/Contact.h @@ -26,14 +26,14 @@ namespace kiwano { namespace physics { - class PhysicBody; + class Body; // 接触 - class KGE_API PhysicContact + class KGE_API Contact { public: - PhysicContact(); - PhysicContact(b2Contact* contact); + Contact(); + Contact(b2Contact* contact); // 是否是接触 bool IsTouching() const { KGE_ASSERT(contact_); return contact_->IsTouching(); } @@ -43,16 +43,16 @@ namespace kiwano bool IsEnabled() const { KGE_ASSERT(contact_); return contact_->IsEnabled(); } // 获取下一接触 - PhysicContact GetNext(); - const PhysicContact GetNext() const; + Contact GetNext(); + const Contact GetNext() const; // 夹具 A - PhysicFixture GetFixtureA(); - const PhysicFixture GetFixtureA() const; + Fixture GetFixtureA(); + const Fixture GetFixtureA() const; // 夹具 B - PhysicFixture GetFixtureB(); - const PhysicFixture GetFixtureB() const; + Fixture GetFixtureB(); + const Fixture GetFixtureB() const; // 摩擦 void SetFriction(float friction) { KGE_ASSERT(contact_); contact_->SetFriction(friction); } @@ -78,27 +78,27 @@ namespace kiwano // 接触边 - class KGE_API PhysicContactEdge + class KGE_API ContactEdge { public: - PhysicContactEdge(); - PhysicContactEdge(b2ContactEdge* edge); + ContactEdge(); + ContactEdge(b2ContactEdge* edge); // 获取接触物体 - PhysicBody* GetOtherBody() { KGE_ASSERT(edge_); return static_cast(edge_->other->GetUserData()); } - const PhysicBody* GetOtherBody() const { KGE_ASSERT(edge_); return static_cast(edge_->other->GetUserData()); } + Body* GetOtherBody() { KGE_ASSERT(edge_); return static_cast(edge_->other->GetUserData()); } + const Body* GetOtherBody() const { KGE_ASSERT(edge_); return static_cast(edge_->other->GetUserData()); } // 获取接触 - PhysicContact GetContact() { KGE_ASSERT(edge_); return PhysicContact(edge_->contact); } - const PhysicContact GetContact() const { KGE_ASSERT(edge_); return PhysicContact(edge_->contact); } + Contact GetContact() { KGE_ASSERT(edge_); return Contact(edge_->contact); } + const Contact GetContact() const { KGE_ASSERT(edge_); return Contact(edge_->contact); } // 获取上一接触边 - PhysicContactEdge GetPrev() { KGE_ASSERT(edge_); return PhysicContactEdge(edge_->prev); } - const PhysicContactEdge GetPrev() const { KGE_ASSERT(edge_); return PhysicContactEdge(edge_->prev); } + ContactEdge GetPrev() { KGE_ASSERT(edge_); return ContactEdge(edge_->prev); } + const ContactEdge GetPrev() const { KGE_ASSERT(edge_); return ContactEdge(edge_->prev); } // 获取下一接触边 - PhysicContactEdge GetNext() { KGE_ASSERT(edge_); return PhysicContactEdge(edge_->next); } - const PhysicContactEdge GetNext() const { KGE_ASSERT(edge_); return PhysicContactEdge(edge_->next); } + ContactEdge GetNext() { KGE_ASSERT(edge_); return ContactEdge(edge_->next); } + const ContactEdge GetNext() const { KGE_ASSERT(edge_); return ContactEdge(edge_->next); } b2ContactEdge* GetB2ContactEdge() { return edge_; } const b2ContactEdge* GetB2ContactEdge() const { return edge_; } diff --git a/src/kiwano-physics/ContactEvent.cpp b/src/kiwano-physics/ContactEvent.cpp new file mode 100644 index 00000000..108134a7 --- /dev/null +++ b/src/kiwano-physics/ContactEvent.cpp @@ -0,0 +1,65 @@ +// Copyright (c) 2018-2019 Kiwano - Nomango +// +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files (the "Software"), to deal +// in the Software without restriction, including without limitation the rights +// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +// copies of the Software, and to permit persons to whom the Software is +// furnished to do so, subject to the following conditions: +// +// The above copyright notice and this permission notice shall be included in +// all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +// THE SOFTWARE. + +#include + +namespace kiwano +{ + namespace event + { + EventType event::ContactBegin = EventType(L"ContactBegin"); + EventType event::ContactEnd = EventType(L"ContactEnd"); + } + + namespace physics + { + + ContactBeginEvent::ContactBeginEvent() + : Event(event::ContactBegin) + , body_a(nullptr) + , body_b(nullptr) + { + } + + ContactBeginEvent::ContactBeginEvent(Contact const& contact) + : ContactBeginEvent() + { + this->contact = contact; + body_a = this->contact.GetFixtureA().GetBody(); + body_b = this->contact.GetFixtureB().GetBody(); + } + + ContactEndEvent::ContactEndEvent() + : Event(event::ContactEnd) + , body_a(nullptr) + , body_b(nullptr) + { + } + + ContactEndEvent::ContactEndEvent(Contact const& contact) + : ContactEndEvent() + { + this->contact = contact; + body_a = this->contact.GetFixtureA().GetBody(); + body_b = this->contact.GetFixtureB().GetBody(); + } + +} +} diff --git a/src/kiwano-physics/ContactEvent.h b/src/kiwano-physics/ContactEvent.h new file mode 100644 index 00000000..ba2488f4 --- /dev/null +++ b/src/kiwano-physics/ContactEvent.h @@ -0,0 +1,62 @@ +// Copyright (c) 2018-2019 Kiwano - Nomango +// +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files (the "Software"), to deal +// in the Software without restriction, including without limitation the rights +// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +// copies of the Software, and to permit persons to whom the Software is +// furnished to do so, subject to the following conditions: +// +// The above copyright notice and this permission notice shall be included in +// all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +// THE SOFTWARE. + +#pragma once +#include +#include + +namespace kiwano +{ + namespace physics + { + // 接触开始事件 + class KGE_API ContactBeginEvent + : public Event + { + public: + Contact contact; + Body* body_a; + Body* body_b; + + ContactBeginEvent(); + ContactBeginEvent(Contact const& contact); + }; + + // 接触结束事件 + class KGE_API ContactEndEvent + : public Event + { + public: + Contact contact; + Body* body_a; + Body* body_b; + + ContactEndEvent(); + ContactEndEvent(Contact const& contact); + }; + + } + + namespace event + { + extern EventType ContactBegin; // 接触开始 + extern EventType ContactEnd; // 接触结束 + } +} diff --git a/src/kiwano-physics/ContactListener.cpp b/src/kiwano-physics/ContactListener.cpp deleted file mode 100644 index 276d5a78..00000000 --- a/src/kiwano-physics/ContactListener.cpp +++ /dev/null @@ -1,158 +0,0 @@ -// Copyright (c) 2018-2019 Kiwano - Nomango -// -// Permission is hereby granted, free of charge, to any person obtaining a copy -// of this software and associated documentation files (the "Software"), to deal -// in the Software without restriction, including without limitation the rights -// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -// copies of the Software, and to permit persons to whom the Software is -// furnished to do so, subject to the following conditions: -// -// The above copyright notice and this permission notice shall be included in -// all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -// THE SOFTWARE. - -#include -#include -#include - -namespace kiwano -{ - namespace physics - { - PhysicContactListener::PhysicContactListener() - : running_(true) - { - } - - PhysicContactListener::~PhysicContactListener() - { - } - - - PhysicContactCallbackListener::PhysicContactCallbackListener() - { - } - - PhysicContactCallbackListener::~PhysicContactCallbackListener() - { - } - - - PhysicContactListener* PhysicContactDispatcher::AddContactListener(PhysicContactListenerPtr listener) - { - return AddContactListener(listener.get()); - } - - PhysicContactListener* PhysicContactDispatcher::AddContactListener(PhysicContactListener* listener) - { - KGE_ASSERT(listener && "AddListener failed, NULL pointer exception"); - - if (listener) - { - listeners_.push_back(listener); - } - return listener; - } - - void PhysicContactDispatcher::StartContactListeners(String const& listener_name) - { - for (auto listener : listeners_) - { - if (listener->IsName(listener_name)) - { - listener->Start(); - } - } - } - - void PhysicContactDispatcher::StopContactListeners(String const& listener_name) - { - for (auto listener : listeners_) - { - if (listener->IsName(listener_name)) - { - listener->Stop(); - } - } - } - - void PhysicContactDispatcher::RemoveContactListeners(String const& listener_name) - { - PhysicContactListenerPtr next; - for (auto listener = listeners_.first_item(); listener; listener = next) - { - next = listener->next_item(); - - if (listener->IsName(listener_name)) - { - listeners_.remove(listener); - } - } - } - - void PhysicContactDispatcher::StartAllContactListeners() - { - for (auto listener : listeners_) - { - listener->Start(); - } - } - - void PhysicContactDispatcher::StopAllContactListeners() - { - for (auto listener : listeners_) - { - listener->Stop(); - } - } - - void PhysicContactDispatcher::RemoveAllContactListeners() - { - listeners_.clear(); - } - - void PhysicContactDispatcher::OnContactBegin(b2Contact* b2contact) - { - if (listeners_.empty()) - return; - - PhysicContact contact(b2contact); - PhysicContactListenerPtr next; - for (auto listener = listeners_.first_item(); listener; listener = next) - { - next = listener->next_item(); - - if (listener->IsRunning()) - { - listener->OnContactBegin(contact); - } - } - } - - void PhysicContactDispatcher::OnContactEnd(b2Contact* b2contact) - { - if (listeners_.empty()) - return; - - PhysicContact contact(b2contact); - PhysicContactListenerPtr next; - for (auto listener = listeners_.first_item(); listener; listener = next) - { - next = listener->next_item(); - - if (listener->IsRunning()) - { - listener->OnContactEnd(contact); - } - } - } - - } -} diff --git a/src/kiwano-physics/ContactListener.h b/src/kiwano-physics/ContactListener.h deleted file mode 100644 index 9556d633..00000000 --- a/src/kiwano-physics/ContactListener.h +++ /dev/null @@ -1,141 +0,0 @@ -// Copyright (c) 2018-2019 Kiwano - Nomango -// -// Permission is hereby granted, free of charge, to any person obtaining a copy -// of this software and associated documentation files (the "Software"), to deal -// in the Software without restriction, including without limitation the rights -// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -// copies of the Software, and to permit persons to whom the Software is -// furnished to do so, subject to the following conditions: -// -// The above copyright notice and this permission notice shall be included in -// all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -// THE SOFTWARE. - -#pragma once -#include - -namespace kiwano -{ - namespace physics - { - class PhysicContactDispatcher; - - KGE_DECLARE_SMART_PTR(PhysicContactListener); - - // 接触监听器 - class KGE_API PhysicContactListener - : public ObjectBase - , protected IntrusiveListItem - { - friend IntrusiveList; - friend class PhysicContactDispatcher; - - public: - PhysicContactListener(); - virtual ~PhysicContactListener(); - - // 接触开始 - virtual void OnContactBegin(PhysicContact contact) { KGE_NOT_USED(contact); } - - // 接触结束 - virtual void OnContactEnd(PhysicContact contact) { KGE_NOT_USED(contact); } - - inline void Start() { running_ = true; } - inline void Stop() { running_ = true; } - inline bool IsRunning() const { return running_; } - - protected: - bool running_; - }; - - - KGE_DECLARE_SMART_PTR(PhysicContactCallbackListener); - - // 接触回调监听器 - class KGE_API PhysicContactCallbackListener - : public PhysicContactListener - { - friend IntrusiveList; - friend class PhysicContactDispatcher; - - public: - using ContactBeginCallback = Function; - using ContactEndCallback = Function; - - PhysicContactCallbackListener(); - virtual ~PhysicContactCallbackListener(); - - // 接触开始回调 - void SetCallbackOnContactBegin(ContactBeginCallback const& cb) { begin_ = cb; } - ContactBeginCallback GetCallbackOnContactBegin() const { return begin_; } - - // 接触结束回调 - void SetCallbackOnContactEnd(ContactEndCallback const& cb) { end_ = cb; } - ContactEndCallback GetCallbackOnContactEnd() const { return end_; } - - void OnContactBegin(PhysicContact contact) override { if (begin_) begin_(contact); } - void OnContactEnd(PhysicContact contact) override { if (end_) end_(contact); } - - protected: - ContactBeginCallback begin_; - ContactEndCallback end_; - }; - - - // 接触分发器 - class KGE_API PhysicContactDispatcher - { - public: - using Listeners = IntrusiveList; - - // 添加监听器 - PhysicContactListener* AddContactListener( - PhysicContactListenerPtr listener - ); - - // 添加监听器 - PhysicContactListener* AddContactListener( - PhysicContactListener* listener - ); - - // 启动监听器 - void StartContactListeners( - String const& listener_name - ); - - // 停止监听器 - void StopContactListeners( - String const& listener_name - ); - - // 移除监听器 - void RemoveContactListeners( - String const& listener_name - ); - - // 启动所有监听器 - void StartAllContactListeners(); - - // 停止所有监听器 - void StopAllContactListeners(); - - // 移除所有监听器 - void RemoveAllContactListeners(); - - protected: - void OnContactBegin(b2Contact* contact); - - void OnContactEnd(b2Contact* contact); - - private: - Listeners listeners_; - }; - } -} diff --git a/src/kiwano-physics/Fixture.cpp b/src/kiwano-physics/Fixture.cpp index 35f264e6..dc6a8c52 100644 --- a/src/kiwano-physics/Fixture.cpp +++ b/src/kiwano-physics/Fixture.cpp @@ -27,19 +27,19 @@ namespace kiwano namespace physics { - PhysicFixture::PhysicFixture() + Fixture::Fixture() : fixture_(nullptr) { } - PhysicFixture::PhysicFixture(b2Fixture* fixture) - : PhysicFixture() + Fixture::Fixture(b2Fixture* fixture) + : Fixture() { SetB2Fixture(fixture); } - PhysicFixture::PhysicFixture(PhysicBody* body, PhysicShape* shape, const Param& param) - : PhysicFixture() + Fixture::Fixture(Body* body, Shape* shape, const Param& param) + : Fixture() { KGE_ASSERT(body); @@ -58,38 +58,38 @@ namespace kiwano } } - PhysicBody* PhysicFixture::GetBody() + Body* Fixture::GetBody() { KGE_ASSERT(fixture_); - return static_cast(fixture_->GetBody()->GetUserData()); + return static_cast(fixture_->GetBody()->GetUserData()); } - const PhysicBody* PhysicFixture::GetBody() const + const Body* Fixture::GetBody() const { KGE_ASSERT(fixture_); - return static_cast(fixture_->GetBody()->GetUserData()); + return static_cast(fixture_->GetBody()->GetUserData()); } - PhysicShape PhysicFixture::GetShape() const + Shape Fixture::GetShape() const { KGE_ASSERT(fixture_); - return PhysicShape(fixture_->GetShape()); + return Shape(fixture_->GetShape()); } - PhysicFixture PhysicFixture::GetNext() const + Fixture Fixture::GetNext() const { KGE_ASSERT(fixture_); - return PhysicFixture(fixture_->GetNext()); + return Fixture(fixture_->GetNext()); } - void PhysicFixture::GetMassData(float* mass, Point* center, float* inertia) const + void Fixture::GetMassData(float* mass, Point* center, float* inertia) const { KGE_ASSERT(fixture_); - const PhysicBody* body = GetBody(); + const Body* body = GetBody(); KGE_ASSERT(body); - const PhysicWorld* world = body->GetWorld(); + const World* world = body->GetWorld(); KGE_ASSERT(world); b2MassData data; @@ -100,14 +100,14 @@ namespace kiwano if (inertia) *inertia = data.I; } - bool PhysicFixture::TestPoint(const Point& p) const + bool Fixture::TestPoint(const Point& p) const { KGE_ASSERT(fixture_); - const PhysicBody* body = GetBody(); + const Body* body = GetBody(); KGE_ASSERT(body); - const PhysicWorld* world = body->GetWorld(); + const World* world = body->GetWorld(); KGE_ASSERT(world); return fixture_->TestPoint(world->Stage2World(p)); diff --git a/src/kiwano-physics/Fixture.h b/src/kiwano-physics/Fixture.h index 85cb3895..2097d5a2 100644 --- a/src/kiwano-physics/Fixture.h +++ b/src/kiwano-physics/Fixture.h @@ -26,10 +26,10 @@ namespace kiwano { namespace physics { - class PhysicBody; + class Body; // 夹具 - class PhysicFixture + class Fixture { public: struct Param @@ -49,19 +49,19 @@ namespace kiwano {} }; - PhysicFixture(); - PhysicFixture(b2Fixture* fixture); - PhysicFixture(PhysicBody* body, PhysicShape* shape, const Param& param); + Fixture(); + Fixture(b2Fixture* fixture); + Fixture(Body* body, Shape* shape, const Param& param); // 物体 - PhysicBody* GetBody(); - const PhysicBody* GetBody() const; + Body* GetBody(); + const Body* GetBody() const; // 形状 - PhysicShape GetShape() const; + Shape GetShape() const; // 下一夹具 (同一物体上) - PhysicFixture GetNext() const; + Fixture GetNext() const; // 接触传感器 bool IsSensor() const { KGE_ASSERT(fixture_); return fixture_->IsSensor(); } diff --git a/src/kiwano-physics/Joint.cpp b/src/kiwano-physics/Joint.cpp index e32a2598..08be38b7 100644 --- a/src/kiwano-physics/Joint.cpp +++ b/src/kiwano-physics/Joint.cpp @@ -26,29 +26,29 @@ namespace kiwano namespace physics { // - // PhysicJoint + // Joint // - PhysicJoint::PhysicJoint() + Joint::Joint() : joint_(nullptr) , world_(nullptr) , type_(Type::Unknown) { } - PhysicJoint::PhysicJoint(b2Joint* joint) - : PhysicJoint() + Joint::Joint(b2Joint* joint) + : Joint() { SetB2Joint(joint); } - PhysicJoint::PhysicJoint(PhysicWorld* world, b2JointDef* joint_def) - : PhysicJoint() + Joint::Joint(World* world, b2JointDef* joint_def) + : Joint() { Init(world, joint_def); } - PhysicJoint::~PhysicJoint() + Joint::~Joint() { if (world_) { @@ -56,7 +56,7 @@ namespace kiwano } } - void PhysicJoint::Init(PhysicWorld* world, b2JointDef* joint_def) + void Joint::Init(World* world, b2JointDef* joint_def) { world_ = world; if (world_) @@ -68,28 +68,28 @@ namespace kiwano } } - PhysicBodyPtr PhysicJoint::GetBodyA() const + BodyPtr Joint::GetBodyA() const { KGE_ASSERT(joint_); b2Body* body = joint_->GetBodyA(); - return PhysicBodyPtr(static_cast(body->GetUserData())); + return BodyPtr(static_cast(body->GetUserData())); } - PhysicBodyPtr PhysicJoint::GetBodyB() const + BodyPtr Joint::GetBodyB() const { KGE_ASSERT(joint_); b2Body* body = joint_->GetBodyB(); - return PhysicBodyPtr(static_cast(body->GetUserData())); + return BodyPtr(static_cast(body->GetUserData())); } - void PhysicJoint::SetB2Joint(b2Joint* joint) + void Joint::SetB2Joint(b2Joint* joint) { joint_ = joint; if (joint_) { - type_ = PhysicJoint::Type(joint_->GetType()); + type_ = Joint::Type(joint_->GetType()); } } @@ -98,19 +98,19 @@ namespace kiwano // DistanceJoint::DistanceJoint() - : PhysicJoint() + : Joint() , raw_joint_(nullptr) { } - DistanceJoint::DistanceJoint(PhysicWorld* world, b2DistanceJointDef* def) - : PhysicJoint(world, def) + DistanceJoint::DistanceJoint(World* world, b2DistanceJointDef* def) + : Joint(world, def) , raw_joint_(nullptr) { } - DistanceJoint::DistanceJoint(PhysicWorld* world, DistanceJoint::Param const& param) - : PhysicJoint() + DistanceJoint::DistanceJoint(World* world, DistanceJoint::Param const& param) + : Joint() , raw_joint_(nullptr) { KGE_ASSERT(param.body_a && param.body_b); @@ -141,19 +141,19 @@ namespace kiwano // FrictionJoint::FrictionJoint() - : PhysicJoint() + : Joint() , raw_joint_(nullptr) { } - FrictionJoint::FrictionJoint(PhysicWorld* world, b2FrictionJointDef* def) - : PhysicJoint(world, def) + FrictionJoint::FrictionJoint(World* world, b2FrictionJointDef* def) + : Joint(world, def) , raw_joint_(nullptr) { } - FrictionJoint::FrictionJoint(PhysicWorld* world, FrictionJoint::Param const& param) - : PhysicJoint() + FrictionJoint::FrictionJoint(World* world, FrictionJoint::Param const& param) + : Joint() , raw_joint_(nullptr) { KGE_ASSERT(param.body_a && param.body_b); @@ -196,19 +196,19 @@ namespace kiwano // GearJoint::GearJoint() - : PhysicJoint() + : Joint() , raw_joint_(nullptr) { } - GearJoint::GearJoint(PhysicWorld* world, b2GearJointDef* def) - : PhysicJoint(world, def) + GearJoint::GearJoint(World* world, b2GearJointDef* def) + : Joint(world, def) , raw_joint_(nullptr) { } - GearJoint::GearJoint(PhysicWorld* world, GearJoint::Param const& param) - : PhysicJoint() + GearJoint::GearJoint(World* world, GearJoint::Param const& param) + : Joint() , raw_joint_(nullptr) { KGE_ASSERT(param.joint_a && param.joint_b); @@ -239,19 +239,19 @@ namespace kiwano // MotorJoint::MotorJoint() - : PhysicJoint() + : Joint() , raw_joint_(nullptr) { } - MotorJoint::MotorJoint(PhysicWorld* world, b2MotorJointDef* def) - : PhysicJoint(world, def) + MotorJoint::MotorJoint(World* world, b2MotorJointDef* def) + : Joint(world, def) , raw_joint_(nullptr) { } - MotorJoint::MotorJoint(PhysicWorld* world, MotorJoint::Param const& param) - : PhysicJoint() + MotorJoint::MotorJoint(World* world, MotorJoint::Param const& param) + : Joint() , raw_joint_(nullptr) { KGE_ASSERT(param.body_a && param.body_b); @@ -294,19 +294,19 @@ namespace kiwano // PrismaticJoint::PrismaticJoint() - : PhysicJoint() + : Joint() , raw_joint_(nullptr) { } - PrismaticJoint::PrismaticJoint(PhysicWorld* world, b2PrismaticJointDef* def) - : PhysicJoint(world, def) + PrismaticJoint::PrismaticJoint(World* world, b2PrismaticJointDef* def) + : Joint(world, def) , raw_joint_(nullptr) { } - PrismaticJoint::PrismaticJoint(PhysicWorld* world, PrismaticJoint::Param const& param) - : PhysicJoint() + PrismaticJoint::PrismaticJoint(World* world, PrismaticJoint::Param const& param) + : Joint() , raw_joint_(nullptr) { KGE_ASSERT(param.body_a && param.body_b); @@ -359,19 +359,19 @@ namespace kiwano // PulleyJoint::PulleyJoint() - : PhysicJoint() + : Joint() , raw_joint_(nullptr) { } - PulleyJoint::PulleyJoint(PhysicWorld* world, b2PulleyJointDef* def) - : PhysicJoint(world, def) + PulleyJoint::PulleyJoint(World* world, b2PulleyJointDef* def) + : Joint(world, def) , raw_joint_(nullptr) { } - PulleyJoint::PulleyJoint(PhysicWorld* world, PulleyJoint::Param const& param) - : PhysicJoint() + PulleyJoint::PulleyJoint(World* world, PulleyJoint::Param const& param) + : Joint() , raw_joint_(nullptr) { KGE_ASSERT(param.body_a && param.body_b); @@ -431,19 +431,19 @@ namespace kiwano // RevoluteJoint::RevoluteJoint() - : PhysicJoint() + : Joint() , raw_joint_(nullptr) { } - RevoluteJoint::RevoluteJoint(PhysicWorld* world, b2RevoluteJointDef* def) - : PhysicJoint(world, def) + RevoluteJoint::RevoluteJoint(World* world, b2RevoluteJointDef* def) + : Joint(world, def) , raw_joint_(nullptr) { } - RevoluteJoint::RevoluteJoint(PhysicWorld* world, RevoluteJoint::Param const& param) - : PhysicJoint() + RevoluteJoint::RevoluteJoint(World* world, RevoluteJoint::Param const& param) + : Joint() , raw_joint_(nullptr) { KGE_ASSERT(param.body_a && param.body_b); @@ -508,19 +508,19 @@ namespace kiwano // RopeJoint::RopeJoint() - : PhysicJoint() + : Joint() , raw_joint_(nullptr) { } - RopeJoint::RopeJoint(PhysicWorld* world, b2RopeJointDef* def) - : PhysicJoint(world, def) + RopeJoint::RopeJoint(World* world, b2RopeJointDef* def) + : Joint(world, def) , raw_joint_(nullptr) { } - RopeJoint::RopeJoint(PhysicWorld* world, RopeJoint::Param const& param) - : PhysicJoint() + RopeJoint::RopeJoint(World* world, RopeJoint::Param const& param) + : Joint() , raw_joint_(nullptr) { KGE_ASSERT(param.body_a && param.body_b); @@ -553,19 +553,19 @@ namespace kiwano // WeldJoint::WeldJoint() - : PhysicJoint() + : Joint() , raw_joint_(nullptr) { } - WeldJoint::WeldJoint(PhysicWorld* world, b2WeldJointDef* def) - : PhysicJoint(world, def) + WeldJoint::WeldJoint(World* world, b2WeldJointDef* def) + : Joint(world, def) , raw_joint_(nullptr) { } - WeldJoint::WeldJoint(PhysicWorld* world, WeldJoint::Param const& param) - : PhysicJoint() + WeldJoint::WeldJoint(World* world, WeldJoint::Param const& param) + : Joint() , raw_joint_(nullptr) { KGE_ASSERT(param.body_a && param.body_b); @@ -584,19 +584,19 @@ namespace kiwano // WheelJoint::WheelJoint() - : PhysicJoint() + : Joint() , raw_joint_(nullptr) { } - WheelJoint::WheelJoint(PhysicWorld* world, b2WheelJointDef* def) - : PhysicJoint(world, def) + WheelJoint::WheelJoint(World* world, b2WheelJointDef* def) + : Joint(world, def) , raw_joint_(nullptr) { } - WheelJoint::WheelJoint(PhysicWorld* world, WheelJoint::Param const& param) - : PhysicJoint() + WheelJoint::WheelJoint(World* world, WheelJoint::Param const& param) + : Joint() , raw_joint_(nullptr) { KGE_ASSERT(param.body_a && param.body_b); @@ -642,19 +642,19 @@ namespace kiwano // MouseJoint::MouseJoint() - : PhysicJoint() + : Joint() , raw_joint_(nullptr) { } - MouseJoint::MouseJoint(PhysicWorld* world, b2MouseJointDef* def) - : PhysicJoint(world, def) + MouseJoint::MouseJoint(World* world, b2MouseJointDef* def) + : Joint(world, def) , raw_joint_(nullptr) { } - MouseJoint::MouseJoint(PhysicWorld* world, MouseJoint::Param const& param) - : PhysicJoint() + MouseJoint::MouseJoint(World* world, MouseJoint::Param const& param) + : Joint() , raw_joint_(nullptr) { KGE_ASSERT(param.body_a && param.body_b); diff --git a/src/kiwano-physics/Joint.h b/src/kiwano-physics/Joint.h index e2a8b0df..46548a4f 100644 --- a/src/kiwano-physics/Joint.h +++ b/src/kiwano-physics/Joint.h @@ -26,7 +26,7 @@ namespace kiwano { namespace physics { - KGE_DECLARE_SMART_PTR(PhysicJoint); + KGE_DECLARE_SMART_PTR(Joint); KGE_DECLARE_SMART_PTR(DistanceJoint); KGE_DECLARE_SMART_PTR(FrictionJoint); KGE_DECLARE_SMART_PTR(GearJoint); @@ -40,7 +40,7 @@ namespace kiwano KGE_DECLARE_SMART_PTR(WheelJoint); // 关节 - class KGE_API PhysicJoint + class KGE_API Joint : public virtual RefCounter { public: @@ -62,43 +62,43 @@ namespace kiwano struct ParamBase { - PhysicBody* body_a; - PhysicBody* body_b; + Body* body_a; + Body* body_b; - ParamBase(PhysicBody* body_a, PhysicBody* body_b) : body_a(body_a), body_b(body_b) {} - ParamBase(PhysicBodyPtr body_a, PhysicBodyPtr body_b) : body_a(body_a.get()), body_b(body_b.get()) {} + ParamBase(Body* body_a, Body* body_b) : body_a(body_a), body_b(body_b) {} + ParamBase(BodyPtr body_a, BodyPtr body_b) : body_a(body_a.get()), body_b(body_b.get()) {} }; - PhysicJoint(); - PhysicJoint(b2Joint* joint); - PhysicJoint(PhysicWorld* world, b2JointDef* joint_def); - virtual ~PhysicJoint(); + Joint(); + Joint(b2Joint* joint); + Joint(World* world, b2JointDef* joint_def); + virtual ~Joint(); - void Init(PhysicWorld* world, b2JointDef* joint_def); + void Init(World* world, b2JointDef* joint_def); - PhysicBodyPtr GetBodyA() const; - PhysicBodyPtr GetBodyB() const; + BodyPtr GetBodyA() const; + BodyPtr GetBodyB() const; b2Joint* GetB2Joint() { return joint_; } const b2Joint* GetB2Joint() const { return joint_; } void SetB2Joint(b2Joint* joint); - PhysicWorld* GetWorld() { return world_; } - const PhysicWorld* GetWorld() const { return world_; } + World* GetWorld() { return world_; } + const World* GetWorld() const { return world_; } protected: b2Joint* joint_; - PhysicWorld* world_; + World* world_; Type type_; }; // 固定距离关节 class KGE_API DistanceJoint - : public PhysicJoint + : public Joint { public: - struct Param : public PhysicJoint::ParamBase + struct Param : public Joint::ParamBase { Point anchor_a; Point anchor_b; @@ -106,8 +106,8 @@ namespace kiwano float damping_ratio; Param( - PhysicBody* body_a, - PhysicBody* body_b, + Body* body_a, + Body* body_b, Point const& anchor_a, Point const& anchor_b, float frequency_hz = 0.f, @@ -121,8 +121,8 @@ namespace kiwano {} Param( - PhysicBodyPtr body_a, - PhysicBodyPtr body_b, + BodyPtr body_a, + BodyPtr body_b, Point const& anchor_a, Point const& anchor_b, float frequency_hz = 0.f, @@ -133,8 +133,8 @@ namespace kiwano }; DistanceJoint(); - DistanceJoint(PhysicWorld* world, b2DistanceJointDef* def); - DistanceJoint(PhysicWorld* world, Param const& param); + DistanceJoint(World* world, b2DistanceJointDef* def); + DistanceJoint(World* world, Param const& param); void SetLength(float length); float GetLength() const; @@ -154,18 +154,18 @@ namespace kiwano // 摩擦关节 class KGE_API FrictionJoint - : public PhysicJoint + : public Joint { public: - struct Param : public PhysicJoint::ParamBase + struct Param : public Joint::ParamBase { Point anchor; float max_force; float max_torque; Param( - PhysicBody* body_a, - PhysicBody* body_b, + Body* body_a, + Body* body_b, Point const& anchor, float max_force = 0.f, float max_torque = 0.f @@ -177,8 +177,8 @@ namespace kiwano {} Param( - PhysicBodyPtr body_a, - PhysicBodyPtr body_b, + BodyPtr body_a, + BodyPtr body_b, Point const& anchor, float max_force = 0.f, float max_torque = 0.f @@ -188,8 +188,8 @@ namespace kiwano }; FrictionJoint(); - FrictionJoint(PhysicWorld* world, b2FrictionJointDef* def); - FrictionJoint(PhysicWorld* world, Param const& param); + FrictionJoint(World* world, b2FrictionJointDef* def); + FrictionJoint(World* world, Param const& param); // 设定最大摩擦力 void SetMaxForce(float force); @@ -206,18 +206,18 @@ namespace kiwano // 齿轮关节 class KGE_API GearJoint - : public PhysicJoint + : public Joint { public: - struct Param : public PhysicJoint::ParamBase + struct Param : public Joint::ParamBase { - PhysicJointPtr joint_a; - PhysicJointPtr joint_b; + JointPtr joint_a; + JointPtr joint_b; float ratio; Param( - PhysicJoint* joint_a, - PhysicJoint* joint_b, + Joint* joint_a, + Joint* joint_b, float ratio = 1.f ) : ParamBase(nullptr, nullptr) @@ -227,8 +227,8 @@ namespace kiwano {} Param( - PhysicJointPtr joint_a, - PhysicJointPtr joint_b, + JointPtr joint_a, + JointPtr joint_b, float ratio = 1.f ) : Param(joint_a.get(), joint_b.get(), ratio) @@ -236,8 +236,8 @@ namespace kiwano }; GearJoint(); - GearJoint(PhysicWorld* world, b2GearJointDef* def); - GearJoint(PhysicWorld* world, Param const& param); + GearJoint(World* world, b2GearJointDef* def); + GearJoint(World* world, Param const& param); // 设定齿轮传动比 void SetRatio(float ratio); @@ -250,18 +250,18 @@ namespace kiwano // 马达关节 class KGE_API MotorJoint - : public PhysicJoint + : public Joint { public: - struct Param : public PhysicJoint::ParamBase + struct Param : public Joint::ParamBase { float max_force; float max_torque; float correction_factor; Param( - PhysicBody* body_a, - PhysicBody* body_b, + Body* body_a, + Body* body_b, float max_force = 1.f, float max_torque = 100.f, float correction_factor = 0.3f @@ -273,8 +273,8 @@ namespace kiwano {} Param( - PhysicBodyPtr body_a, - PhysicBodyPtr body_b, + BodyPtr body_a, + BodyPtr body_b, float max_force = 0.f, float max_torque = 0.f, float correction_factor = 0.3f @@ -284,8 +284,8 @@ namespace kiwano }; MotorJoint(); - MotorJoint(PhysicWorld* world, b2MotorJointDef* def); - MotorJoint(PhysicWorld* world, Param const& param); + MotorJoint(World* world, b2MotorJointDef* def); + MotorJoint(World* world, Param const& param); // 设定最大摩擦力 void SetMaxForce(float force); @@ -302,10 +302,10 @@ namespace kiwano // 平移关节 class KGE_API PrismaticJoint - : public PhysicJoint + : public Joint { public: - struct Param : public PhysicJoint::ParamBase + struct Param : public Joint::ParamBase { Point anchor; Vec2 axis; @@ -317,8 +317,8 @@ namespace kiwano float motor_speed; Param( - PhysicBody* body_a, - PhysicBody* body_b, + Body* body_a, + Body* body_b, Point const& anchor, Vec2 const& axis, bool enable_limit = false, @@ -340,8 +340,8 @@ namespace kiwano {} Param( - PhysicBodyPtr body_a, - PhysicBodyPtr body_b, + BodyPtr body_a, + BodyPtr body_b, Point const& anchor, Vec2 const& axis, bool enable_limit = false, @@ -356,8 +356,8 @@ namespace kiwano }; PrismaticJoint(); - PrismaticJoint(PhysicWorld* world, b2PrismaticJointDef* def); - PrismaticJoint(PhysicWorld* world, Param const& param); + PrismaticJoint(World* world, b2PrismaticJointDef* def); + PrismaticJoint(World* world, Param const& param); float GetReferenceAngle() const { KGE_ASSERT(raw_joint_); return math::Radian2Degree(raw_joint_->GetReferenceAngle()); } float GetJointTranslation() const; @@ -388,10 +388,10 @@ namespace kiwano // 滑轮关节 class KGE_API PulleyJoint - : public PhysicJoint + : public Joint { public: - struct Param : public PhysicJoint::ParamBase + struct Param : public Joint::ParamBase { Point anchor_a; Point anchor_b; @@ -400,8 +400,8 @@ namespace kiwano float ratio; Param( - PhysicBody* body_a, - PhysicBody* body_b, + Body* body_a, + Body* body_b, Point const& anchor_a, Point const& anchor_b, Point const& ground_anchor_a, @@ -417,8 +417,8 @@ namespace kiwano {} Param( - PhysicBodyPtr body_a, - PhysicBodyPtr body_b, + BodyPtr body_a, + BodyPtr body_b, Point const& anchor_a, Point const& anchor_b, Point const& ground_anchor_a, @@ -430,8 +430,8 @@ namespace kiwano }; PulleyJoint(); - PulleyJoint(PhysicWorld* world, b2PulleyJointDef* def); - PulleyJoint(PhysicWorld* world, Param const& param); + PulleyJoint(World* world, b2PulleyJointDef* def); + PulleyJoint(World* world, Param const& param); Point GetGroundAnchorA() const; Point GetGroundAnchorB() const; @@ -451,10 +451,10 @@ namespace kiwano // 旋转关节 class KGE_API RevoluteJoint - : public PhysicJoint + : public Joint { public: - struct Param : public PhysicJoint::ParamBase + struct Param : public Joint::ParamBase { Point anchor; bool enable_limit; @@ -465,8 +465,8 @@ namespace kiwano float motor_speed; Param( - PhysicBody* body_a, - PhysicBody* body_b, + Body* body_a, + Body* body_b, Point const& anchor, bool enable_limit = false, float lower_angle = 0.0f, @@ -486,8 +486,8 @@ namespace kiwano {} Param( - PhysicBodyPtr body_a, - PhysicBodyPtr body_b, + BodyPtr body_a, + BodyPtr body_b, Point const& anchor, bool enable_limit = false, float lower_angle = 0.0f, @@ -501,8 +501,8 @@ namespace kiwano }; RevoluteJoint(); - RevoluteJoint(PhysicWorld* world, b2RevoluteJointDef* def); - RevoluteJoint(PhysicWorld* world, Param const& param); + RevoluteJoint(World* world, b2RevoluteJointDef* def); + RevoluteJoint(World* world, Param const& param); float GetReferenceAngle() const { KGE_ASSERT(raw_joint_); return math::Radian2Degree(raw_joint_->GetReferenceAngle()); } float GetJointAngle() const; @@ -533,18 +533,18 @@ namespace kiwano // 绳关节 class KGE_API RopeJoint - : public PhysicJoint + : public Joint { public: - struct Param : public PhysicJoint::ParamBase + struct Param : public Joint::ParamBase { Point local_anchor_a; Point local_anchor_b; float max_length; Param( - PhysicBody* body_a, - PhysicBody* body_b, + Body* body_a, + Body* body_b, Point const& local_anchor_a, Point const& local_anchor_b, float max_length = 0.f @@ -556,8 +556,8 @@ namespace kiwano {} Param( - PhysicBodyPtr body_a, - PhysicBodyPtr body_b, + BodyPtr body_a, + BodyPtr body_b, Point const& local_anchor_a, Point const& local_anchor_b, float max_length = 0.f @@ -567,8 +567,8 @@ namespace kiwano }; RopeJoint(); - RopeJoint(PhysicWorld* world, b2RopeJointDef* def); - RopeJoint(PhysicWorld* world, Param const& param); + RopeJoint(World* world, b2RopeJointDef* def); + RopeJoint(World* world, Param const& param); void SetMaxLength(float length); float GetMaxLength() const; @@ -580,18 +580,18 @@ namespace kiwano // 焊接关节 class KGE_API WeldJoint - : public PhysicJoint + : public Joint { public: - struct Param : public PhysicJoint::ParamBase + struct Param : public Joint::ParamBase { Point anchor; float frequency_hz; float damping_ratio; Param( - PhysicBody* body_a, - PhysicBody* body_b, + Body* body_a, + Body* body_b, Point const& anchor, float frequency_hz = 0.f, float damping_ratio = 0.f @@ -603,8 +603,8 @@ namespace kiwano {} Param( - PhysicBodyPtr body_a, - PhysicBodyPtr body_b, + BodyPtr body_a, + BodyPtr body_b, Point const& anchor, float frequency_hz = 0.f, float damping_ratio = 0.f @@ -614,8 +614,8 @@ namespace kiwano }; WeldJoint(); - WeldJoint(PhysicWorld* world, b2WeldJointDef* def); - WeldJoint(PhysicWorld* world, Param const& param); + WeldJoint(World* world, b2WeldJointDef* def); + WeldJoint(World* world, Param const& param); // 设置弹簧阻尼器频率 [赫兹] void SetFrequency(float hz) { KGE_ASSERT(raw_joint_); raw_joint_->SetFrequency(hz); } @@ -632,10 +632,10 @@ namespace kiwano // 轮关节 class KGE_API WheelJoint - : public PhysicJoint + : public Joint { public: - struct Param : public PhysicJoint::ParamBase + struct Param : public Joint::ParamBase { Point anchor; Vec2 axis; @@ -646,8 +646,8 @@ namespace kiwano float damping_ratio; Param( - PhysicBody* body_a, - PhysicBody* body_b, + Body* body_a, + Body* body_b, Point const& anchor, Vec2 const& axis, float frequency_hz = 2.0f, @@ -667,8 +667,8 @@ namespace kiwano {} Param( - PhysicBodyPtr body_a, - PhysicBodyPtr body_b, + BodyPtr body_a, + BodyPtr body_b, Point const& anchor, Vec2 const& axis, float frequency_hz = 2.0f, @@ -682,8 +682,8 @@ namespace kiwano }; WheelJoint(); - WheelJoint(PhysicWorld* world, b2WheelJointDef* def); - WheelJoint(PhysicWorld* world, Param const& param); + WheelJoint(World* world, b2WheelJointDef* def); + WheelJoint(World* world, Param const& param); float GetJointTranslation() const; float GetJointLinearSpeed() const; @@ -715,10 +715,10 @@ namespace kiwano // 鼠标关节 // 用于使身体的某个点追踪世界上的指定点,例如让物体追踪鼠标位置 class KGE_API MouseJoint - : public PhysicJoint + : public Joint { public: - struct Param : public PhysicJoint::ParamBase + struct Param : public Joint::ParamBase { Point target; float max_force; @@ -726,8 +726,8 @@ namespace kiwano float damping_ratio; Param( - PhysicBody* body_a, - PhysicBody* body_b, + Body* body_a, + Body* body_b, Point const& target, float max_force, float frequency_hz = 5.0f, @@ -741,8 +741,8 @@ namespace kiwano {} Param( - PhysicBodyPtr body_a, - PhysicBodyPtr body_b, + BodyPtr body_a, + BodyPtr body_b, Point const& target, float max_force, float frequency_hz = 5.0f, @@ -753,8 +753,8 @@ namespace kiwano }; MouseJoint(); - MouseJoint(PhysicWorld* world, b2MouseJointDef* def); - MouseJoint(PhysicWorld* world, Param const& param); + MouseJoint(World* world, b2MouseJointDef* def); + MouseJoint(World* world, Param const& param); // 设定最大摩擦力 [N] void SetMaxForce(float force); diff --git a/src/kiwano-physics/Shape.cpp b/src/kiwano-physics/Shape.cpp index e380fa3b..47d6dc0d 100644 --- a/src/kiwano-physics/Shape.cpp +++ b/src/kiwano-physics/Shape.cpp @@ -25,55 +25,55 @@ namespace kiwano { namespace physics { - PhysicShape::PhysicShape() + Shape::Shape() : shape_(nullptr) { } - PhysicShape::PhysicShape(b2Shape* shape) + Shape::Shape(b2Shape* shape) : shape_(shape) { } - b2Shape* PhysicShape::GetB2Shape() + b2Shape* Shape::GetB2Shape() { return shape_; } - const b2Shape* PhysicShape::GetB2Shape() const + const b2Shape* Shape::GetB2Shape() const { return shape_; } - void PhysicShape::SetB2Shape(b2Shape* shape) + void Shape::SetB2Shape(b2Shape* shape) { shape_ = shape; } // - // PhysicCircleShape + // CircleShape // - PhysicCircleShape::PhysicCircleShape() - : PhysicShape(&circle_) + CircleShape::CircleShape() + : Shape(&circle_) , circle_() , radius_(0.f) { } - PhysicCircleShape::PhysicCircleShape(float radius, Point const& offset) - : PhysicCircleShape() + CircleShape::CircleShape(float radius, Point const& offset) + : CircleShape() { Set(radius, offset); } - void PhysicCircleShape::Set(float radius, Point const& offset) + void CircleShape::Set(float radius, Point const& offset) { radius_ = radius; offset_ = offset; } - void PhysicCircleShape::FitWorld(PhysicWorld* world) + void CircleShape::FitWorld(World* world) { KGE_ASSERT(world); circle_.m_radius = world->Stage2World(radius_); @@ -81,30 +81,30 @@ namespace kiwano } // - // PhysicBoxShape + // BoxShape // - PhysicBoxShape::PhysicBoxShape() - : PhysicShape(&polygon_) + BoxShape::BoxShape() + : Shape(&polygon_) , polygon_() , rotation_(0.f) { } - PhysicBoxShape::PhysicBoxShape(Vec2 const& size, Point const& offset, float rotation) - : PhysicBoxShape() + BoxShape::BoxShape(Vec2 const& size, Point const& offset, float rotation) + : BoxShape() { Set(size, offset, rotation); } - void PhysicBoxShape::Set(Vec2 const& size, Point const& offset, float rotation) + void BoxShape::Set(Vec2 const& size, Point const& offset, float rotation) { box_size_ = size; offset_ = offset; rotation_ = rotation; } - void PhysicBoxShape::FitWorld(PhysicWorld* world) + void BoxShape::FitWorld(World* world) { KGE_ASSERT(world); @@ -114,27 +114,27 @@ namespace kiwano } // - // PhysicPolygonShape + // PolygonShape // - PhysicPolygonShape::PhysicPolygonShape() - : PhysicShape(&polygon_) + PolygonShape::PolygonShape() + : Shape(&polygon_) , polygon_() { } - PhysicPolygonShape::PhysicPolygonShape(Vector const& vertexs) - : PhysicPolygonShape() + PolygonShape::PolygonShape(Vector const& vertexs) + : PolygonShape() { Set(vertexs); } - void PhysicPolygonShape::Set(Vector const& vertexs) + void PolygonShape::Set(Vector const& vertexs) { vertexs_ = vertexs; } - void PhysicPolygonShape::FitWorld(PhysicWorld* world) + void PolygonShape::FitWorld(World* world) { KGE_ASSERT(world); @@ -149,28 +149,28 @@ namespace kiwano } // - // PhysicEdgeShape + // EdgeShape // - PhysicEdgeShape::PhysicEdgeShape() - : PhysicShape(&edge_) + EdgeShape::EdgeShape() + : Shape(&edge_) , edge_() { } - PhysicEdgeShape::PhysicEdgeShape(Point const& p1, Point const& p2) - : PhysicEdgeShape() + EdgeShape::EdgeShape(Point const& p1, Point const& p2) + : EdgeShape() { Set(p1, p2); } - void PhysicEdgeShape::Set(Point const& p1, Point const& p2) + void EdgeShape::Set(Point const& p1, Point const& p2) { p_[0] = p1; p_[1] = p2; } - void PhysicEdgeShape::FitWorld(PhysicWorld* world) + void EdgeShape::FitWorld(World* world) { KGE_ASSERT(world); @@ -180,29 +180,29 @@ namespace kiwano } // - // PhysicChainShape + // ChainShape // - PhysicChainShape::PhysicChainShape() - : PhysicShape(&chain_) + ChainShape::ChainShape() + : Shape(&chain_) , chain_() , loop_(false) { } - PhysicChainShape::PhysicChainShape(Vector const& vertexs, bool loop) - : PhysicChainShape() + ChainShape::ChainShape(Vector const& vertexs, bool loop) + : ChainShape() { Set(vertexs, loop); } - void PhysicChainShape::Set(Vector const& vertexs, bool loop) + void ChainShape::Set(Vector const& vertexs, bool loop) { vertexs_ = vertexs; loop_ = loop; } - void PhysicChainShape::FitWorld(PhysicWorld* world) + void ChainShape::FitWorld(World* world) { KGE_ASSERT(world); diff --git a/src/kiwano-physics/Shape.h b/src/kiwano-physics/Shape.h index 1d51a5df..0d891f62 100644 --- a/src/kiwano-physics/Shape.h +++ b/src/kiwano-physics/Shape.h @@ -25,37 +25,37 @@ namespace kiwano { namespace physics { - class PhysicWorld; + class World; // 形状基类 - class KGE_API PhysicShape + class KGE_API Shape { public: - PhysicShape(); - PhysicShape(b2Shape* shape); + Shape(); + Shape(b2Shape* shape); b2Shape* GetB2Shape(); const b2Shape* GetB2Shape() const; void SetB2Shape(b2Shape* shape); - virtual void FitWorld(PhysicWorld* world) {} + virtual void FitWorld(World* world) {} protected: b2Shape* shape_; }; // 圆形形状 - class KGE_API PhysicCircleShape - : public PhysicShape + class KGE_API CircleShape + : public Shape { public: - PhysicCircleShape(); + CircleShape(); - PhysicCircleShape(float radius, Point const& offset = Point()); + CircleShape(float radius, Point const& offset = Point()); void Set(float radius, Point const& offset = Point()); - void FitWorld(PhysicWorld* world) override; + void FitWorld(World* world) override; protected: float radius_; @@ -64,17 +64,17 @@ namespace kiwano }; // 盒子形状 - class KGE_API PhysicBoxShape - : public PhysicShape + class KGE_API BoxShape + : public Shape { public: - PhysicBoxShape(); + BoxShape(); - PhysicBoxShape(Vec2 const& size, Point const& offset = Point(), float rotation = 0.f); + BoxShape(Vec2 const& size, Point const& offset = Point(), float rotation = 0.f); void Set(Vec2 const& size, Point const& offset = Point(), float rotation = 0.f); - void FitWorld(PhysicWorld* world) override; + void FitWorld(World* world) override; protected: float rotation_; @@ -84,17 +84,17 @@ namespace kiwano }; // 多边形形状 - class KGE_API PhysicPolygonShape - : public PhysicShape + class KGE_API PolygonShape + : public Shape { public: - PhysicPolygonShape(); + PolygonShape(); - PhysicPolygonShape(Vector const& vertexs); + PolygonShape(Vector const& vertexs); void Set(Vector const& vertexs); - void FitWorld(PhysicWorld* world) override; + void FitWorld(World* world) override; protected: Vector vertexs_; @@ -102,17 +102,17 @@ namespace kiwano }; // 线段形状, 用于表示一条边 - class KGE_API PhysicEdgeShape - : public PhysicShape + class KGE_API EdgeShape + : public Shape { public: - PhysicEdgeShape(); + EdgeShape(); - PhysicEdgeShape(Point const& p1, Point const& p2); + EdgeShape(Point const& p1, Point const& p2); void Set(Point const& p1, Point const& p2); - void FitWorld(PhysicWorld* world) override; + void FitWorld(World* world) override; protected: Point p_[2]; @@ -120,17 +120,17 @@ namespace kiwano }; // 链式形状 - class KGE_API PhysicChainShape - : public PhysicShape + class KGE_API ChainShape + : public Shape { public: - PhysicChainShape(); + ChainShape(); - PhysicChainShape(Vector const& vertexs, bool loop = false); + ChainShape(Vector const& vertexs, bool loop = false); void Set(Vector const& vertexs, bool loop = false); - void FitWorld(PhysicWorld* world) override; + void FitWorld(World* world) override; protected: bool loop_; diff --git a/src/kiwano-physics/World.cpp b/src/kiwano-physics/World.cpp index 01ea268d..9a808a16 100644 --- a/src/kiwano-physics/World.cpp +++ b/src/kiwano-physics/World.cpp @@ -19,6 +19,7 @@ // THE SOFTWARE. #include "World.h" +#include namespace kiwano { @@ -29,12 +30,12 @@ namespace kiwano const float DefaultGlobalScale = 100.f; // 100 pixels per meters } - class PhysicWorld::DestructionListener : public b2DestructionListener + class World::DestructionListener : public b2DestructionListener { - PhysicWorld* world_; + World* world_; public: - DestructionListener(PhysicWorld* world) + DestructionListener(World* world) : world_(world) { } @@ -53,24 +54,34 @@ namespace kiwano } }; - class PhysicWorld::ContactListener + class World::ContactListener : public b2ContactListener { - PhysicWorld* world_; + World* world_; public: - ContactListener(PhysicWorld* world) + ContactListener(World* world) : world_(world) { } - void BeginContact(b2Contact* contact) override { world_->OnContactBegin(contact); } - void EndContact(b2Contact* contact) override { world_->OnContactEnd(contact); } + void BeginContact(b2Contact* contact) override + { + ContactBeginEvent evt(contact); + world_->Dispatch(&evt); + } + + void EndContact(b2Contact* contact) override + { + ContactEndEvent evt(contact); + world_->Dispatch(&evt); + } + void PreSolve(b2Contact* contact, const b2Manifold* oldManifold) override { KGE_NOT_USED(contact); KGE_NOT_USED(oldManifold); } void PostSolve(b2Contact* contact, const b2ContactImpulse* impulse) override { KGE_NOT_USED(contact); KGE_NOT_USED(impulse); } }; - PhysicWorld::PhysicWorld() + World::World() : world_(b2Vec2(0, 10.0f)) , vel_iter_(6) , pos_iter_(2) @@ -86,7 +97,7 @@ namespace kiwano world_.SetContactListener(contact_listener_); } - PhysicWorld::~PhysicWorld() + World::~World() { world_.SetDestructionListener(nullptr); if (destruction_listener_) @@ -102,15 +113,13 @@ namespace kiwano contact_listener_ = nullptr; } - RemoveAllContactListeners(); - // Make sure b2World was destroyed after b2Body RemoveAllChildren(); RemoveAllBodies(); RemoveAllJoints(); } - void PhysicWorld::RemoveBody(PhysicBody* body) + void World::RemoveBody(Body* body) { if (body && body->GetB2Body()) { @@ -118,7 +127,7 @@ namespace kiwano } } - void PhysicWorld::RemoveAllBodies() + void World::RemoveAllBodies() { if (world_.GetBodyCount()) { @@ -132,7 +141,7 @@ namespace kiwano } } - void PhysicWorld::AddJoint(PhysicJoint* joint) + void World::AddJoint(Joint* joint) { if (joint) { @@ -140,7 +149,7 @@ namespace kiwano } } - void PhysicWorld::RemoveJoint(PhysicJoint* joint) + void World::RemoveJoint(Joint* joint) { if (joint) { @@ -159,7 +168,7 @@ namespace kiwano } } - void PhysicWorld::RemoveAllJoints() + void World::RemoveAllJoints() { if (world_.GetJointCount()) { @@ -178,14 +187,14 @@ namespace kiwano joints_.clear(); } - void PhysicWorld::JointRemoved(b2Joint* joint) + void World::JointRemoved(b2Joint* joint) { if (!removing_joint_ && joint) { auto iter = std::find_if( joints_.begin(), joints_.end(), - [joint](PhysicJoint* j) -> bool { return j->GetB2Joint() == joint; } + [joint](Joint* j) -> bool { return j->GetB2Joint() == joint; } ); if (iter != joints_.end()) @@ -195,36 +204,36 @@ namespace kiwano } } - b2World* PhysicWorld::GetB2World() + b2World* World::GetB2World() { return &world_; } - const b2World* PhysicWorld::GetB2World() const + const b2World* World::GetB2World() const { return &world_; } - Vec2 PhysicWorld::GetGravity() const + Vec2 World::GetGravity() const { b2Vec2 g = world_.GetGravity(); return Vec2(g.x, g.y); } - void PhysicWorld::SetGravity(Vec2 gravity) + void World::SetGravity(Vec2 gravity) { world_.SetGravity(b2Vec2(gravity.x, gravity.y)); } - void PhysicWorld::Update(Duration dt) + void World::Update(Duration dt) { Stage::Update(dt); b2Body* b2body = world_.GetBodyList(); while (b2body) { - PhysicBody* body = static_cast(b2body->GetUserData()); - if (body && body->GetType() != PhysicBody::Type::Static) + Body* body = static_cast(b2body->GetUserData()); + if (body && body->GetType() != Body::Type::Static) { body->UpdateFromActor(); } @@ -237,8 +246,8 @@ namespace kiwano b2body = world_.GetBodyList(); while (b2body) { - PhysicBody* body = static_cast(b2body->GetUserData()); - if (body && body->GetType() != PhysicBody::Type::Static) + Body* body = static_cast(b2body->GetUserData()); + if (body && body->GetType() != Body::Type::Static) { body->UpdateActor(); } diff --git a/src/kiwano-physics/World.h b/src/kiwano-physics/World.h index 5cebada3..51bab4fb 100644 --- a/src/kiwano-physics/World.h +++ b/src/kiwano-physics/World.h @@ -21,24 +21,22 @@ #pragma once #include #include -#include namespace kiwano { namespace physics { // 物理世界 - class KGE_API PhysicWorld + class KGE_API World : public Stage - , public PhysicContactDispatcher { - friend class PhysicBody; - friend class PhysicJoint; + friend class Body; + friend class Joint; public: - PhysicWorld(); + World(); - virtual ~PhysicWorld(); + virtual ~World(); // 获取重力 Vec2 GetGravity() const; @@ -71,16 +69,16 @@ namespace kiwano private: // 移除物体 - void RemoveBody(PhysicBody* body); + void RemoveBody(Body* body); // 移除所有物体 void RemoveAllBodies(); // 添加关节 - void AddJoint(PhysicJoint* joint); + void AddJoint(Joint* joint); // 移除关节 - void RemoveJoint(PhysicJoint* joint); + void RemoveJoint(Joint* joint); // 移除所有关节 void RemoveAllJoints(); @@ -105,9 +103,9 @@ namespace kiwano ContactListener* contact_listener_; bool removing_joint_; - Vector joints_; + Vector joints_; }; - KGE_DECLARE_SMART_PTR(PhysicWorld); + KGE_DECLARE_SMART_PTR(World); } } diff --git a/src/kiwano-physics/kiwano-physics.h b/src/kiwano-physics/kiwano-physics.h index 58f9cf29..fcc446d2 100644 --- a/src/kiwano-physics/kiwano-physics.h +++ b/src/kiwano-physics/kiwano-physics.h @@ -23,7 +23,7 @@ #include #include #include -#include +#include #include #include #include diff --git a/src/kiwano/2d/Actor.cpp b/src/kiwano/2d/Actor.cpp index 100520c7..3570d728 100644 --- a/src/kiwano/2d/Actor.cpp +++ b/src/kiwano/2d/Actor.cpp @@ -20,7 +20,7 @@ #include #include -#include +#include #include namespace kiwano @@ -155,7 +155,7 @@ namespace kiwano return visible_in_rt_; } - void Actor::Dispatch(Event& evt) + void Actor::Dispatch(Event* evt) { if (!visible_) return; @@ -167,21 +167,25 @@ namespace kiwano child->Dispatch(evt); } - if (responsible_ && MouseEvent::Check(evt.type)) + if (responsible_) { - if (evt.type == Event::MouseMove) + if (evt->type == event::MouseMove) { - if (!evt.target && ContainsPoint(Point{ evt.mouse.x, evt.mouse.y })) + auto mouse_evt = evt->SafeCast(); + if (!mouse_evt->target && ContainsPoint(mouse_evt->pos)) { - evt.target = this; + mouse_evt->target = this; if (!hover_) { hover_ = true; - Event hover = evt; - hover.type = Event::MouseHover; - EventDispatcher::Dispatch(hover); + MouseHoverEvent hover; + hover.pos = mouse_evt->pos; + hover.left_btn_down = mouse_evt->left_btn_down; + hover.right_btn_down = mouse_evt->right_btn_down; + hover.target = this; + EventDispatcher::Dispatch(&hover); } } else if (hover_) @@ -189,27 +193,34 @@ namespace kiwano hover_ = false; pressed_ = false; - Event out = evt; + MouseOutEvent out; + out.pos = mouse_evt->pos; + out.left_btn_down = mouse_evt->left_btn_down; + out.right_btn_down = mouse_evt->right_btn_down; out.target = this; - out.type = Event::MouseOut; - EventDispatcher::Dispatch(out); + EventDispatcher::Dispatch(&out); } } - if (evt.type == Event::MouseBtnDown && hover_) + if (evt->type == event::MouseDown && hover_) { pressed_ = true; - evt.target = this; + evt->SafeCast()->target = this; } - if (evt.type == Event::MouseBtnUp && pressed_) + if (evt->type == event::MouseUp && pressed_) { pressed_ = false; - evt.target = this; - Event click = evt; - click.type = Event::Click; - EventDispatcher::Dispatch(click); + auto mouse_up_evt = evt->SafeCast(); + mouse_up_evt->target = this; + + MouseOutEvent click; + click.pos = mouse_up_evt->pos; + click.left_btn_down = mouse_up_evt->left_btn_down; + click.right_btn_down = mouse_up_evt->right_btn_down; + click.target = this; + EventDispatcher::Dispatch(&click); } } diff --git a/src/kiwano/2d/Actor.h b/src/kiwano/2d/Actor.h index 6d805471..8b0e97fd 100644 --- a/src/kiwano/2d/Actor.h +++ b/src/kiwano/2d/Actor.h @@ -22,8 +22,8 @@ #include #include #include -#include -#include +#include +#include namespace kiwano { @@ -49,109 +49,109 @@ namespace kiwano Actor(); // 更新角色 - virtual void OnUpdate(Duration dt) { KGE_NOT_USED(dt); } + virtual void OnUpdate(Duration dt); // 渲染角色 - virtual void OnRender(RenderTarget* rt) { KGE_NOT_USED(rt); } + virtual void OnRender(RenderTarget* rt); // 获取显示状态 - bool IsVisible() const { return visible_; } + bool IsVisible() const; // 获取响应状态 - bool IsResponsible() const { return responsible_; } + bool IsResponsible() const; // 是否启用级联透明度 - bool IsCascadeOpacityEnabled() const { return cascade_opacity_; } + bool IsCascadeOpacityEnabled() const; // 获取名称的 Hash 值 - size_t GetHashName() const { return hash_name_; } + size_t GetHashName() const; // 获取 Z 轴顺序 - int GetZOrder() const { return z_order_; } + int GetZOrder() const; // 获取坐标 - Point const& GetPosition() const { return transform_.position; } + Point const& GetPosition() const; // 获取 x 坐标 - float GetPositionX() const { return GetPosition().x; } + float GetPositionX() const; // 获取 y 坐标 - float GetPositionY() const { return GetPosition().y; } + float GetPositionY() const; // 获取缩放比例 - Point const& GetScale() const { return transform_.scale; } + Point const& GetScale() const; // 获取横向缩放比例 - float GetScaleX() const { return GetScale().x; } + float GetScaleX() const; // 获取纵向缩放比例 - float GetScaleY() const { return GetScale().y; } + float GetScaleY() const; // 获取错切角度 - Point const& GetSkew() const { return transform_.skew; } + Point const& GetSkew() const; // 获取横向错切角度 - float GetSkewX() const { return GetSkew().x; } + float GetSkewX() const; // 获取纵向错切角度 - float GetSkewY() const { return GetSkew().y; } + float GetSkewY() const; // 获取旋转角度 - float GetRotation() const { return transform_.rotation; } + float GetRotation() const; // 获取宽度 - float GetWidth() const { return GetSize().x; } + float GetWidth() const; // 获取高度 - float GetHeight() const { return GetSize().y; } + float GetHeight() const; // 获取大小 - Size const& GetSize() const { return size_; } + Size const& GetSize() const; // 获取缩放后的宽度 - float GetScaledWidth() const { return GetWidth() * GetScaleX(); } + float GetScaledWidth() const; // 获取缩放后的高度 - float GetScaledHeight() const { return GetHeight() * GetScaleY(); } + float GetScaledHeight() const; // 获取缩放后的大小 - Size GetScaledSize() const { return Size{ GetScaledWidth(), GetScaledHeight() }; } + Size GetScaledSize() const; // 获取锚点 - Point const& GetAnchor() const { return anchor_; } + Point const& GetAnchor() const; // 获取 x 方向锚点 - float GetAnchorX() const { return GetAnchor().x; } + float GetAnchorX() const; // 获取 y 方向锚点 - float GetAnchorY() const { return GetAnchor().y; } + float GetAnchorY() const; // 获取透明度 - float GetOpacity() const { return opacity_; } + float GetOpacity() const; // 获取显示透明度 - float GetDisplayedOpacity() const { return displayed_opacity_; } + float GetDisplayedOpacity() const; // 获取变换 - Transform GetTransform() const { return transform_; } + Transform GetTransform() const; // 获取父角色 - inline Actor* GetParent() const { return parent_; } + Actor* GetParent() const; // 获取所在舞台 - inline Stage* GetStage() const { return stage_; } + Stage* GetStage() const; // 获取边框 - virtual Rect GetBounds() const; + virtual Rect GetBounds() const; // 获取外切包围盒 - virtual Rect GetBoundingBox() const; + virtual Rect GetBoundingBox() const; // 获取二维变换矩阵 - Matrix3x2 const& GetTransformMatrix() const; + Matrix3x2 const& GetTransformMatrix() const; // 获取二维变换的逆矩阵 - Matrix3x2 const& GetTransformInverseMatrix() const; + Matrix3x2 const& GetTransformInverseMatrix() const; // 设置是否显示 void SetVisible( @@ -169,13 +169,10 @@ namespace kiwano ); // 设置坐标 - inline void SetPosition( + void SetPosition( float x, float y - ) - { - SetPosition(Point{ x, y }); - } + ); // 设置横坐标 void SetPositionX( @@ -193,13 +190,10 @@ namespace kiwano ); // 移动坐标 - inline void Move( + void Move( float vx, float vy - ) - { - Move(Vec2{ vx, vy }); - } + ); // 设置缩放比例 // 默认为 (1.0, 1.0) @@ -209,13 +203,10 @@ namespace kiwano // 设置缩放比例 // 默认为 (1.0, 1.0) - inline void SetScale( + void SetScale( float scalex, float scaley - ) - { - SetScale(Vec2{ scalex, scaley }); - } + ); // 设置错切角度 // 默认为 (0, 0) @@ -225,13 +216,10 @@ namespace kiwano // 设置错切角度 // 默认为 (0, 0) - inline void SetSkew( + void SetSkew( float skewx, float skewy - ) - { - SetSkew(Vec2{ skewx, skewy }); - } + ); // 设置旋转角度 // 默认为 0 @@ -247,13 +235,10 @@ namespace kiwano // 设置锚点位置 // 默认为 (0, 0), 范围 [0, 1] - inline void SetAnchor( + void SetAnchor( float anchorx, float anchory - ) - { - SetAnchor(Vec2{ anchorx, anchory }); - } + ); // 修改宽度 virtual void SetWidth( @@ -271,13 +256,10 @@ namespace kiwano ); // 修改大小 - inline void SetSize( + void SetSize( float width, float height - ) - { - SetSize(Size{ width, height }); - } + ); // 设置透明度 // 默认为 1.0, 范围 [0, 1] @@ -364,8 +346,26 @@ namespace kiwano // 判断点是否在角色内 virtual bool ContainsPoint(const Point& point) const; + // 暂停角色更新 + void PauseUpdating(); + + // 继续角色更新 + void ResumeUpdating(); + + // 角色更新是否暂停 + bool IsUpdatePausing() const; + + // 设置更新时的回调函数 + void SetCallbackOnUpdate(UpdateCallback const& cb); + + // 获取更新时的回调函数 + UpdateCallback GetCallbackOnUpdate() const; + + // 渲染角色边界 + void ShowBorder(bool show); + // 事件分发 - void Dispatch(Event& evt) override; + void Dispatch(Event* evt) override; // 设置默认锚点 static void SetDefaultAnchor( @@ -373,24 +373,6 @@ namespace kiwano float anchor_y ); - // 暂停角色更新 - inline void PauseUpdating() { update_pausing_ = true; } - - // 继续角色更新 - inline void ResumeUpdating() { update_pausing_ = false; } - - // 角色更新是否暂停 - inline bool IsUpdatePausing() const { return update_pausing_; } - - // 设置更新时的回调函数 - inline void SetCallbackOnUpdate(UpdateCallback const& cb) { cb_update_ = cb; } - - // 获取更新时的回调函数 - inline UpdateCallback GetCallbackOnUpdate() const { return cb_update_; } - - // 渲染角色边界 - inline void ShowBorder(bool show) { show_border_ = show; } - protected: virtual void Update(Duration dt); @@ -439,4 +421,219 @@ namespace kiwano mutable Matrix3x2 transform_matrix_inverse_; }; + inline void Actor::OnUpdate(Duration dt) + { + KGE_NOT_USED(dt); + } + + inline void Actor::OnRender(RenderTarget* rt) + { + KGE_NOT_USED(rt); + } + + inline bool Actor::IsVisible() const + { + return visible_; + } + + inline bool Actor::IsResponsible() const + { + return responsible_; + } + + inline bool Actor::IsCascadeOpacityEnabled() const + { + return cascade_opacity_; + } + + inline size_t Actor::GetHashName() const + { + return hash_name_; + } + + inline int Actor::GetZOrder() const + { + return z_order_; + } + + inline Point const& Actor::GetPosition() const + { + return transform_.position; + } + + inline float Actor::GetPositionX() const + { + return GetPosition().x; + } + + inline float Actor::GetPositionY() const + { + return GetPosition().y; + } + + inline Point const& Actor::GetScale() const + { + return transform_.scale; + } + + inline float Actor::GetScaleX() const + { + return GetScale().x; + } + + inline float Actor::GetScaleY() const + { + return GetScale().y; + } + + inline Point const& Actor::GetSkew() const + { + return transform_.skew; + } + + inline float Actor::GetSkewX() const + { + return GetSkew().x; + } + + inline float Actor::GetSkewY() const + { + return GetSkew().y; + } + + inline float Actor::GetRotation() const + { + return transform_.rotation; + } + + inline float Actor::GetWidth() const + { + return GetSize().x; + } + + inline float Actor::GetHeight() const + { + return GetSize().y; + } + + inline Size const& Actor::GetSize() const + { + return size_; + } + + inline float Actor::GetScaledWidth() const + { + return GetWidth() * GetScaleX(); + } + + inline float Actor::GetScaledHeight() const + { + return GetHeight() * GetScaleY(); + } + + inline Size Actor::GetScaledSize() const + { + return Size{ GetScaledWidth(), GetScaledHeight() }; + } + + inline Point const& Actor::GetAnchor() const + { + return anchor_; + } + + inline float Actor::GetAnchorX() const + { + return GetAnchor().x; + } + + inline float Actor::GetAnchorY() const + { + return GetAnchor().y; + } + + inline float Actor::GetOpacity() const + { + return opacity_; + } + + inline float Actor::GetDisplayedOpacity() const + { + return displayed_opacity_; + } + + inline Transform Actor::GetTransform() const + { + return transform_; + } + + inline Actor* Actor::GetParent() const + { + return parent_; + } + + inline Stage* Actor::GetStage() const + { + return stage_; + } + + inline void Actor::PauseUpdating() + { + update_pausing_ = true; + } + + inline void Actor::ResumeUpdating() + { + update_pausing_ = false; + } + + inline bool Actor::IsUpdatePausing() const + { + return update_pausing_; + } + + inline void Actor::SetCallbackOnUpdate(UpdateCallback const& cb) + { + cb_update_ = cb; + } + + inline Actor::UpdateCallback Actor::GetCallbackOnUpdate() const + { + return cb_update_; + } + + inline void Actor::ShowBorder(bool show) + { + show_border_ = show; + } + + inline void Actor::SetPosition(float x, float y) + { + SetPosition(Point{ x, y }); + } + + inline void Actor::Move(float vx, float vy) + { + Move(Vec2{ vx, vy }); + } + + inline void Actor::SetScale(float scalex, float scaley) + { + SetScale(Vec2{ scalex, scaley }); + } + + inline void Actor::SetAnchor(float anchorx, float anchory) + { + SetAnchor(Vec2{ anchorx, anchory }); + } + + inline void Actor::SetSize(float width, float height) + { + SetSize(Size{ width, height }); + } + + inline void Actor::SetSkew(float skewx, float skewy) + { + SetSkew(Vec2{ skewx, skewy }); + } + } diff --git a/src/kiwano/2d/Canvas.cpp b/src/kiwano/2d/Canvas.cpp index c4852768..cbb6b60e 100644 --- a/src/kiwano/2d/Canvas.cpp +++ b/src/kiwano/2d/Canvas.cpp @@ -19,7 +19,7 @@ // THE SOFTWARE. #include -#include +#include #include namespace kiwano diff --git a/src/kiwano/2d/DebugActor.cpp b/src/kiwano/2d/DebugActor.cpp index 65dc2900..5d53e1fa 100644 --- a/src/kiwano/2d/DebugActor.cpp +++ b/src/kiwano/2d/DebugActor.cpp @@ -66,8 +66,8 @@ namespace kiwano style.line_spacing = 20.f; debug_text_->SetStyle(style); - AddListener(Event::MouseHover, [=](const Event&) { SetOpacity(0.4f); }); - AddListener(Event::MouseOut, [=](const Event&) { SetOpacity(1.f); }); + AddListener(event::MouseHover, [=](Event*) { SetOpacity(0.4f); }); + AddListener(event::MouseOut, [=](Event*) { SetOpacity(1.f); }); } DebugActor::~DebugActor() @@ -87,7 +87,7 @@ namespace kiwano KGE_NOT_USED(dt); frame_time_.push_back(Time::Now()); - while (frame_time_.back() - frame_time_.front() >= time::Sec) + while (frame_time_.back() - frame_time_.front() >= Duration::Second) { frame_time_.erase(frame_time_.begin()); } diff --git a/src/kiwano/2d/Frame.h b/src/kiwano/2d/Frame.h index 881b3c05..f9b1a947 100644 --- a/src/kiwano/2d/Frame.h +++ b/src/kiwano/2d/Frame.h @@ -19,7 +19,7 @@ // THE SOFTWARE. #pragma once -#include +#include #include namespace kiwano diff --git a/src/kiwano/2d/FrameSequence.cpp b/src/kiwano/2d/FrameSequence.cpp index 0bc00b5e..c72e2d01 100644 --- a/src/kiwano/2d/FrameSequence.cpp +++ b/src/kiwano/2d/FrameSequence.cpp @@ -20,7 +20,7 @@ #include #include -#include +#include namespace kiwano { diff --git a/src/kiwano/2d/GifSprite.cpp b/src/kiwano/2d/GifSprite.cpp index 1ff49add..b8dc4e64 100644 --- a/src/kiwano/2d/GifSprite.cpp +++ b/src/kiwano/2d/GifSprite.cpp @@ -19,7 +19,7 @@ // THE SOFTWARE. #include -#include +#include #include #include diff --git a/src/kiwano/2d/GifSprite.h b/src/kiwano/2d/GifSprite.h index bc5c4cb8..10ebb933 100644 --- a/src/kiwano/2d/GifSprite.h +++ b/src/kiwano/2d/GifSprite.h @@ -20,7 +20,7 @@ #pragma once #include -#include +#include #include #include diff --git a/src/kiwano/2d/Layer.cpp b/src/kiwano/2d/Layer.cpp index 8a01bc63..270c50a7 100644 --- a/src/kiwano/2d/Layer.cpp +++ b/src/kiwano/2d/Layer.cpp @@ -29,14 +29,14 @@ namespace kiwano { auto handler = Closure(this, &Layer::HandleMessages); - AddListener(Event::MouseBtnDown, handler); - AddListener(Event::MouseBtnUp, handler); - AddListener(Event::MouseMove, handler); - AddListener(Event::MouseWheel, handler); + AddListener(event::MouseDown, handler); + AddListener(event::MouseUp, handler); + AddListener(event::MouseMove, handler); + AddListener(event::MouseWheel, handler); - AddListener(Event::KeyDown, handler); - AddListener(Event::KeyUp, handler); - AddListener(Event::Char, handler); + AddListener(event::KeyDown, handler); + AddListener(event::KeyUp, handler); + AddListener(event::KeyChar, handler); } Layer::~Layer() @@ -64,7 +64,7 @@ namespace kiwano area_.SetMaskTransform(transform); } - void Layer::Dispatch(Event& evt) + void Layer::Dispatch(Event* evt) { if (!IsVisible()) return; @@ -91,31 +91,42 @@ namespace kiwano rt->PopLayer(); } - void Layer::HandleMessages(Event const& evt) + void Layer::HandleMessages(Event* evt) { - switch (evt.type) + if (evt->type == event::MouseDown) { - case Event::MouseBtnDown: - OnMouseButtonDown(evt.mouse.button, Point{ evt.mouse.x, evt.mouse.y }); - break; - case Event::MouseBtnUp: - OnMouseButtonUp(evt.mouse.button, Point{ evt.mouse.x, evt.mouse.y }); - break; - case Event::MouseMove: - OnMouseMoved(Point{ evt.mouse.x, evt.mouse.y }); - break; - case Event::MouseWheel: - OnMouseWheel(evt.mouse.wheel); - break; - case Event::KeyDown: - OnKeyDown(evt.key.code); - break; - case Event::KeyUp: - OnKeyUp(evt.key.code); - break; - case Event::Char: - OnChar(evt.key.c); - break; + auto real_evt = evt->SafeCast(); + OnMouseButtonDown(real_evt->button, real_evt->pos); + } + else if (evt->type == event::MouseUp) + { + auto real_evt = evt->SafeCast(); + OnMouseButtonUp(real_evt->button, real_evt->pos); + } + else if (evt->type == event::MouseMove) + { + auto real_evt = evt->SafeCast(); + OnMouseMoved(real_evt->pos); + } + else if (evt->type == event::MouseWheel) + { + auto real_evt = evt->SafeCast(); + OnMouseWheel(real_evt->wheel); + } + else if (evt->type == event::KeyDown) + { + auto real_evt = evt->SafeCast(); + OnKeyDown(real_evt->code); + } + else if (evt->type == event::KeyUp) + { + auto real_evt = evt->SafeCast(); + OnKeyUp(real_evt->code); + } + else if (evt->type == event::KeyChar) + { + auto real_evt = evt->SafeCast(); + OnChar(real_evt->value); } } diff --git a/src/kiwano/2d/Layer.h b/src/kiwano/2d/Layer.h index 5f4716c0..fa06e350 100644 --- a/src/kiwano/2d/Layer.h +++ b/src/kiwano/2d/Layer.h @@ -34,8 +34,8 @@ namespace kiwano virtual ~Layer(); // 重载下列函数以获取图层事件 - virtual void OnMouseButtonDown(int btn, Point const& p) {} - virtual void OnMouseButtonUp(int btn, Point const& p) {} + virtual void OnMouseButtonDown(MouseButton::Value btn, Point const& p) {} + virtual void OnMouseButtonUp(MouseButton::Value btn, Point const& p) {} virtual void OnMouseMoved(Point const& p) {} virtual void OnMouseWheel(float wheel) {} virtual void OnKeyDown(int key) {} @@ -67,12 +67,12 @@ namespace kiwano inline LayerArea const& GetArea() const { return area_; } public: - void Dispatch(Event& evt) override; + void Dispatch(Event* evt) override; protected: void Render(RenderTarget* rt) override; - void HandleMessages(Event const& evt); + void HandleMessages(Event* evt); protected: bool swallow_; diff --git a/src/kiwano/2d/ShapeActor.cpp b/src/kiwano/2d/ShapeActor.cpp index 759e12e7..f6b9b809 100644 --- a/src/kiwano/2d/ShapeActor.cpp +++ b/src/kiwano/2d/ShapeActor.cpp @@ -19,7 +19,7 @@ // THE SOFTWARE. #include -#include +#include #include namespace kiwano diff --git a/src/kiwano/2d/Stage.cpp b/src/kiwano/2d/Stage.cpp index d3f12fbd..6dcaac31 100644 --- a/src/kiwano/2d/Stage.cpp +++ b/src/kiwano/2d/Stage.cpp @@ -19,7 +19,7 @@ // THE SOFTWARE. #include -#include +#include #include namespace kiwano diff --git a/src/kiwano/2d/Text.cpp b/src/kiwano/2d/Text.cpp index 47d60b9a..5f3fa022 100644 --- a/src/kiwano/2d/Text.cpp +++ b/src/kiwano/2d/Text.cpp @@ -19,7 +19,7 @@ // THE SOFTWARE. #include -#include +#include #include namespace kiwano diff --git a/src/kiwano/2d/Transition.cpp b/src/kiwano/2d/Transition.cpp index 5dc4b8a3..5000a306 100644 --- a/src/kiwano/2d/Transition.cpp +++ b/src/kiwano/2d/Transition.cpp @@ -21,8 +21,8 @@ #include #include #include -#include -#include +#include +#include #include namespace kiwano diff --git a/src/kiwano/2d/action/Action.h b/src/kiwano/2d/action/Action.h index 2b222214..915f29f8 100644 --- a/src/kiwano/2d/action/Action.h +++ b/src/kiwano/2d/action/Action.h @@ -36,42 +36,33 @@ namespace kiwano friend IntrusiveList; public: - enum class Status - { - NotStarted, - Delayed, - Started, - Done, - Removeable - }; - Action(); virtual ~Action(); // 继续动作 - inline void Resume() { running_ = true; } + void Resume(); // 暂停动作 - inline void Pause() { running_ = false; } + void Pause(); // 停止动作 - inline void Stop() { status_ = Status::Removeable; } + void Stop(); // 设置动作延时 - inline void SetDelay(Duration delay) { delay_ = delay; } + void SetDelay(Duration delay); // 设置循环次数 (-1 为永久循环) - inline void SetLoops(int loops) { loops_ = loops; } + void SetLoops(int loops); // 动作结束时移除目标角色 - inline void RemoveTargetWhenDone() { detach_target_ = true; } + void RemoveTargetWhenDone(); // 设置动作结束时的回调函数 - inline void SetDoneCallback(ActionCallback const& cb) { cb_done_ = cb; } + void SetDoneCallback(ActionCallback const& cb); // 设置动作循环结束时的回调函数 - inline void SetLoopDoneCallback(ActionCallback const& cb) { cb_loop_done_ = cb; } + void SetLoopDoneCallback(ActionCallback const& cb); // 获取动作的拷贝 virtual ActionPtr Clone() const = 0; @@ -79,25 +70,15 @@ namespace kiwano // 获取动作的倒转 virtual ActionPtr Reverse() const = 0; - inline void Done() { status_ = Status::Done; } + bool IsRunning() const; - inline Status GetStatus() const { return status_; } + int GetLoops() const; - inline bool IsRunning() const { return running_; } + Duration GetDelay() const; - inline bool IsDone() const { return status_ == Status::Done || status_ == Status::Removeable; } + ActionCallback GetDoneCallback() const; - inline bool IsRemoveable() const { return status_ == Status::Removeable; } - - inline int GetLoops() const { return loops_; } - - inline Duration GetDelay() const { return delay_; } - - inline Duration GetElapsed() const { return elapsed_; } - - inline ActionCallback GetDoneCallback() const { return cb_done_; } - - inline ActionCallback GetLoopDoneCallback() const { return cb_loop_done_; } + ActionCallback GetLoopDoneCallback() const; protected: virtual void Init(ActorPtr target); @@ -110,7 +91,28 @@ namespace kiwano void Restart(ActorPtr target); - protected: + enum class Status + { + NotStarted, + Delayed, + Started, + Done, + Removeable + }; + + Status GetStatus() const; + + Duration GetElapsed() const; + + int GetLoopsDone() const; + + void Done(); + + bool IsDone() const; + + bool IsRemoveable() const; + + private: Status status_; bool running_; bool detach_target_; @@ -121,4 +123,100 @@ namespace kiwano ActionCallback cb_done_; ActionCallback cb_loop_done_; }; + + + inline void Action::Resume() + { + running_ = true; + } + + inline void Action::Pause() + { + running_ = false; + } + + inline void Action::Stop() + { + Done(); + } + + inline void Action::SetDelay(Duration delay) + { + delay_ = delay; + } + + inline void Action::SetLoops(int loops) + { + loops_ = loops; + } + + inline void Action::RemoveTargetWhenDone() + { + detach_target_ = true; + } + + inline void Action::SetDoneCallback(ActionCallback const& cb) + { + cb_done_ = cb; + } + + inline void Action::SetLoopDoneCallback(ActionCallback const& cb) + { + cb_loop_done_ = cb; + } + + inline void Action::Done() + { + status_ = Status::Done; + } + + inline Action::Status Action::GetStatus() const + { + return status_; + } + + inline bool Action::IsRunning() const + { + return running_; + } + + inline bool Action::IsDone() const + { + return status_ == Status::Done || status_ == Status::Removeable; + } + + inline bool Action::IsRemoveable() const + { + return status_ == Status::Removeable; + } + + inline int Action::GetLoops() const + { + return loops_; + } + + inline Duration Action::GetDelay() const + { + return delay_; + } + + inline Duration Action::GetElapsed() const + { + return elapsed_; + } + + inline int Action::GetLoopsDone() const + { + return loops_done_; + } + + inline ActionCallback Action::GetDoneCallback() const + { + return cb_done_; + } + + inline ActionCallback Action::GetLoopDoneCallback() const + { + return cb_loop_done_; + } } diff --git a/src/kiwano/2d/action/ActionDelay.cpp b/src/kiwano/2d/action/ActionDelay.cpp index 17aea335..9daa2945 100644 --- a/src/kiwano/2d/action/ActionDelay.cpp +++ b/src/kiwano/2d/action/ActionDelay.cpp @@ -29,12 +29,12 @@ namespace kiwano ActionPtr ActionDelay::Clone() const { - return new ActionDelay(delay_); + return new ActionDelay(GetDelay()); } ActionPtr ActionDelay::Reverse() const { - return new ActionDelay(delay_); + return new ActionDelay(GetDelay()); } } diff --git a/src/kiwano/2d/action/ActionGroup.cpp b/src/kiwano/2d/action/ActionGroup.cpp index d2e53e52..a913ae20 100644 --- a/src/kiwano/2d/action/ActionGroup.cpp +++ b/src/kiwano/2d/action/ActionGroup.cpp @@ -20,7 +20,7 @@ #include #include -#include +#include namespace kiwano { diff --git a/src/kiwano/2d/action/ActionHelper.h b/src/kiwano/2d/action/ActionHelper.h index 36eef88c..e2ea18e9 100644 --- a/src/kiwano/2d/action/ActionHelper.h +++ b/src/kiwano/2d/action/ActionHelper.h @@ -30,71 +30,71 @@ namespace kiwano struct ActionHelper { // 设置循环次数 - inline ActionHelper& SetLoops(int loops) { base->SetLoops(loops); return (*this); } + inline ActionHelper& SetLoops(int loops) { core->SetLoops(loops); return (*this); } // 设置动作延迟 - inline ActionHelper& SetDelay(Duration delay) { base->SetDelay(delay); return (*this); } + inline ActionHelper& SetDelay(Duration delay) { core->SetDelay(delay); return (*this); } // 设置动作结束回调函数 - inline ActionHelper& SetDoneCallback(ActionCallback const& cb) { base->SetDoneCallback(cb); return (*this); } + inline ActionHelper& SetDoneCallback(ActionCallback const& cb) { core->SetDoneCallback(cb); return (*this); } // 设置动作循环结束时的回调函数 - inline ActionHelper& SetLoopDoneCallback(ActionCallback const& cb) { base->SetLoopDoneCallback(cb); return (*this); } + inline ActionHelper& SetLoopDoneCallback(ActionCallback const& cb) { core->SetLoopDoneCallback(cb); return (*this); } // 动作结束时移除目标角色 - inline ActionHelper& RemoveTargetWhenDone() { base->RemoveTargetWhenDone(); return (*this); } + inline ActionHelper& RemoveTargetWhenDone() { core->RemoveTargetWhenDone(); return (*this); } // 设置名称 - inline ActionHelper& SetName(String const& name) { base->SetName(name); return (*this); } + inline ActionHelper& SetName(String const& name) { core->SetName(name); return (*this); } // 获取指针 - inline ActionPtr Get() const { return base; } + inline ActionPtr Get() const { return core; } - inline ActionHelper(ActionPtr base) : base(base) {} + inline ActionHelper(ActionPtr core) : core(core) {} - inline operator ActionPtr() const { return base; } + inline operator ActionPtr() const { return core; } protected: - ActionPtr base; + ActionPtr core; }; struct TweenHelper { // 设置动画持续时长 - inline TweenHelper& SetDuration(Duration dur) { base->SetDuration(dur); return (*this); } + inline TweenHelper& SetDuration(Duration dur) { core->SetDuration(dur); return (*this); } // 设置循环次数 - inline TweenHelper& SetLoops(int loops) { base->SetLoops(loops); return (*this); } + inline TweenHelper& SetLoops(int loops) { core->SetLoops(loops); return (*this); } // 设置缓动函数 - inline TweenHelper& SetEaseFunc(EaseFunc ease) { base->SetEaseFunc(ease); return (*this); } + inline TweenHelper& SetEaseFunc(EaseFunc ease) { core->SetEaseFunc(ease); return (*this); } // 设置动作延迟 - inline TweenHelper& SetDelay(Duration delay) { base->SetDelay(delay); return (*this); } + inline TweenHelper& SetDelay(Duration delay) { core->SetDelay(delay); return (*this); } // 设置动作结束回调函数 - inline TweenHelper& SetDoneCallback(ActionCallback const& cb) { base->SetDoneCallback(cb); return (*this); } + inline TweenHelper& SetDoneCallback(ActionCallback const& cb) { core->SetDoneCallback(cb); return (*this); } // 设置动作循环结束时的回调函数 - inline TweenHelper& SetLoopDoneCallback(ActionCallback const& cb) { base->SetLoopDoneCallback(cb); return (*this); } + inline TweenHelper& SetLoopDoneCallback(ActionCallback const& cb) { core->SetLoopDoneCallback(cb); return (*this); } // 动作结束时移除目标角色 - inline TweenHelper& RemoveTargetWhenDone() { base->RemoveTargetWhenDone(); return (*this); } + inline TweenHelper& RemoveTargetWhenDone() { core->RemoveTargetWhenDone(); return (*this); } // 设置名称 - inline TweenHelper& SetName(String const& name) { base->SetName(name); return (*this); } + inline TweenHelper& SetName(String const& name) { core->SetName(name); return (*this); } // 获取指针 - inline ActionTweenPtr Get() const { return base; } + inline ActionTweenPtr Get() const { return core; } - inline TweenHelper(ActionTweenPtr base) : base(base) {} + inline TweenHelper(ActionTweenPtr core) : core(core) {} - inline operator ActionPtr() const { return base; } + inline operator ActionPtr() const { return core; } - inline operator ActionTweenPtr() const { return base; } + inline operator ActionTweenPtr() const { return core; } protected: - ActionTweenPtr base; + ActionTweenPtr core; }; // Tween actions helper diff --git a/src/kiwano/2d/action/ActionManager.cpp b/src/kiwano/2d/action/ActionManager.cpp index 52b603f1..d4a790c0 100644 --- a/src/kiwano/2d/action/ActionManager.cpp +++ b/src/kiwano/2d/action/ActionManager.cpp @@ -20,7 +20,7 @@ #include #include -#include +#include namespace kiwano { diff --git a/src/kiwano/2d/action/ActionTween.cpp b/src/kiwano/2d/action/ActionTween.cpp index 48e135b2..0a53988b 100644 --- a/src/kiwano/2d/action/ActionTween.cpp +++ b/src/kiwano/2d/action/ActionTween.cpp @@ -108,15 +108,15 @@ namespace kiwano } else { - Duration elapsed = elapsed_ - delay_; + Duration elapsed = GetElapsed() - GetDelay(); float loops_done = elapsed / dur_; - while (loops_done_ < static_cast(loops_done)) + while (GetLoopsDone() < static_cast(loops_done)) { Complete(target); // loops_done_++ } - percent = (status_ == Status::Done) ? 1.f : (loops_done - static_cast(loops_done_)); + percent = (GetStatus() == Status::Done) ? 1.f : (loops_done - static_cast(GetLoopsDone())); } if (ease_func_) diff --git a/src/kiwano/2d/action/ActionTween.h b/src/kiwano/2d/action/ActionTween.h index 83eef1cc..27a50115 100644 --- a/src/kiwano/2d/action/ActionTween.h +++ b/src/kiwano/2d/action/ActionTween.h @@ -20,7 +20,7 @@ #pragma once #include -#include +#include namespace kiwano { diff --git a/src/kiwano/2d/include-forwards.h b/src/kiwano/2d/include-forwards.h index 00dd6d33..c4ef9e6e 100644 --- a/src/kiwano/2d/include-forwards.h +++ b/src/kiwano/2d/include-forwards.h @@ -19,11 +19,11 @@ // THE SOFTWARE. #pragma once -#include -#include -#include -#include -#include +#include +#include +#include +#include +#include #include #include diff --git a/src/kiwano/base/Event.hpp b/src/kiwano/base/Event.hpp deleted file mode 100644 index 154699c0..00000000 --- a/src/kiwano/base/Event.hpp +++ /dev/null @@ -1,181 +0,0 @@ -// Copyright (c) 2016-2018 Kiwano - Nomango -// -// Permission is hereby granted, free of charge, to any person obtaining a copy -// of this software and associated documentation files (the "Software"), to deal -// in the Software without restriction, including without limitation the rights -// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -// copies of the Software, and to permit persons to whom the Software is -// furnished to do so, subject to the following conditions: -// -// The above copyright notice and this permission notice shall be included in -// all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -// THE SOFTWARE. - -#pragma once -#include - -namespace kiwano -{ - // 事件类型 - typedef int EventType; - - // 鼠标事件 - struct MouseEvent - { - float x; - float y; - bool left_btn_down; // 左键是否按下 - bool right_btn_down; // 右键是否按下 - - union - { - struct // Events::MouseDown | Events::MouseUp | Events::MouseClick - { - MouseButton::Value button; - }; - - struct // Events::MouseWheel - { - float wheel; - }; - }; - - static bool Check(EventType type); - }; - - // 键盘事件 - struct KeyboardEvent - { - int count; - union - { - struct // Events::KeyDown | Events::KeyUp - { - KeyCode::Value code; - }; - - struct // Events::Char - { - char c; - }; - }; - - static bool Check(EventType type); - }; - - // 窗口事件 - struct WindowEvent - { - union - { - struct // Events::WindowMoved - { - int x; - int y; - }; - - struct // Events::WindowResized - { - int width; - int height; - }; - - struct // Events::WindowFocusChanged - { - bool focus; - }; - - struct // Events::WindowTitleChanged - { - const wchar_t* title; - }; - }; - - static bool Check(EventType type); - }; - - // 自定义事件 - struct CustomEvent - { - void* data; - }; - - class Actor; - - // 事件 - struct KGE_API Event - { - enum Type : EventType - { - First, - - // 鼠标事件 - MouseFirst, - MouseMove, // 移动 - MouseBtnDown, // 鼠标按下 - MouseBtnUp, // 鼠标抬起 - MouseWheel, // 滚轮滚动 - MouseHover, // 鼠标移入 - MouseOut, // 鼠标移出 - Click, // 鼠标点击 - MouseLast, - - // 按键事件 - KeyFirst, - KeyDown, // 按键按下 - KeyUp, // 按键抬起 - Char, // 输出字符 - KeyLast, - - // 窗口消息 - WindowFirst, - WindowMoved, // 窗口移动 - WindowResized, // 窗口大小变化 - WindowFocusChanged, // 获得或失去焦点 - WindowTitleChanged, // 标题变化 - WindowClosed, // 窗口被关闭 - WindowLast, - - Last - }; - - int type; - Actor* target; - - union - { - MouseEvent mouse; - KeyboardEvent key; - WindowEvent window; - CustomEvent custom; - }; - - Event(EventType type = Type::First) : type(type), target(nullptr) {} - }; - - - // Check-functions - - inline bool MouseEvent::Check(EventType type) - { - return type > Event::MouseFirst && type < Event::MouseLast; - } - - inline bool KeyboardEvent::Check(EventType type) - { - return type > Event::KeyFirst && type < Event::KeyLast; - } - - inline bool WindowEvent::Check(EventType type) - { - return type > Event::WindowFirst && type < Event::WindowLast; - } - -} diff --git a/src/kiwano/base/time.cpp b/src/kiwano/base/time.cpp deleted file mode 100644 index 5010ef5c..00000000 --- a/src/kiwano/base/time.cpp +++ /dev/null @@ -1,426 +0,0 @@ -// Copyright (c) 2016-2018 Kiwano - Nomango -// -// Permission is hereby granted, free of charge, to any person obtaining a copy -// of this software and associated documentation files (the "Software"), to deal -// in the Software without restriction, including without limitation the rights -// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -// copies of the Software, and to permit persons to whom the Software is -// furnished to do so, subject to the following conditions: -// -// The above copyright notice and this permission notice shall be included in -// all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -// THE SOFTWARE. - -#include -#include - -#include -#include - -namespace kiwano -{ - namespace time - { - //------------------------------------------------------- - // Time - //------------------------------------------------------- - - Time::Time() - : dur_(0) - { - } - - Time::Time(long dur) - : dur_(dur) - { - } - - const Time Time::operator+(const Duration & dur) const - { - return Time{ dur_ + dur.Milliseconds() }; - } - - const Time Time::operator-(const Duration & dur) const - { - return Time{ dur_ - dur.Milliseconds() }; - } - - Time & Time::operator+=(const Duration & other) - { - dur_ += other.Milliseconds(); - return (*this); - } - - Time & Time::operator-=(const Duration &other) - { - dur_ -= other.Milliseconds(); - return (*this); - } - - const Duration Time::operator-(const Time & other) const - { - return Duration(dur_ - other.dur_); - } - - Time Time::Now() noexcept - { - static LARGE_INTEGER freq = {}; - if (freq.QuadPart == 0LL) - { - // the Function will always succceed on systems that run Windows XP or later - QueryPerformanceFrequency(&freq); - } - - LARGE_INTEGER count; - QueryPerformanceCounter(&count); - - const long long whole = (count.QuadPart / freq.QuadPart) * 1000LL; - const long long part = (count.QuadPart % freq.QuadPart) * 1000LL / freq.QuadPart; - return Time{ static_cast(whole + part) }; - } - - - //------------------------------------------------------- - // Duration - //------------------------------------------------------- - - const Duration Ms = 1L; - const Duration Sec = 1000 * Ms; - const Duration Min = 60 * Sec; - const Duration Hour = 60 * Min; - - namespace - { - const auto duration_regex = std::wregex(LR"(^[-+]?([0-9]*(\.[0-9]*)?(h|m|s|ms)+)+$)"); - - typedef std::unordered_map UnitMap; - const auto unit_map = UnitMap - { - {L"ms", Ms}, - {L"s", Sec}, - {L"m", Min}, - {L"h", Hour} - }; - } - - Duration::Duration() - : milliseconds_(0) - { - } - - Duration::Duration(long milliseconds) - : milliseconds_(milliseconds) - { - } - - float Duration::Seconds() const - { - long sec = milliseconds_ / Sec.milliseconds_; - long ms = milliseconds_ % Sec.milliseconds_; - return static_cast(sec) + static_cast(ms) / 1000.f; - } - - float Duration::Minutes() const - { - long min = milliseconds_ / Min.milliseconds_; - long ms = milliseconds_ % Min.milliseconds_; - return static_cast(min) + static_cast(ms) / (60 * 1000.f); - } - - float Duration::Hours() const - { - long hour = milliseconds_ / Hour.milliseconds_; - long ms = milliseconds_ % Hour.milliseconds_; - return static_cast(hour) + static_cast(ms) / (60 * 60 * 1000.f); - } - - String kiwano::time::Duration::ToString() const - { - if (IsZero()) - { - return String(L"0s"); - } - - String result; - long total_ms = milliseconds_; - if (total_ms < 0) - { - result.append(L"-"); - total_ms = -total_ms; - } - - long hour = total_ms / Hour.milliseconds_; - long min = total_ms / Min.milliseconds_ - hour * 60; - long sec = total_ms / Sec.milliseconds_ - (hour * 60 * 60 + min * 60); - long ms = total_ms % Sec.milliseconds_; - - if (hour) - { - result.append(String::parse(hour)).append(L"h"); - result.append(String::parse(min)).append(L"m"); - } - else if(min) - { - result.append(String::parse(min)).append(L"m"); - } - - if (ms != 0) - { - result.append(String::parse(static_cast(sec) + static_cast(ms) / 1000.f)) - .append(L"s"); - } - else if (sec != 0) - { - result.append(String::parse(sec)).append(L"s"); - } - return result; - } - - bool Duration::operator==(const Duration & other) const - { - return milliseconds_ == other.milliseconds_; - } - - bool Duration::operator!=(const Duration & other) const - { - return milliseconds_ != other.milliseconds_; - } - - bool Duration::operator>(const Duration & other) const - { - return milliseconds_ > other.milliseconds_; - } - - bool Duration::operator>=(const Duration & other) const - { - return milliseconds_ >= other.milliseconds_; - } - - bool Duration::operator<(const Duration & other) const - { - return milliseconds_ < other.milliseconds_; - } - - bool Duration::operator<=(const Duration & other) const - { - return milliseconds_ <= other.milliseconds_; - } - - float kiwano::time::Duration::operator/(const Duration & other) const - { - return static_cast(milliseconds_) / other.milliseconds_; - } - - const Duration Duration::operator+(const Duration & other) const - { - return Duration(milliseconds_ + other.milliseconds_); - } - - const Duration Duration::operator-(const Duration & other) const - { - return Duration(milliseconds_ - other.milliseconds_); - } - - const Duration Duration::operator-() const - { - return Duration(-milliseconds_); - } - - const Duration Duration::operator*(int val) const - { - return Duration(milliseconds_ * val); - } - - const Duration kiwano::time::Duration::operator*(unsigned long long val) const - { - return Duration(static_cast(milliseconds_ * val)); - } - - const Duration Duration::operator*(float val) const - { - return Duration(static_cast(milliseconds_ * val)); - } - - const Duration Duration::operator*(double val) const - { - return Duration(static_cast(milliseconds_ * val)); - } - - const Duration Duration::operator*(long double val) const - { - return Duration(static_cast(milliseconds_ * val)); - } - - const Duration Duration::operator/(int val) const - { - return Duration(milliseconds_ / val); - } - - const Duration Duration::operator/(float val) const - { - return Duration(static_cast(milliseconds_ / val)); - } - - const Duration Duration::operator/(double val) const - { - return Duration(static_cast(milliseconds_ / val)); - } - - Duration & Duration::operator+=(const Duration &other) - { - milliseconds_ += other.milliseconds_; - return (*this); - } - - Duration & Duration::operator-=(const Duration &other) - { - milliseconds_ -= other.milliseconds_; - return (*this); - } - - Duration & Duration::operator*=(int val) - { - milliseconds_ *= val; - return (*this); - } - - Duration & Duration::operator/=(int val) - { - milliseconds_ = static_cast(milliseconds_ / val); - return (*this); - } - - Duration & Duration::operator*=(float val) - { - milliseconds_ = static_cast(milliseconds_ * val); - return (*this); - } - - Duration & Duration::operator/=(float val) - { - milliseconds_ = static_cast(milliseconds_ / val); - return (*this); - } - - Duration & Duration::operator*=(double val) - { - milliseconds_ = static_cast(milliseconds_ * val); - return (*this); - } - - Duration & Duration::operator/=(double val) - { - milliseconds_ = static_cast(milliseconds_ / val); - return (*this); - } - - const Duration kiwano::time::operator*(int val, const Duration & dur) - { - return dur * val; - } - - const Duration kiwano::time::operator/(int val, const Duration & dur) - { - return dur / val; - } - - const Duration kiwano::time::operator*(float val, const Duration & dur) - { - return dur * val; - } - - const Duration kiwano::time::operator/(float val, const Duration & dur) - { - return dur / val; - } - - const Duration kiwano::time::operator*(double val, const Duration & dur) - { - return dur * val; - } - - const Duration kiwano::time::operator/(double val, const Duration & dur) - { - return dur / val; - } - - const Duration kiwano::time::operator*(long double val, const Duration & dur) - { - return dur * val; - } - - Duration Duration::Parse(const String& str) - { - bool negative = false; - size_t len = str.length(); - size_t pos = 0; - Duration ret; - - if (!std::regex_match(str.c_str(), duration_regex)) - { - KGE_ERROR_LOG(L"Duration::Parse failed, invalid duration"); - return ret; - } - - if (str.empty() || str == L"0") { return ret; } - - // 符号位 - if (str[0] == L'-' || str[0] == L'+') - { - negative = (str[0] == L'-'); - pos++; - } - - while (pos < len) - { - // 数值 - size_t i = pos; - for (; i < len; ++i) - { - wchar_t ch = str[i]; - if (!(ch == L'.' || L'0' <= ch && ch <= L'9')) - { - break; - } - } - - String num_str = str.substr(pos, i - pos); - pos = i; - - KGE_ASSERT(!(num_str.empty() || num_str == L".") && "Duration::Parse failed, invalid duration"); - - // 单位 - for (; i < len; ++i) - { - wchar_t ch = str[i]; - if (ch == L'.' || L'0' <= ch && ch <= L'9') - { - break; - } - } - - String unit_str = str.substr(pos, i - pos); - pos = i; - - KGE_ASSERT(unit_map.find(unit_str) != unit_map.end() && "Duration::Parse failed, invalid duration"); - - double num = std::wcstod(num_str.c_str(), nullptr); - Duration unit = unit_map.at(unit_str); - ret += unit * num; - } - - if (negative) - { - ret = -ret; - } - return ret; - } - } -} diff --git a/src/kiwano/base/time.h b/src/kiwano/base/time.h deleted file mode 100644 index 1457db43..00000000 --- a/src/kiwano/base/time.h +++ /dev/null @@ -1,247 +0,0 @@ -// Copyright (c) 2016-2018 Kiwano - Nomango -// -// Permission is hereby granted, free of charge, to any person obtaining a copy -// of this software and associated documentation files (the "Software"), to deal -// in the Software without restriction, including without limitation the rights -// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -// copies of the Software, and to permit persons to whom the Software is -// furnished to do so, subject to the following conditions: -// -// The above copyright notice and this permission notice shall be included in -// all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -// THE SOFTWARE. - -#pragma once -#include -#include - -#include -#include - -namespace kiwano -{ - namespace time - { - // 时间段 - // - // 时间段表示法: - // 5 秒: time::Sec * 5 - // 1.5 小时: time::Hour * 1.5 - // 3 小时 45 分 15 秒: time::Hour * 3 + time::Min * 45 + time::Sec * 15 - // 在 VS2015 及更高版本可以使用 time literals: - // 5 秒: 5_s - // 1.5 小时: 1.5_h - // 3 小时 45 分 15 秒: 3_h + 45_m + 15_s - // - struct KGE_API Duration - { - Duration(); - - Duration( - long milliseconds - ); - - // 转化为毫秒 - inline long Milliseconds() const { return milliseconds_; } - - // 转化为秒 - float Seconds() const; - - // 转化为分钟 - float Minutes() const; - - // 转化为小时 - float Hours() const; - - // 时长是否是零 - inline bool IsZero() const { return milliseconds_ == 0LL; } - - inline void SetMilliseconds(long ms) { milliseconds_ = ms; } - - inline void SetSeconds(float seconds) { milliseconds_ = static_cast(seconds * 1000.f); } - - inline void SetMinutes(float minutes) { milliseconds_ = static_cast(minutes * 60 * 1000.f); } - - inline void SetHours(float hours) { milliseconds_ = static_cast(hours * 60 * 60 * 1000.f); } - - // 转为字符串 - String ToString() const; - - inline operator bool() const { return !IsZero(); } - - bool operator== (const Duration &) const; - bool operator!= (const Duration &) const; - bool operator> (const Duration &) const; - bool operator>= (const Duration &) const; - bool operator< (const Duration &) const; - bool operator<= (const Duration &) const; - - float operator / (const Duration &) const; - - const Duration operator + (const Duration &) const; - const Duration operator - (const Duration &) const; - const Duration operator - () const; - const Duration operator * (int) const; - const Duration operator * (unsigned long long) const; - const Duration operator * (float) const; - const Duration operator * (double) const; - const Duration operator * (long double) const; - const Duration operator / (int) const; - const Duration operator / (float) const; - const Duration operator / (double) const; - - Duration& operator += (const Duration &); - Duration& operator -= (const Duration &); - Duration& operator *= (int); - Duration& operator *= (float); - Duration& operator *= (double); - Duration& operator /= (int); - Duration& operator /= (float); - Duration& operator /= (double); - - friend const Duration operator* (int, const Duration &); - friend const Duration operator* (float, const Duration &); - friend const Duration operator* (double, const Duration &); - friend const Duration operator* (long double, const Duration &); - friend const Duration operator/ (int, const Duration &); - friend const Duration operator/ (float, const Duration &); - friend const Duration operator/ (double, const Duration &); - - public: - // 时间段格式化 - // - // 时间段字符串允许是有符号的浮点数, 并且带有时间单位后缀 - // 例如: "300ms", "-1.5h", "2h45m" - // 允许的时间单位有 "ms", "s", "m", "h" - static Duration Parse(const String& parse_str); - - template - friend inline std::basic_ostream<_Char>& operator<<(std::basic_ostream<_Char>& out, const Duration& dur) - { - return out << dur.ToString(); - } - - template - friend inline std::basic_istream<_Char>& operator>>(std::basic_istream<_Char>& in, Duration& dur) - { - String str; - if (in >> str) - { - dur = Duration::Parse(str); - } - return in; - } - - private: - long milliseconds_; - }; - - /* 预定义的时间段 */ - KGE_API extern const Duration Ms; // 毫秒 - KGE_API extern const Duration Sec; // 秒 - KGE_API extern const Duration Min; // 分钟 - KGE_API extern const Duration Hour; // 小时 - - - // 时间 - // - // 获取当前时间: Time now = Time::Now(); - // 两时间相减, 得到一个 Duration 对象, 例如: - // Time t1, t2; - // int ms = (t2 - t1).Milliseconds(); // 获取两时间相差的毫秒数 - // - struct KGE_API Time - { - Time(); - - Time(long); - - // 是否是零时 - inline bool IsZero() const { return dur_ == 0; } - - const Time operator + (const Duration &) const; - const Time operator - (const Duration &) const; - - Time& operator += (const Duration &); - Time& operator -= (const Duration &); - - const Duration operator - (const Time &) const; - - public: - // 获取当前时间 - // 由于该时间点基于系统启动时间开始计算, 所以无法格式化该时间, - // 也无法获得该时间的 Unix 时间戳 - static Time Now() noexcept; - - private: - long dur_; - }; - } -} - -namespace kiwano -{ - using namespace time; -} - -#if KGE_VS_VER > KGE_VS_2013 - -namespace kiwano -{ - inline namespace literals - { - inline const kiwano::time::Duration operator "" _ms(long double val) - { - return kiwano::time::Ms * val; - } - - inline const kiwano::time::Duration operator "" _s(long double val) - { - return kiwano::time::Sec * val; - } - - inline const kiwano::time::Duration operator "" _m(long double val) - { - return kiwano::time::Min * val; - } - - inline const kiwano::time::Duration operator "" _h(long double val) - { - return kiwano::time::Hour * val; - } - - inline const kiwano::time::Duration operator "" _ms(unsigned long long val) - { - return kiwano::time::Ms * val; - } - - inline const kiwano::time::Duration operator "" _s(unsigned long long val) - { - return kiwano::time::Sec * val; - } - - inline const kiwano::time::Duration operator "" _m(unsigned long long val) - { - return kiwano::time::Min * val; - } - - inline const kiwano::time::Duration operator "" _h(unsigned long long val) - { - return kiwano::time::Hour * val; - } - } - - namespace time - { - using namespace kiwano::literals; - } -} - -#endif diff --git a/src/kiwano/core/any.hpp b/src/kiwano/common/any.hpp similarity index 98% rename from src/kiwano/core/any.hpp rename to src/kiwano/common/any.hpp index 81d66390..0b3dfd6d 100644 --- a/src/kiwano/core/any.hpp +++ b/src/kiwano/common/any.hpp @@ -26,7 +26,7 @@ namespace kiwano { -namespace core +namespace common { class bad_any_cast : public std::exception @@ -519,13 +519,13 @@ _Ty any_cast(any&& a) return static_cast<_Ty>(std::move(*ptr)); } -} // namespace core +} // namespace common } // namespace kiwano namespace std { - inline void swap(kiwano::core::any& lhs, kiwano::core::any& rhs) noexcept + inline void swap(kiwano::common::any& lhs, kiwano::common::any& rhs) noexcept { lhs.swap(rhs); } diff --git a/src/kiwano/core/basic_json.hpp b/src/kiwano/common/basic_json.hpp similarity index 99% rename from src/kiwano/core/basic_json.hpp rename to src/kiwano/common/basic_json.hpp index 05080c47..b72653ce 100644 --- a/src/kiwano/core/basic_json.hpp +++ b/src/kiwano/common/basic_json.hpp @@ -28,7 +28,7 @@ namespace kiwano { -namespace core +namespace common { // @@ -1602,14 +1602,14 @@ namespace __json_detail if ((std::isdigit(current) && current != '0') || (current == '-') || (current == '+')) { - float_type base = 10; + float_type core = 10; if (current == '+') { read_next(); } else if (current == '-') { - base = static_cast(0.1); + core = static_cast(0.1); read_next(); } @@ -1620,9 +1620,9 @@ namespace __json_detail } float_type power = 1; - for (; exponent; exponent >>= 1, base *= base) + for (; exponent; exponent >>= 1, core *= core) if (exponent & 1) - power *= base; + power *= core; number_value *= power; return token_type::value_float; @@ -2728,7 +2728,7 @@ private: __json_detail::json_value value_; }; -} // namespace core +} // namespace common } // namespace kiwano diff --git a/src/kiwano/core/core.h b/src/kiwano/common/common.h similarity index 77% rename from src/kiwano/core/core.h rename to src/kiwano/common/common.h index be374b02..c09b8cd4 100644 --- a/src/kiwano/core/core.h +++ b/src/kiwano/common/common.h @@ -28,24 +28,24 @@ #include #include -#include -#include -#include -#include -#include -#include -#include -#include -#include +#include +#include +#include +#include +#include +#include +#include +#include +#include namespace kiwano { - using String = kiwano::core::wstring; + using String = kiwano::common::wstring; using StringStream = std::wstringstream; template - using Vector = kiwano::core::vector<_Ty, _Args...>; + using Vector = kiwano::common::vector<_Ty, _Args...>; template using List = std::list<_Ty, _Args...>; @@ -72,21 +72,21 @@ namespace kiwano using UnorderedMap = std::unordered_map<_Kty, _Ty, _Args...>; template - using Function = kiwano::core::function<_FuncTy>; + using Function = kiwano::common::function<_FuncTy>; - using Any = kiwano::core::any; + using Any = kiwano::common::any; - using Json = kiwano::core::basic_json; template - using Singleton = core::singleton<_Ty>; + using Singleton = common::singleton<_Ty>; template - using IntrusiveList = core::intrusive_list<_Ty>; + using IntrusiveList = common::intrusive_list<_Ty>; template - using IntrusiveListItem = core::intrusive_list_item<_Ty>; + using IntrusiveListItem = common::intrusive_list_item<_Ty>; } namespace std diff --git a/src/kiwano/core/function.hpp b/src/kiwano/common/function.hpp similarity index 95% rename from src/kiwano/core/function.hpp rename to src/kiwano/common/function.hpp index 3a686226..c561db6f 100644 --- a/src/kiwano/core/function.hpp +++ b/src/kiwano/common/function.hpp @@ -25,7 +25,7 @@ namespace kiwano { -namespace core +namespace common { // // function is a light weight ::std::function<>-like class @@ -321,7 +321,7 @@ private: __function_detail::callable<_Ret, _Args...>* callable_; }; -} // namespace core +} // namespace common } // namespace kiwano @@ -335,9 +335,9 @@ namespace kiwano typename _Ret, typename... _Args > - inline core::function<_Ret(_Args...)> Closure(_Uty* ptr, _Ret(_Ty::* func)(_Args...)) + inline common::function<_Ret(_Args...)> Closure(_Uty* ptr, _Ret(_Ty::* func)(_Args...)) { - return core::function<_Ret(_Args...)>(ptr, func); + return common::function<_Ret(_Args...)>(ptr, func); } template - inline core::function<_Ret(_Args...)> Closure(_Uty* ptr, _Ret(_Ty::* func)(_Args...) const) + inline common::function<_Ret(_Args...)> Closure(_Uty* ptr, _Ret(_Ty::* func)(_Args...) const) { - return core::function<_Ret(_Args...)>(ptr, func); + return common::function<_Ret(_Args...)>(ptr, func); } } diff --git a/src/kiwano/core/intrusive_list.hpp b/src/kiwano/common/intrusive_list.hpp similarity index 98% rename from src/kiwano/core/intrusive_list.hpp rename to src/kiwano/common/intrusive_list.hpp index 4ce55f9f..0e49d091 100644 --- a/src/kiwano/core/intrusive_list.hpp +++ b/src/kiwano/common/intrusive_list.hpp @@ -32,7 +32,7 @@ namespace kiwano { -namespace core +namespace common { template @@ -261,7 +261,7 @@ private: // disable warning 4996 using _Unchecked_type = _Ty; - inline iterator_impl(value_type base = nullptr, bool is_end = false) : base_(base), is_end_(is_end) {} + inline iterator_impl(value_type core = nullptr, bool is_end = false) : base_(core), is_end_(is_end) {} inline _Ty operator*() const { KGE_ASSERT(base_); return static_cast<_Ty>(const_cast(base_)); } inline iterator_impl& operator++() { KGE_ASSERT(base_ && !is_end_); value_type next = base_->next_item(); if (next) base_ = next; else is_end_ = true; return (*this);} @@ -307,7 +307,7 @@ private: value_type last_; }; -} // namespace core +} // namespace common } // namespace kiwano diff --git a/src/kiwano/core/intrusive_ptr.hpp b/src/kiwano/common/intrusive_ptr.hpp similarity index 99% rename from src/kiwano/core/intrusive_ptr.hpp rename to src/kiwano/common/intrusive_ptr.hpp index 8a84e987..70aadb9c 100644 --- a/src/kiwano/core/intrusive_ptr.hpp +++ b/src/kiwano/common/intrusive_ptr.hpp @@ -26,7 +26,7 @@ namespace kiwano { -namespace core +namespace common { template @@ -141,6 +141,6 @@ inline void swap(intrusive_ptr<_Ty, manager_type>& lhs, intrusive_ptr<_Ty, manag lhs.swap(rhs); } -} // namespace core +} // namespace common } // namespace kiwano diff --git a/src/kiwano/core/noncopyable.hpp b/src/kiwano/common/noncopyable.hpp similarity index 97% rename from src/kiwano/core/noncopyable.hpp rename to src/kiwano/common/noncopyable.hpp index 741cf806..9328c7e7 100644 --- a/src/kiwano/core/noncopyable.hpp +++ b/src/kiwano/common/noncopyable.hpp @@ -22,7 +22,7 @@ namespace kiwano { -namespace core +namespace common { class noncopyable @@ -36,5 +36,5 @@ private: noncopyable& operator=(const noncopyable&) = delete; }; -} // namespace core +} // namespace common } // namespace kiwano diff --git a/src/kiwano/core/singleton.hpp b/src/kiwano/common/singleton.hpp similarity index 96% rename from src/kiwano/core/singleton.hpp rename to src/kiwano/common/singleton.hpp index be4aabd7..afc3fff4 100644 --- a/src/kiwano/core/singleton.hpp +++ b/src/kiwano/common/singleton.hpp @@ -27,13 +27,13 @@ #ifndef KGE_DECLARE_SINGLETON #define KGE_DECLARE_SINGLETON( CLASS ) \ - friend ::kiwano::core::singleton< CLASS >; \ + friend ::kiwano::common::singleton< CLASS >; \ friend typename std::unique_ptr< CLASS >::deleter_type #endif namespace kiwano { -namespace core +namespace common { template @@ -81,5 +81,5 @@ std::once_flag singleton<_Ty>::once_; template std::unique_ptr<_Ty> singleton<_Ty>::instance_; -} // namespace core +} // namespace common } // namespace kiwano diff --git a/src/kiwano/core/string.hpp b/src/kiwano/common/string.hpp similarity index 94% rename from src/kiwano/core/string.hpp rename to src/kiwano/common/string.hpp index e210387b..a34789e8 100644 --- a/src/kiwano/core/string.hpp +++ b/src/kiwano/common/string.hpp @@ -29,7 +29,7 @@ namespace kiwano { -namespace core +namespace common { // @@ -56,10 +56,10 @@ private: // disable warning 4996 using _Unchecked_type = _Ty; - inline iterator_impl(pointer base = nullptr) : base_(base) {} + inline iterator_impl(pointer core = nullptr) : base_(core) {} inline reference operator*() const { return *base_; } - inline pointer base() const { return base_; } + inline pointer core() const { return base_; } inline iterator_impl& operator++() { ++base_; return (*this); } inline iterator_impl operator++(int) { iterator_impl old = (*this); ++(*this); return old; } @@ -176,8 +176,8 @@ public: inline basic_string& assign(_Iter first, _Iter last) { assign_iter(first, last); return(*this); } basic_string& erase(size_type offset = 0, size_type count = npos); - iterator erase(const const_iterator where) { size_type off = where - cbegin(); erase(off, 1); return begin().base() + off; } - iterator erase(const const_iterator first, const const_iterator last) { size_type off = first - cbegin(); erase(first - cbegin(), last - first); return begin().base() + off; } + iterator erase(const const_iterator where) { size_type off = where - cbegin(); erase(off, 1); return begin().core() + off; } + iterator erase(const const_iterator first, const const_iterator last) { size_type off = first - cbegin(); erase(first - cbegin(), last - first); return begin().core() + off; } basic_string substr(size_type pos = 0, size_type count = npos) const { return basic_string(*this, pos, count); } @@ -186,7 +186,7 @@ public: basic_string& insert(size_type index, const basic_string& str, size_type off, size_type count = npos); inline basic_string& insert(size_type index, const char_type* s) { return insert(index, s, traits_type::length(s)); } inline basic_string& insert(size_type index, const basic_string& str) { return insert(index, str, 0, str.size()); } - inline iterator insert(const_iterator pos, size_type count, char_type ch) { size_type off = pos - cbegin(); insert(off, count, ch); return begin().base() + off; } + inline iterator insert(const_iterator pos, size_type count, char_type ch) { size_type off = pos - cbegin(); insert(off, count, ch); return begin().core() + off; } inline iterator insert(const_iterator pos, char_type ch) { return insert(pos, 1, ch); } inline void push_back(const char_type ch) { append(1, ch); } @@ -425,8 +425,8 @@ basic_string format_string(const wchar_t* const fmt, _Args&& ... args); // // string && wstring // -using string = ::kiwano::core::basic_string; -using wstring = ::kiwano::core::basic_string; +using string = ::kiwano::common::basic_string; +using wstring = ::kiwano::common::basic_string; inline string to_string(int val) { return to_basic_string(val); } @@ -450,7 +450,7 @@ inline wstring to_wstring(double val) { return to_basic_string(val); inline wstring to_wstring(long double val) { return to_basic_string(val); } -} // namespace core +} // namespace common } // namespace kiwano namespace kiwano @@ -515,7 +515,7 @@ namespace __string_details } } -namespace core +namespace common { template @@ -670,7 +670,7 @@ namespace core } size_ = count; - traits_type::move(str_, rhs.begin().base() + pos, size_); + traits_type::move(str_, rhs.begin().core() + pos, size_); traits_type::assign(str_[size_], value_type()); return (*this); } @@ -693,8 +693,8 @@ namespace core } size_type new_size = size_ - count; - iterator erase_at = begin().base() + offset; - traits_type::move(erase_at.base(), erase_at.base() + count, new_size - offset + 1); + iterator erase_at = begin().core() + offset; + traits_type::move(erase_at.core(), erase_at.core() + count, new_size - offset + 1); return (*this); } @@ -807,7 +807,7 @@ namespace core char_type* const insert_at = new_ptr + index; traits_type::move(new_ptr, old_ptr, index); // (0) - (index) - traits_type::move(insert_at, str.begin().base() + off, count); // (index) - (index + count) + traits_type::move(insert_at, str.begin().core() + off, count); // (index) - (index + count) traits_type::move(insert_at + count, old_ptr + index, suffix_size); // (index + count) - (old_size - index) deallocate(str_, old_capacity + 1); @@ -817,7 +817,7 @@ namespace core { char_type* const insert_at = old_ptr + index; traits_type::move(insert_at + count, old_ptr + index, suffix_size); - traits_type::move(insert_at, str.begin().base() + off, count); + traits_type::move(insert_at, str.begin().core() + off, count); } return (*this); @@ -880,7 +880,7 @@ namespace core char_type* new_str = allocate(new_cap); traits_type::move(new_str, str_, size_); - traits_type::move(new_str + size_, other.begin().base() + pos, count); + traits_type::move(new_str + size_, other.begin().core() + pos, count); traits_type::assign(new_str[new_size], value_type()); destroy(); @@ -948,7 +948,7 @@ namespace core if (offset >= size_) return basic_string<_CharTy>::npos; - const_iterator citer = traits_type::find(cbegin().base() + offset, size_, ch); + const_iterator citer = traits_type::find(cbegin().core() + offset, size_, ch); return citer ? (citer - cbegin()) : basic_string<_CharTy>::npos; } @@ -966,7 +966,7 @@ namespace core if (offset >= size_) return basic_string<_CharTy>::npos; - const_iterator citer = std::find_first_of(cbegin().base() + offset, cend().base(), str, str + count); + const_iterator citer = std::find_first_of(cbegin().core() + offset, cend().core(), str, str + count); return (citer != cend()) ? (citer - cbegin()) : basic_string<_CharTy>::npos; } @@ -977,7 +977,7 @@ namespace core return npos; const_reverse_iterator criter = std::find(crbegin(), crend(), ch); - return (criter != crend()) ? (criter.base() - cbegin()) : basic_string<_CharTy>::npos; + return (criter != crend()) ? (criter.core() - cbegin()) : basic_string<_CharTy>::npos; } template @@ -1090,7 +1090,7 @@ namespace core check_offset(pos); count = clamp_suffix_size(pos, count); - traits_type::move(cstr, cbegin().base() + pos, count); + traits_type::move(cstr, cbegin().core() + pos, count); return count; } @@ -1159,31 +1159,31 @@ namespace core // template - inline basic_string<_CharTy> basic_string<_CharTy>::parse(int val) { return ::kiwano::core::to_basic_string(val); } + inline basic_string<_CharTy> basic_string<_CharTy>::parse(int val) { return ::kiwano::common::to_basic_string(val); } template - inline basic_string<_CharTy> basic_string<_CharTy>::parse(unsigned int val) { return ::kiwano::core::to_basic_string(val); } + inline basic_string<_CharTy> basic_string<_CharTy>::parse(unsigned int val) { return ::kiwano::common::to_basic_string(val); } template - inline basic_string<_CharTy> basic_string<_CharTy>::parse(long val) { return ::kiwano::core::to_basic_string(val); } + inline basic_string<_CharTy> basic_string<_CharTy>::parse(long val) { return ::kiwano::common::to_basic_string(val); } template - inline basic_string<_CharTy> basic_string<_CharTy>::parse(unsigned long val) { return ::kiwano::core::to_basic_string(val); } + inline basic_string<_CharTy> basic_string<_CharTy>::parse(unsigned long val) { return ::kiwano::common::to_basic_string(val); } template - inline basic_string<_CharTy> basic_string<_CharTy>::parse(long long val) { return ::kiwano::core::to_basic_string(val); } + inline basic_string<_CharTy> basic_string<_CharTy>::parse(long long val) { return ::kiwano::common::to_basic_string(val); } template - inline basic_string<_CharTy> basic_string<_CharTy>::parse(unsigned long long val) { return ::kiwano::core::to_basic_string(val); } + inline basic_string<_CharTy> basic_string<_CharTy>::parse(unsigned long long val) { return ::kiwano::common::to_basic_string(val); } template - inline basic_string<_CharTy> basic_string<_CharTy>::parse(float val) { return ::kiwano::core::to_basic_string(val); } + inline basic_string<_CharTy> basic_string<_CharTy>::parse(float val) { return ::kiwano::common::to_basic_string(val); } template - inline basic_string<_CharTy> basic_string<_CharTy>::parse(double val) { return ::kiwano::core::to_basic_string(val); } + inline basic_string<_CharTy> basic_string<_CharTy>::parse(double val) { return ::kiwano::common::to_basic_string(val); } template - inline basic_string<_CharTy> basic_string<_CharTy>::parse(long double val) { return ::kiwano::core::to_basic_string(val); } + inline basic_string<_CharTy> basic_string<_CharTy>::parse(long double val) { return ::kiwano::common::to_basic_string(val); } // // details of basic_string::format @@ -1193,7 +1193,7 @@ namespace core template inline basic_string<_CharTy> basic_string<_CharTy>::format(const char_type* fmt, _Args&& ... args) { - return ::kiwano::core::format_string(fmt, std::forward<_Args>(args)...); + return ::kiwano::common::format_string(fmt, std::forward<_Args>(args)...); } // @@ -1527,8 +1527,8 @@ class string_convert enum : size_t { BUFFER_INCREASE = 8, BUFFER_MAX = 16 }; public: - using byte_string = ::kiwano::core::basic_string; - using wide_string = ::kiwano::core::basic_string<_Elem>; + using byte_string = ::kiwano::common::basic_string; + using wide_string = ::kiwano::common::basic_string<_Elem>; using codecvt_type = _Codecvt; using state_type = typename codecvt_type::state_type; using int_type = typename wide_string::traits_type::int_type; @@ -1702,25 +1702,25 @@ class chs_codecvt public: chs_codecvt() : codecvt_byname("chs") {} - static inline ::kiwano::core::wstring string_to_wide(::kiwano::core::string const& str) + static inline ::kiwano::common::wstring string_to_wide(::kiwano::common::string const& str) { string_convert conv; return conv.from_bytes(str); } - static inline ::kiwano::core::string wide_to_string(::kiwano::core::wstring const& str) + static inline ::kiwano::common::string wide_to_string(::kiwano::common::wstring const& str) { string_convert conv; return conv.to_bytes(str); } }; -inline ::kiwano::core::wstring string_to_wide(::kiwano::core::string const& str) +inline ::kiwano::common::wstring string_to_wide(::kiwano::common::string const& str) { return kiwano::chs_codecvt::string_to_wide(str); } -inline ::kiwano::core::string wide_to_string(::kiwano::core::wstring const& str) +inline ::kiwano::common::string wide_to_string(::kiwano::common::wstring const& str) { return kiwano::chs_codecvt::wide_to_string(str); } @@ -1730,18 +1730,18 @@ inline ::kiwano::core::string wide_to_string(::kiwano::core::wstring const& str) namespace std { template<> - struct hash<::kiwano::core::string> + struct hash<::kiwano::common::string> { - inline size_t operator()(const ::kiwano::core::string& key) const + inline size_t operator()(const ::kiwano::common::string& key) const { return key.hash(); } }; template<> - struct hash<::kiwano::core::wstring> + struct hash<::kiwano::common::wstring> { - inline size_t operator()(const ::kiwano::core::wstring& key) const + inline size_t operator()(const ::kiwano::common::wstring& key) const { return key.hash(); } @@ -1751,13 +1751,13 @@ namespace std namespace std { template<> - inline void swap<::kiwano::core::string>(::kiwano::core::string& lhs, ::kiwano::core::string& rhs) noexcept + inline void swap<::kiwano::common::string>(::kiwano::common::string& lhs, ::kiwano::common::string& rhs) noexcept { lhs.swap(rhs); } template<> - inline void swap<::kiwano::core::wstring>(::kiwano::core::wstring& lhs, ::kiwano::core::wstring& rhs) noexcept + inline void swap<::kiwano::common::wstring>(::kiwano::common::wstring& lhs, ::kiwano::common::wstring& rhs) noexcept { lhs.swap(rhs); } diff --git a/src/kiwano/core/vector.hpp b/src/kiwano/common/vector.hpp similarity index 99% rename from src/kiwano/core/vector.hpp rename to src/kiwano/common/vector.hpp index 0194c248..dc8f9e0d 100644 --- a/src/kiwano/core/vector.hpp +++ b/src/kiwano/common/vector.hpp @@ -25,7 +25,7 @@ namespace kiwano { -namespace core +namespace common { @@ -284,5 +284,5 @@ namespace __vector_details }; } -} // namespace core +} // namespace common } // namespace kiwano diff --git a/src/kiwano/base/AsyncTask.cpp b/src/kiwano/core/AsyncTask.cpp similarity index 98% rename from src/kiwano/base/AsyncTask.cpp rename to src/kiwano/core/AsyncTask.cpp index c33cbe17..119b91ff 100644 --- a/src/kiwano/base/AsyncTask.cpp +++ b/src/kiwano/core/AsyncTask.cpp @@ -18,7 +18,7 @@ // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. -#include +#include #include namespace kiwano diff --git a/src/kiwano/base/AsyncTask.h b/src/kiwano/core/AsyncTask.h similarity index 98% rename from src/kiwano/base/AsyncTask.h rename to src/kiwano/core/AsyncTask.h index 2b0bac32..095f4bc7 100644 --- a/src/kiwano/base/AsyncTask.h +++ b/src/kiwano/core/AsyncTask.h @@ -22,7 +22,7 @@ #include #include -#include +#include namespace kiwano { diff --git a/src/kiwano/base/Component.cpp b/src/kiwano/core/Component.cpp similarity index 98% rename from src/kiwano/base/Component.cpp rename to src/kiwano/core/Component.cpp index 41e3b0ad..ed18c619 100644 --- a/src/kiwano/base/Component.cpp +++ b/src/kiwano/core/Component.cpp @@ -18,7 +18,7 @@ // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. -#include +#include #define KGE_DEFINE_COMPONENT_FLAG(OFFSET) ( 0x01 << (OFFSET % 32) ) diff --git a/src/kiwano/base/Component.h b/src/kiwano/core/Component.h similarity index 95% rename from src/kiwano/base/Component.h rename to src/kiwano/core/Component.h index c76e0e8d..8c556108 100644 --- a/src/kiwano/base/Component.h +++ b/src/kiwano/core/Component.h @@ -20,11 +20,13 @@ #pragma once #include -#include -#include +#include namespace kiwano { + class RenderTarget; + class Event; + // 基础组件 class KGE_API ComponentBase { @@ -42,8 +44,6 @@ namespace kiwano }; - class RenderTarget; - // 渲染支持组件 class KGE_API RenderComponent : public virtual ComponentBase @@ -85,7 +85,7 @@ namespace kiwano : public virtual ComponentBase { public: - virtual void HandleEvent(Event&) {} + virtual void HandleEvent(Event*) {} virtual void HandleMessage(HWND, UINT32, WPARAM, LPARAM) {} diff --git a/src/kiwano/base/Director.cpp b/src/kiwano/core/Director.cpp similarity index 98% rename from src/kiwano/base/Director.cpp rename to src/kiwano/core/Director.cpp index ac6d5ab1..7d41966f 100644 --- a/src/kiwano/base/Director.cpp +++ b/src/kiwano/core/Director.cpp @@ -18,7 +18,7 @@ // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. -#include +#include #include #include #include @@ -180,7 +180,7 @@ namespace kiwano } } - void Director::HandleEvent(Event& evt) + void Director::HandleEvent(Event* evt) { if (debug_actor_) debug_actor_->Dispatch(evt); diff --git a/src/kiwano/base/Director.h b/src/kiwano/core/Director.h similarity index 96% rename from src/kiwano/base/Director.h rename to src/kiwano/core/Director.h index 56ca957a..f96ca9b6 100644 --- a/src/kiwano/base/Director.h +++ b/src/kiwano/core/Director.h @@ -20,7 +20,7 @@ #pragma once #include -#include +#include namespace kiwano { @@ -72,7 +72,7 @@ namespace kiwano void OnRender(RenderTarget* rt) override; - void HandleEvent(Event& evt) override; + void HandleEvent(Event* evt) override; protected: Director(); diff --git a/src/kiwano/core/Event.cpp b/src/kiwano/core/Event.cpp new file mode 100644 index 00000000..681d92ee --- /dev/null +++ b/src/kiwano/core/Event.cpp @@ -0,0 +1,134 @@ +#include + +namespace kiwano +{ + EventType event::MouseMove = EventType(L"MouseMove"); + EventType event::MouseDown = EventType(L"MouseBtnDown"); + EventType event::MouseUp = EventType(L"MouseBtnUp"); + EventType event::MouseWheel = EventType(L"MouseWheel"); + EventType event::MouseHover = EventType(L"MouseHover"); + EventType event::MouseOut = EventType(L"MouseOut"); + EventType event::MouseClick = EventType(L"MouseClick"); + + EventType event::KeyDown = EventType(L"KeyDown"); + EventType event::KeyUp = EventType(L"KeyUp"); + EventType event::KeyChar = EventType(L"KeyChar"); + + EventType event::WindowMoved = EventType(L"WindowMoved"); + EventType event::WindowResized = EventType(L"WindowResized"); + EventType event::WindowFocusChanged = EventType(L"WindowFocusChanged"); + EventType event::WindowTitleChanged = EventType(L"WindowTitleChanged"); + EventType event::WindowClosed = EventType(L"WindowClosed"); + + + Event::Event(EventType const& type) + : type(type) + { + } + + Event::~Event() + { + } + + MouseEvent::MouseEvent(EventType const& type) + : Event(type) + , pos() + , left_btn_down(false) + , right_btn_down(false) + , target(nullptr) + { + } + + MouseMoveEvent::MouseMoveEvent() + : MouseEvent(event::MouseMove) + , button(0) + { + } + + MouseDownEvent::MouseDownEvent() + : MouseEvent(event::MouseDown) + , button(0) + { + } + + MouseUpEvent::MouseUpEvent() + : MouseEvent(event::MouseUp) + , button(0) + { + } + + MouseClickEvent::MouseClickEvent() + : MouseEvent(event::MouseClick) + , button(0) + { + } + + MouseHoverEvent::MouseHoverEvent() + : MouseEvent(event::MouseHover) + { + } + + MouseOutEvent::MouseOutEvent() + : MouseEvent(event::MouseOut) + { + } + + MouseWheelEvent::MouseWheelEvent() + : MouseEvent(event::MouseWheel) + , wheel(0.f) + { + } + + KeyDownEvent::KeyDownEvent() + : Event(event::KeyDown) + , code(0) + , count(0) + { + } + + KeyUpEvent::KeyUpEvent() + : Event(event::KeyUp) + , code(0) + , count(0) + { + } + + KeyCharEvent::KeyCharEvent() + : Event(event::KeyChar) + , value() + , count(0) + { + } + + WindowMovedEvent::WindowMovedEvent() + : Event(event::WindowMoved) + , x(0) + , y(0) + { + } + + WindowResizedEvent::WindowResizedEvent() + : Event(event::WindowResized) + , width(0) + , height(0) + { + } + + WindowFocusChangedEvent::WindowFocusChangedEvent() + : Event(event::WindowFocusChanged) + , focus(false) + { + } + + WindowTitleChangedEvent::WindowTitleChangedEvent() + : Event(event::WindowTitleChanged) + , title() + { + } + + WindowClosedEvent::WindowClosedEvent() + : Event(event::WindowClosed) + { + } + +} diff --git a/src/kiwano/core/Event.h b/src/kiwano/core/Event.h new file mode 100644 index 00000000..c5e64394 --- /dev/null +++ b/src/kiwano/core/Event.h @@ -0,0 +1,272 @@ +// Copyright (c) 2016-2018 Kiwano - Nomango +// +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files (the "Software"), to deal +// in the Software without restriction, including without limitation the rights +// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +// copies of the Software, and to permit persons to whom the Software is +// furnished to do so, subject to the following conditions: +// +// The above copyright notice and this permission notice shall be included in +// all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +// THE SOFTWARE. + +#pragma once +#include +#include +#include + +namespace kiwano +{ + class Actor; + + // 事件类型 + struct EventType + { + inline EventType() : hash(0), type() + { + } + + inline EventType(String const& type) : hash(0), type(type) + { + hash = type.hash(); + } + + inline bool operator==(const EventType& rhs) const + { + return hash == rhs.hash && type == rhs.type; + } + + size_t hash; + String type; + }; + + + namespace event + { + // 鼠标事件 + extern EventType MouseMove; // 移动 + extern EventType MouseDown; // 鼠标按下 + extern EventType MouseUp; // 鼠标抬起 + extern EventType MouseWheel; // 滚轮滚动 + extern EventType MouseHover; // 鼠标移入 + extern EventType MouseOut; // 鼠标移出 + extern EventType MouseClick; // 鼠标点击 + + // 按键事件 + extern EventType KeyDown; // 按键按下 + extern EventType KeyUp; // 按键抬起 + extern EventType KeyChar; // 输出字符 + + // 窗口消息 + extern EventType WindowMoved; // 窗口移动 + extern EventType WindowResized; // 窗口大小变化 + extern EventType WindowFocusChanged; // 获得或失去焦点 + extern EventType WindowTitleChanged; // 标题变化 + extern EventType WindowClosed; // 窗口被关闭 + } + + + // 事件 + class KGE_API Event + { + public: + const EventType type; + + Event(EventType const& type); + virtual ~Event(); + + template < + typename _Ty, + typename = typename std::enable_if::value, int>::type + > + inline const _Ty* SafeCast() const + { + const _Ty* ptr = dynamic_cast(this); + if (ptr) + { + return ptr; + } + return nullptr; + } + + template < + typename _Ty, + typename = typename std::enable_if::value, int>::type + > + inline _Ty* SafeCast() + { + return const_cast<_Ty*>(const_cast(this)->SafeCast<_Ty>()); + } + }; + + // 鼠标事件 + class KGE_API MouseEvent + : public Event + { + public: + Point pos; + bool left_btn_down; // 左键是否按下 + bool right_btn_down; // 右键是否按下 + Actor* target; + + MouseEvent(EventType const& type); + }; + + // 鼠标移动事件 + class KGE_API MouseMoveEvent + : public MouseEvent + { + public: + MouseButton::Value button; + + MouseMoveEvent(); + }; + + // 鼠标按键按下事件 + class KGE_API MouseDownEvent + : public MouseEvent + { + public: + MouseButton::Value button; + + MouseDownEvent(); + }; + + // 鼠标按键抬起事件 + class KGE_API MouseUpEvent + : public MouseEvent + { + public: + MouseButton::Value button; + + MouseUpEvent(); + }; + + // 鼠标点击事件 + class KGE_API MouseClickEvent + : public MouseEvent + { + public: + MouseButton::Value button; + + MouseClickEvent(); + }; + + // 鼠标移入事件 + class KGE_API MouseHoverEvent + : public MouseEvent + { + public: + MouseHoverEvent(); + }; + + // 鼠标移出事件 + class KGE_API MouseOutEvent + : public MouseEvent + { + public: + MouseOutEvent(); + }; + + // 鼠标滚轮事件 + class KGE_API MouseWheelEvent + : public MouseEvent + { + public: + float wheel; + + MouseWheelEvent(); + }; + + // 键盘按下事件 + class KGE_API KeyDownEvent + : public Event + { + public: + KeyCode::Value code; + int count; + + KeyDownEvent(); + }; + + // 键盘抬起事件 + class KGE_API KeyUpEvent + : public Event + { + public: + KeyCode::Value code; + int count; + + KeyUpEvent(); + }; + + // 键盘字符事件 + class KGE_API KeyCharEvent + : public Event + { + public: + char value; + int count; + + KeyCharEvent(); + }; + + // 窗口移动事件 + class KGE_API WindowMovedEvent + : public Event + { + public: + int x; + int y; + + WindowMovedEvent(); + }; + + // 窗口大小变化事件 + class KGE_API WindowResizedEvent + : public Event + { + public: + int width; + int height; + + WindowResizedEvent(); + }; + + // 窗口焦点变化事件 + class KGE_API WindowFocusChangedEvent + : public Event + { + public: + bool focus; + + WindowFocusChangedEvent(); + }; + + // 窗口标题更改事件 + class KGE_API WindowTitleChangedEvent + : public Event + { + public: + String title; + + WindowTitleChangedEvent(); + }; + + // 窗口关闭事件 + class KGE_API WindowClosedEvent + : public Event + { + public: + WindowClosedEvent(); + }; + +} diff --git a/src/kiwano/base/EventDispatcher.cpp b/src/kiwano/core/EventDispatcher.cpp similarity index 82% rename from src/kiwano/base/EventDispatcher.cpp rename to src/kiwano/core/EventDispatcher.cpp index ee5d6673..222bd4b7 100644 --- a/src/kiwano/base/EventDispatcher.cpp +++ b/src/kiwano/core/EventDispatcher.cpp @@ -18,12 +18,12 @@ // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. -#include -#include +#include +#include namespace kiwano { - void EventDispatcher::Dispatch(Event& evt) + void EventDispatcher::Dispatch(Event* evt) { if (listeners_.empty()) return; @@ -33,7 +33,7 @@ namespace kiwano { next = listener->next_item(); - if (listener->IsRunning() && listener->type_ == evt.type) + if (listener->IsRunning() && listener->type_ == evt->type) { listener->callback_(evt); } @@ -56,9 +56,15 @@ namespace kiwano return listener; } - EventListener* EventDispatcher::AddListener(EventType type, EventListener::Callback callback, String const& name) + EventListener* EventDispatcher::AddListener(String const& name, EventType type, EventListener::Callback callback) { - EventListenerPtr listener = new EventListener(type, callback, name); + EventListenerPtr listener = new EventListener(name, type, callback); + return AddListener(listener); + } + + EventListener* EventDispatcher::AddListener(EventType type, EventListener::Callback callback) + { + EventListenerPtr listener = new EventListener(type, callback); return AddListener(listener); } @@ -98,7 +104,7 @@ namespace kiwano } } - void EventDispatcher::StartListeners(uint32_t type) + void EventDispatcher::StartListeners(const EventType& type) { for (auto listener = listeners_.first_item(); listener; listener = listener->next_item()) { @@ -109,7 +115,7 @@ namespace kiwano } } - void EventDispatcher::StopListeners(uint32_t type) + void EventDispatcher::StopListeners(const EventType& type) { for (auto listener = listeners_.first_item(); listener; listener = listener->next_item()) { @@ -120,7 +126,7 @@ namespace kiwano } } - void EventDispatcher::RemoveListeners(uint32_t type) + void EventDispatcher::RemoveListeners(const EventType& type) { EventListenerPtr next; for (auto listener = listeners_.first_item(); listener; listener = next) diff --git a/src/kiwano/base/EventDispatcher.h b/src/kiwano/core/EventDispatcher.h similarity index 85% rename from src/kiwano/base/EventDispatcher.h rename to src/kiwano/core/EventDispatcher.h index 31f83298..49147faf 100644 --- a/src/kiwano/base/EventDispatcher.h +++ b/src/kiwano/core/EventDispatcher.h @@ -19,7 +19,7 @@ // THE SOFTWARE. #pragma once -#include +#include namespace kiwano { @@ -40,9 +40,15 @@ namespace kiwano // 添加监听器 EventListener* AddListener( + String const& name, EventType type, - EventListener::Callback callback, - String const& name = L"" + EventListener::Callback callback + ); + + // 添加监听器 + EventListener* AddListener( + EventType type, + EventListener::Callback callback ); // 启动监听器 @@ -62,20 +68,20 @@ namespace kiwano // 启动监听器 void StartListeners( - uint32_t type + const EventType& type ); // 停止监听器 void StopListeners( - uint32_t type + const EventType& type ); // 移除监听器 void RemoveListeners( - uint32_t type + const EventType& type ); - virtual void Dispatch(Event& evt); + virtual void Dispatch(Event* evt); protected: Listeners listeners_; diff --git a/src/kiwano/base/EventListener.cpp b/src/kiwano/core/EventListener.cpp similarity index 79% rename from src/kiwano/base/EventListener.cpp rename to src/kiwano/core/EventListener.cpp index e8ffcb6b..1250a80e 100644 --- a/src/kiwano/base/EventListener.cpp +++ b/src/kiwano/core/EventListener.cpp @@ -19,14 +19,26 @@ // THE SOFTWARE. #pragma once -#include +#include namespace kiwano { - EventListener::EventListener(EventType type, Callback const & callback, String const & name) + EventListener::EventListener() + : type_() + , callback_() + , running_(true) + { + } + + EventListener::EventListener(EventType type, Callback const& callback) : type_(type) , callback_(callback) , running_(true) + { + } + + EventListener::EventListener(String const& name, EventType type, Callback const& callback) + : EventListener(type, callback) { SetName(name); } diff --git a/src/kiwano/core/EventListener.h b/src/kiwano/core/EventListener.h new file mode 100644 index 00000000..5c8f51c2 --- /dev/null +++ b/src/kiwano/core/EventListener.h @@ -0,0 +1,115 @@ +// Copyright (c) 2016-2018 Kiwano - Nomango +// +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files (the "Software"), to deal +// in the Software without restriction, including without limitation the rights +// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +// copies of the Software, and to permit persons to whom the Software is +// furnished to do so, subject to the following conditions: +// +// The above copyright notice and this permission notice shall be included in +// all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +// THE SOFTWARE. + +#pragma once +#include +#include +#include +#include + +namespace kiwano +{ + class EventDispatcher; + + KGE_DECLARE_SMART_PTR(EventListener); + + // 事件监听器 + class KGE_API EventListener + : public ObjectBase + , protected IntrusiveListItem + { + friend class EventDispatcher; + friend IntrusiveList; + + public: + using Callback = Function; + + EventListener(); + + EventListener( + EventType type, + Callback const& callback + ); + + EventListener( + String const& name, + EventType type, + Callback const& callback + ); + + virtual ~EventListener(); + + void Start(); + + void Stop(); + + bool IsRunning() const; + + Callback GetCallback() const; + + void SetCallback(Callback const& cb); + + EventType const& GetEventType() const; + + void SetEventType(EventType const& type); + + protected: + bool running_; + EventType type_; + Callback callback_; + }; + + + inline void EventListener::Start() + { + running_ = true; + } + + inline void EventListener::Stop() + { + running_ = false; + } + + inline bool EventListener::IsRunning() const + { + return running_; + } + + inline EventListener::Callback EventListener::GetCallback() const + { + return callback_; + } + + inline void EventListener::SetCallback(Callback const& cb) + { + callback_ = cb; + } + + inline EventType const& EventListener::GetEventType() const + { + return type_; + } + + inline void EventListener::SetEventType(EventType const& type) + { + type_ = type; + } + +} diff --git a/src/kiwano/core/Library.cpp b/src/kiwano/core/Library.cpp new file mode 100644 index 00000000..1f4c0c94 --- /dev/null +++ b/src/kiwano/core/Library.cpp @@ -0,0 +1,68 @@ +// Copyright (c) 2016-2018 Kiwano - Nomango +// +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files (the "Software"), to deal +// in the Software without restriction, including without limitation the rights +// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +// copies of the Software, and to permit persons to whom the Software is +// furnished to do so, subject to the following conditions: +// +// The above copyright notice and this permission notice shall be included in +// all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +// THE SOFTWARE. + +#include + +namespace kiwano +{ + + Library::Library() + : instance_(nullptr) + { + } + + Library::Library(String const& lib) + : instance_(nullptr) + { + Load(lib); + } + + Library::~Library() + { + Free(); + } + + bool Library::Load(String const& lib) + { + instance_ = ::LoadLibraryW(lib.c_str()); + return IsValid(); + } + + bool Library::IsValid() const + { + return instance_ != nullptr; + } + + void Library::Free() + { + if (instance_) + { + ::FreeLibrary(instance_); + instance_ = nullptr; + } + } + + FARPROC Library::GetProcess(String const& proc_name) + { + KGE_ASSERT(instance_ != nullptr); + return GetProcAddress(instance_, wide_to_string(proc_name).c_str()); + } + +} diff --git a/src/kiwano/base/EventListener.h b/src/kiwano/core/Library.h similarity index 60% rename from src/kiwano/base/EventListener.h rename to src/kiwano/core/Library.h index 42317aae..64aebf83 100644 --- a/src/kiwano/base/EventListener.h +++ b/src/kiwano/core/Library.h @@ -19,45 +19,35 @@ // THE SOFTWARE. #pragma once -#include -#include -#include -#include +#include +#include namespace kiwano { - class EventDispatcher; - - KGE_DECLARE_SMART_PTR(EventListener); - - // 事件监听器 - class KGE_API EventListener - : public ObjectBase - , protected IntrusiveListItem + // DLL 库 + class KGE_API Library { - friend class EventDispatcher; - friend IntrusiveList; - public: - using Callback = Function; + Library(); + Library(String const& lib); + virtual ~Library(); - EventListener( - EventType type, - Callback const& callback, - String const& name = L"" - ); + bool Load(String const& lib); - virtual ~EventListener(); + bool IsValid() const; - inline void Start() { running_ = true; } + void Free(); - inline void Stop() { running_ = true; } + FARPROC GetProcess(String const& proc_name); - inline bool IsRunning() const { return running_; } + template + inline _Proc GetProcess(String const& proc_name) + { + return reinterpret_cast<_Proc>(GetProcess(proc_name)); + } - protected: - bool running_; - EventType type_; - Callback callback_; + private: + HMODULE instance_; }; + } diff --git a/src/kiwano/base/Logger.cpp b/src/kiwano/core/Logger.cpp similarity index 99% rename from src/kiwano/base/Logger.cpp rename to src/kiwano/core/Logger.cpp index 7454ab2a..cadc07de 100644 --- a/src/kiwano/base/Logger.cpp +++ b/src/kiwano/core/Logger.cpp @@ -21,7 +21,7 @@ #include #include -#include +#include namespace { diff --git a/src/kiwano/base/Logger.h b/src/kiwano/core/Logger.h similarity index 99% rename from src/kiwano/base/Logger.h rename to src/kiwano/core/Logger.h index d7f7a3c7..9f4732e9 100644 --- a/src/kiwano/base/Logger.h +++ b/src/kiwano/core/Logger.h @@ -24,7 +24,7 @@ #include #include -#include +#include #ifndef KGE_LOG # ifdef KGE_DEBUG diff --git a/src/kiwano/base/ObjectBase.cpp b/src/kiwano/core/ObjectBase.cpp similarity index 98% rename from src/kiwano/base/ObjectBase.cpp rename to src/kiwano/core/ObjectBase.cpp index f0fc6729..ce4b7ff3 100644 --- a/src/kiwano/base/ObjectBase.cpp +++ b/src/kiwano/core/ObjectBase.cpp @@ -19,8 +19,8 @@ // THE SOFTWARE. #include -#include -#include +#include +#include namespace kiwano { diff --git a/src/kiwano/base/ObjectBase.h b/src/kiwano/core/ObjectBase.h similarity index 95% rename from src/kiwano/base/ObjectBase.h rename to src/kiwano/core/ObjectBase.h index 8f4d9b94..88a87500 100644 --- a/src/kiwano/base/ObjectBase.h +++ b/src/kiwano/core/ObjectBase.h @@ -20,9 +20,9 @@ #pragma once #include -#include -#include -#include +#include +#include +#include namespace kiwano { diff --git a/src/kiwano/base/RefCounter.hpp b/src/kiwano/core/RefCounter.hpp similarity index 95% rename from src/kiwano/base/RefCounter.hpp rename to src/kiwano/core/RefCounter.hpp index e4c7eb6e..14bfa5d2 100644 --- a/src/kiwano/base/RefCounter.hpp +++ b/src/kiwano/core/RefCounter.hpp @@ -20,12 +20,12 @@ #pragma once #include -#include +#include namespace kiwano { class KGE_API RefCounter - : protected core::noncopyable + : protected common::noncopyable { public: // 增加引用计数 diff --git a/src/kiwano/base/Resource.cpp b/src/kiwano/core/Resource.cpp similarity index 97% rename from src/kiwano/base/Resource.cpp rename to src/kiwano/core/Resource.cpp index 6dfc3ceb..f2c7c8af 100644 --- a/src/kiwano/base/Resource.cpp +++ b/src/kiwano/core/Resource.cpp @@ -20,8 +20,8 @@ #include -#include -#include +#include +#include namespace kiwano { diff --git a/src/kiwano/base/Resource.h b/src/kiwano/core/Resource.h similarity index 98% rename from src/kiwano/base/Resource.h rename to src/kiwano/core/Resource.h index 53aed99c..f81dc4d1 100644 --- a/src/kiwano/base/Resource.h +++ b/src/kiwano/core/Resource.h @@ -20,7 +20,7 @@ #pragma once #include -#include +#include namespace kiwano { diff --git a/src/kiwano/base/SmartPtr.hpp b/src/kiwano/core/SmartPtr.hpp similarity index 90% rename from src/kiwano/base/SmartPtr.hpp rename to src/kiwano/core/SmartPtr.hpp index 09a60358..15edf87d 100644 --- a/src/kiwano/base/SmartPtr.hpp +++ b/src/kiwano/core/SmartPtr.hpp @@ -19,8 +19,8 @@ // THE SOFTWARE. #pragma once -#include -#include +#include +#include namespace kiwano { @@ -38,7 +38,7 @@ namespace kiwano }; template - using SmartPtr = core::intrusive_ptr<_Ty, DefaultIntrusivePtrManager>; + using SmartPtr = common::intrusive_ptr<_Ty, DefaultIntrusivePtrManager>; } diff --git a/src/kiwano/base/Timer.cpp b/src/kiwano/core/Timer.cpp similarity index 98% rename from src/kiwano/base/Timer.cpp rename to src/kiwano/core/Timer.cpp index 66792e5c..39efeb99 100644 --- a/src/kiwano/base/Timer.cpp +++ b/src/kiwano/core/Timer.cpp @@ -18,7 +18,7 @@ // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. -#include +#include namespace kiwano { diff --git a/src/kiwano/base/Timer.h b/src/kiwano/core/Timer.h similarity index 96% rename from src/kiwano/base/Timer.h rename to src/kiwano/core/Timer.h index 2ab574a8..0ac216cb 100644 --- a/src/kiwano/base/Timer.h +++ b/src/kiwano/core/Timer.h @@ -21,8 +21,8 @@ #pragma once #include -#include -#include +#include +#include namespace kiwano { diff --git a/src/kiwano/base/TimerManager.cpp b/src/kiwano/core/TimerManager.cpp similarity index 97% rename from src/kiwano/base/TimerManager.cpp rename to src/kiwano/core/TimerManager.cpp index 67885689..77c5ca2f 100644 --- a/src/kiwano/base/TimerManager.cpp +++ b/src/kiwano/core/TimerManager.cpp @@ -18,8 +18,8 @@ // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. -#include -#include +#include +#include namespace kiwano { diff --git a/src/kiwano/base/TimerManager.h b/src/kiwano/core/TimerManager.h similarity index 98% rename from src/kiwano/base/TimerManager.h rename to src/kiwano/core/TimerManager.h index c1b989ae..3b3a5d8b 100644 --- a/src/kiwano/base/TimerManager.h +++ b/src/kiwano/core/TimerManager.h @@ -19,7 +19,7 @@ // THE SOFTWARE. #pragma once -#include +#include namespace kiwano { diff --git a/src/kiwano/base/keys.hpp b/src/kiwano/core/keys.h similarity index 100% rename from src/kiwano/base/keys.hpp rename to src/kiwano/core/keys.h diff --git a/src/kiwano/core/time.cpp b/src/kiwano/core/time.cpp new file mode 100644 index 00000000..568aff2b --- /dev/null +++ b/src/kiwano/core/time.cpp @@ -0,0 +1,424 @@ +// Copyright (c) 2016-2018 Kiwano - Nomango +// +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files (the "Software"), to deal +// in the Software without restriction, including without limitation the rights +// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +// copies of the Software, and to permit persons to whom the Software is +// furnished to do so, subject to the following conditions: +// +// The above copyright notice and this permission notice shall be included in +// all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +// THE SOFTWARE. + +#include +#include + +#include +#include + +namespace kiwano +{ + //------------------------------------------------------- + // Time + //------------------------------------------------------- + + Time::Time() + : dur_(0) + { + } + + Time::Time(long dur) + : dur_(dur) + { + } + + const Time Time::operator+(const Duration & dur) const + { + return Time{ dur_ + dur.Milliseconds() }; + } + + const Time Time::operator-(const Duration & dur) const + { + return Time{ dur_ - dur.Milliseconds() }; + } + + Time & Time::operator+=(const Duration & other) + { + dur_ += other.Milliseconds(); + return (*this); + } + + Time & Time::operator-=(const Duration &other) + { + dur_ -= other.Milliseconds(); + return (*this); + } + + const Duration Time::operator-(const Time & other) const + { + return Duration(dur_ - other.dur_); + } + + Time Time::Now() noexcept + { + static LARGE_INTEGER freq = {}; + if (freq.QuadPart == 0LL) + { + // the Function will always succceed on systems that run Windows XP or later + QueryPerformanceFrequency(&freq); + } + + LARGE_INTEGER count; + QueryPerformanceCounter(&count); + + const long long whole = (count.QuadPart / freq.QuadPart) * 1000LL; + const long long part = (count.QuadPart % freq.QuadPart) * 1000LL / freq.QuadPart; + return Time{ static_cast(whole + part) }; + } + + + //------------------------------------------------------- + // Duration + //------------------------------------------------------- + + const Duration Duration::Ms = 1L; + const Duration Duration::Second = 1000 * Duration::Ms; + const Duration Duration::Minute = 60 * Duration::Second; + const Duration Duration::Hour = 60 * Duration::Minute; + + namespace + { + const auto duration_regex = std::wregex(LR"(^[-+]?([0-9]*(\.[0-9]*)?(h|m|s|ms)+)+$)"); + + typedef std::unordered_map UnitMap; + const auto unit_map = UnitMap + { + {L"ms", Duration::Ms}, + {L"s", Duration::Second}, + {L"m", Duration::Minute}, + {L"h", Duration::Hour} + }; + } + + Duration::Duration() + : milliseconds_(0) + { + } + + Duration::Duration(long milliseconds) + : milliseconds_(milliseconds) + { + } + + float Duration::Seconds() const + { + long sec = milliseconds_ / Second.milliseconds_; + long ms = milliseconds_ % Second.milliseconds_; + return static_cast(sec) + static_cast(ms) / 1000.f; + } + + float Duration::Minutes() const + { + long min = milliseconds_ / Minute.milliseconds_; + long ms = milliseconds_ % Minute.milliseconds_; + return static_cast(min) + static_cast(ms) / (60 * 1000.f); + } + + float Duration::Hours() const + { + long hour = milliseconds_ / Hour.milliseconds_; + long ms = milliseconds_ % Hour.milliseconds_; + return static_cast(hour) + static_cast(ms) / (60 * 60 * 1000.f); + } + + String Duration::ToString() const + { + if (IsZero()) + { + return String(L"0s"); + } + + String result; + long total_ms = milliseconds_; + if (total_ms < 0) + { + result.append(L"-"); + total_ms = -total_ms; + } + + long hour = total_ms / Hour.milliseconds_; + long min = total_ms / Minute.milliseconds_ - hour * 60; + long sec = total_ms / Second.milliseconds_ - (hour * 60 * 60 + min * 60); + long ms = total_ms % Second.milliseconds_; + + if (hour) + { + result.append(String::parse(hour)).append(L"h"); + result.append(String::parse(min)).append(L"m"); + } + else if(min) + { + result.append(String::parse(min)).append(L"m"); + } + + if (ms != 0) + { + result.append(String::parse(static_cast(sec) + static_cast(ms) / 1000.f)) + .append(L"s"); + } + else if (sec != 0) + { + result.append(String::parse(sec)).append(L"s"); + } + return result; + } + + bool Duration::operator==(const Duration & other) const + { + return milliseconds_ == other.milliseconds_; + } + + bool Duration::operator!=(const Duration & other) const + { + return milliseconds_ != other.milliseconds_; + } + + bool Duration::operator>(const Duration & other) const + { + return milliseconds_ > other.milliseconds_; + } + + bool Duration::operator>=(const Duration & other) const + { + return milliseconds_ >= other.milliseconds_; + } + + bool Duration::operator<(const Duration & other) const + { + return milliseconds_ < other.milliseconds_; + } + + bool Duration::operator<=(const Duration & other) const + { + return milliseconds_ <= other.milliseconds_; + } + + float Duration::operator/(const Duration & other) const + { + return static_cast(milliseconds_) / other.milliseconds_; + } + + const Duration Duration::operator+(const Duration & other) const + { + return Duration(milliseconds_ + other.milliseconds_); + } + + const Duration Duration::operator-(const Duration & other) const + { + return Duration(milliseconds_ - other.milliseconds_); + } + + const Duration Duration::operator-() const + { + return Duration(-milliseconds_); + } + + const Duration Duration::operator*(int val) const + { + return Duration(milliseconds_ * val); + } + + const Duration Duration::operator*(unsigned long long val) const + { + return Duration(static_cast(milliseconds_ * val)); + } + + const Duration Duration::operator*(float val) const + { + return Duration(static_cast(milliseconds_ * val)); + } + + const Duration Duration::operator*(double val) const + { + return Duration(static_cast(milliseconds_ * val)); + } + + const Duration Duration::operator*(long double val) const + { + return Duration(static_cast(milliseconds_ * val)); + } + + const Duration Duration::operator/(int val) const + { + return Duration(milliseconds_ / val); + } + + const Duration Duration::operator/(float val) const + { + return Duration(static_cast(milliseconds_ / val)); + } + + const Duration Duration::operator/(double val) const + { + return Duration(static_cast(milliseconds_ / val)); + } + + Duration & Duration::operator+=(const Duration &other) + { + milliseconds_ += other.milliseconds_; + return (*this); + } + + Duration & Duration::operator-=(const Duration &other) + { + milliseconds_ -= other.milliseconds_; + return (*this); + } + + Duration & Duration::operator*=(int val) + { + milliseconds_ *= val; + return (*this); + } + + Duration & Duration::operator/=(int val) + { + milliseconds_ = static_cast(milliseconds_ / val); + return (*this); + } + + Duration & Duration::operator*=(float val) + { + milliseconds_ = static_cast(milliseconds_ * val); + return (*this); + } + + Duration & Duration::operator/=(float val) + { + milliseconds_ = static_cast(milliseconds_ / val); + return (*this); + } + + Duration & Duration::operator*=(double val) + { + milliseconds_ = static_cast(milliseconds_ * val); + return (*this); + } + + Duration & Duration::operator/=(double val) + { + milliseconds_ = static_cast(milliseconds_ / val); + return (*this); + } + + const Duration operator*(int val, const Duration & dur) + { + return dur * val; + } + + const Duration operator/(int val, const Duration & dur) + { + return dur / val; + } + + const Duration operator*(float val, const Duration & dur) + { + return dur * val; + } + + const Duration operator/(float val, const Duration & dur) + { + return dur / val; + } + + const Duration operator*(double val, const Duration & dur) + { + return dur * val; + } + + const Duration operator/(double val, const Duration & dur) + { + return dur / val; + } + + const Duration operator*(long double val, const Duration & dur) + { + return dur * val; + } + + Duration Duration::Parse(const String& str) + { + bool negative = false; + size_t len = str.length(); + size_t pos = 0; + Duration ret; + + if (!std::regex_match(str.c_str(), duration_regex)) + { + KGE_ERROR_LOG(L"Duration::Parse failed, invalid duration"); + return ret; + } + + if (str.empty() || str == L"0") { return ret; } + + // 符号位 + if (str[0] == L'-' || str[0] == L'+') + { + negative = (str[0] == L'-'); + pos++; + } + + while (pos < len) + { + // 数值 + size_t i = pos; + for (; i < len; ++i) + { + wchar_t ch = str[i]; + if (!(ch == L'.' || L'0' <= ch && ch <= L'9')) + { + break; + } + } + + String num_str = str.substr(pos, i - pos); + pos = i; + + KGE_ASSERT(!(num_str.empty() || num_str == L".") && "Duration::Parse failed, invalid duration"); + + // 单位 + for (; i < len; ++i) + { + wchar_t ch = str[i]; + if (ch == L'.' || L'0' <= ch && ch <= L'9') + { + break; + } + } + + String unit_str = str.substr(pos, i - pos); + pos = i; + + KGE_ASSERT(unit_map.find(unit_str) != unit_map.end() && "Duration::Parse failed, invalid duration"); + + double num = std::wcstod(num_str.c_str(), nullptr); + Duration unit = unit_map.at(unit_str); + ret += unit * num; + } + + if (negative) + { + ret = -ret; + } + return ret; + } + +} diff --git a/src/kiwano/core/time.h b/src/kiwano/core/time.h new file mode 100644 index 00000000..f6c47257 --- /dev/null +++ b/src/kiwano/core/time.h @@ -0,0 +1,225 @@ +// Copyright (c) 2016-2018 Kiwano - Nomango +// +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files (the "Software"), to deal +// in the Software without restriction, including without limitation the rights +// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +// copies of the Software, and to permit persons to whom the Software is +// furnished to do so, subject to the following conditions: +// +// The above copyright notice and this permission notice shall be included in +// all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +// THE SOFTWARE. + +#pragma once +#include +#include + +namespace kiwano +{ + // 时间段 + // + // 时间段表示法: + // 5 秒: time::Second * 5 + // 1.5 小时: time::Hour * 1.5 + // 3 小时 45 分 15 秒: time::Hour * 3 + time::Minute * 45 + time::Second * 15 + // 在 VS2015 及更高版本可以使用 time literals: + // 5 秒: 5_s + // 1.5 小时: 1.5_h + // 3 小时 45 分 15 秒: 3_h + 45_m + 15_s + // + struct KGE_API Duration + { + Duration(); + + Duration( + long milliseconds + ); + + // 转化为毫秒 + long Milliseconds() const; + + // 转化为秒 + float Seconds() const; + + // 转化为分钟 + float Minutes() const; + + // 转化为小时 + float Hours() const; + + // 时长是否是零 + bool IsZero() const; + + void SetMilliseconds(long ms); + + void SetSeconds(float seconds); + + void SetMinutes(float minutes); + + void SetHours(float hours); + + // 转为字符串 + String ToString() const; + + bool operator== (const Duration &) const; + bool operator!= (const Duration &) const; + bool operator> (const Duration &) const; + bool operator>= (const Duration &) const; + bool operator< (const Duration &) const; + bool operator<= (const Duration &) const; + + float operator / (const Duration &) const; + + const Duration operator + (const Duration &) const; + const Duration operator - (const Duration &) const; + const Duration operator - () const; + const Duration operator * (int) const; + const Duration operator * (unsigned long long) const; + const Duration operator * (float) const; + const Duration operator * (double) const; + const Duration operator * (long double) const; + const Duration operator / (int) const; + const Duration operator / (float) const; + const Duration operator / (double) const; + + Duration& operator += (const Duration &); + Duration& operator -= (const Duration &); + Duration& operator *= (int); + Duration& operator *= (float); + Duration& operator *= (double); + Duration& operator /= (int); + Duration& operator /= (float); + Duration& operator /= (double); + + friend const Duration operator* (int, const Duration &); + friend const Duration operator* (float, const Duration &); + friend const Duration operator* (double, const Duration &); + friend const Duration operator* (long double, const Duration &); + friend const Duration operator/ (int, const Duration &); + friend const Duration operator/ (float, const Duration &); + friend const Duration operator/ (double, const Duration &); + + // 时间段格式化 + // + // 时间段字符串允许是有符号的浮点数, 并且带有时间单位后缀 + // 例如: "300ms", "-1.5h", "2h45m" + // 允许的时间单位有 "ms", "s", "m", "h" + static Duration Parse(const String& parse_str); + + static const Duration Ms; // 毫秒 + static const Duration Second; // 秒 + static const Duration Minute; // 分钟 + static const Duration Hour; // 小时 + + private: + long milliseconds_; + }; + + + // 时间 + // + // 获取当前时间: Time now = Time::Now(); + // 两时间相减, 得到一个 Duration 对象, 例如: + // Time t1, t2; + // int ms = (t2 - t1).Milliseconds(); // 获取两时间相差的毫秒数 + // + struct KGE_API Time + { + Time(); + + // 是否是零时 + bool IsZero() const; + + const Duration operator -(const Time&) const; + + const Time operator +(const Duration &) const; + const Time operator -(const Duration &) const; + + Time& operator +=(const Duration &); + Time& operator -=(const Duration &); + + // 获取当前时间 + // 由于该时间点基于系统启动时间开始计算, 所以无法格式化该时间, + // 也无法获得该时间的 Unix 时间戳 + static Time Now() noexcept; + + private: + Time(long ms); + + private: + long dur_; + }; + + + inline long Duration::Milliseconds() const { return milliseconds_; } + + inline bool Duration::IsZero() const { return milliseconds_ == 0LL; } + + inline void Duration::SetMilliseconds(long ms) { milliseconds_ = ms; } + + inline void Duration::SetSeconds(float seconds) { milliseconds_ = static_cast(seconds * 1000.f); } + + inline void Duration::SetMinutes(float minutes) { milliseconds_ = static_cast(minutes * 60 * 1000.f); } + + inline void Duration::SetHours(float hours) { milliseconds_ = static_cast(hours * 60 * 60 * 1000.f); } + + inline bool Time::IsZero() const { return dur_ == 0; } +} + +#if KGE_VS_VER > KGE_VS_2013 + +namespace kiwano +{ + inline namespace literals + { + inline const kiwano::Duration operator "" _ms(long double val) + { + return kiwano::Duration::Ms * val; + } + + inline const kiwano::Duration operator "" _s(long double val) + { + return kiwano::Duration::Second * val; + } + + inline const kiwano::Duration operator "" _m(long double val) + { + return kiwano::Duration::Minute * val; + } + + inline const kiwano::Duration operator "" _h(long double val) + { + return kiwano::Duration::Hour * val; + } + + inline const kiwano::Duration operator "" _ms(unsigned long long val) + { + return kiwano::Duration::Ms * val; + } + + inline const kiwano::Duration operator "" _s(unsigned long long val) + { + return kiwano::Duration::Second * val; + } + + inline const kiwano::Duration operator "" _m(unsigned long long val) + { + return kiwano::Duration::Minute * val; + } + + inline const kiwano::Duration operator "" _h(unsigned long long val) + { + return kiwano::Duration::Hour * val; + } + } +} + +#endif diff --git a/src/kiwano/base/win32/ComPtr.hpp b/src/kiwano/core/win32/ComPtr.hpp similarity index 93% rename from src/kiwano/base/win32/ComPtr.hpp rename to src/kiwano/core/win32/ComPtr.hpp index 6d705861..0cc76527 100644 --- a/src/kiwano/base/win32/ComPtr.hpp +++ b/src/kiwano/core/win32/ComPtr.hpp @@ -20,7 +20,7 @@ #pragma once #include -#include +#include #include namespace kiwano @@ -42,6 +42,6 @@ namespace kiwano template< typename _Ty, typename = typename std::enable_if::value, int>::type> - using ComPtr = core::intrusive_ptr<_Ty, ComPtrManager>; + using ComPtr = common::intrusive_ptr<_Ty, ComPtrManager>; } diff --git a/src/kiwano/base/win32/helper.h b/src/kiwano/core/win32/helper.h similarity index 97% rename from src/kiwano/base/win32/helper.h rename to src/kiwano/core/win32/helper.h index bc8ea1f9..a731dc96 100644 --- a/src/kiwano/base/win32/helper.h +++ b/src/kiwano/core/win32/helper.h @@ -18,7 +18,7 @@ // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. -#include +#include #include <3rd-party/StackWalker/StackWalker.h> namespace kiwano diff --git a/src/kiwano/kiwano.h b/src/kiwano/kiwano.h index 9db500d8..f8b51499 100644 --- a/src/kiwano/kiwano.h +++ b/src/kiwano/kiwano.h @@ -29,19 +29,19 @@ // -// core +// common // -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include // @@ -72,23 +72,21 @@ // -// base +// core // -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include // @@ -129,6 +127,9 @@ // #include +#include +#include +#include #include @@ -136,7 +137,7 @@ // utils // -#include +#include #include #include diff --git a/src/kiwano/math/math.h b/src/kiwano/math/math.h index 79aa3cd4..775e204b 100644 --- a/src/kiwano/math/math.h +++ b/src/kiwano/math/math.h @@ -19,7 +19,7 @@ // THE SOFTWARE. #pragma once -#include +#include #include #include #include diff --git a/src/kiwano/math/scalar.h b/src/kiwano/math/scalar.h index 90a02471..e81edaa2 100644 --- a/src/kiwano/math/scalar.h +++ b/src/kiwano/math/scalar.h @@ -33,8 +33,8 @@ namespace kiwano inline float Sqrt(float val) { return ::sqrtf(val); } inline double Sqrt(double val) { return ::sqrt(val); } - inline float Pow(float base, float exponent) { return ::powf(base, exponent); } - inline double Pow(double base, double exponent) { return ::pow(base, exponent); } + inline float Pow(float core, float exponent) { return ::powf(core, exponent); } + inline double Pow(double core, double exponent) { return ::pow(core, exponent); } inline int Sign(int val) { return val < 0 ? -1 : 1; } inline float Sign(float val) { return val < 0 ? -1.f : 1.f; } diff --git a/src/kiwano/platform/Application.cpp b/src/kiwano/platform/Application.cpp index b88b3694..57f56e4b 100644 --- a/src/kiwano/platform/Application.cpp +++ b/src/kiwano/platform/Application.cpp @@ -22,9 +22,9 @@ #include #include -#include -#include -#include +#include +#include +#include #include #include @@ -261,7 +261,7 @@ namespace kiwano } } - void Application::DispatchEvent(Event& evt) + void Application::DispatchEvent(Event* evt) { for (auto c : event_comps_) { @@ -307,21 +307,29 @@ namespace kiwano case WM_SYSKEYUP: { bool down = msg == WM_KEYDOWN || msg == WM_SYSKEYDOWN; - Event evt(down ? Event::KeyDown : Event::KeyUp); - evt.key.code = static_cast(wparam); - evt.key.count = static_cast(lparam & 0xFF); - - app->DispatchEvent(evt); + if (down) + { + KeyDownEvent evt; + evt.code = static_cast(wparam); + evt.count = static_cast(lparam & 0xFF); + app->DispatchEvent(&evt); + } + else + { + KeyUpEvent evt; + evt.code = static_cast(wparam); + evt.count = static_cast(lparam & 0xFF); + app->DispatchEvent(&evt); + } } break; case WM_CHAR: { - Event evt(Event::Char); - evt.key.c = static_cast(wparam); - evt.key.count = static_cast(lparam & 0xFF); - - app->DispatchEvent(evt); + KeyCharEvent evt; + evt.value = static_cast(wparam); + evt.count = static_cast(lparam & 0xFF); + app->DispatchEvent(&evt); } break; @@ -337,23 +345,44 @@ namespace kiwano case WM_MOUSEMOVE: case WM_MOUSEWHEEL: { - Event evt; + auto UpdateMouseData = [&](MouseEvent* evt) + { + evt->pos = Point(static_cast(GET_X_LPARAM(lparam)), static_cast(GET_Y_LPARAM(lparam))); + evt->left_btn_down = !!(wparam & MK_LBUTTON); + evt->left_btn_down = !!(wparam & MK_RBUTTON); + }; - evt.mouse.x = static_cast(GET_X_LPARAM(lparam)); - evt.mouse.y = static_cast(GET_Y_LPARAM(lparam)); - evt.mouse.left_btn_down = !!(wparam & MK_LBUTTON); - evt.mouse.left_btn_down = !!(wparam & MK_RBUTTON); - - if (msg == WM_MOUSEMOVE) { evt.type = Event::MouseMove; } - else if (msg == WM_LBUTTONDOWN || msg == WM_RBUTTONDOWN || msg == WM_MBUTTONDOWN) { evt.type = Event::MouseBtnDown; } - else if (msg == WM_LBUTTONUP || msg == WM_RBUTTONUP || msg == WM_MBUTTONUP) { evt.type = Event::MouseBtnUp; } - else if (msg == WM_MOUSEWHEEL) { evt.type = Event::MouseWheel; evt.mouse.wheel = GET_WHEEL_DELTA_WPARAM(wparam) / (float)WHEEL_DELTA; } - - if (msg == WM_LBUTTONDOWN || msg == WM_LBUTTONUP) { evt.mouse.button = MouseButton::Left; } - else if (msg == WM_RBUTTONDOWN || msg == WM_RBUTTONUP) { evt.mouse.button = MouseButton::Right; } - else if (msg == WM_MBUTTONDOWN || msg == WM_MBUTTONUP) { evt.mouse.button = MouseButton::Middle; } - - app->DispatchEvent(evt); + if (msg == WM_MOUSEMOVE) + { + MouseMoveEvent evt; + UpdateMouseData(&evt); + app->DispatchEvent(&evt); + } + else if (msg == WM_LBUTTONDOWN || msg == WM_RBUTTONDOWN || msg == WM_MBUTTONDOWN) + { + MouseDownEvent evt; + UpdateMouseData(&evt); + if (msg == WM_LBUTTONDOWN) { evt.button = MouseButton::Left; } + else if (msg == WM_RBUTTONDOWN) { evt.button = MouseButton::Right; } + else if (msg == WM_MBUTTONDOWN) { evt.button = MouseButton::Middle; } + app->DispatchEvent(&evt); + } + else if (msg == WM_LBUTTONUP || msg == WM_RBUTTONUP || msg == WM_MBUTTONUP) + { + MouseDownEvent evt; + UpdateMouseData(&evt); + if (msg == WM_LBUTTONUP) { evt.button = MouseButton::Left; } + else if (msg == WM_RBUTTONUP) { evt.button = MouseButton::Right; } + else if (msg == WM_MBUTTONUP) { evt.button = MouseButton::Middle; } + app->DispatchEvent(&evt); + } + else if (msg == WM_MOUSEWHEEL) + { + MouseWheelEvent evt; + UpdateMouseData(&evt); + evt.wheel = GET_WHEEL_DELTA_WPARAM(wparam) / (float)WHEEL_DELTA; + app->DispatchEvent(&evt); + } } break; @@ -369,10 +398,10 @@ namespace kiwano Window::GetInstance()->UpdateWindowRect(); - Event evt(Event::WindowResized); - evt.window.width = LOWORD(lparam); - evt.window.height = HIWORD(lparam); - app->DispatchEvent(evt); + WindowResizedEvent evt; + evt.width = LOWORD(lparam); + evt.height = HIWORD(lparam); + app->DispatchEvent(&evt); } } break; @@ -382,10 +411,10 @@ namespace kiwano int x = (int)(short)LOWORD(lparam); int y = (int)(short)HIWORD(lparam); - Event evt(Event::WindowMoved); - evt.window.x = x; - evt.window.y = y; - app->DispatchEvent(evt); + WindowMovedEvent evt; + evt.x = x; + evt.y = y; + app->DispatchEvent(&evt); } break; @@ -395,9 +424,9 @@ namespace kiwano Window::GetInstance()->SetActive(active); - Event evt(Event::WindowFocusChanged); - evt.window.focus = active; - app->DispatchEvent(evt); + WindowFocusChangedEvent evt; + evt.focus = active; + app->DispatchEvent(&evt); } break; @@ -405,9 +434,9 @@ namespace kiwano { // KGE_LOG(L"Window title changed"); - Event evt(Event::WindowTitleChanged); - evt.window.title = reinterpret_cast(lparam); - app->DispatchEvent(evt); + WindowTitleChangedEvent evt; + evt.title = reinterpret_cast(lparam); + app->DispatchEvent(&evt); } break; @@ -437,8 +466,8 @@ namespace kiwano if (!app->OnClosing()) { - Event evt(Event::WindowClosed); - app->DispatchEvent(evt); + WindowClosedEvent evt; + app->DispatchEvent(&evt); return 0; } } diff --git a/src/kiwano/platform/Application.h b/src/kiwano/platform/Application.h index f1224b39..7f5280fa 100644 --- a/src/kiwano/platform/Application.h +++ b/src/kiwano/platform/Application.h @@ -19,11 +19,11 @@ // THE SOFTWARE. #pragma once -#include -#include -#include -#include -#include +#include +#include +#include +#include +#include #include namespace kiwano @@ -50,7 +50,7 @@ namespace kiwano // 应用 class KGE_API Application - : protected core::noncopyable + : protected common::noncopyable { public: Application(); @@ -91,7 +91,7 @@ namespace kiwano ); // 分发事件 - void DispatchEvent(Event& evt); + void DispatchEvent(Event* evt); // 在 Kiwano 主线程中执行函数 // 当在其他线程调用 Kiwano 函数时使用 diff --git a/src/kiwano/utils/FileSystem.cpp b/src/kiwano/platform/FileSystem.cpp similarity index 99% rename from src/kiwano/utils/FileSystem.cpp rename to src/kiwano/platform/FileSystem.cpp index 1d23d934..af2ad9c2 100644 --- a/src/kiwano/utils/FileSystem.cpp +++ b/src/kiwano/platform/FileSystem.cpp @@ -18,7 +18,7 @@ // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. -#include +#include #include namespace kiwano diff --git a/src/kiwano/utils/FileSystem.h b/src/kiwano/platform/FileSystem.h similarity index 98% rename from src/kiwano/utils/FileSystem.h rename to src/kiwano/platform/FileSystem.h index 3d41f129..7e9d47a3 100644 --- a/src/kiwano/utils/FileSystem.h +++ b/src/kiwano/platform/FileSystem.h @@ -19,7 +19,7 @@ // THE SOFTWARE. #pragma once -#include +#include namespace kiwano { diff --git a/src/kiwano/base/Input.cpp b/src/kiwano/platform/Input.cpp similarity index 98% rename from src/kiwano/base/Input.cpp rename to src/kiwano/platform/Input.cpp index 976c8f72..9803760c 100644 --- a/src/kiwano/base/Input.cpp +++ b/src/kiwano/platform/Input.cpp @@ -18,8 +18,8 @@ // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. -#include -#include +#include +#include #include // GET_X_LPARAM, GET_Y_LPARAM namespace kiwano diff --git a/src/kiwano/base/Input.h b/src/kiwano/platform/Input.h similarity index 95% rename from src/kiwano/base/Input.h rename to src/kiwano/platform/Input.h index 9cb9753c..5b17d98e 100644 --- a/src/kiwano/base/Input.h +++ b/src/kiwano/platform/Input.h @@ -20,10 +20,10 @@ #pragma once #include -#include +#include #include -#include -#include +#include +#include namespace kiwano { diff --git a/src/kiwano/base/Window.cpp b/src/kiwano/platform/Window.cpp similarity index 99% rename from src/kiwano/base/Window.cpp rename to src/kiwano/platform/Window.cpp index ff0f1f91..dff73d1e 100644 --- a/src/kiwano/base/Window.cpp +++ b/src/kiwano/platform/Window.cpp @@ -18,8 +18,8 @@ // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. -#include -#include +#include +#include #include #define WINDOW_FIXED_STYLE WS_OVERLAPPED | WS_CAPTION | WS_SYSMENU | WS_MINIMIZEBOX diff --git a/src/kiwano/base/Window.h b/src/kiwano/platform/Window.h similarity index 98% rename from src/kiwano/base/Window.h rename to src/kiwano/platform/Window.h index d8ace2f0..d2279335 100644 --- a/src/kiwano/base/Window.h +++ b/src/kiwano/platform/Window.h @@ -20,7 +20,7 @@ #pragma once #include -#include +#include #include namespace kiwano diff --git a/src/kiwano/platform/modules.cpp b/src/kiwano/platform/modules.cpp index 0f3dac51..dd5d57dd 100644 --- a/src/kiwano/platform/modules.cpp +++ b/src/kiwano/platform/modules.cpp @@ -19,25 +19,21 @@ // THE SOFTWARE. #include -#include +#include namespace kiwano { namespace modules { Shlwapi::Shlwapi() - : shlwapi(nullptr) + : shlwapi() , PathFileExistsW(nullptr) , SHCreateMemStream(nullptr) { - shlwapi = LoadLibraryW(L"shlwapi.dll"); - if (shlwapi) + if (shlwapi.Load(L"shlwapi.dll")) { - PathFileExistsW = (PFN_PathFileExistsW) - GetProcAddress(shlwapi, "PathFileExistsW"); - - SHCreateMemStream = (PFN_SHCreateMemStream) - GetProcAddress(shlwapi, "SHCreateMemStream"); + PathFileExistsW = shlwapi.GetProcess(L"PathFileExistsW"); + SHCreateMemStream = shlwapi.GetProcess(L"SHCreateMemStream"); } else { diff --git a/src/kiwano/platform/modules.h b/src/kiwano/platform/modules.h index 6a5bf47b..cbb561dc 100644 --- a/src/kiwano/platform/modules.h +++ b/src/kiwano/platform/modules.h @@ -20,10 +20,7 @@ #pragma once #include -#include -#include -#include -#include +#include namespace kiwano { @@ -31,14 +28,6 @@ namespace kiwano { class KGE_API Shlwapi { - Shlwapi(); - - HMODULE shlwapi; - - // Shlwapi functions - typedef BOOL(WINAPI *PFN_PathFileExistsW)(LPCWSTR); - typedef IStream*(WINAPI *PFN_SHCreateMemStream)(const BYTE*, UINT); - public: static inline Shlwapi& Get() { @@ -46,8 +35,20 @@ namespace kiwano return instance; } + // Shlwapi functions + typedef BOOL(WINAPI* PFN_PathFileExistsW)(LPCWSTR); + typedef IStream* (WINAPI* PFN_SHCreateMemStream)(const BYTE*, UINT); + PFN_PathFileExistsW PathFileExistsW; PFN_SHCreateMemStream SHCreateMemStream; + + private: + Shlwapi(); + + Shlwapi(const Shlwapi&) = delete; + Shlwapi& operator=(const Shlwapi&) = delete; + + Library shlwapi; }; } } diff --git a/src/kiwano/renderer/Brush.cpp b/src/kiwano/renderer/Brush.cpp index d9b43eee..9ada29e3 100644 --- a/src/kiwano/renderer/Brush.cpp +++ b/src/kiwano/renderer/Brush.cpp @@ -20,7 +20,7 @@ #include #include -#include +#include namespace kiwano { diff --git a/src/kiwano/renderer/Color.h b/src/kiwano/renderer/Color.h index 79afdb74..1771555d 100644 --- a/src/kiwano/renderer/Color.h +++ b/src/kiwano/renderer/Color.h @@ -20,7 +20,7 @@ #pragma once #include -#include +#include namespace kiwano { diff --git a/src/kiwano/renderer/FontCollection.h b/src/kiwano/renderer/FontCollection.h index 711e85bb..92148509 100644 --- a/src/kiwano/renderer/FontCollection.h +++ b/src/kiwano/renderer/FontCollection.h @@ -19,8 +19,8 @@ // THE SOFTWARE. #pragma once -#include -#include +#include +#include #include namespace kiwano diff --git a/src/kiwano/renderer/Geometry.cpp b/src/kiwano/renderer/Geometry.cpp index 41bd7619..6b008ffc 100644 --- a/src/kiwano/renderer/Geometry.cpp +++ b/src/kiwano/renderer/Geometry.cpp @@ -20,7 +20,7 @@ #include #include -#include +#include namespace kiwano { diff --git a/src/kiwano/renderer/Geometry.h b/src/kiwano/renderer/Geometry.h index e522ee7a..859e07cc 100644 --- a/src/kiwano/renderer/Geometry.h +++ b/src/kiwano/renderer/Geometry.h @@ -129,7 +129,7 @@ namespace kiwano // 几何体生成器 class KGE_API GeometrySink - : protected core::noncopyable + : protected common::noncopyable { public: GeometrySink(); diff --git a/src/kiwano/renderer/GifImage.cpp b/src/kiwano/renderer/GifImage.cpp index d2dffb9b..25282aef 100644 --- a/src/kiwano/renderer/GifImage.cpp +++ b/src/kiwano/renderer/GifImage.cpp @@ -20,7 +20,7 @@ #include #include -#include +#include namespace kiwano { diff --git a/src/kiwano/renderer/GifImage.h b/src/kiwano/renderer/GifImage.h index e199f005..a77139e5 100644 --- a/src/kiwano/renderer/GifImage.h +++ b/src/kiwano/renderer/GifImage.h @@ -20,7 +20,7 @@ #pragma once #include -#include +#include namespace kiwano { diff --git a/src/kiwano/renderer/RenderTarget.cpp b/src/kiwano/renderer/RenderTarget.cpp index fddf7b0c..cbe5a428 100644 --- a/src/kiwano/renderer/RenderTarget.cpp +++ b/src/kiwano/renderer/RenderTarget.cpp @@ -19,7 +19,7 @@ // THE SOFTWARE. #include -#include +#include namespace kiwano { diff --git a/src/kiwano/renderer/RenderTarget.h b/src/kiwano/renderer/RenderTarget.h index 2f2ae489..c886da3e 100644 --- a/src/kiwano/renderer/RenderTarget.h +++ b/src/kiwano/renderer/RenderTarget.h @@ -19,7 +19,7 @@ // THE SOFTWARE. #pragma once -#include +#include #include #include #include @@ -41,7 +41,7 @@ namespace kiwano // 渲染目标 class KGE_API RenderTarget - : public core::noncopyable + : public common::noncopyable { public: bool IsValid() const; diff --git a/src/kiwano/renderer/Renderer.cpp b/src/kiwano/renderer/Renderer.cpp index 537f5f80..e1573261 100644 --- a/src/kiwano/renderer/Renderer.cpp +++ b/src/kiwano/renderer/Renderer.cpp @@ -19,9 +19,9 @@ // THE SOFTWARE. #include -#include -#include -#include +#include +#include +#include namespace kiwano { diff --git a/src/kiwano/renderer/Renderer.h b/src/kiwano/renderer/Renderer.h index a613ac99..53488183 100644 --- a/src/kiwano/renderer/Renderer.h +++ b/src/kiwano/renderer/Renderer.h @@ -19,7 +19,7 @@ // THE SOFTWARE. #pragma once -#include +#include #include #include #include diff --git a/src/kiwano/renderer/TextLayout.cpp b/src/kiwano/renderer/TextLayout.cpp index 21c230ae..9eb57318 100644 --- a/src/kiwano/renderer/TextLayout.cpp +++ b/src/kiwano/renderer/TextLayout.cpp @@ -20,7 +20,7 @@ #include #include -#include +#include namespace kiwano { diff --git a/src/kiwano/renderer/Texture.cpp b/src/kiwano/renderer/Texture.cpp index 42481fa6..01f0f921 100644 --- a/src/kiwano/renderer/Texture.cpp +++ b/src/kiwano/renderer/Texture.cpp @@ -20,7 +20,7 @@ #include #include -#include +#include namespace kiwano { diff --git a/src/kiwano/renderer/TextureCache.cpp b/src/kiwano/renderer/TextureCache.cpp index d69bb537..70ec4990 100644 --- a/src/kiwano/renderer/TextureCache.cpp +++ b/src/kiwano/renderer/TextureCache.cpp @@ -20,7 +20,7 @@ #include #include -#include +#include namespace kiwano { diff --git a/src/kiwano/renderer/win32/D2DDeviceResources.cpp b/src/kiwano/renderer/win32/D2DDeviceResources.cpp index 2f21bad9..4ccdb0cd 100644 --- a/src/kiwano/renderer/win32/D2DDeviceResources.cpp +++ b/src/kiwano/renderer/win32/D2DDeviceResources.cpp @@ -19,7 +19,7 @@ // THE SOFTWARE. #include -#include +#include #pragma comment(lib, "d2d1.lib") #pragma comment(lib, "dwrite.lib") diff --git a/src/kiwano/renderer/win32/D2DDeviceResources.h b/src/kiwano/renderer/win32/D2DDeviceResources.h index 3cae6230..31ca7a0d 100644 --- a/src/kiwano/renderer/win32/D2DDeviceResources.h +++ b/src/kiwano/renderer/win32/D2DDeviceResources.h @@ -22,7 +22,7 @@ #include #include #include -#include +#include #include #include #include diff --git a/src/kiwano/renderer/win32/D3D10DeviceResources.cpp b/src/kiwano/renderer/win32/D3D10DeviceResources.cpp index 604d43ee..274618ec 100644 --- a/src/kiwano/renderer/win32/D3D10DeviceResources.cpp +++ b/src/kiwano/renderer/win32/D3D10DeviceResources.cpp @@ -20,7 +20,7 @@ #include -#include +#include #pragma comment(lib, "d3d10_1.lib") diff --git a/src/kiwano/renderer/win32/D3D11DeviceResources.cpp b/src/kiwano/renderer/win32/D3D11DeviceResources.cpp index b2cf19b7..b6ebbd6c 100644 --- a/src/kiwano/renderer/win32/D3D11DeviceResources.cpp +++ b/src/kiwano/renderer/win32/D3D11DeviceResources.cpp @@ -20,7 +20,7 @@ #include -#include +#include #include // IsWindows10OrGreater #pragma comment(lib, "d3d11.lib") diff --git a/src/kiwano/ui/Button.cpp b/src/kiwano/ui/Button.cpp index 35d3a7c3..13c15f1c 100644 --- a/src/kiwano/ui/Button.cpp +++ b/src/kiwano/ui/Button.cpp @@ -20,7 +20,7 @@ #include #include -#include +#include namespace kiwano { @@ -32,10 +32,10 @@ namespace kiwano { SetResponsible(true); - AddListener(Event::MouseHover, Closure(this, &Button::UpdateStatus)); - AddListener(Event::MouseOut, Closure(this, &Button::UpdateStatus)); - AddListener(Event::MouseBtnDown, Closure(this, &Button::UpdateStatus)); - AddListener(Event::MouseBtnUp, Closure(this, &Button::UpdateStatus)); + AddListener(event::MouseHover, Closure(this, &Button::UpdateStatus)); + AddListener(event::MouseOut, Closure(this, &Button::UpdateStatus)); + AddListener(event::MouseDown, Closure(this, &Button::UpdateStatus)); + AddListener(event::MouseUp, Closure(this, &Button::UpdateStatus)); } Button::Button(const Callback& click) @@ -103,13 +103,14 @@ namespace kiwano } } - void Button::UpdateStatus(Event const& evt) + void Button::UpdateStatus(Event* evt) { - KGE_ASSERT(MouseEvent::Check(evt.type)); + auto mouse_evt = evt->SafeCast(); + KGE_ASSERT(mouse_evt); - if (enabled_ && (evt.target == this)) + if (enabled_ && (mouse_evt->target == this)) { - if (evt.type == Event::MouseHover) + if (evt->type == event::MouseHover) { SetStatus(Status::Hover); Window::GetInstance()->SetCursor(CursorType::Hand); @@ -117,7 +118,7 @@ namespace kiwano if (mouse_over_callback_) mouse_over_callback_(); } - else if (evt.type == Event::MouseOut) + else if (evt->type == event::MouseOut) { SetStatus(Status::Normal); Window::GetInstance()->SetCursor(CursorType::Arrow); @@ -125,14 +126,14 @@ namespace kiwano if (mouse_out_callback_) mouse_out_callback_(); } - else if (evt.type == Event::MouseBtnDown && status_ == Status::Hover) + else if (evt->type == event::MouseDown && status_ == Status::Hover) { SetStatus(Status::Pressed); if (pressed_callback_) pressed_callback_(); } - else if (evt.type == Event::MouseBtnUp && status_ == Status::Pressed) + else if (evt->type == event::MouseUp && status_ == Status::Pressed) { SetStatus(Status::Hover); diff --git a/src/kiwano/ui/Button.h b/src/kiwano/ui/Button.h index 29e0c67c..28e16537 100644 --- a/src/kiwano/ui/Button.h +++ b/src/kiwano/ui/Button.h @@ -84,7 +84,7 @@ namespace kiwano Status status ); - void UpdateStatus(Event const& evt); + void UpdateStatus(Event* evt); private: bool enabled_; diff --git a/src/kiwano/utils/LocalStorage.h b/src/kiwano/utils/LocalStorage.h index 27cf579e..affc43ea 100644 --- a/src/kiwano/utils/LocalStorage.h +++ b/src/kiwano/utils/LocalStorage.h @@ -20,7 +20,7 @@ #pragma once #include -#include +#include namespace kiwano { diff --git a/src/kiwano/utils/ResourceCache.cpp b/src/kiwano/utils/ResourceCache.cpp index 05d657a7..7f36b8ac 100644 --- a/src/kiwano/utils/ResourceCache.cpp +++ b/src/kiwano/utils/ResourceCache.cpp @@ -21,8 +21,8 @@ #include #include -#include -#include +#include +#include #include #include #include @@ -83,7 +83,7 @@ namespace kiwano KGE_WARNING_LOG(L"ResourceCache::LoadFromJsonFile failed: Cannot open file. (%s)", string_to_wide(e.what()).c_str()); return false; } - catch (core::json_exception& e) + catch (common::json_exception& e) { KGE_WARNING_LOG(L"ResourceCache::LoadFromJsonFile failed: Cannot parse to JSON. (%s)", string_to_wide(e.what()).c_str()); return false; diff --git a/src/kiwano/utils/ResourceCache.h b/src/kiwano/utils/ResourceCache.h index a67003c0..15a831e1 100644 --- a/src/kiwano/utils/ResourceCache.h +++ b/src/kiwano/utils/ResourceCache.h @@ -19,7 +19,7 @@ // THE SOFTWARE. #pragma once -#include +#include #include #include #include <3rd-party/tinyxml2/tinyxml2.h> diff --git a/src/kiwano/utils/UserData.h b/src/kiwano/utils/UserData.h index 4584e0e7..250f3388 100644 --- a/src/kiwano/utils/UserData.h +++ b/src/kiwano/utils/UserData.h @@ -19,7 +19,7 @@ // THE SOFTWARE. #pragma once -#include +#include namespace kiwano {