diff --git a/projects/kiwano/kiwano.vcxproj b/projects/kiwano/kiwano.vcxproj index 11cb1697..dcb0634a 100644 --- a/projects/kiwano/kiwano.vcxproj +++ b/projects/kiwano/kiwano.vcxproj @@ -16,8 +16,8 @@ - - + + @@ -52,7 +52,7 @@ - + @@ -102,6 +102,7 @@ + @@ -133,8 +134,7 @@ - - + @@ -180,6 +180,7 @@ + diff --git a/projects/kiwano/kiwano.vcxproj.filters b/projects/kiwano/kiwano.vcxproj.filters index c0a05373..eaef9e8b 100644 --- a/projects/kiwano/kiwano.vcxproj.filters +++ b/projects/kiwano/kiwano.vcxproj.filters @@ -65,9 +65,6 @@ math - - core - 2d @@ -303,9 +300,6 @@ base - - base - event @@ -345,15 +339,24 @@ utils - - base - core 2d\action + + base + + + core + + + base + + + utils + @@ -539,9 +542,6 @@ base - - base - event @@ -575,12 +575,15 @@ utils - - base - 2d\action + + base + + + utils + diff --git a/src/kiwano-audio/Sound.cpp b/src/kiwano-audio/Sound.cpp index 4f3b2636..f04421c4 100644 --- a/src/kiwano-audio/Sound.cpp +++ b/src/kiwano-audio/Sound.cpp @@ -27,26 +27,16 @@ namespace kiwano { namespace audio { -SoundPtr Sound::Create(const String& file_path) +Sound::Sound(const String& file_path) + : Sound() { - SoundPtr ptr = new (std::nothrow) Sound; - if (ptr) - { - if (!ptr->Load(file_path)) - return nullptr; - } - return ptr; + Load(file_path); } -SoundPtr Sound::Create(const Resource& res) +Sound::Sound(const Resource& res) + : Sound() { - SoundPtr ptr = new (std::nothrow) Sound; - if (ptr) - { - if (!ptr->Load(res)) - return nullptr; - } - return ptr; + Load(res); } Sound::Sound() diff --git a/src/kiwano-audio/Sound.h b/src/kiwano-audio/Sound.h index 299d9083..ebd2ce84 100644 --- a/src/kiwano-audio/Sound.h +++ b/src/kiwano-audio/Sound.h @@ -50,12 +50,12 @@ public: /// \~chinese /// @brief 创建音频对象 /// @param res 本地音频文件路径 - static SoundPtr Create(const String& file_path); + Sound(const String& file_path); /// \~chinese /// @brief 创建音频对象 /// @param res 音频资源 - static SoundPtr Create(const Resource& res); + Sound(const Resource& res); Sound(); diff --git a/src/kiwano-audio/SoundPlayer.cpp b/src/kiwano-audio/SoundPlayer.cpp index dde27202..bfe7a562 100644 --- a/src/kiwano-audio/SoundPlayer.cpp +++ b/src/kiwano-audio/SoundPlayer.cpp @@ -25,12 +25,6 @@ namespace kiwano namespace audio { -SoundPlayerPtr SoundPlayer::Create() -{ - SoundPlayerPtr ptr = new (std::nothrow) SoundPlayer; - return ptr; -} - SoundPlayer::SoundPlayer() : volume_(1.f) { @@ -47,8 +41,7 @@ size_t SoundPlayer::Load(const String& file_path) if (sound_cache_.end() != sound_cache_.find(hash)) return hash; - SoundPtr sound = new (std::nothrow) Sound; - + SoundPtr sound = MakePtr(); if (sound) { if (sound->Load(file_path)) @@ -67,7 +60,7 @@ size_t SoundPlayer::Load(const Resource& res) if (sound_cache_.end() != sound_cache_.find(hash_code)) return hash_code; - SoundPtr sound = new (std::nothrow) Sound; + SoundPtr sound = MakePtr(); if (sound) { diff --git a/src/kiwano-audio/SoundPlayer.h b/src/kiwano-audio/SoundPlayer.h index 789c66b5..d9ae2719 100644 --- a/src/kiwano-audio/SoundPlayer.h +++ b/src/kiwano-audio/SoundPlayer.h @@ -40,10 +40,6 @@ KGE_DECLARE_SMART_PTR(SoundPlayer); class KGE_API SoundPlayer : public ObjectBase { public: - /// \~chinese - /// @brief 创建音频播放器 - static SoundPlayerPtr Create(); - SoundPlayer(); ~SoundPlayer(); diff --git a/src/kiwano-imgui/ImGuiLayer.cpp b/src/kiwano-imgui/ImGuiLayer.cpp index aecd488d..128f28d2 100644 --- a/src/kiwano-imgui/ImGuiLayer.cpp +++ b/src/kiwano-imgui/ImGuiLayer.cpp @@ -25,27 +25,17 @@ namespace kiwano namespace imgui { -ImGuiLayerPtr ImGuiLayer::Create() -{ - ImGuiLayerPtr ptr = new (std::nothrow) ImGuiLayer; - return ptr; -} - -ImGuiLayerPtr ImGuiLayer::Create(const String& name, const ImGuiPipeline& item) -{ - ImGuiLayerPtr ptr = new (std::nothrow) ImGuiLayer; - if (ptr) - { - ptr->AddItem(name, item); - } - return ptr; -} - ImGuiLayer::ImGuiLayer() { SetSwallowEvents(true); } +ImGuiLayer::ImGuiLayer(const String& name, const ImGuiPipeline& item) + : ImGuiLayer() +{ + AddItem(name, item); +} + ImGuiLayer::~ImGuiLayer() {} void ImGuiLayer::OnRender(RenderContext& ctx) diff --git a/src/kiwano-imgui/ImGuiLayer.h b/src/kiwano-imgui/ImGuiLayer.h index 67417f42..1d52d5ae 100644 --- a/src/kiwano-imgui/ImGuiLayer.h +++ b/src/kiwano-imgui/ImGuiLayer.h @@ -38,17 +38,13 @@ using ImGuiPipeline = Function; class ImGuiLayer : public LayerActor { public: - /// \~chinese - /// @brief 创建ImGui图层 - static ImGuiLayerPtr Create(); + ImGuiLayer(); /// \~chinese /// @brief 创建ImGui图层 /// @param name 元素名称 /// @param item 管道 - static ImGuiLayerPtr Create(const String& name, const ImGuiPipeline& item); - - ImGuiLayer(); + ImGuiLayer(const String& name, const ImGuiPipeline& item); virtual ~ImGuiLayer(); diff --git a/src/kiwano-imgui/ImGuiModule.cpp b/src/kiwano-imgui/ImGuiModule.cpp index ccfe6a28..3331f82a 100644 --- a/src/kiwano-imgui/ImGuiModule.cpp +++ b/src/kiwano-imgui/ImGuiModule.cpp @@ -65,12 +65,12 @@ void ImGuiModule::DestroyModule() ImGui::DestroyContext(); } -void ImGuiModule::OnUpdate(Duration dt) +void ImGuiModule::OnUpdate(UpdateModuleContext& ctx) { ImGuiIO& io = ImGui::GetIO(); // Setup time step - io.DeltaTime = dt.Seconds(); + io.DeltaTime = ctx.dt.Seconds(); // Read keyboard modifiers inputs io.KeyCtrl = Input::GetInstance().IsDown(KeyCode::Ctrl); @@ -84,9 +84,11 @@ void ImGuiModule::OnUpdate(Duration dt) // Update OS mouse cursor with the cursor requested by imgui UpdateMouseCursor(); + + ctx.Next(); } -void ImGuiModule::BeforeRender() +void ImGuiModule::BeforeRender(RenderModuleContext& ctx) { ImGui_Impl_NewFrame(); @@ -100,70 +102,74 @@ void ImGuiModule::BeforeRender() ImGui::NewFrame(); } -void ImGuiModule::AfterRender() +void ImGuiModule::AfterRender(RenderModuleContext& ctx) { ImGui::Render(); ImGui_Impl_RenderDrawData(ImGui::GetDrawData()); } -void ImGuiModule::HandleEvent(Event* evt) +void ImGuiModule::HandleEvent(EventModuleContext& ctx) { - if (ImGui::GetCurrentContext() == NULL) - return; + if (ImGui::GetCurrentContext() != NULL) + { + Event* evt = ctx.evt; - ImGuiIO& io = ImGui::GetIO(); - if (evt->IsType()) - { - if (evt->IsType()) + ImGuiIO& io = ImGui::GetIO(); + if (evt->IsType()) { - MouseButton button = dynamic_cast(evt)->button; - int index = 0; - if (button == MouseButton::Left) - index = 0; - else if (button == MouseButton::Right) - index = 1; - else if (button == MouseButton::Middle) - index = 2; - io.MouseDown[index] = true; + if (evt->IsType()) + { + MouseButton button = dynamic_cast(evt)->button; + int index = 0; + if (button == MouseButton::Left) + index = 0; + else if (button == MouseButton::Right) + index = 1; + else if (button == MouseButton::Middle) + index = 2; + io.MouseDown[index] = true; + } + else if (evt->IsType()) + { + MouseButton button = dynamic_cast(evt)->button; + int index = 0; + if (button == MouseButton::Left) + index = 0; + else if (button == MouseButton::Right) + index = 1; + else if (button == MouseButton::Middle) + index = 2; + io.MouseDown[index] = false; + } + else if (evt->IsType()) + { + float wheel = dynamic_cast(evt)->wheel; + io.MouseWheel += wheel; + } } - else if (evt->IsType()) + else if (evt->IsType()) { - MouseButton button = dynamic_cast(evt)->button; - int index = 0; - if (button == MouseButton::Left) - index = 0; - else if (button == MouseButton::Right) - index = 1; - else if (button == MouseButton::Middle) - index = 2; - io.MouseDown[index] = false; - } - else if (evt->IsType()) - { - float wheel = dynamic_cast(evt)->wheel; - io.MouseWheel += wheel; - } - } - else if (evt->IsType()) - { - if (evt->IsType()) - { - KeyCode key = dynamic_cast(evt)->code; - io.KeysDown[(int)key] = true; - } - else if (evt->IsType()) - { - KeyCode key = dynamic_cast(evt)->code; - io.KeysDown[(int)key] = false; - } - else if (evt->IsType()) - { - // You can also use ToAscii()+GetKeyboardState() to retrieve characters. - char ch = dynamic_cast(evt)->value; - io.AddInputCharacter(static_cast(ch)); + if (evt->IsType()) + { + KeyCode key = dynamic_cast(evt)->code; + io.KeysDown[(int)key] = true; + } + else if (evt->IsType()) + { + KeyCode key = dynamic_cast(evt)->code; + io.KeysDown[(int)key] = false; + } + else if (evt->IsType()) + { + // You can also use ToAscii()+GetKeyboardState() to retrieve characters. + char ch = dynamic_cast(evt)->value; + io.AddInputCharacter(static_cast(ch)); + } } } + + ctx.Next(); } void ImGuiModule::UpdateMousePos() diff --git a/src/kiwano-imgui/ImGuiModule.h b/src/kiwano-imgui/ImGuiModule.h index b5c2d159..171e795b 100644 --- a/src/kiwano-imgui/ImGuiModule.h +++ b/src/kiwano-imgui/ImGuiModule.h @@ -34,9 +34,7 @@ namespace imgui */ class ImGuiModule : public Singleton - , public RenderModule - , public UpdateModule - , public EventModule + , public Module { friend Singleton; @@ -47,13 +45,13 @@ public: void DestroyModule() override; - void BeforeRender() override; + void OnUpdate(UpdateModuleContext& ctx) override; - void AfterRender() override; + void BeforeRender(RenderModuleContext& ctx) override; - void HandleEvent(Event* evt) override; + void AfterRender(RenderModuleContext& ctx) override; - void OnUpdate(Duration dt) override; + void HandleEvent(EventModuleContext& ctx) override; private: void UpdateMousePos(); diff --git a/src/kiwano-network/HttpModule.cpp b/src/kiwano-network/HttpModule.cpp index 4fae5217..83f16e69 100644 --- a/src/kiwano-network/HttpModule.cpp +++ b/src/kiwano-network/HttpModule.cpp @@ -253,7 +253,7 @@ void HttpModule::NetworkThread() return; } - HttpResponsePtr response = new (std::nothrow) HttpResponse(request); + HttpResponsePtr response = MakePtr(request); Perform(request, response); response_mutex_.lock(); diff --git a/src/kiwano-network/HttpRequest.cpp b/src/kiwano-network/HttpRequest.cpp index 7392aa9c..923a72d7 100644 --- a/src/kiwano-network/HttpRequest.cpp +++ b/src/kiwano-network/HttpRequest.cpp @@ -26,42 +26,23 @@ namespace kiwano namespace network { -HttpRequestPtr HttpRequest::Create(const String& url, HttpType type, const ResponseCallback& callback) +HttpRequest::HttpRequest(const String& url, HttpType type, const ResponseCallback& callback) + : type_(type) + , url_(url) + , response_cb_(callback) { - HttpRequestPtr ptr = new (std::nothrow) HttpRequest; - if (ptr) - { - ptr->SetUrl(url); - ptr->SetType(type); - ptr->SetResponseCallback(callback); - } - return ptr; } -HttpRequestPtr HttpRequest::Create(const String& url, HttpType type, const String& data, const ResponseCallback& callback) +HttpRequest::HttpRequest(const String& url, HttpType type, const String& data, const ResponseCallback& callback) + : HttpRequest(url, type, callback) { - HttpRequestPtr ptr = new (std::nothrow) HttpRequest; - if (ptr) - { - ptr->SetUrl(url); - ptr->SetType(type); - ptr->SetData(data); - ptr->SetResponseCallback(callback); - } - return ptr; + SetData(data); } -HttpRequestPtr HttpRequest::Create(const String& url, HttpType type, const Json& json, const ResponseCallback& callback) +HttpRequest::HttpRequest(const String& url, HttpType type, const Json& json, const ResponseCallback& callback) + : HttpRequest(url, type, callback) { - HttpRequestPtr ptr = new (std::nothrow) HttpRequest; - if (ptr) - { - ptr->SetUrl(url); - ptr->SetType(type); - ptr->SetJsonData(json); - ptr->SetResponseCallback(callback); - } - return ptr; + SetJsonData(json); } void HttpRequest::SetJsonData(const Json& json) diff --git a/src/kiwano-network/HttpRequest.h b/src/kiwano-network/HttpRequest.h index 1760c3ea..51203b7a 100644 --- a/src/kiwano-network/HttpRequest.h +++ b/src/kiwano-network/HttpRequest.h @@ -63,7 +63,7 @@ public: /// @param url 请求地址 /// @param type 请求类型 /// @param callback 响应回调函数 - static HttpRequestPtr Create(const String& url, HttpType type, const ResponseCallback& callback); + HttpRequest(const String& url, HttpType type, const ResponseCallback& callback); /// \~chinese /// @brief 创建HTTP请求 @@ -71,7 +71,7 @@ public: /// @param type 请求类型 /// @param data 请求数据 /// @param callback 响应回调函数 - static HttpRequestPtr Create(const String& url, HttpType type, const String& data, const ResponseCallback& callback); + HttpRequest(const String& url, HttpType type, const String& data, const ResponseCallback& callback); /// \~chinese /// @brief 创建HTTP请求 @@ -79,12 +79,10 @@ public: /// @param type 请求类型 /// @param json 请求的JSON数据 /// @param callback 响应回调函数 - static HttpRequestPtr Create(const String& url, HttpType type, const Json& json, const ResponseCallback& callback); + HttpRequest(const String& url, HttpType type, const Json& json, const ResponseCallback& callback); HttpRequest(); - HttpRequest(HttpType type); - /// \~chinese /// @brief 设置请求地址 void SetUrl(const String& url); @@ -152,11 +150,6 @@ inline HttpRequest::HttpRequest() { } -inline HttpRequest::HttpRequest(HttpType type) - : type_(type) -{ -} - inline void HttpRequest::SetUrl(const String& url) { url_ = url; diff --git a/src/kiwano-physics/Fixture.cpp b/src/kiwano-physics/Fixture.cpp index 2576a707..ca217610 100644 --- a/src/kiwano-physics/Fixture.cpp +++ b/src/kiwano-physics/Fixture.cpp @@ -29,7 +29,7 @@ namespace physics FixturePtr Fixture::CreateCircle(const Param& param, float radius, const Point& offset) { - FixturePtr ptr = new (std::nothrow) Fixture; + FixturePtr ptr = MakePtr(); if (ptr) { auto shape = std::make_unique(); @@ -44,7 +44,7 @@ FixturePtr Fixture::CreateCircle(const Param& param, float radius, const Point& FixturePtr Fixture::CreateRect(const Param& param, const Size& size, const Point& offset, float rotation) { - FixturePtr ptr = new (std::nothrow) Fixture; + FixturePtr ptr = MakePtr(); if (ptr) { b2Vec2 b2size = global::LocalToWorld(size); @@ -61,7 +61,7 @@ FixturePtr Fixture::CreateRect(const Param& param, const Size& size, const Point FixturePtr Fixture::CreatePolygon(const Param& param, const Vector& vertexs) { - FixturePtr ptr = new (std::nothrow) Fixture; + FixturePtr ptr = MakePtr(); if (ptr) { Vector b2vertexs; @@ -82,7 +82,7 @@ FixturePtr Fixture::CreatePolygon(const Param& param, const Vector& verte FixturePtr Fixture::CreateEdge(const Param& param, const Point& p1, const Point& p2) { - FixturePtr ptr = new (std::nothrow) Fixture; + FixturePtr ptr = MakePtr(); if (ptr) { b2Vec2 start = global::LocalToWorld(p1); @@ -99,7 +99,7 @@ FixturePtr Fixture::CreateEdge(const Param& param, const Point& p1, const Point& FixturePtr Fixture::CreateChain(const Param& param, const Vector& vertices, bool loop) { - FixturePtr ptr = new (std::nothrow) Fixture; + FixturePtr ptr = MakePtr(); if (ptr) { Vector b2vertices; diff --git a/src/kiwano-physics/Joint.cpp b/src/kiwano-physics/Joint.cpp index bef942a6..6c3d06ae 100644 --- a/src/kiwano-physics/Joint.cpp +++ b/src/kiwano-physics/Joint.cpp @@ -107,18 +107,9 @@ void Joint::Destroy() // DistanceJoint // -DistanceJointPtr DistanceJoint::Create(const Param& param) -{ - DistanceJointPtr ptr = new (std::nothrow) DistanceJoint; - if (ptr) - { - ptr->param_ = param; - } - return ptr; -} - -DistanceJoint::DistanceJoint() - : raw_joint_(nullptr) +DistanceJoint::DistanceJoint(const Param& param) + : param_(param) + , raw_joint_(nullptr) { } @@ -154,18 +145,9 @@ float DistanceJoint::GetLength() const // FrictionJoint // -FrictionJointPtr FrictionJoint::Create(const Param& param) -{ - FrictionJointPtr ptr = new (std::nothrow) FrictionJoint; - if (ptr) - { - ptr->param_ = param; - } - return ptr; -} - -FrictionJoint::FrictionJoint() - : raw_joint_(nullptr) +FrictionJoint::FrictionJoint(const Param& param) + : param_(param) + , raw_joint_(nullptr) { } @@ -212,18 +194,9 @@ float FrictionJoint::GetMaxTorque() const // GearJoint // -GearJointPtr GearJoint::Create(const Param& param) -{ - GearJointPtr ptr = new (std::nothrow) GearJoint; - if (ptr) - { - ptr->param_ = param; - } - return ptr; -} - -GearJoint::GearJoint() - : raw_joint_(nullptr) +GearJoint::GearJoint(const Param& param) + : param_(param) + , raw_joint_(nullptr) { } @@ -258,18 +231,9 @@ float GearJoint::GetRatio() const // MotorJoint // -MotorJointPtr MotorJoint::Create(const Param& param) -{ - MotorJointPtr ptr = new (std::nothrow) MotorJoint; - if (ptr) - { - ptr->param_ = param; - } - return ptr; -} - -MotorJoint::MotorJoint() - : raw_joint_(nullptr) +MotorJoint::MotorJoint(const Param& param) + : param_(param) + , raw_joint_(nullptr) { } @@ -317,18 +281,9 @@ float MotorJoint::GetMaxTorque() const // PrismaticJoint // -PrismaticJointPtr PrismaticJoint::Create(const Param& param) -{ - PrismaticJointPtr ptr = new (std::nothrow) PrismaticJoint; - if (ptr) - { - ptr->param_ = param; - } - return ptr; -} - -PrismaticJoint::PrismaticJoint() - : raw_joint_(nullptr) +PrismaticJoint::PrismaticJoint(const Param& param) + : param_(param) + , raw_joint_(nullptr) { } @@ -386,18 +341,9 @@ void PrismaticJoint::SetLimits(float lower, float upper) // PulleyJoint // -PulleyJointPtr PulleyJoint::Create(const Param& param) -{ - PulleyJointPtr ptr = new (std::nothrow) PulleyJoint; - if (ptr) - { - ptr->param_ = param; - } - return ptr; -} - -PulleyJoint::PulleyJoint() - : raw_joint_(nullptr) +PulleyJoint::PulleyJoint(const Param& param) + : param_(param) + , raw_joint_(nullptr) { } @@ -462,18 +408,9 @@ float PulleyJoint::GetCurrentLengthB() const // RevoluteJoint // -RevoluteJointPtr RevoluteJoint::Create(const Param& param) -{ - RevoluteJointPtr ptr = new (std::nothrow) RevoluteJoint; - if (ptr) - { - ptr->param_ = param; - } - return ptr; -} - -RevoluteJoint::RevoluteJoint() - : raw_joint_(nullptr) +RevoluteJoint::RevoluteJoint(const Param& param) + : param_(param) + , raw_joint_(nullptr) { } @@ -542,18 +479,9 @@ float RevoluteJoint::GetMaxMotorTorque() const // RopeJoint // -RopeJointPtr RopeJoint::Create(const Param& param) -{ - RopeJointPtr ptr = new (std::nothrow) RopeJoint; - if (ptr) - { - ptr->param_ = param; - } - return ptr; -} - -RopeJoint::RopeJoint() - : raw_joint_(nullptr) +RopeJoint::RopeJoint(const Param& param) + : param_(param) + , raw_joint_(nullptr) { } @@ -590,18 +518,9 @@ float RopeJoint::GetMaxLength() const // WeldJoint // -WeldJointPtr WeldJoint::Create(const Param& param) -{ - WeldJointPtr ptr = new (std::nothrow) WeldJoint; - if (ptr) - { - ptr->param_ = param; - } - return ptr; -} - -WeldJoint::WeldJoint() - : raw_joint_(nullptr) +WeldJoint::WeldJoint(const Param& param) + : param_(param) + , raw_joint_(nullptr) { } @@ -624,18 +543,9 @@ bool WeldJoint::Init(PhysicWorld* world) // WheelJoint // -WheelJointPtr WheelJoint::Create(const Param& param) -{ - WheelJointPtr ptr = new (std::nothrow) WheelJoint; - if (ptr) - { - ptr->param_ = param; - } - return ptr; -} - -WheelJoint::WheelJoint() - : raw_joint_(nullptr) +WheelJoint::WheelJoint(const Param& param) + : param_(param) + , raw_joint_(nullptr) { } @@ -686,18 +596,9 @@ float WheelJoint::GetMaxMotorTorque() const // MouseJoint // -MouseJointPtr MouseJoint::Create(const Param& param) -{ - MouseJointPtr ptr = new (std::nothrow) MouseJoint; - if (ptr) - { - ptr->param_ = param; - } - return ptr; -} - -MouseJoint::MouseJoint() - : raw_joint_(nullptr) +MouseJoint::MouseJoint(const Param& param) + : param_(param) + , raw_joint_(nullptr) { } diff --git a/src/kiwano-physics/Joint.h b/src/kiwano-physics/Joint.h index afd9c152..059f5812 100644 --- a/src/kiwano-physics/Joint.h +++ b/src/kiwano-physics/Joint.h @@ -161,9 +161,7 @@ public: /// \~chinese /// @brief 创建固定距离关节 /// @param param 关节参数 - static DistanceJointPtr Create(const Param& param); - - DistanceJoint(); + DistanceJoint(const Param& param); /// \~chinese /// @brief 初始化关节 @@ -226,9 +224,7 @@ public: /// \~chinese /// @brief 创建摩擦关节 /// @param param 关节参数 - static FrictionJointPtr Create(const Param& param); - - FrictionJoint(); + FrictionJoint(const Param& param); /// \~chinese /// @brief 初始化关节 @@ -285,9 +281,7 @@ public: /// \~chinese /// @brief 创建齿轮关节 /// @param param 关节参数 - static GearJointPtr Create(const Param& param); - - GearJoint(); + GearJoint(const Param& param); /// \~chinese /// @brief 初始化关节 @@ -336,9 +330,7 @@ public: /// \~chinese /// @brief 创建马达关节 /// @param param 关节参数 - static MotorJointPtr Create(const Param& param); - - MotorJoint(); + MotorJoint(const Param& param); /// \~chinese /// @brief 初始化关节 @@ -405,9 +397,7 @@ public: /// \~chinese /// @brief 创建平移关节 /// @param param 关节参数 - static PrismaticJointPtr Create(const Param& param); - - PrismaticJoint(); + PrismaticJoint(const Param& param); /// \~chinese /// @brief 初始化关节 @@ -509,9 +499,7 @@ public: /// \~chinese /// @brief 创建滑轮关节 /// @param param 关节参数 - static PulleyJointPtr Create(const Param& param); - - PulleyJoint(); + PulleyJoint(const Param& param); /// \~chinese /// @brief 初始化关节 @@ -588,9 +576,7 @@ public: /// \~chinese /// @brief 创建旋转关节 /// @param param 关节参数 - static RevoluteJointPtr Create(const Param& param); - - RevoluteJoint(); + RevoluteJoint(const Param& param); /// \~chinese /// @brief 初始化关节 @@ -687,9 +673,7 @@ public: /// \~chinese /// @brief 创建绳关节 /// @param param 关节参数 - static RopeJointPtr Create(const Param& param); - - RopeJoint(); + RopeJoint(const Param& param); /// \~chinese /// @brief 初始化关节 @@ -738,9 +722,7 @@ public: /// \~chinese /// @brief 创建焊接关节 /// @param param 关节参数 - static WeldJointPtr Create(const Param& param); - - WeldJoint(); + WeldJoint(const Param& param); /// \~chinese /// @brief 初始化关节 @@ -809,9 +791,7 @@ public: /// \~chinese /// @brief 创建轮关节 /// @param param 关节参数 - static WheelJointPtr Create(const Param& param); - - WheelJoint(); + WheelJoint(const Param& param); /// \~chinese /// @brief 初始化关节 @@ -911,9 +891,7 @@ public: /// \~chinese /// @brief 创建鼠标关节 /// @param param 关节参数 - static MouseJointPtr Create(const Param& param); - - MouseJoint(); + MouseJoint(const Param& param); /// \~chinese /// @brief 初始化关节 diff --git a/src/kiwano-physics/PhysicBody.cpp b/src/kiwano-physics/PhysicBody.cpp index 6652b5d6..b24dd7ec 100644 --- a/src/kiwano-physics/PhysicBody.cpp +++ b/src/kiwano-physics/PhysicBody.cpp @@ -28,37 +28,25 @@ namespace kiwano namespace physics { -PhysicBodyPtr PhysicBody::Create(PhysicWorldPtr world, Type type) -{ - return PhysicBody::Create(world.Get(), type); -} - -PhysicBodyPtr PhysicBody::Create(PhysicWorld* world, Type type) -{ - KGE_ASSERT(world); - - PhysicBodyPtr ptr = new (std::nothrow) PhysicBody; - if (ptr) - { - ptr->SetType(type); - if (ptr->Init(world)) - { - world->AddBody(ptr); - return ptr; - } - } - return nullptr; -} - -PhysicBody::PhysicBody() +PhysicBody::PhysicBody(PhysicWorld* world, Type type) : body_(nullptr) - , world_(nullptr) - , type_(Type::Static) + , world_(world) + , type_(type) , category_bits_(0x0001) , mask_bits_(0xFFFF) , group_index_(0) { SetName(KGE_PHYSIC_COMP_NAME); + + if (Init(world)) + { + world->AddBody(this); + } +} + +PhysicBody::PhysicBody(PhysicWorldPtr world, Type type) + : PhysicBody(world.Get(), type) +{ } PhysicBody::~PhysicBody() {} @@ -88,11 +76,6 @@ void PhysicBody::DestroyComponent() } } -bool PhysicBody::Init(PhysicWorldPtr world) -{ - return Init(world.Get()); -} - bool PhysicBody::Init(PhysicWorld* world) { KGE_ASSERT(body_ == nullptr); diff --git a/src/kiwano-physics/PhysicBody.h b/src/kiwano-physics/PhysicBody.h index 875e4a8a..baade4a6 100644 --- a/src/kiwano-physics/PhysicBody.h +++ b/src/kiwano-physics/PhysicBody.h @@ -54,23 +54,16 @@ public: /// @brief 初始化物体 /// @param world 物理世界 /// @param type 物体类型 - static PhysicBodyPtr Create(PhysicWorldPtr world, Type type); + PhysicBody(PhysicWorld* world, Type type); /// \~chinese /// @brief 初始化物体 /// @param world 物理世界 /// @param type 物体类型 - static PhysicBodyPtr Create(PhysicWorld* world, Type type); - - PhysicBody(); + PhysicBody(PhysicWorldPtr world, Type type); virtual ~PhysicBody(); - /// \~chinese - /// @brief 初始化物体 - /// @param[in] world 物理世界 - bool Init(PhysicWorldPtr world); - /// \~chinese /// @brief 初始化物体 /// @param[in] world 物理世界 diff --git a/src/kiwano-physics/PhysicWorld.cpp b/src/kiwano-physics/PhysicWorld.cpp index e97384b7..acdd9ce4 100644 --- a/src/kiwano-physics/PhysicWorld.cpp +++ b/src/kiwano-physics/PhysicWorld.cpp @@ -31,11 +31,11 @@ class PhysicWorld::DebugDrawer : public b2Draw public: DebugDrawer(const Size& size) { - canvas_ = Canvas::Create(size); + canvas_ = MakePtr(size); ctx_ = canvas_->GetContext2D(); - fill_brush_ = Brush::Create(Color::White); - line_brush_ = Brush::Create(Color::White); + fill_brush_ = MakePtr(Color::White); + line_brush_ = MakePtr(Color::White); b2Draw::SetFlags(b2Draw::e_shapeBit | b2Draw::e_jointBit | b2Draw::e_jointBit | b2Draw::e_centerOfMassBit); } @@ -211,20 +211,10 @@ public: } }; -PhysicWorldPtr PhysicWorld::Create() +PhysicWorld::PhysicWorld(const Vec2& gravity) + : PhysicWorld() { - PhysicWorldPtr ptr = new (std::nothrow) PhysicWorld; - return ptr; -} - -PhysicWorldPtr PhysicWorld::Create(const Vec2& gravity) -{ - PhysicWorldPtr ptr = new (std::nothrow) PhysicWorld; - if (ptr) - { - ptr->SetGravity(gravity); - } - return ptr; + SetGravity(gravity); } PhysicWorld::PhysicWorld() diff --git a/src/kiwano-physics/PhysicWorld.h b/src/kiwano-physics/PhysicWorld.h index ed1af0d5..472959a2 100644 --- a/src/kiwano-physics/PhysicWorld.h +++ b/src/kiwano-physics/PhysicWorld.h @@ -47,16 +47,12 @@ class KGE_API PhysicWorld : public Component friend class Joint; public: - /// \~chinese - /// @brief 创建物理世界 - static PhysicWorldPtr Create(); + PhysicWorld(); /// \~chinese /// @brief 创建物理世界 /// @param gravity 重力 - static PhysicWorldPtr Create(const Vec2& gravity); - - PhysicWorld(); + PhysicWorld(const Vec2& gravity); virtual ~PhysicWorld(); diff --git a/src/kiwano/2d/Actor.cpp b/src/kiwano/2d/Actor.cpp index c7a65db2..ecca2e7e 100644 --- a/src/kiwano/2d/Actor.cpp +++ b/src/kiwano/2d/Actor.cpp @@ -39,12 +39,6 @@ void Actor::SetDefaultAnchor(float anchor_x, float anchor_y) default_anchor_y = anchor_y; } -ActorPtr Actor::Create() -{ - ActorPtr ptr = memory::New(); - return ptr; -} - Actor::Actor() : ComponentManager(this) , visible_(true) @@ -264,8 +258,8 @@ bool Actor::HandleEvent(Event* evt) { hover_ = true; - MouseHoverEventPtr hover = memory::New(); - hover->pos = mouse_evt->pos; + MouseHoverEventPtr hover = new MouseHoverEvent; + hover->pos = mouse_evt->pos; HandleEvent(hover.Get()); } else if (hover_ && !contains) @@ -273,8 +267,8 @@ bool Actor::HandleEvent(Event* evt) hover_ = false; pressed_ = false; - MouseOutEventPtr out = memory::New(); - out->pos = mouse_evt->pos; + MouseOutEventPtr out = new MouseOutEvent; + out->pos = mouse_evt->pos; HandleEvent(out.Get()); } } @@ -290,7 +284,7 @@ bool Actor::HandleEvent(Event* evt) auto mouse_up_evt = dynamic_cast(evt); - MouseClickEventPtr click = memory::New(); + MouseClickEventPtr click = new MouseClickEvent; click->pos = mouse_up_evt->pos; click->button = mouse_up_evt->button; HandleEvent(click.Get()); @@ -523,8 +517,6 @@ void Actor::SetRotation(float angle) void Actor::AddChild(ActorPtr child, int zorder) { - KGE_ASSERT(child && "Actor::AddChild failed, NULL pointer exception"); - if (child) { KGE_ASSERT(!child->parent_ && "Actor::AddChild failed, the actor to be added already has a parent"); @@ -551,6 +543,10 @@ void Actor::AddChild(ActorPtr child, int zorder) child->Reorder(); child->UpdateOpacity(); } + else + { + Fail("Actor::AddChild failed, NULL pointer exception"); + } } void Actor::AddChildren(const Vector& children) @@ -620,8 +616,6 @@ void Actor::RemoveFromParent() void Actor::RemoveChild(ActorPtr child) { - KGE_ASSERT(child && "Actor::RemoveChild failed, NULL pointer exception"); - if (children_.IsEmpty()) return; @@ -632,6 +626,10 @@ void Actor::RemoveChild(ActorPtr child) child->SetStage(nullptr); children_.Remove(child); } + else + { + Fail("Actor::RemoveChild failed, NULL pointer exception"); + } } void Actor::RemoveChildren(const String& child_name) diff --git a/src/kiwano/2d/Actor.h b/src/kiwano/2d/Actor.h index b9193ad1..e99b12b6 100644 --- a/src/kiwano/2d/Actor.h +++ b/src/kiwano/2d/Actor.h @@ -77,10 +77,6 @@ public: /// @brief 角色更新回调函数 typedef Function UpdateCallback; - /// \~chinese - /// @brief 创建角色 - static ActorPtr Create(); - Actor(); virtual ~Actor(); diff --git a/src/kiwano/2d/Canvas.cpp b/src/kiwano/2d/Canvas.cpp index 1cbbd781..b12f8a7d 100644 --- a/src/kiwano/2d/Canvas.cpp +++ b/src/kiwano/2d/Canvas.cpp @@ -24,26 +24,18 @@ namespace kiwano { -CanvasPtr Canvas::Create(const Size& size) +Canvas::Canvas(const Size& size) { - void* mem = memory::Alloc(sizeof(Canvas)); - CanvasPtr ptr = ::new (mem) Canvas; - if (ptr) + try { - try - { - ptr->ResizeAndClear(size); - } - catch (std::exception) - { - return nullptr; - } + ResizeAndClear(size); + } + catch (Exception& e) + { + Fail(String("Canvas::ResizeAndClear failed: ") + e.what()); } - return ptr; } -Canvas::Canvas() {} - RenderContextPtr Canvas::GetContext2D() const { return render_ctx_; @@ -59,10 +51,17 @@ void Canvas::OnRender(RenderContext& ctx) void Canvas::ResizeAndClear(Size size) { - texture_cached_ = memory::New(); + texture_cached_ = MakePtr(); render_ctx_ = RenderContext::Create(*texture_cached_, size); - SetSize(render_ctx_->GetSize()); + if (render_ctx_) + { + SetSize(render_ctx_->GetSize()); + } + else + { + Fail("Canvas::ResizeAndClear failed"); + } } TexturePtr Canvas::ExportToTexture() const diff --git a/src/kiwano/2d/Canvas.h b/src/kiwano/2d/Canvas.h index f0f147f0..e625ec04 100644 --- a/src/kiwano/2d/Canvas.h +++ b/src/kiwano/2d/Canvas.h @@ -45,7 +45,7 @@ public: /// \~chinese /// @brief 创建画布 /// @param size 画布大小 - static CanvasPtr Create(const Size& size); + Canvas(const Size& size); /// \~chinese /// @brief 获取2D绘图上下文 @@ -62,9 +62,6 @@ public: void OnRender(RenderContext& ctx) override; -private: - Canvas(); - private: TexturePtr texture_cached_; RenderContextPtr render_ctx_; diff --git a/src/kiwano/2d/DebugActor.cpp b/src/kiwano/2d/DebugActor.cpp index 92cf5989..2fbdba50 100644 --- a/src/kiwano/2d/DebugActor.cpp +++ b/src/kiwano/2d/DebugActor.cpp @@ -54,10 +54,10 @@ DebugActor::DebugActor() comma_locale_ = std::locale(std::locale(), new comma_numpunct); - background_brush_ = memory::New(); + background_brush_ = MakePtr(); background_brush_->SetColor(Color::Rgba(0x000000, 0.7f)); - BrushPtr fill_brush = memory::New(); + BrushPtr fill_brush = MakePtr(); fill_brush->SetColor(Color::White); debug_text_style_.font_family = "Arial"; diff --git a/src/kiwano/2d/GifSprite.cpp b/src/kiwano/2d/GifSprite.cpp index 5cd2cf19..50eeb989 100644 --- a/src/kiwano/2d/GifSprite.cpp +++ b/src/kiwano/2d/GifSprite.cpp @@ -25,38 +25,6 @@ namespace kiwano { -GifSpritePtr GifSprite::Create(const String& file_path) -{ - GifSpritePtr ptr = memory::New(); - if (ptr) - { - if (!ptr->Load(file_path)) - return nullptr; - } - return ptr; -} - -GifSpritePtr GifSprite::Create(const Resource& res) -{ - GifSpritePtr ptr = memory::New(); - if (ptr) - { - if (!ptr->Load(res)) - return nullptr; - } - return ptr; -} - -GifSpritePtr GifSprite::Create(GifImagePtr gif) -{ - GifSpritePtr ptr = memory::New(); - if (ptr) - { - ptr->SetGifImage(gif); - } - return ptr; -} - GifSprite::GifSprite() : animating_(false) , next_index_(0) @@ -65,6 +33,24 @@ GifSprite::GifSprite() { } +GifSprite::GifSprite(const String& file_path) + : GifSprite() +{ + Load(file_path); +} + +GifSprite::GifSprite(const Resource& res) + : GifSprite() +{ + Load(res); +} + +GifSprite::GifSprite(GifImagePtr gif) + : GifSprite() +{ + SetGifImage(gif); +} + bool GifSprite::Load(const String& file_path) { GifImagePtr image = TextureCache::GetInstance().AddOrGetGifImage(file_path); @@ -92,17 +78,27 @@ bool GifSprite::Load(GifImagePtr gif) frame_rt_.Reset(); Size frame_size = Size(float(gif_->GetWidthInPixels()), float(gif_->GetHeightInPixels())); - frame_to_render_ = memory::New(); + frame_to_render_ = MakePtr(); frame_rt_ = RenderContext::Create(*frame_to_render_, frame_size); - SetSize(frame_rt_->GetSize()); - - if (gif_->GetFramesCount() > 0) + if (frame_rt_) { - ComposeNextFrame(); + SetSize(frame_rt_->GetSize()); + + if (gif_->GetFramesCount() > 0) + { + ComposeNextFrame(); + } + return true; + } + else + { + Fail("GifSprite::Load failed: RenderContext::Create returns null"); + return false; } - return true; } + + Fail("GifSprite::Load failed: GifImage is invalid"); return false; } @@ -229,7 +225,7 @@ void GifSprite::SaveComposedFrame() if (!saved_frame_) { - saved_frame_ = memory::New(); + saved_frame_ = MakePtr(); frame_rt_->CreateTexture(*saved_frame_, frame_to_render_->GetSizeInPixels()); } saved_frame_->CopyFrom(frame_to_render_); diff --git a/src/kiwano/2d/GifSprite.h b/src/kiwano/2d/GifSprite.h index 12dd1a70..cc575b5e 100644 --- a/src/kiwano/2d/GifSprite.h +++ b/src/kiwano/2d/GifSprite.h @@ -48,22 +48,22 @@ public: /// @brief GIF播放结束回调 using DoneCallback = Function; + GifSprite(); + /// \~chinese /// @brief 创建GIF精灵 /// @param file_path GIF图片路径 - static GifSpritePtr Create(const String& file_path); + GifSprite(const String& file_path); /// \~chinese /// @brief 创建GIF精灵 /// @param res GIF图片资源 - static GifSpritePtr Create(const Resource& res); + GifSprite(const Resource& res); /// \~chinese /// @brief 创建GIF精灵 /// @param gif GIF图片 - static GifSpritePtr Create(GifImagePtr gif); - - GifSprite(); + GifSprite(GifImagePtr gif); /// \~chinese /// @brief 加载GIF图片 diff --git a/src/kiwano/2d/LayerActor.cpp b/src/kiwano/2d/LayerActor.cpp index 4daaddd8..a45aec31 100644 --- a/src/kiwano/2d/LayerActor.cpp +++ b/src/kiwano/2d/LayerActor.cpp @@ -25,12 +25,6 @@ namespace kiwano { -LayerActorPtr LayerActor::Create() -{ - LayerActorPtr ptr = memory::New(); - return ptr; -} - LayerActor::LayerActor() : swallow_(false) { diff --git a/src/kiwano/2d/LayerActor.h b/src/kiwano/2d/LayerActor.h index 38cd2454..53d486b1 100644 --- a/src/kiwano/2d/LayerActor.h +++ b/src/kiwano/2d/LayerActor.h @@ -39,10 +39,6 @@ KGE_DECLARE_SMART_PTR(LayerActor); class KGE_API LayerActor : public Actor { public: - /// \~chinese - /// @brief 创建图层 - static LayerActorPtr Create(); - LayerActor(); virtual ~LayerActor(); diff --git a/src/kiwano/2d/ShapeActor.cpp b/src/kiwano/2d/ShapeActor.cpp index 5186451a..ba80091e 100644 --- a/src/kiwano/2d/ShapeActor.cpp +++ b/src/kiwano/2d/ShapeActor.cpp @@ -25,40 +25,25 @@ namespace kiwano { -ShapeActorPtr ShapeActor::Create(ShapePtr shape) +ShapeActor::ShapeActor() {} + +ShapeActor::ShapeActor(ShapePtr shape) { - ShapeActorPtr ptr = memory::New(); - if (ptr) - { - ptr->SetShape(shape); - } - return ptr; + SetShape(shape); } -ShapeActorPtr ShapeActor::Create(ShapePtr shape, const Color& fill_color, const Color& stroke_color) +ShapeActor::ShapeActor(ShapePtr shape, const Color& fill_color, const Color& stroke_color) + : ShapeActor(shape) { - ShapeActorPtr ptr = ShapeActor::Create(shape); - if (ptr) - { - ptr->SetFillColor(fill_color); - ptr->SetStrokeColor(stroke_color); - } - return ptr; + SetFillColor(fill_color); + SetStrokeColor(stroke_color); } -ShapeActorPtr ShapeActor::Create(ShapePtr shape, BrushPtr fill_brush, BrushPtr stroke_brush) -{ - ShapeActorPtr ptr = ShapeActor::Create(shape); - if (ptr) - { - ptr->SetFillBrush(fill_brush); - ptr->SetStrokeBrush(stroke_brush); - } - return ptr; -} - -ShapeActor::ShapeActor() +ShapeActor::ShapeActor(ShapePtr shape, BrushPtr fill_brush, BrushPtr stroke_brush) + : ShapeActor(shape) { + SetFillBrush(fill_brush); + SetStrokeBrush(stroke_brush); } ShapeActor::~ShapeActor() {} @@ -127,18 +112,13 @@ bool ShapeActor::CheckVisibility(RenderContext& ctx) const // LineActor //------------------------------------------------------- -LineActorPtr LineActor::Create(const Point& begin, const Point& end) -{ - LineActorPtr ptr = memory::New(); - if (ptr) - { - ptr->SetLine(begin, end); - } - return ptr; -} - LineActor::LineActor() {} +LineActor::LineActor(const Point& begin, const Point& end) +{ + SetLine(begin, end); +} + LineActor::~LineActor() {} void LineActor::SetLine(const Point& begin, const Point& end) @@ -155,18 +135,13 @@ void LineActor::SetLine(const Point& begin, const Point& end) // RectActor //------------------------------------------------------- -RectActorPtr RectActor::Create(const Size& size) -{ - RectActorPtr ptr = memory::New(); - if (ptr) - { - ptr->SetRectSize(size); - } - return ptr; -} - RectActor::RectActor() {} +RectActor::RectActor(const Size& size) +{ + SetRectSize(size); +} + RectActor::~RectActor() {} void RectActor::SetRectSize(const Size& size) @@ -182,18 +157,13 @@ void RectActor::SetRectSize(const Size& size) // RoundedRectActor //------------------------------------------------------- -RoundedRectActorPtr RoundedRectActor::Create(const Size& size, const Vec2& radius) -{ - RoundedRectActorPtr ptr = memory::New(); - if (ptr) - { - ptr->SetRoundedRect(size, radius); - } - return ptr; -} - RoundedRectActor::RoundedRectActor() {} +RoundedRectActor::RoundedRectActor(const Size& size, const Vec2& radius) +{ + SetRoundedRect(size, radius); +} + RoundedRectActor::~RoundedRectActor() {} void RoundedRectActor::SetRadius(const Vec2& radius) @@ -220,21 +190,17 @@ void RoundedRectActor::SetRoundedRect(const Size& size, const Vec2& radius) // CircleActor //------------------------------------------------------- -CircleActorPtr CircleActor::Create(float radius) -{ - CircleActorPtr ptr = memory::New(); - if (ptr) - { - ptr->SetRadius(radius); - } - return ptr; -} - CircleActor::CircleActor() : radius_(0.f) { } +CircleActor::CircleActor(float radius) + : radius_(0.f) +{ + SetRadius(radius); +} + CircleActor::~CircleActor() {} void CircleActor::SetRadius(float radius) @@ -250,18 +216,13 @@ void CircleActor::SetRadius(float radius) // EllipseActor //------------------------------------------------------- -EllipseActorPtr EllipseActor::Create(const Vec2& radius) -{ - EllipseActorPtr ptr = memory::New(); - if (ptr) - { - ptr->SetRadius(radius); - } - return ptr; -} - EllipseActor::EllipseActor() {} +EllipseActor::EllipseActor(const Vec2& radius) +{ + SetRadius(radius); +} + EllipseActor::~EllipseActor() {} void EllipseActor::SetRadius(const Vec2& radius) @@ -277,30 +238,25 @@ void EllipseActor::SetRadius(const Vec2& radius) // PolygonActor //------------------------------------------------------- -PolygonActorPtr PolygonActor::Create(const Vector& points) -{ - PolygonActorPtr ptr = memory::New(); - if (ptr) - { - ptr->SetVertices(points); - } - return ptr; -} - PolygonActor::PolygonActor() {} +PolygonActor::PolygonActor(const Vector& points) +{ + SetVertices(points); +} + PolygonActor::~PolygonActor() {} void PolygonActor::SetVertices(const Vector& points) { if (points.size() > 1) { - ShapeMakerPtr maker = ShapeMaker::Create(); - maker->BeginPath(points[0]); - maker->AddLines(&points[1], points.size() - 1); - maker->EndPath(true); + ShapeMaker maker; + maker.BeginPath(points[0]); + maker.AddLines(&points[1], points.size() - 1); + maker.EndPath(true); - SetShape(maker->GetShape()); + SetShape(maker.GetShape()); } } diff --git a/src/kiwano/2d/ShapeActor.h b/src/kiwano/2d/ShapeActor.h index 6dcaf82b..480bd056 100644 --- a/src/kiwano/2d/ShapeActor.h +++ b/src/kiwano/2d/ShapeActor.h @@ -48,28 +48,26 @@ KGE_DECLARE_SMART_PTR(PolygonActor); class KGE_API ShapeActor : public Actor { public: + ShapeActor(); + /// \~chinese /// @brief 创建形状角色 /// @param shape 形状 - static ShapeActorPtr Create(ShapePtr shape); + ShapeActor(ShapePtr shape); /// \~chinese /// @brief 创建形状角色 /// @param shape 形状 /// @param fill_color 填充颜色 /// @param stroke_color 轮廓颜色 - static ShapeActorPtr Create(ShapePtr shape, const Color& fill_color, const Color& stroke_color); + ShapeActor(ShapePtr shape, const Color& fill_color, const Color& stroke_color); /// \~chinese /// @brief 创建形状角色 /// @param shape 形状 /// @param fill_brush 填充画刷 /// @param stroke_brush 轮廓画刷 - static ShapeActorPtr Create(ShapePtr shape, BrushPtr fill_brush, BrushPtr stroke_brush); - - /// \~chinese - /// @brief 构造形状角色 - ShapeActor(); + ShapeActor(ShapePtr shape, BrushPtr fill_brush, BrushPtr stroke_brush); virtual ~ShapeActor(); @@ -147,13 +145,13 @@ private: class KGE_API LineActor : public ShapeActor { public: + LineActor(); + /// \~chinese /// @brief 创建线段角色 /// @param begin 线段起点 /// @param end 线段终点 - static LineActorPtr Create(const Point& begin, const Point& end); - - LineActor(); + LineActor(const Point& begin, const Point& end); virtual ~LineActor(); @@ -191,12 +189,12 @@ private: class KGE_API RectActor : public ShapeActor { public: + RectActor(); + /// \~chinese /// @brief 创建矩形角色 /// @param size 矩形大小 - static RectActorPtr Create(const Size& size); - - RectActor(); + RectActor(const Size& size); virtual ~RectActor(); @@ -218,13 +216,13 @@ private: class KGE_API RoundedRectActor : public ShapeActor { public: + RoundedRectActor(); + /// \~chinese /// @brief 创建圆角矩形角色 /// @param size 圆角矩形大小 /// @param radius 圆角半径 - static RoundedRectActorPtr Create(const Size& size, const Vec2& radius); - - RoundedRectActor(); + RoundedRectActor(const Size& size, const Vec2& radius); virtual ~RoundedRectActor(); @@ -262,12 +260,12 @@ private: class KGE_API CircleActor : public ShapeActor { public: + CircleActor(); + /// \~chinese /// @brief 创建圆形角色 /// @param radius 圆形半径 - static CircleActorPtr Create(float radius); - - CircleActor(); + CircleActor(float radius); virtual ~CircleActor(); @@ -289,12 +287,12 @@ private: class KGE_API EllipseActor : public ShapeActor { public: + EllipseActor(); + /// \~chinese /// @brief 创建椭圆角色 /// @param radius 椭圆半径 - static EllipseActorPtr Create(const Vec2& radius); - - EllipseActor(); + EllipseActor(const Vec2& radius); virtual ~EllipseActor(); @@ -316,12 +314,12 @@ private: class KGE_API PolygonActor : public ShapeActor { public: + PolygonActor(); + /// \~chinese /// @brief 创建多边形角色 /// @param points 多边形端点集合 - static PolygonActorPtr Create(const Vector& points); - - PolygonActor(); + PolygonActor(const Vector& points); virtual ~PolygonActor(); @@ -338,7 +336,7 @@ inline void ShapeActor::SetStrokeColor(const Color& color) { if (!stroke_brush_) { - stroke_brush_ = memory::New(); + stroke_brush_ = MakePtr(); } stroke_brush_->SetColor(color); } @@ -347,7 +345,7 @@ inline void ShapeActor::SetFillColor(const Color& color) { if (!fill_brush_) { - fill_brush_ = memory::New(); + fill_brush_ = MakePtr(); } fill_brush_->SetColor(color); } diff --git a/src/kiwano/2d/Sprite.cpp b/src/kiwano/2d/Sprite.cpp index 1a717463..3298be2f 100644 --- a/src/kiwano/2d/Sprite.cpp +++ b/src/kiwano/2d/Sprite.cpp @@ -24,81 +24,58 @@ namespace kiwano { -SpritePtr Sprite::Create(const String& file_path) -{ - SpritePtr ptr = memory::New(); - if (ptr) - { - if (!ptr->Load(file_path)) - return nullptr; - } - return ptr; -} - -SpritePtr Sprite::Create(const Resource& res) -{ - SpritePtr ptr = memory::New(); - if (ptr) - { - if (!ptr->Load(res)) - return nullptr; - } - return ptr; -} - -SpritePtr Sprite::Create(FramePtr frame) -{ - SpritePtr ptr = memory::New(); - if (ptr) - { - ptr->SetFrame(frame); - } - return ptr; -} - -SpritePtr Sprite::Create(const String& file_path, const Rect& crop_rect) -{ - SpritePtr ptr = Sprite::Create(file_path); - if (ptr) - { - ptr->SetCropRect(crop_rect); - } - return ptr; -} - -SpritePtr Sprite::Create(const Resource& res, const Rect& crop_rect) -{ - SpritePtr ptr = Sprite::Create(res); - if (ptr) - { - ptr->SetCropRect(crop_rect); - } - return ptr; -} - Sprite::Sprite() {} +Sprite::Sprite(const String& file_path) +{ + Load(file_path); +} + +Sprite::Sprite(const Resource& res) +{ + Load(res); +} + +Sprite::Sprite(FramePtr frame) +{ + SetFrame(frame); +} + +Sprite::Sprite(const String& file_path, const Rect& crop_rect) + : Sprite(file_path) +{ + SetCropRect(crop_rect); +} + +Sprite::Sprite(const Resource& res, const Rect& crop_rect) + : Sprite(res) +{ + SetCropRect(crop_rect); +} + Sprite::~Sprite() {} bool Sprite::Load(const String& file_path, bool autoresize) { - FramePtr frame = Frame::Create(file_path); - if (frame) + FramePtr frame = MakePtr(file_path); + if (frame && frame->IsValid()) { SetFrame(frame, autoresize); return true; } + Fail("Sprite::Load failed"); return false; } bool Sprite::Load(const Resource& res, bool autoresize) { - FramePtr frame = Frame::Create(res); + FramePtr frame = MakePtr(res); if (frame) { SetFrame(frame, autoresize); return true; } + Fail("Sprite::Load failed"); return false; } diff --git a/src/kiwano/2d/Sprite.h b/src/kiwano/2d/Sprite.h index 934abbac..f754d2f9 100644 --- a/src/kiwano/2d/Sprite.h +++ b/src/kiwano/2d/Sprite.h @@ -38,34 +38,34 @@ KGE_DECLARE_SMART_PTR(Sprite); class KGE_API Sprite : public Actor { public: + Sprite(); + /// \~chinese /// @brief 创建精灵 /// @param file_path 本地图片路径 - static SpritePtr Create(const String& file_path); + Sprite(const String& file_path); /// \~chinese /// @brief 创建精灵 /// @param res 图片资源 - static SpritePtr Create(const Resource& res); + Sprite(const Resource& res); /// \~chinese /// @brief 创建精灵 /// @param frame 图像帧 - static SpritePtr Create(FramePtr frame); + Sprite(FramePtr frame); /// \~chinese /// @brief 创建精灵 /// @param file_path 本地图片路径 /// @param crop_rect 裁剪矩形 - static SpritePtr Create(const String& file_path, const Rect& crop_rect); + Sprite(const String& file_path, const Rect& crop_rect); /// \~chinese /// @brief 创建精灵 /// @param res 图片资源 /// @param crop_rect 裁剪矩形 - static SpritePtr Create(const Resource& res, const Rect& crop_rect); - - Sprite(); + Sprite(const Resource& res, const Rect& crop_rect); virtual ~Sprite(); diff --git a/src/kiwano/2d/Stage.cpp b/src/kiwano/2d/Stage.cpp index 2c65c309..d1df2af7 100644 --- a/src/kiwano/2d/Stage.cpp +++ b/src/kiwano/2d/Stage.cpp @@ -25,12 +25,6 @@ namespace kiwano { -StagePtr Stage::Create() -{ - StagePtr ptr = memory::New(); - return ptr; -} - Stage::Stage() { SetStage(this); @@ -57,13 +51,13 @@ void Stage::RenderBorder(RenderContext& ctx) if (!border_fill_brush_) { - border_fill_brush_ = memory::New(); + border_fill_brush_ = MakePtr(); border_fill_brush_->SetColor(Color(Color::Red, .4f)); } if (!border_stroke_brush_) { - border_stroke_brush_ = memory::New(); + border_stroke_brush_ = MakePtr(); border_stroke_brush_->SetColor(Color(Color::Red, .8f)); } diff --git a/src/kiwano/2d/Stage.h b/src/kiwano/2d/Stage.h index 4f92704e..e0a3dbef 100644 --- a/src/kiwano/2d/Stage.h +++ b/src/kiwano/2d/Stage.h @@ -43,10 +43,6 @@ class KGE_API Stage : public Actor friend class Director; public: - /// \~chinese - /// @brief 进入舞台时 - static StagePtr Create(); - Stage(); virtual ~Stage(); diff --git a/src/kiwano/2d/TextActor.cpp b/src/kiwano/2d/TextActor.cpp index dfe0010d..9e4e8305 100644 --- a/src/kiwano/2d/TextActor.cpp +++ b/src/kiwano/2d/TextActor.cpp @@ -25,24 +25,17 @@ namespace kiwano { -TextActorPtr TextActor::Create(const String& text) +TextActor::TextActor() {} + +TextActor::TextActor(const String& text) + : TextActor(text, TextStyle()) { - return TextActor::Create(text, TextStyle()); } -TextActorPtr TextActor::Create(const String& text, const TextStyle& style) -{ - TextActorPtr ptr = memory::New(); - if (ptr) - { - ptr->SetStyle(style); - ptr->SetText(text); - } - return ptr; -} - -TextActor::TextActor() +TextActor::TextActor(const String& text, const TextStyle& style) { + SetStyle(style); + SetText(text); } TextActor::~TextActor() {} @@ -65,9 +58,17 @@ void TextActor::SetText(const String& text) { if (!layout_) { - layout_ = TextLayout::Create(); + layout_ = MakePtr(); + } + + try + { + layout_->Reset(text, style_); + } + catch (SystemError& e) + { + Fail(String("TextActor::SetText failed: ") + e.what()); } - layout_->Reset(text, style_); } void TextActor::SetStyle(const TextStyle& style) @@ -215,7 +216,7 @@ void TextActor::SetFillColor(const Color& color) } else { - SetFillBrush(Brush::Create(color)); + SetFillBrush(MakePtr(color)); } } @@ -227,7 +228,7 @@ void TextActor::SetOutlineColor(const Color& outline_color) } else { - SetFillBrush(Brush::Create(outline_color)); + SetFillBrush(MakePtr(outline_color)); } } diff --git a/src/kiwano/2d/TextActor.h b/src/kiwano/2d/TextActor.h index f7939c1a..78ce1593 100644 --- a/src/kiwano/2d/TextActor.h +++ b/src/kiwano/2d/TextActor.h @@ -39,18 +39,18 @@ KGE_DECLARE_SMART_PTR(TextActor); class KGE_API TextActor : public Actor { public: + TextActor(); + /// \~chinese /// @brief 创建文本角色 /// @param text 文字内容 - static TextActorPtr Create(const String& text); + TextActor(const String& text); /// \~chinese /// @brief 创建文本角色 /// @param text 文字内容 /// @param style 文本样式 - static TextActorPtr Create(const String& text, const TextStyle& style); - - TextActor(); + TextActor(const String& text, const TextStyle& style); virtual ~TextActor(); diff --git a/src/kiwano/2d/Transition.cpp b/src/kiwano/2d/Transition.cpp index acf0c722..b62167e3 100644 --- a/src/kiwano/2d/Transition.cpp +++ b/src/kiwano/2d/Transition.cpp @@ -51,7 +51,7 @@ bool Transition::IsDone() return done_; } -void Transition::Init(StagePtr prev, StagePtr next) +void Transition::Init(Stage* prev, Stage* next) { process_ = 0; delta_ = Duration{}; @@ -126,19 +126,14 @@ void Transition::Stop() // BoxTransition //------------------------------------------------------- -BoxTransitionPtr BoxTransition::Create(Duration duration) +BoxTransition::BoxTransition(Duration duration) { - BoxTransitionPtr ptr = memory::New(); - if (ptr) - { - ptr->SetDuration(duration); - } - return ptr; + SetDuration(duration); } BoxTransition::BoxTransition() {} -void BoxTransition::Init(StagePtr prev, StagePtr next) +void BoxTransition::Init(Stage* prev, Stage* next) { Transition::Init(prev, next); @@ -167,19 +162,14 @@ void BoxTransition::Update(Duration dt) // EmergeTransition //------------------------------------------------------- -EmergeTransitionPtr EmergeTransition::Create(Duration duration) +EmergeTransition::EmergeTransition(Duration duration) { - EmergeTransitionPtr ptr = memory::New(); - if (ptr) - { - ptr->SetDuration(duration); - } - return ptr; + SetDuration(duration); } EmergeTransition::EmergeTransition() {} -void EmergeTransition::Init(StagePtr prev, StagePtr next) +void EmergeTransition::Init(Stage* prev, Stage* next) { Transition::Init(prev, next); @@ -199,19 +189,14 @@ void EmergeTransition::Update(Duration dt) // FadeTransition //------------------------------------------------------- -FadeTransitionPtr FadeTransition::Create(Duration duration) +FadeTransition::FadeTransition(Duration duration) { - FadeTransitionPtr ptr = memory::New(); - if (ptr) - { - ptr->SetDuration(duration); - } - return ptr; + SetDuration(duration); } FadeTransition::FadeTransition() {} -void FadeTransition::Init(StagePtr prev, StagePtr next) +void FadeTransition::Init(Stage* prev, Stage* next) { Transition::Init(prev, next); @@ -239,15 +224,10 @@ void FadeTransition::Update(Duration dt) // MoveTransition //------------------------------------------------------- -MoveTransitionPtr MoveTransition::Create(Duration duration, Type type) +MoveTransition::MoveTransition(Duration duration, Type type) + : type_(type) { - MoveTransitionPtr ptr = memory::New(); - if (ptr) - { - ptr->type_ = type; - ptr->SetDuration(duration); - } - return ptr; + SetDuration(duration); } MoveTransition::MoveTransition() @@ -255,7 +235,7 @@ MoveTransition::MoveTransition() { } -void MoveTransition::Init(StagePtr prev, StagePtr next) +void MoveTransition::Init(Stage* prev, Stage* next) { Transition::Init(prev, next); @@ -328,15 +308,10 @@ void MoveTransition::Reset() // RotationTransition //------------------------------------------------------- -RotationTransitionPtr RotationTransition::Create(Duration duration, float rotation) +RotationTransition::RotationTransition(Duration duration, float rotation) + : rotation_(rotation) { - RotationTransitionPtr ptr = memory::New(); - if (ptr) - { - ptr->rotation_ = rotation; - ptr->SetDuration(duration); - } - return ptr; + SetDuration(duration); } RotationTransition::RotationTransition() @@ -344,7 +319,7 @@ RotationTransition::RotationTransition() { } -void RotationTransition::Init(StagePtr prev, StagePtr next) +void RotationTransition::Init(Stage* prev, Stage* next) { Transition::Init(prev, next); diff --git a/src/kiwano/2d/Transition.h b/src/kiwano/2d/Transition.h index 9444af79..86ced945 100644 --- a/src/kiwano/2d/Transition.h +++ b/src/kiwano/2d/Transition.h @@ -66,7 +66,7 @@ protected: * @param[in] prev 转出场景 * @param[in] next 转入场景 */ - virtual void Init(StagePtr prev, StagePtr next); + virtual void Init(Stage* prev, Stage* next); /** * \~chinese @@ -95,15 +95,15 @@ protected: virtual void Reset() {} protected: - bool done_; - float process_; - Duration duration_; - Duration delta_; - Size window_size_; - StagePtr out_stage_; - StagePtr in_stage_; - Layer out_layer_; - Layer in_layer_; + bool done_; + float process_; + Duration duration_; + Duration delta_; + Size window_size_; + StagePtr out_stage_; + StagePtr in_stage_; + Layer out_layer_; + Layer in_layer_; }; /** @@ -119,14 +119,14 @@ public: * @brief 创建淡入淡出过渡动画 * @param duration 动画时长 */ - static FadeTransitionPtr Create(Duration duration); + FadeTransition(Duration duration); FadeTransition(); protected: void Update(Duration dt) override; - virtual void Init(StagePtr prev, StagePtr next) override; + virtual void Init(Stage* prev, Stage* next) override; }; /** @@ -142,14 +142,14 @@ public: * @brief 创建渐变过渡动画 * @param duration 动画时长 */ - static EmergeTransitionPtr Create(Duration duration); + EmergeTransition(Duration duration); EmergeTransition(); protected: void Update(Duration dt) override; - virtual void Init(StagePtr prev, StagePtr next) override; + virtual void Init(Stage* prev, Stage* next) override; }; /** @@ -165,14 +165,14 @@ public: * @brief 创建盒状过渡动画 * @param duration 动画时长 */ - static BoxTransitionPtr Create(Duration duration); + BoxTransition(Duration duration); BoxTransition(); protected: void Update(Duration dt) override; - virtual void Init(StagePtr prev, StagePtr next) override; + virtual void Init(Stage* prev, Stage* next) override; }; /** @@ -201,14 +201,14 @@ public: * @param duration 动画时长 * @param type 位移方式 */ - static MoveTransitionPtr Create(Duration duration, Type type); + MoveTransition(Duration duration, Type type); MoveTransition(); protected: void Update(Duration dt) override; - virtual void Init(StagePtr prev, StagePtr next) override; + virtual void Init(Stage* prev, Stage* next) override; void Reset() override; @@ -232,14 +232,14 @@ public: * @param duration 动画时长 * @param rotation 旋转度数 */ - static RotationTransitionPtr Create(Duration duration, float rotation = 360.0f); + RotationTransition(Duration duration, float rotation = 360.0f); RotationTransition(); protected: void Update(Duration dt) override; - virtual void Init(StagePtr prev, StagePtr next) override; + virtual void Init(Stage* prev, Stage* next) override; void Reset() override; diff --git a/src/kiwano/2d/action/Action.cpp b/src/kiwano/2d/action/Action.cpp index 36654579..abdf00e5 100644 --- a/src/kiwano/2d/action/Action.cpp +++ b/src/kiwano/2d/action/Action.cpp @@ -106,7 +106,7 @@ void ActionEntity::Reset() loops_done_ = 0; } -ActionEntityPtr ActionEntity::DoClone(ActionEntityPtr to) const +void ActionEntity::DoClone(ActionEntity* to) const { if (to) { @@ -116,7 +116,6 @@ ActionEntityPtr ActionEntity::DoClone(ActionEntityPtr to) const to->SetLoops(this->GetLoops()); to->SetName(this->GetName()); } - return to; } } // namespace kiwano diff --git a/src/kiwano/2d/action/Action.h b/src/kiwano/2d/action/Action.h index f9d0ac5c..e3c6cf87 100644 --- a/src/kiwano/2d/action/Action.h +++ b/src/kiwano/2d/action/Action.h @@ -22,7 +22,6 @@ #include #include #include -#include #include #include #include @@ -103,7 +102,7 @@ public: /// \~chinese /// @brief 获取动画的倒转 - virtual ActionEntityPtr Reverse() const = 0; + virtual ActionEntity* Reverse() const = 0; /// \~chinese /// @brief 获取动画的运行状态 @@ -183,7 +182,7 @@ protected: /// \~chinese /// @brief 执行克隆 - ActionEntityPtr DoClone(ActionEntityPtr to) const; + void DoClone(ActionEntity* to) const; private: Status status_; @@ -300,6 +299,11 @@ public: return Get(); } + inline operator ActionEntity*() const + { + return Get(); + } + inline operator ActionEntityPtr() const { return ptr; diff --git a/src/kiwano/2d/action/ActionDelay.cpp b/src/kiwano/2d/action/ActionDelay.cpp index 06f1023f..1a9017e8 100644 --- a/src/kiwano/2d/action/ActionDelay.cpp +++ b/src/kiwano/2d/action/ActionDelay.cpp @@ -25,27 +25,24 @@ namespace kiwano ActionDelay::ActionDelay(Duration delay) { - SetEntity(ActionDelayEntity::Create(delay)); + SetEntity(MakePtr(delay)); } -ActionDelayEntityPtr ActionDelayEntity::Create(Duration delay) +ActionDelayEntity::ActionDelayEntity(Duration delay) { - ActionDelayEntityPtr ptr = memory::New(); - if (ptr) - { - ptr->SetDelay(delay); - } + this->SetDelay(delay); +} + +ActionDelayEntity* ActionDelayEntity::Clone() const +{ + ActionDelayEntity* ptr = new ActionDelayEntity(GetDelay()); + DoClone(ptr); return ptr; } -ActionEntityPtr ActionDelayEntity::Clone() const +ActionDelayEntity* ActionDelayEntity::Reverse() const { - return DoClone(ActionDelayEntity::Create(GetDelay())); -} - -ActionEntityPtr ActionDelayEntity::Reverse() const -{ - return DoClone(ActionDelayEntity::Create(GetDelay())); + return Clone(); } } // namespace kiwano diff --git a/src/kiwano/2d/action/ActionDelay.h b/src/kiwano/2d/action/ActionDelay.h index 2a702f53..51b39681 100644 --- a/src/kiwano/2d/action/ActionDelay.h +++ b/src/kiwano/2d/action/ActionDelay.h @@ -50,15 +50,15 @@ public: /// \~chinese /// @brief 创建延时动画 /// @param delay 延时时长 - static ActionDelayEntityPtr Create(Duration delay); + ActionDelayEntity(Duration delay); /// \~chinese /// @brief 获取该动画的拷贝对象 - ActionEntityPtr Clone() const override; + ActionDelayEntity* Clone() const override; /// \~chinese /// @brief 获取该动画的倒转 - ActionEntityPtr Reverse() const override; + ActionDelayEntity* Reverse() const override; }; /** @} */ diff --git a/src/kiwano/2d/action/ActionGroup.cpp b/src/kiwano/2d/action/ActionGroup.cpp index f11b7509..7dd6292f 100644 --- a/src/kiwano/2d/action/ActionGroup.cpp +++ b/src/kiwano/2d/action/ActionGroup.cpp @@ -27,18 +27,7 @@ namespace kiwano ActionGroup::ActionGroup(const Vector& actions, bool parallel) { - SetEntity(ActionGroupEntity::Create(actions, parallel)); -} - -ActionGroupEntityPtr ActionGroupEntity::Create(const Vector& actions, bool parallel) -{ - ActionGroupEntityPtr ptr = memory::New(); - if (ptr) - { - ptr->parallel_ = parallel; - ptr->AddActions(actions); - } - return ptr; + SetEntity(MakePtr(actions, parallel)); } ActionGroupEntity::ActionGroupEntity() @@ -46,9 +35,10 @@ ActionGroupEntity::ActionGroupEntity() { } -ActionGroupEntity::ActionGroupEntity(bool parallel) +ActionGroupEntity::ActionGroupEntity(const Vector& actions, bool parallel) : parallel_(parallel) { + AddActions(actions); } ActionGroupEntity::~ActionGroupEntity() {} @@ -123,7 +113,7 @@ void ActionGroupEntity::AddActions(const Vector& actions) AddAction(action); } -ActionEntityPtr ActionGroupEntity::Clone() const +ActionGroupEntity* ActionGroupEntity::Clone() const { Vector actions; if (!actions_.IsEmpty()) @@ -133,10 +123,12 @@ ActionEntityPtr ActionGroupEntity::Clone() const actions.push_back(action->Clone()); } } - return DoClone(ActionGroupEntity::Create(actions, parallel_)); + ActionGroupEntity* ptr = new ActionGroupEntity(actions, parallel_); + DoClone(ptr); + return ptr; } -ActionEntityPtr ActionGroupEntity::Reverse() const +ActionGroupEntity* ActionGroupEntity::Reverse() const { Vector actions; if (!actions_.IsEmpty()) @@ -146,7 +138,9 @@ ActionEntityPtr ActionGroupEntity::Reverse() const actions.push_back(action->Reverse()); } } - return DoClone(ActionGroupEntity::Create(actions, parallel_)); + ActionGroupEntity* ptr = new ActionGroupEntity(actions, parallel_); + DoClone(ptr); + return ptr; } } // namespace kiwano diff --git a/src/kiwano/2d/action/ActionGroup.h b/src/kiwano/2d/action/ActionGroup.h index 1afcb678..341f3904 100644 --- a/src/kiwano/2d/action/ActionGroup.h +++ b/src/kiwano/2d/action/ActionGroup.h @@ -47,15 +47,13 @@ public: class KGE_API ActionGroupEntity : public ActionEntity { public: + ActionGroupEntity(); + /// \~chinese /// @brief 创建动画组合 /// @param actions 动画集合 /// @param parallel 同步执行 - static ActionGroupEntityPtr Create(const Vector& actions, bool parallel = false); - - ActionGroupEntity(); - - ActionGroupEntity(bool parallel); + ActionGroupEntity(const Vector& actions, bool parallel = false); virtual ~ActionGroupEntity(); @@ -75,11 +73,11 @@ public: /// \~chinese /// @brief 获取该动画的拷贝对象 - ActionEntityPtr Clone() const override; + ActionGroupEntity* Clone() const override; /// \~chinese /// @brief 获取该动画的倒转 - ActionEntityPtr Reverse() const override; + ActionGroupEntity* Reverse() const override; protected: void Init(Actor* target) override; diff --git a/src/kiwano/2d/action/ActionScheduler.cpp b/src/kiwano/2d/action/ActionScheduler.cpp index c34a8480..e1ff9f77 100644 --- a/src/kiwano/2d/action/ActionScheduler.cpp +++ b/src/kiwano/2d/action/ActionScheduler.cpp @@ -87,14 +87,14 @@ void ActionScheduler::StopAllActions() } } -ActionEntityPtr ActionScheduler::GetAction(const String& name) +ActionEntity* ActionScheduler::GetAction(const String& name) { if (actions_.IsEmpty()) return nullptr; for (auto& action : actions_) if (action->IsName(name)) - return action; + return action.Get(); return nullptr; } diff --git a/src/kiwano/2d/action/ActionScheduler.h b/src/kiwano/2d/action/ActionScheduler.h index ddb9027c..60a6dc20 100644 --- a/src/kiwano/2d/action/ActionScheduler.h +++ b/src/kiwano/2d/action/ActionScheduler.h @@ -55,7 +55,7 @@ public: /// \~chinese /// @brief 获取指定名称的动画 /// @param name 动画名称 - ActionEntityPtr GetAction(const String& name); + ActionEntity* GetAction(const String& name); /// \~chinese /// @brief 获取所有动画 diff --git a/src/kiwano/2d/action/ActionTween.cpp b/src/kiwano/2d/action/ActionTween.cpp index c0c65865..421ff940 100644 --- a/src/kiwano/2d/action/ActionTween.cpp +++ b/src/kiwano/2d/action/ActionTween.cpp @@ -95,9 +95,9 @@ ActionTweenEntity::ActionTweenEntity() { } -ActionTweenEntity::ActionTweenEntity(Duration duration, EaseFunc func) +ActionTweenEntity::ActionTweenEntity(Duration duration) : dur_(duration) - , ease_func_(func) + , ease_func_(nullptr) { } @@ -129,33 +129,26 @@ void ActionTweenEntity::Update(Actor* target, Duration dt) UpdateTween(target, percent); } -ActionEntityPtr ActionTweenEntity::DoClone(ActionTweenEntityPtr to) const +void ActionTweenEntity::DoClone(ActionTweenEntity* to) const { if (to) { + ActionEntity::DoClone(to); to->SetDuration(this->GetDuration()); to->SetEaseFunc(this->GetEaseFunc()); } - return ActionEntity::DoClone(to); } //------------------------------------------------------- // Move Action //------------------------------------------------------- -ActionMoveByEntityPtr ActionMoveByEntity::Create(Duration duration, const Vec2& displacement) +ActionMoveByEntity::ActionMoveByEntity(Duration duration, const Vec2& displacement) + : ActionTweenEntity(duration) + , displacement_(displacement) { - ActionMoveByEntityPtr ptr = memory::New(); - if (ptr) - { - ptr->SetDuration(duration); - ptr->SetDisplacement(displacement); - } - return ptr; } -ActionMoveByEntity::ActionMoveByEntity() {} - void ActionMoveByEntity::Init(Actor* target) { if (target) @@ -175,32 +168,31 @@ void ActionMoveByEntity::UpdateTween(Actor* target, float percent) prev_pos_ = new_pos; } -ActionEntityPtr ActionMoveByEntity::Clone() const +ActionMoveByEntity* ActionMoveByEntity::Clone() const { - return DoClone(ActionMoveByEntity::Create(GetDuration(), displacement_)); -} - -ActionEntityPtr ActionMoveByEntity::Reverse() const -{ - return DoClone(ActionMoveByEntity::Create(GetDuration(), -displacement_)); -} - -ActionMoveToEntityPtr ActionMoveToEntity::Create(Duration duration, const Point& distination) -{ - ActionMoveToEntityPtr ptr = memory::New(); - if (ptr) - { - ptr->SetDuration(duration); - ptr->SetDistination(distination); - } + ActionMoveByEntity* ptr = new ActionMoveByEntity(GetDuration(), displacement_); + DoClone(ptr); return ptr; } -ActionMoveToEntity::ActionMoveToEntity() {} - -ActionEntityPtr ActionMoveToEntity::Clone() const +ActionMoveByEntity* ActionMoveByEntity::Reverse() const { - return DoClone(ActionMoveToEntity::Create(GetDuration(), distination_)); + ActionMoveByEntity* ptr = new ActionMoveByEntity(GetDuration(), -displacement_); + DoClone(ptr); + return ptr; +} + +ActionMoveToEntity::ActionMoveToEntity(Duration duration, const Point& distination) + : ActionMoveByEntity(duration, Vec2()) + , distination_(distination) +{ +} + +ActionMoveToEntity* ActionMoveToEntity::Clone() const +{ + ActionMoveToEntity* ptr = new ActionMoveToEntity(GetDuration(), distination_); + DoClone(ptr); + return ptr; } void ActionMoveToEntity::Init(Actor* target) @@ -213,33 +205,26 @@ void ActionMoveToEntity::Init(Actor* target) // Jump Action //------------------------------------------------------- -ActionJumpByEntityPtr ActionJumpByEntity::Create(Duration duration, const Vec2& displacement, float height, int count) +ActionJumpByEntity::ActionJumpByEntity(Duration duration, const Vec2& displacement, float height, int count) + : ActionTweenEntity(duration) + , height_(height) + , jump_count_(count) + , displacement_(displacement) { - ActionJumpByEntityPtr ptr = memory::New(); - if (ptr) - { - ptr->SetDuration(duration); - ptr->SetJumpHeight(height); - ptr->SetJumpCount(count); - ptr->SetDisplacement(displacement); - } +} + +ActionJumpByEntity* ActionJumpByEntity::Clone() const +{ + ActionJumpByEntity* ptr = new ActionJumpByEntity(GetDuration(), displacement_, height_, jump_count_); + DoClone(ptr); return ptr; } -ActionJumpByEntity::ActionJumpByEntity() - : height_(0.0f) - , jump_count_(0) +ActionJumpByEntity* ActionJumpByEntity::Reverse() const { -} - -ActionEntityPtr ActionJumpByEntity::Clone() const -{ - return DoClone(ActionJumpByEntity::Create(GetDuration(), displacement_, height_, jump_count_)); -} - -ActionEntityPtr ActionJumpByEntity::Reverse() const -{ - return DoClone(ActionJumpByEntity::Create(GetDuration(), -displacement_, height_, jump_count_)); + ActionJumpByEntity* ptr = new ActionJumpByEntity(GetDuration(), -displacement_, height_, jump_count_); + DoClone(ptr); + return ptr; } void ActionJumpByEntity::Init(Actor* target) @@ -266,24 +251,17 @@ void ActionJumpByEntity::UpdateTween(Actor* target, float percent) prev_pos_ = new_pos; } -ActionJumpToEntityPtr ActionJumpToEntity::Create(Duration duration, const Point& distination, float height, int count) +ActionJumpToEntity::ActionJumpToEntity(Duration duration, const Point& distination, float height, int count) + : ActionJumpByEntity(duration, Vec2(), height, count) + , distination_(distination) { - ActionJumpToEntityPtr ptr = memory::New(); - if (ptr) - { - ptr->SetDuration(duration); - ptr->SetJumpHeight(height); - ptr->SetJumpCount(count); - ptr->SetDistination(distination); - } - return ptr; } -ActionJumpToEntity::ActionJumpToEntity() {} - -ActionEntityPtr ActionJumpToEntity::Clone() const +ActionJumpToEntity* ActionJumpToEntity::Clone() const { - return DoClone(ActionJumpToEntity::Create(GetDuration(), distination_, height_, jump_count_)); + ActionJumpToEntity* ptr = new ActionJumpToEntity(GetDuration(), distination_, height_, jump_count_); + DoClone(ptr); + return ptr; } void ActionJumpToEntity::Init(Actor* target) @@ -296,21 +274,10 @@ void ActionJumpToEntity::Init(Actor* target) // Scale Action //------------------------------------------------------- -ActionScaleByEntityPtr ActionScaleByEntity::Create(Duration duration, float scale_x, float scale_y) -{ - ActionScaleByEntityPtr ptr = memory::New(); - if (ptr) - { - ptr->SetDuration(duration); - ptr->SetScaleX(scale_x); - ptr->SetScaleY(scale_y); - } - return ptr; -} - -ActionScaleByEntity::ActionScaleByEntity() - : delta_x_(0.0f) - , delta_y_(0.0f) +ActionScaleByEntity::ActionScaleByEntity(Duration duration, float scale_x, float scale_y) + : ActionTweenEntity(duration) + , delta_x_(scale_x) + , delta_y_(scale_y) , start_scale_x_(0.f) , start_scale_y_(0.f) { @@ -330,37 +297,32 @@ void ActionScaleByEntity::UpdateTween(Actor* target, float percent) target->SetScale(Vec2{ start_scale_x_ + delta_x_ * percent, start_scale_y_ + delta_y_ * percent }); } -ActionEntityPtr ActionScaleByEntity::Clone() const +ActionScaleByEntity* ActionScaleByEntity::Clone() const { - return DoClone(ActionScaleByEntity::Create(GetDuration(), delta_x_, delta_y_)); -} - -ActionEntityPtr ActionScaleByEntity::Reverse() const -{ - return DoClone(ActionScaleByEntity::Create(GetDuration(), -delta_x_, -delta_y_)); -} - -ActionScaleToEntityPtr ActionScaleToEntity::Create(Duration duration, float scale_x, float scale_y) -{ - ActionScaleToEntityPtr ptr = memory::New(); - if (ptr) - { - ptr->SetDuration(duration); - ptr->SetTargetScaleX(scale_x); - ptr->SetTargetScaleY(scale_y); - } + ActionScaleByEntity* ptr = new ActionScaleByEntity(GetDuration(), delta_x_, delta_y_); + DoClone(ptr); return ptr; } -ActionScaleToEntity::ActionScaleToEntity() - : end_scale_x_(0.0f) - , end_scale_y_(0.0f) +ActionScaleByEntity* ActionScaleByEntity::Reverse() const +{ + ActionScaleByEntity* ptr = new ActionScaleByEntity(GetDuration(), -delta_x_, -delta_y_); + DoClone(ptr); + return ptr; +} + +ActionScaleToEntity::ActionScaleToEntity(Duration duration, float scale_x, float scale_y) + : ActionScaleByEntity(duration, 0, 0) + , end_scale_x_(scale_x) + , end_scale_y_(scale_y) { } -ActionEntityPtr ActionScaleToEntity::Clone() const +ActionScaleToEntity* ActionScaleToEntity::Clone() const { - return DoClone(ActionScaleToEntity::Create(GetDuration(), end_scale_x_, end_scale_y_)); + ActionScaleToEntity* ptr = new ActionScaleToEntity(GetDuration(), end_scale_x_, end_scale_y_); + DoClone(ptr); + return ptr; } void ActionScaleToEntity::Init(Actor* target) @@ -374,21 +336,11 @@ void ActionScaleToEntity::Init(Actor* target) // Opacity Action //------------------------------------------------------- -ActionFadeToEntityPtr ActionFadeToEntity::Create(Duration duration, float opacity) -{ - ActionFadeToEntityPtr ptr = memory::New(); - if (ptr) - { - ptr->SetDuration(duration); - ptr->SetTargetOpacity(opacity); - } - return ptr; -} - -ActionFadeToEntity::ActionFadeToEntity() - : delta_val_(0.0f) +ActionFadeToEntity::ActionFadeToEntity(Duration duration, float opacity) + : ActionTweenEntity(duration) + , delta_val_(0.0f) , start_val_(0.f) - , end_val_(0.0f) + , end_val_(opacity) { } @@ -406,29 +358,21 @@ void ActionFadeToEntity::UpdateTween(Actor* target, float percent) target->SetOpacity(start_val_ + delta_val_ * percent); } -ActionEntityPtr ActionFadeToEntity::Clone() const +ActionFadeToEntity* ActionFadeToEntity::Clone() const { - return DoClone(ActionFadeToEntity::Create(GetDuration(), end_val_)); + ActionFadeToEntity* ptr = new ActionFadeToEntity(GetDuration(), end_val_); + DoClone(ptr); + return ptr; } //------------------------------------------------------- // Rotate Action //------------------------------------------------------- -ActionRotateByEntityPtr ActionRotateByEntity::Create(Duration duration, float rotation) -{ - ActionRotateByEntityPtr ptr = memory::New(); - if (ptr) - { - ptr->SetDuration(duration); - ptr->SetRotation(rotation); - } - return ptr; -} - -ActionRotateByEntity::ActionRotateByEntity() - : start_val_(0.0f) - , delta_val_(0.0f) +ActionRotateByEntity::ActionRotateByEntity(Duration duration, float rotation) + : ActionTweenEntity(duration) + , delta_val_(rotation) + , start_val_(0.0f) { } @@ -449,35 +393,31 @@ void ActionRotateByEntity::UpdateTween(Actor* target, float percent) target->SetRotation(rotation); } -ActionEntityPtr ActionRotateByEntity::Clone() const +ActionRotateByEntity* ActionRotateByEntity::Clone() const { - return DoClone(ActionRotateByEntity::Create(GetDuration(), delta_val_)); -} - -ActionEntityPtr ActionRotateByEntity::Reverse() const -{ - return DoClone(ActionRotateByEntity::Create(GetDuration(), -delta_val_)); -} - -ActionRotateToEntityPtr ActionRotateToEntity::Create(Duration duration, float rotation) -{ - ActionRotateToEntityPtr ptr = memory::New(); - if (ptr) - { - ptr->SetDuration(duration); - ptr->SetTargetRotation(rotation); - } + ActionRotateByEntity* ptr = new ActionRotateByEntity(GetDuration(), delta_val_); + DoClone(ptr); return ptr; } -ActionRotateToEntity::ActionRotateToEntity() - : end_val_(0.0f) +ActionRotateByEntity* ActionRotateByEntity::Reverse() const +{ + ActionRotateByEntity* ptr = new ActionRotateByEntity(GetDuration(), -delta_val_); + DoClone(ptr); + return ptr; +} + +ActionRotateToEntity::ActionRotateToEntity(Duration duration, float rotation) + : ActionRotateByEntity(duration, 0) + , end_val_(rotation) { } -ActionEntityPtr ActionRotateToEntity::Clone() const +ActionRotateToEntity* ActionRotateToEntity::Clone() const { - return DoClone(ActionRotateToEntity::Create(GetDuration(), end_val_)); + ActionRotateToEntity* ptr = new ActionRotateToEntity(GetDuration(), end_val_); + DoClone(ptr); + return ptr; } void ActionRotateToEntity::Init(Actor* target) @@ -490,22 +430,17 @@ void ActionRotateToEntity::Init(Actor* target) // ActionCustomEntity //------------------------------------------------------- -ActionCustomEntityPtr ActionCustomEntity::Create(Duration duration, ActionCustom::TweenFunc tween_func) +ActionCustomEntity::ActionCustomEntity(Duration duration, ActionCustom::TweenFunc tween_func) + : ActionTweenEntity(duration) + , tween_func_(tween_func) { - ActionCustomEntityPtr ptr = memory::New(); - if (ptr) - { - ptr->SetDuration(duration); - ptr->SetTweenFunc(tween_func); - } - return ptr; } -ActionCustomEntity::ActionCustomEntity() {} - -ActionEntityPtr ActionCustomEntity::Clone() const +ActionCustomEntity* ActionCustomEntity::Clone() const { - return DoClone(ActionCustomEntity::Create(GetDuration(), tween_func_)); + ActionCustomEntity* ptr = new ActionCustomEntity(GetDuration(), tween_func_); + DoClone(ptr); + return ptr; } void ActionCustomEntity::Init(Actor* target) @@ -522,72 +457,72 @@ void ActionCustomEntity::UpdateTween(Actor* target, float percent) ActionMoveBy::ActionMoveBy(Duration duration, const Vec2& displacement) { - SetEntity(ActionMoveByEntity::Create(duration, displacement)); + SetEntity(MakePtr(duration, displacement)); } ActionMoveTo::ActionMoveTo(Duration duration, const Point& distination) { - SetEntity(ActionMoveToEntity::Create(duration, distination)); + SetEntity(MakePtr(duration, distination)); } ActionJumpBy::ActionJumpBy(Duration duration, const Vec2& displacement, float height, int count) { - SetEntity(ActionJumpByEntity::Create(duration, displacement, height, count)); + SetEntity(MakePtr(duration, displacement, height, count)); } ActionJumpTo::ActionJumpTo(Duration duration, const Point& distination, float height, int count) { - SetEntity(ActionJumpToEntity::Create(duration, distination, height, count)); + SetEntity(MakePtr(duration, distination, height, count)); } ActionScaleBy::ActionScaleBy(Duration duration, float scale_x, float scale_y) { - SetEntity(ActionScaleByEntity::Create(duration, scale_x, scale_y)); + SetEntity(MakePtr(duration, scale_x, scale_y)); } ActionScaleBy::ActionScaleBy(Duration duration, Vec2 scale) { - SetEntity(ActionScaleByEntity::Create(duration, scale.x, scale.y)); + SetEntity(MakePtr(duration, scale.x, scale.y)); } ActionScaleTo::ActionScaleTo(Duration duration, float scale_x, float scale_y) { - SetEntity(ActionScaleToEntity::Create(duration, scale_x, scale_y)); + SetEntity(MakePtr(duration, scale_x, scale_y)); } ActionScaleTo::ActionScaleTo(Duration duration, Vec2 scale) { - SetEntity(ActionScaleToEntity::Create(duration, scale.x, scale.y)); + SetEntity(MakePtr(duration, scale.x, scale.y)); } ActionFadeTo::ActionFadeTo(Duration duration, float opacity) { - SetEntity(ActionFadeToEntity::Create(duration, opacity)); + SetEntity(MakePtr(duration, opacity)); } ActionFadeIn::ActionFadeIn(Duration duration) { - SetEntity(ActionFadeToEntity::Create(duration, 1.0f)); + SetEntity(MakePtr(duration, 1.0f)); } ActionFadeOut::ActionFadeOut(Duration duration) { - SetEntity(ActionFadeToEntity::Create(duration, 0.0f)); + SetEntity(MakePtr(duration, 0.0f)); } ActionRotateBy::ActionRotateBy(Duration duration, float rotation) { - SetEntity(ActionRotateByEntity::Create(duration, rotation)); + SetEntity(MakePtr(duration, rotation)); } ActionRotateTo::ActionRotateTo(Duration duration, float rotation) { - SetEntity(ActionRotateToEntity::Create(duration, rotation)); + SetEntity(MakePtr(duration, rotation)); } ActionCustom::ActionCustom(Duration duration, TweenFunc tween_func) { - SetEntity(ActionCustomEntity::Create(duration, tween_func)); + SetEntity(MakePtr(duration, tween_func)); } } // namespace kiwano diff --git a/src/kiwano/2d/action/ActionTween.h b/src/kiwano/2d/action/ActionTween.h index 4f1c2085..53d1608a 100644 --- a/src/kiwano/2d/action/ActionTween.h +++ b/src/kiwano/2d/action/ActionTween.h @@ -88,14 +88,6 @@ KGE_DECLARE_SMART_PTR(ActionCustomEntity); class KGE_API ActionTweenEntity : public ActionEntity { public: - ActionTweenEntity(); - - /// \~chinese - /// @brief 补间动画 - /// @param duration 动画时长 - /// @param func 动画速度缓动函数 - ActionTweenEntity(Duration duration, EaseFunc ease); - /// \~chinese /// @brief 获取动画时长 Duration GetDuration() const; @@ -113,11 +105,19 @@ public: void SetEaseFunc(const EaseFunc& func); protected: + ActionTweenEntity(); + + /// \~chinese + /// @brief 补间动画 + /// @param duration 动画时长 + /// @param func 动画速度缓动函数 + ActionTweenEntity(Duration duration); + void Update(Actor* target, Duration dt) override; virtual void UpdateTween(Actor* target, float percent) = 0; - ActionEntityPtr DoClone(ActionTweenEntityPtr to) const; + void DoClone(ActionTweenEntity* to) const; private: Duration dur_; @@ -132,8 +132,8 @@ public: ActionTween() = default; inline ActionTween(ActionTweenEntityPtr ptr) - : Action(ptr.Get()) { + SetEntity(ptr); } /// \~chinese @@ -150,14 +150,14 @@ public: /// @brief 获取指针 inline ActionTweenEntity* Get() const { - return const_cast(static_cast(ptr.Get())); + return static_cast(Action::Get()); } /// \~chinese /// @brief 设置动画实体 inline void SetEntity(ActionTweenEntityPtr tween_ptr) { - this->ptr = static_cast(tween_ptr.Get()); + Action::SetEntity(tween_ptr.Get()); } inline ActionTweenEntity* operator->() const @@ -187,9 +187,7 @@ public: /// @brief 创建相对位移动画 /// @param duration 动画时长 /// @param displacement 位移向量 - static ActionMoveByEntityPtr Create(Duration duration, const Vec2& displacement); - - ActionMoveByEntity(); + ActionMoveByEntity(Duration duration, const Vec2& displacement); /// \~chinese /// @brief 获取位移向量 @@ -201,11 +199,11 @@ public: /// \~chinese /// @brief 获取该动画的拷贝对象 - ActionEntityPtr Clone() const override; + ActionMoveByEntity* Clone() const override; /// \~chinese /// @brief 获取该动画的倒转 - ActionEntityPtr Reverse() const override; + ActionMoveByEntity* Reverse() const override; protected: void Init(Actor* target) override; @@ -239,9 +237,7 @@ public: /// @brief 创建位移动画 /// @param duration 动画时长 /// @param distination 目的坐标 - static ActionMoveToEntityPtr Create(Duration duration, const Point& distination); - - ActionMoveToEntity(); + ActionMoveToEntity(Duration duration, const Point& distination); /// \~chinese /// @brief 获取目的坐标 @@ -253,11 +249,11 @@ public: /// \~chinese /// @brief 获取该动画的拷贝对象 - ActionEntityPtr Clone() const override; + ActionMoveToEntity* Clone() const override; /// \~chinese /// @brief 获取该动画的倒转 - virtual ActionEntityPtr Reverse() const override + ActionMoveToEntity* Reverse() const override { KGE_ERRORF("Reverse() not supported in ActionMoveToEntity"); return nullptr; @@ -295,9 +291,7 @@ public: /// @param displacement 跳跃位移向量 /// @param height 跳跃高度 /// @param count 跳跃次数 - static ActionJumpByEntityPtr Create(Duration duration, const Vec2& displacement, float height, int count = 1); - - ActionJumpByEntity(); + ActionJumpByEntity(Duration duration, const Vec2& displacement, float height, int count = 1); /// \~chinese /// @brief 获取跳跃位移 @@ -325,11 +319,11 @@ public: /// \~chinese /// @brief 获取该动画的拷贝对象 - ActionEntityPtr Clone() const override; + ActionJumpByEntity* Clone() const override; /// \~chinese /// @brief 获取该动画的倒转 - ActionEntityPtr Reverse() const override; + ActionJumpByEntity* Reverse() const override; protected: void Init(Actor* target) override; @@ -369,9 +363,7 @@ public: /// @param distination 目的坐标 /// @param height 跳跃高度 /// @param count 跳跃次数 - static ActionJumpToEntityPtr Create(Duration duration, const Point& distination, float height, int count = 1); - - ActionJumpToEntity(); + ActionJumpToEntity(Duration duration, const Point& distination, float height, int count = 1); /// \~chinese /// @brief 获取目的坐标 @@ -383,11 +375,11 @@ public: /// \~chinese /// @brief 获取该动画的拷贝对象 - ActionEntityPtr Clone() const override; + ActionJumpToEntity* Clone() const override; /// \~chinese /// @brief 获取该动画的倒转 - virtual ActionEntityPtr Reverse() const override + ActionJumpToEntity* Reverse() const override { KGE_ERRORF("Reverse() not supported in ActionJumpToEntity"); return nullptr; @@ -429,9 +421,7 @@ public: /// @param duration 动画时长 /// @param scale_x 横向缩放相对变化值 /// @param scale_y 纵向缩放相对变化值 - static ActionScaleByEntityPtr Create(Duration duration, float scale_x, float scale_y); - - ActionScaleByEntity(); + ActionScaleByEntity(Duration duration, float scale_x, float scale_y); /// \~chinese /// @brief 获取横向缩放相对变化值 @@ -451,11 +441,11 @@ public: /// \~chinese /// @brief 获取该动画的拷贝对象 - ActionEntityPtr Clone() const override; + ActionScaleByEntity* Clone() const override; /// \~chinese /// @brief 获取该动画的倒转 - ActionEntityPtr Reverse() const override; + ActionScaleByEntity* Reverse() const override; protected: void Init(Actor* target) override; @@ -498,9 +488,7 @@ public: /// @param duration 动画时长 /// @param scale_x 横向缩放目标值 /// @param scale_y 纵向缩放目标值 - static ActionScaleToEntityPtr Create(Duration duration, float scale_x, float scale_y); - - ActionScaleToEntity(); + ActionScaleToEntity(Duration duration, float scale_x, float scale_y); /// \~chinese /// @brief 获取横向缩放目标值 @@ -520,11 +508,11 @@ public: /// \~chinese /// @brief 获取该动画的拷贝对象 - ActionEntityPtr Clone() const override; + ActionScaleToEntity* Clone() const override; /// \~chinese /// @brief 获取该动画的倒转 - virtual ActionEntityPtr Reverse() const override + ActionScaleToEntity* Reverse() const override { KGE_ERRORF("Reverse() not supported in ActionScaleToEntity"); return nullptr; @@ -581,9 +569,7 @@ public: /// @brief 创建透明度渐变动画 /// @param duration 动画时长 /// @param opacity 目标透明度 - static ActionFadeToEntityPtr Create(Duration duration, float opacity); - - ActionFadeToEntity(); + ActionFadeToEntity(Duration duration, float opacity); /// \~chinese /// @brief 获取目标透明度 @@ -595,11 +581,11 @@ public: /// \~chinese /// @brief 获取该动画的拷贝对象 - ActionEntityPtr Clone() const override; + ActionFadeToEntity* Clone() const override; /// \~chinese /// @brief 获取该动画的倒转 - virtual ActionEntityPtr Reverse() const override + ActionFadeToEntity* Reverse() const override { KGE_ERRORF("Reverse() not supported in ActionFadeToEntity"); return nullptr; @@ -637,9 +623,7 @@ public: /// @brief 创建相对旋转动画 /// @param duration 动画时长 /// @param rotation 角度相对变化值 - static ActionRotateByEntityPtr Create(Duration duration, float rotation); - - ActionRotateByEntity(); + ActionRotateByEntity(Duration duration, float rotation); /// \~chinese /// @brief 获取角度相对变化值 @@ -651,11 +635,11 @@ public: /// \~chinese /// @brief 获取该动画的拷贝对象 - ActionEntityPtr Clone() const override; + ActionRotateByEntity* Clone() const override; /// \~chinese /// @brief 获取该动画的倒转 - ActionEntityPtr Reverse() const override; + ActionRotateByEntity* Reverse() const override; protected: void Init(Actor* target) override; @@ -688,9 +672,7 @@ public: /// @brief 创建旋转动画 /// @param duration 动画时长 /// @param rotation 目标角度 - static ActionRotateToEntityPtr Create(Duration duration, float rotation); - - ActionRotateToEntity(); + ActionRotateToEntity(Duration duration, float rotation); /// \~chinese /// @brief 获取目标角度 @@ -702,11 +684,11 @@ public: /// \~chinese /// @brief 获取该动画的拷贝对象 - ActionEntityPtr Clone() const override; + ActionRotateToEntity* Clone() const override; /// \~chinese /// @brief 获取该动画的倒转 - virtual ActionEntityPtr Reverse() const override + ActionRotateToEntity* Reverse() const override { KGE_ERRORF("Reverse() not supported in ActionRotateToEntity"); return nullptr; @@ -745,9 +727,7 @@ public: /// @brief 创建自定义动画 /// @param duration 动画时长 /// @param tween_func 动画回调函数 - static ActionCustomEntityPtr Create(Duration duration, ActionCustom::TweenFunc tween_func); - - ActionCustomEntity(); + ActionCustomEntity(Duration duration, ActionCustom::TweenFunc tween_func); /// \~chinese /// @brief 获取动画回调函数 @@ -759,11 +739,11 @@ public: /// \~chinese /// @brief 获取该动画的拷贝对象 - ActionEntityPtr Clone() const override; + ActionCustomEntity* Clone() const override; /// \~chinese /// @brief 获取该动画的倒转 - ActionEntityPtr Reverse() const override + ActionCustomEntity* Reverse() const override { KGE_ERRORF("Reverse() not supported in ActionCustomEntity"); return nullptr; diff --git a/src/kiwano/2d/action/ActionWalk.cpp b/src/kiwano/2d/action/ActionWalk.cpp index 8a1eb12c..71d1c3d7 100644 --- a/src/kiwano/2d/action/ActionWalk.cpp +++ b/src/kiwano/2d/action/ActionWalk.cpp @@ -26,39 +26,31 @@ namespace kiwano ActionWalk::ActionWalk(Duration duration, ShapePtr path, bool rotating, float start, float end) { - SetEntity(ActionWalkEntity::Create(duration, path, rotating, start, end)); + SetEntity(MakePtr(duration, path, rotating, start, end)); } -ActionWalkEntityPtr ActionWalkEntity::Create(Duration duration, ShapePtr path, bool rotating, float start, float end) +ActionWalkEntity::ActionWalkEntity(Duration duration, ShapePtr path, bool rotating, float start, float end) + : ActionTweenEntity(duration) + , start_(start) + , end_(end) + , rotating_(rotating) + , length_(0.f) + , path_(path) { - ActionWalkEntityPtr ptr = memory::New(); - if (ptr) - { - ptr->SetDuration(duration); - ptr->SetPath(path); - ptr->SetRotating(rotating); - ptr->SetStartValue(start); - ptr->SetEndValue(end); - } +} + +ActionWalkEntity* ActionWalkEntity::Clone() const +{ + ActionWalkEntity* ptr = new ActionWalkEntity(GetDuration(), path_, rotating_, start_, end_); + DoClone(ptr); return ptr; } -ActionWalkEntity::ActionWalkEntity() - : start_(0.0f) - , end_(1.0f) - , rotating_(false) - , length_(0.f) +ActionWalkEntity* ActionWalkEntity::Reverse() const { -} - -ActionEntityPtr ActionWalkEntity::Clone() const -{ - return DoClone(ActionWalkEntity::Create(GetDuration(), path_, rotating_, start_, end_)); -} - -ActionEntityPtr ActionWalkEntity::Reverse() const -{ - return DoClone(ActionWalkEntity::Create(GetDuration(), path_, rotating_, end_, start_)); + ActionWalkEntity* ptr = new ActionWalkEntity(GetDuration(), path_, rotating_, end_, start_); + DoClone(ptr); + return ptr; } void ActionWalkEntity::Init(Actor* target) diff --git a/src/kiwano/2d/action/ActionWalk.h b/src/kiwano/2d/action/ActionWalk.h index 4f373f22..9a11873c 100644 --- a/src/kiwano/2d/action/ActionWalk.h +++ b/src/kiwano/2d/action/ActionWalk.h @@ -59,10 +59,7 @@ public: /// @param rotating 是否沿路径切线方向旋转 /// @param start 路径起点(百分比) /// @param end 路径终点(百分比) - static ActionWalkEntityPtr Create(Duration duration, ShapePtr path, bool rotating = false, float start = 0.f, - float end = 1.f); - - ActionWalkEntity(); + ActionWalkEntity(Duration duration, ShapePtr path, bool rotating = false, float start = 0.f, float end = 1.f); /// \~chinese /// @brief 获取路线 @@ -98,11 +95,11 @@ public: /// \~chinese /// @brief 获取该动画的拷贝对象 - ActionEntityPtr Clone() const override; + ActionWalkEntity* Clone() const override; /// \~chinese /// @brief 获取该动画的倒转 - ActionEntityPtr Reverse() const override; + ActionWalkEntity* Reverse() const override; protected: void Init(Actor* target) override; diff --git a/src/kiwano/2d/action/Animation.cpp b/src/kiwano/2d/action/Animation.cpp index 3e494f48..2ac98c25 100644 --- a/src/kiwano/2d/action/Animation.cpp +++ b/src/kiwano/2d/action/Animation.cpp @@ -27,18 +27,7 @@ namespace kiwano Animation::Animation(Duration dur, FrameSequencePtr frame_seq) { - SetEntity(AnimationEntity::Create(dur, frame_seq)); -} - -AnimationEntityPtr AnimationEntity::Create(Duration dur, FrameSequencePtr frame_seq) -{ - AnimationEntityPtr ptr = memory::New(); - if (ptr) - { - ptr->SetDuration(dur); - ptr->SetFrameSequence(frame_seq); - } - return ptr; + SetEntity(MakePtr(dur, frame_seq)); } AnimationEntity::AnimationEntity() @@ -46,6 +35,12 @@ AnimationEntity::AnimationEntity() { } +AnimationEntity::AnimationEntity(Duration dur, FrameSequencePtr frame_seq) + : ActionTweenEntity(dur) + , frame_seq_(frame_seq) +{ +} + AnimationEntity::~AnimationEntity() {} FrameSequencePtr AnimationEntity::GetFrameSequence() const @@ -90,26 +85,24 @@ void AnimationEntity::UpdateTween(Actor* target, float percent) } } -ActionEntityPtr AnimationEntity::Clone() const +AnimationEntity* AnimationEntity::Clone() const { - if (frame_seq_) - { - return DoClone(AnimationEntity::Create(GetDuration(), frame_seq_)); - } - return nullptr; + AnimationEntity* ptr = new AnimationEntity(GetDuration(), frame_seq_); + DoClone(ptr); + return ptr; } -ActionEntityPtr AnimationEntity::Reverse() const +AnimationEntity* AnimationEntity::Reverse() const { + AnimationEntity* ptr = new AnimationEntity(GetDuration(), nullptr); + DoClone(ptr); + if (frame_seq_) { FrameSequencePtr frames = frame_seq_->Reverse(); - if (frames) - { - return DoClone(AnimationEntity::Create(GetDuration(), frames)); - } + ptr->SetFrameSequence(frames); } - return nullptr; + return ptr; } } // namespace kiwano diff --git a/src/kiwano/2d/action/Animation.h b/src/kiwano/2d/action/Animation.h index a161a9a5..714529ad 100644 --- a/src/kiwano/2d/action/Animation.h +++ b/src/kiwano/2d/action/Animation.h @@ -49,13 +49,13 @@ public: class KGE_API AnimationEntity : public ActionTweenEntity { public: + AnimationEntity(); + /// \~chinese /// @brief 创建帧动画 /// @param dur 动画时长 /// @param frame_seq 序列帧 - static AnimationEntityPtr Create(Duration dur, FrameSequencePtr frame_seq); - - AnimationEntity(); + AnimationEntity(Duration dur, FrameSequencePtr frame_seq); virtual ~AnimationEntity(); @@ -70,11 +70,11 @@ public: /// \~chinese /// @brief 获取该动画的拷贝对象 - ActionEntityPtr Clone() const override; + AnimationEntity* Clone() const override; /// \~chinese /// @brief 获取该动画的倒转 - ActionEntityPtr Reverse() const override; + AnimationEntity* Reverse() const override; protected: void Init(Actor* target) override; @@ -86,4 +86,5 @@ private: }; /** @} */ + } // namespace kiwano diff --git a/src/kiwano/base/Director.cpp b/src/kiwano/base/Director.cpp index 6b221030..340076a6 100644 --- a/src/kiwano/base/Director.cpp +++ b/src/kiwano/base/Director.cpp @@ -23,10 +23,10 @@ #include #include #include -#include namespace kiwano { + Director::Director() : render_border_enabled_(false) { @@ -50,7 +50,7 @@ void Director::EnterStage(StagePtr stage, TransitionPtr transition) transition_->Stop(); } transition_ = transition; - transition_->Init(current_stage_, next_stage_); + transition_->Init(current_stage_.Get(), next_stage_.Get()); } } @@ -81,7 +81,7 @@ void Director::PopStage(TransitionPtr transition) transition_->Stop(); } transition_ = transition; - transition_->Init(current_stage_, next_stage_); + transition_->Init(current_stage_.Get(), next_stage_.Get()); } } @@ -100,7 +100,7 @@ void Director::ShowDebugInfo(bool show) if (show) { if (!debug_actor_) - debug_actor_ = memory::New(); + debug_actor_ = MakePtr(); } else { @@ -119,11 +119,11 @@ void Director::ClearStages() debug_actor_.Reset(); } -void Director::OnUpdate(Duration dt) +void Director::OnUpdate(UpdateModuleContext& ctx) { if (transition_) { - transition_->Update(dt); + transition_->Update(ctx.dt); if (transition_->IsDone()) transition_ = nullptr; @@ -143,47 +143,47 @@ void Director::OnUpdate(Duration dt) } if (current_stage_) - current_stage_->Update(dt); + current_stage_->Update(ctx.dt); if (next_stage_) - next_stage_->Update(dt); + next_stage_->Update(ctx.dt); if (debug_actor_) - debug_actor_->Update(dt); + debug_actor_->Update(ctx.dt); } -void Director::OnRender(RenderContext& ctx) +void Director::OnRender(RenderModuleContext& ctx) { if (transition_) { - transition_->Render(ctx); + transition_->Render(ctx.render_ctx); } else if (current_stage_) { - current_stage_->Render(ctx); + current_stage_->Render(ctx.render_ctx); if (render_border_enabled_) { - current_stage_->RenderBorder(ctx); + current_stage_->RenderBorder(ctx.render_ctx); } } if (debug_actor_) { - debug_actor_->Render(ctx); + debug_actor_->Render(ctx.render_ctx); } } -void Director::HandleEvent(Event* evt) +void Director::HandleEvent(EventModuleContext& ctx) { if (current_stage_) - current_stage_->DispatchEvent(evt); + current_stage_->DispatchEvent(ctx.evt); if (next_stage_) - next_stage_->DispatchEvent(evt); + next_stage_->DispatchEvent(ctx.evt); if (debug_actor_) - debug_actor_->DispatchEvent(evt); + debug_actor_->DispatchEvent(ctx.evt); } } // namespace kiwano diff --git a/src/kiwano/base/Director.h b/src/kiwano/base/Director.h index 6a775670..c216e590 100644 --- a/src/kiwano/base/Director.h +++ b/src/kiwano/base/Director.h @@ -34,9 +34,7 @@ namespace kiwano */ class KGE_API Director : public Singleton - , public UpdateModule - , public RenderModule - , public EventModule + , public Module { friend Singleton; @@ -92,15 +90,11 @@ public: void ClearStages(); public: - void SetupModule() override {} + void OnUpdate(UpdateModuleContext& ctx) override; - void DestroyModule() override {} + void OnRender(RenderModuleContext& ctx) override; - void OnUpdate(Duration dt) override; - - void OnRender(RenderContext& ctx) override; - - void HandleEvent(Event* evt) override; + void HandleEvent(EventModuleContext& ctx) override; virtual ~Director(); diff --git a/src/kiwano/base/Module.cpp b/src/kiwano/base/Module.cpp index 009100bb..8a7287fe 100644 --- a/src/kiwano/base/Module.cpp +++ b/src/kiwano/base/Module.cpp @@ -19,28 +19,118 @@ // THE SOFTWARE. #include +#include namespace kiwano { -Module::Module() - : flag_(0) +ModuleContext::ModuleContext(ModuleList& modules) + : index_(-1) + , modules_(modules) { } -RenderModule::RenderModule() +ModuleContext::~ModuleContext() {} + +void ModuleContext::ResetIndex() { - flag_ |= ModuleFlag::value; + index_ = -1; } -UpdateModule::UpdateModule() +void ModuleContext::Next() { - flag_ |= ModuleFlag::value; + index_++; + for (; index_ < (int)modules_.size(); index_++) + { + this->Handle(modules_.at(index_)); + } } -EventModule::EventModule() +RenderModuleContext::RenderModuleContext(ModuleList& modules, RenderContext& ctx) + : ModuleContext(modules) + , step_(Step::Before) + , render_ctx(ctx) +{ + this->Next(); + this->ResetIndex(); + + render_ctx.BeginDraw(); + step_ = Step::Rendering; +} + +RenderModuleContext::~RenderModuleContext() +{ + render_ctx.EndDraw(); + step_ = Step::After; + + this->ResetIndex(); + this->Next(); +} + +void RenderModuleContext::Handle(Module* m) +{ + switch (step_) + { + case RenderModuleContext::Step::Before: + m->BeforeRender(*this); + break; + case RenderModuleContext::Step::Rendering: + m->OnRender(*this); + break; + case RenderModuleContext::Step::After: + m->AfterRender(*this); + break; + default: + break; + } +} + +UpdateModuleContext::UpdateModuleContext(ModuleList& modules, Duration dt) + : ModuleContext(modules) + , dt(dt) +{ +} + +void UpdateModuleContext::Handle(Module* m) +{ + m->OnUpdate(*this); +} + +EventModuleContext::EventModuleContext(ModuleList& modules, Event* evt) + : ModuleContext(modules) + , evt(evt) +{ +} + +void EventModuleContext::Handle(Module* m) +{ + m->HandleEvent(*this); +} + +Module::Module() {} + +void Module::SetupModule() {} + +void Module::DestroyModule() {} + +void Module::OnRender(RenderModuleContext& ctx) +{ +} + +void Module::OnUpdate(UpdateModuleContext& ctx) +{ +} + +void Module::HandleEvent(EventModuleContext& ctx) +{ +} + +void Module::BeforeRender(RenderModuleContext& ctx) +{ +} + +void Module::AfterRender(RenderModuleContext& ctx) { - flag_ |= ModuleFlag::value; } } // namespace kiwano diff --git a/src/kiwano/base/Module.h b/src/kiwano/base/Module.h index f9a95340..7130088c 100644 --- a/src/kiwano/base/Module.h +++ b/src/kiwano/base/Module.h @@ -25,124 +25,126 @@ namespace kiwano { class RenderContext; class Event; +class Module; -template -struct ModuleFlag; +/// \~chinese +/// @brief 模块列表 +typedef Vector ModuleList; + +/// \~chinese +/// @brief 模块上下文 +class KGE_API ModuleContext +{ +public: + void Next(); + +protected: + ModuleContext(ModuleList& modules); + + virtual ~ModuleContext(); + + virtual void Handle(Module* m) = 0; + + void ResetIndex(); + +private: + int index_; + ModuleList& modules_; +}; + +/// \~chinese +/// @brief 渲染模块上下文 +class KGE_API RenderModuleContext : public ModuleContext +{ +public: + RenderContext& render_ctx; + + RenderModuleContext(ModuleList& modules, RenderContext& ctx); + + virtual ~RenderModuleContext(); + +protected: + void Handle(Module* m) override; + +private: + enum class Step + { + Before, + Rendering, + After, + }; + + Step step_; +}; + +/// \~chinese +/// @brief 更新模块上下文 +class KGE_API UpdateModuleContext : public ModuleContext +{ +public: + Duration dt; + + UpdateModuleContext(ModuleList& modules, Duration dt); + +protected: + void Handle(Module* m) override; +}; + +/// \~chinese +/// @brief 时间模块上下文 +class KGE_API EventModuleContext : public ModuleContext +{ +public: + Event* evt; + + EventModuleContext(ModuleList& modules, Event* evt); + +protected: + void Handle(Module* m) override; +}; /** * \~chinese * @brief 基础模块 */ -class KGE_API Module +class KGE_API Module : Noncopyable { public: /// \~chinese /// @brief 启动模块 - virtual void SetupModule() {} + virtual void SetupModule(); /// \~chinese /// @brief 销毁模块 - virtual void DestroyModule() {} + virtual void DestroyModule(); - template - _CompTy* Cast() - { - if (flag_ & ModuleFlag<_CompTy>::value) - return dynamic_cast<_CompTy*>(this); - return nullptr; - } + /// \~chinese + /// @brief 更新时 + /// @param ctx 更新上下文 + virtual void OnUpdate(UpdateModuleContext& ctx); -protected: - Module(); + /// \~chinese + /// @brief 事件处理 + /// @param ctx 事件上下文 + virtual void HandleEvent(EventModuleContext& ctx); -protected: - int flag_; -}; - -/** - * \~chinese - * @brief 渲染模块 - */ -class KGE_API RenderModule : public virtual Module -{ -public: /// \~chinese /// @brief 渲染前 - virtual void BeforeRender() {} + /// @param ctx 渲染上下文 + virtual void BeforeRender(RenderModuleContext& ctx); /// \~chinese /// @brief 渲染时 /// @param ctx 渲染上下文 - virtual void OnRender(RenderContext& ctx) {} + virtual void OnRender(RenderModuleContext& ctx); /// \~chinese /// @brief 渲染后 - virtual void AfterRender() {} + /// @param ctx 渲染上下文 + virtual void AfterRender(RenderModuleContext& ctx); -public: - RenderModule(); +protected: + Module(); }; -/** - * \~chinese - * @brief 更新模块 - */ -class KGE_API UpdateModule : public virtual Module -{ -public: - /// \~chinese - /// @brief 更新前 - virtual void BeforeUpdate() {} - - /// \~chinese - /// @brief 更新时 - /// @param dt 间隔时间 - virtual void OnUpdate(Duration dt) {} - - /// \~chinese - /// @brief 更新后 - virtual void AfterUpdate() {} - -public: - UpdateModule(); -}; - -/** - * \~chinese - * @brief 事件模块 - */ -class KGE_API EventModule : public virtual Module -{ -public: - /// \~chinese - /// @brief 事件处理 - /// @param evt 事件 - virtual void HandleEvent(Event* evt) {} - -public: - EventModule(); -}; - -#define KGE_DEFINE_COMPONENT_FLAG(OFFSET) (0x01 << (OFFSET % 32)) - -template <> -struct ModuleFlag -{ - static constexpr int value = KGE_DEFINE_COMPONENT_FLAG(0); -}; - -template <> -struct ModuleFlag -{ - static constexpr int value = KGE_DEFINE_COMPONENT_FLAG(1); -}; - -template <> -struct ModuleFlag -{ - static constexpr int value = KGE_DEFINE_COMPONENT_FLAG(2); -}; - -#undef KGE_DEFINE_COMPONENT_FLAG - } // namespace kiwano diff --git a/src/kiwano/base/ObjectBase.cpp b/src/kiwano/base/ObjectBase.cpp index 339350ea..7dd31480 100644 --- a/src/kiwano/base/ObjectBase.cpp +++ b/src/kiwano/base/ObjectBase.cpp @@ -18,25 +18,75 @@ // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. +#include +#include #include -#include #include #include -#include namespace kiwano { namespace { -bool tracing_leaks = false; -Vector tracing_objects; -uint32_t last_object_id = 0; + +bool tracing_leaks = false; +Vector tracing_objects; +std::atomic last_object_id = 0; +ObjectPolicyFunc object_policy_ = ObjectPolicy::ErrorLog(); + } // namespace + + +ObjectFailException::ObjectFailException(ObjectBase* obj, const ObjectStatus& status) + : obj_(obj) + , status_(status) +{ +} + +char const* ObjectFailException::what() const +{ + return status_.msg.empty() ? "Object operation failed" : status_.msg.c_str(); +} + +ObjectPolicyFunc ObjectPolicy::WarnLog(int threshold) +{ + return [=](ObjectBase* obj, const ObjectStatus& status) + { + if (!obj->IsValid() || status.code <= threshold) + { + KGE_WARNF("Object operation failed: obj(%p), code(%d), msg(%s)", obj, status.code, status.msg.c_str()); + } + }; +} + +ObjectPolicyFunc ObjectPolicy::ErrorLog(int threshold) +{ + return [=](ObjectBase* obj, const ObjectStatus& status) + { + if (!obj->IsValid() || status.code <= threshold) + { + KGE_ERRORF("Object operation failed: obj(%p), code(%d), msg(%s)", obj, status.code, status.msg.c_str()); + } + }; +} + +ObjectPolicyFunc ObjectPolicy::Exception(int threshold) +{ + return [=](ObjectBase* obj, const ObjectStatus& status) + { + if (!obj->IsValid() || status.code <= threshold) + { + throw ObjectFailException(obj, status); + } + }; +} + ObjectBase::ObjectBase() : tracing_leak_(false) , name_(nullptr) - , user_data_() + , user_data_(nullptr) + , status_(nullptr) , id_(++last_object_id) { #ifdef KGE_DEBUG @@ -52,22 +102,19 @@ ObjectBase::~ObjectBase() name_ = nullptr; } + ClearStatus(); + #ifdef KGE_DEBUG ObjectBase::RemoveObjectFromTracingList(this); #endif } -void ObjectBase::AutoRelease() -{ - ObjectPool::GetInstance().AddObject(this); -} - -const Any& ObjectBase::GetUserData() const +void* ObjectBase::GetUserData() const { return user_data_; } -void ObjectBase::SetUserData(const Any& data) +void ObjectBase::SetUserData(void* data) { user_data_ = data; } @@ -105,6 +152,54 @@ void ObjectBase::DoDeserialize(Deserializer* deserializer) SetName(name); } +bool ObjectBase::IsValid() const +{ + return status_ ? status_->Success() : true; +} + +ObjectStatus* ObjectBase::GetStatus() const +{ + return status_; +} + +void ObjectBase::SetStatus(const ObjectStatus& status) +{ + if (!status_) + { + status_ = new ObjectStatus; + } + + status_->msg = status.msg; + if (status_->code != status.code) + { + status_->code = status.code; + + if (object_policy_) + { + object_policy_(this, *status_); + } + } +} + +void ObjectBase::Fail(const String& msg, int code) +{ + SetStatus(ObjectStatus(code, msg)); +} + +void ObjectBase::ClearStatus() +{ + if (status_) + { + delete status_; + status_ = nullptr; + } +} + +void ObjectBase::SetObjectPolicy(const ObjectPolicyFunc& policy) +{ + object_policy_ = policy; +} + bool ObjectBase::IsTracingLeaks() { return tracing_leaks; diff --git a/src/kiwano/base/ObjectBase.h b/src/kiwano/base/ObjectBase.h index 927e2549..6bd6bb9a 100644 --- a/src/kiwano/base/ObjectBase.h +++ b/src/kiwano/base/ObjectBase.h @@ -21,20 +21,118 @@ #pragma once #include #include +#include #include -#include -#include +#include +#include namespace kiwano { KGE_DECLARE_SMART_PTR(ObjectBase); +/** + * \~chinese + * @brief 对象状态 + */ +struct ObjectStatus +{ + int code = 0; ///< 状态码,等于 0 时为成功状态,否则为失败状态 + String msg; ///< 状态信息 + + ObjectStatus() = default; + + ObjectStatus(int code, const String& msg) + : code(code) + , msg(msg) + { + } + + /// \~chinese + /// @brief 对象状态是否成功 + inline bool Success() const + { + return this->code == 0; + } + + /// \~chinese + /// @brief 对象失败状态 + static const int fail = -1; +}; + +/** + * \~chinese + * @brief 对象失败状态异常 + */ +class ObjectFailException : public Exception +{ +public: + ObjectFailException(ObjectBase* obj, const ObjectStatus& status); + + /// \~chinese + /// @brief 获取失败的对象指针 + inline ObjectBase* GetObj() const + { + return obj_; + } + + /// \~chinese + /// @brief 获取对象状态 + inline ObjectStatus GetStatus() const + { + return status_; + } + + virtual char const* what() const override; + +private: + ObjectBase* obj_; + ObjectStatus status_; +}; + +/** + * \~chinese + * @brief 对象处理策略方法 + */ +typedef Function ObjectPolicyFunc; + +/** + * \~chinese + * @brief 对象处理策略 + */ +struct ObjectPolicy +{ + /// \~chinese + /// @brief 忽略对象失败状态 + static inline ObjectPolicyFunc Ignore() + { + return nullptr; + } + + /// \~chinese + /// @brief 在对象状态变为失败时打印警告日志 + /// @param threshold 触发阈值 + /// @return 对象处理策略方法 + static ObjectPolicyFunc WarnLog(int threshold = ObjectStatus::fail); + + /// \~chinese + /// @brief 在对象状态变为失败时打印错误日志(默认策略) + /// @param threshold 触发阈值 + /// @return 对象处理策略方法 + static ObjectPolicyFunc ErrorLog(int threshold = ObjectStatus::fail); + + /// \~chinese + /// @brief 在对象状态变为失败时抛出 ObjectFailException + /// @param threshold 触发阈值 + /// @return 对象处理策略方法 + static ObjectPolicyFunc Exception(int threshold = ObjectStatus::fail); +}; + /** * \~chinese * @brief 基础对象 */ class KGE_API ObjectBase - : public RefCounter + : public RefObject , public Serializable { public: @@ -44,10 +142,6 @@ public: virtual ~ObjectBase(); - /// \~chinese - /// @brief 自动释放 - void AutoRelease(); - /// \~chinese /// @brief 设置对象名 void SetName(const String& name); @@ -63,15 +157,15 @@ public: /// \~chinese /// @brief 获取用户数据 - const Any& GetUserData() const; + void* GetUserData() const; /// \~chinese /// @brief 设置用户数据 - void SetUserData(const Any& data); + void SetUserData(void* data); /// \~chinese /// @brief 获取对象ID - uint32_t GetObjectID() const; + uint64_t GetObjectID() const; /// \~chinese /// @brief 序列化 @@ -81,6 +175,30 @@ public: /// @brief 反序列化 void DoDeserialize(Deserializer* deserializer) override; + /// \~chinese + /// @brief 判断对象是否有效 + virtual bool IsValid() const; + + /// \~chinese + /// @brief 获取对象状态 + ObjectStatus* GetStatus() const; + + /// \~chinese + /// @brief 设置对象状态 + void SetStatus(const ObjectStatus& status); + + /// \~chinese + /// @brief 将对象标记为失败状态 + void Fail(const String& msg, int code = ObjectStatus::fail); + + /// \~chinese + /// @brief 清除对象状态 + void ClearStatus(); + + /// \~chinese + /// @brief 设置对象处理策略 + static void SetObjectPolicy(const ObjectPolicyFunc& policy); + public: /// \~chinese /// @brief 是否启用了内存泄漏追踪 @@ -108,11 +226,13 @@ private: static void RemoveObjectFromTracingList(ObjectBase*); private: - const uint32_t id_; + const uint64_t id_; bool tracing_leak_; String* name_; - Any user_data_; + void* user_data_; + + ObjectStatus* status_; }; inline String ObjectBase::GetName() const @@ -127,7 +247,7 @@ inline bool ObjectBase::IsName(const String& name) const return name_ ? (*name_ == name) : name.empty(); } -inline uint32_t ObjectBase::GetObjectID() const +inline uint64_t ObjectBase::GetObjectID() const { return id_; } diff --git a/src/kiwano/base/RefCounter.cpp b/src/kiwano/base/RefObject.cpp similarity index 55% rename from src/kiwano/base/RefCounter.cpp rename to src/kiwano/base/RefObject.cpp index 27e44e5e..f4eb7971 100644 --- a/src/kiwano/base/RefCounter.cpp +++ b/src/kiwano/base/RefObject.cpp @@ -18,29 +18,84 @@ // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. -#include +#include namespace kiwano { -RefCounter::RefCounter() + +RefObject::RefObject() : ref_count_(0) { } -RefCounter::~RefCounter() {} +RefObject::~RefObject() {} -void RefCounter::Retain() +void RefObject::Retain() { ++ref_count_; } -void RefCounter::Release() +void RefObject::Release() { --ref_count_; if (ref_count_ == 0) { - memory::Delete(this); + delete this; } } +uint32_t RefObject::GetRefCount() const +{ + return ref_count_.load(); +} + +void* RefObject::operator new(size_t size) +{ + void* ptr = memory::Alloc(size); + if (!ptr) + { + throw std::bad_alloc(); + } + return ptr; +} + +void RefObject::operator delete(void* ptr) +{ + memory::Free(ptr); +} + +void* RefObject::operator new(size_t size, std::nothrow_t const&) +{ + try + { + void* ptr = memory::Alloc(size); + return ptr; + } + catch (...) + { + } + return nullptr; +} + +void RefObject::operator delete(void* ptr, std::nothrow_t const&) +{ + try + { + memory::Free(ptr); + } + catch (...) + { + } +} + +void* RefObject::operator new(size_t size, void* ptr) +{ + return ::operator new(size, ptr); +} + +void RefObject::operator delete(void* ptr, void* place) noexcept +{ + ::operator delete(ptr, place); +} + } // namespace kiwano diff --git a/src/kiwano/base/RefCounter.h b/src/kiwano/base/RefObject.h similarity index 76% rename from src/kiwano/base/RefCounter.h rename to src/kiwano/base/RefObject.h index 9a030876..a5975fc6 100644 --- a/src/kiwano/base/RefCounter.h +++ b/src/kiwano/base/RefObject.h @@ -24,17 +24,14 @@ namespace kiwano { + /** * \~chinese * @brief 引用计数器 */ -class KGE_API RefCounter : protected Noncopyable +class KGE_API RefObject : protected Noncopyable { public: - RefCounter(); - - virtual ~RefCounter(); - /// \~chinese /// @brief 增加引用计数 void Retain(); @@ -47,13 +44,25 @@ public: /// @brief 获取引用计数 uint32_t GetRefCount() const; + static void* operator new(size_t size); + + static void operator delete(void* ptr); + + static void* operator new(size_t size, std::nothrow_t const&) noexcept; + + static void operator delete(void* ptr, std::nothrow_t const&) noexcept; + + static void* operator new(size_t size, void* ptr) noexcept; + + static void operator delete(void* ptr, void* place) noexcept; + + virtual ~RefObject(); + +protected: + RefObject(); + private: std::atomic ref_count_; }; -inline uint32_t RefCounter::GetRefCount() const -{ - return ref_count_; -} - } // namespace kiwano diff --git a/src/kiwano/base/ObjectPool.cpp b/src/kiwano/base/RefPtr.h similarity index 51% rename from src/kiwano/base/ObjectPool.cpp rename to src/kiwano/base/RefPtr.h index 66ba259c..b78c9bc9 100644 --- a/src/kiwano/base/ObjectPool.cpp +++ b/src/kiwano/base/RefPtr.h @@ -18,69 +18,57 @@ // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. -#include +#pragma once +#include +#include namespace kiwano { -List ObjectPool::pools_; - -ObjectPool& ObjectPool::GetInstance() +/// \~chinese +/// @brief 默认的智能指针引用计数策略 +struct DefaultRefPtrPolicy { - static ObjectPool instance; - return *pools_.back(); -} - -ObjectPool::ObjectPool() -{ - pools_.push_back(this); -} - -ObjectPool::~ObjectPool() -{ - Clear(); - - auto iter = std::find(pools_.begin(), pools_.end(), this); - if (iter != pools_.end()) - pools_.erase(iter); -} - -void ObjectPool::AddObject(ObjectBase* obj) -{ - if (obj) + inline void Retain(RefObject* ptr) { - if (!Contains(obj)) - { - obj->Retain(); - - std::lock_guard lock(mutex_); - objects_.push_back(obj); - } - } -} - -bool ObjectPool::Contains(ObjectBase* obj) const -{ - std::lock_guard lock(const_cast(mutex_)); - - for (auto iter = pools_.rbegin(); iter != pools_.rend(); iter++) - for (const auto o : (*iter)->objects_) - if (obj == o) - return true; - return false; -} - -void ObjectPool::Clear() -{ - Vector copied; - - { - std::lock_guard lock(mutex_); - copied = std::move(objects_); + if (ptr) + ptr->Retain(); } - for (auto obj : copied) - obj->Release(); + inline void Release(RefObject* ptr) + { + if (ptr) + ptr->Release(); + } +}; + +/// \~chinese +/// @brief 引用计数对象智能指针 +template +using RefPtr = RefBasePtr<_Ty, DefaultRefPtrPolicy>; + +/// \~chinese +/// @brief 构造引用计数对象智能指针 +template +inline RefPtr<_Ty> MakePtr(_Args&&... args) +{ + static_assert(std::is_base_of::value, "_Ty must be derived from RefObject"); + return RefPtr<_Ty>(new _Ty(std::forward<_Args>(args)...)); +} + +/// \~chinese +/// @brief 构造引用计数对象智能指针 +template +inline RefPtr<_Ty> MakePtr(_Ty* ptr) +{ + static_assert(std::is_base_of::value, "_Ty must be derived from RefObject"); + return RefPtr<_Ty>(ptr); } } // namespace kiwano + +#ifndef KGE_DECLARE_SMART_PTR +#define KGE_DECLARE_SMART_PTR(CLASS) \ + class CLASS; \ + typedef ::kiwano::RefPtr CLASS##Ptr; +#endif diff --git a/src/kiwano/base/component/Button.cpp b/src/kiwano/base/component/Button.cpp index c8fbc49b..6971549d 100644 --- a/src/kiwano/base/component/Button.cpp +++ b/src/kiwano/base/component/Button.cpp @@ -25,23 +25,19 @@ namespace kiwano { -ButtonPtr Button::Create(const Callback& click) +Button::Button(const Callback& click) + : Button(click, nullptr, nullptr, nullptr) { - return Button::Create(click, nullptr, nullptr, nullptr); } -ButtonPtr Button::Create(const Callback& click, const Callback& pressed, const Callback& mouse_over, - const Callback& mouse_out) +Button::Button(const Callback& click, const Callback& pressed, const Callback& mouse_over, const Callback& mouse_out) + : status_(Status::Normal) + , click_callback_(click) + , pressed_callback_(pressed) + , mouse_over_callback_(mouse_over) + , mouse_out_callback_(mouse_out) { - ButtonPtr ptr = memory::New