[deploy]Merge pull request #64 from KiwanoEngine/dev

Merge dev branch
This commit is contained in:
Haibo 2020-07-29 12:03:26 +08:00 committed by GitHub
commit 2cc623b6b2
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
137 changed files with 2416 additions and 2739 deletions

View File

@ -16,8 +16,8 @@
<ClInclude Include="..\..\src\kiwano\base\Director.h" />
<ClInclude Include="..\..\src\kiwano\base\Module.h" />
<ClInclude Include="..\..\src\kiwano\base\ObjectBase.h" />
<ClInclude Include="..\..\src\kiwano\base\ObjectPool.h" />
<ClInclude Include="..\..\src\kiwano\base\RefCounter.h" />
<ClInclude Include="..\..\src\kiwano\base\RefObject.h" />
<ClInclude Include="..\..\src\kiwano\base\RefPtr.h" />
<ClInclude Include="..\..\src\kiwano\core\Allocator.h" />
<ClInclude Include="..\..\src\kiwano\core\Any.h" />
<ClInclude Include="..\..\src\kiwano\core\Cloneable.h" />
@ -52,7 +52,7 @@
<ClInclude Include="..\..\src\kiwano\2d\TextActor.h" />
<ClInclude Include="..\..\src\kiwano\2d\Transition.h" />
<ClInclude Include="..\..\src\kiwano\core\Resource.h" />
<ClInclude Include="..\..\src\kiwano\core\SmartPtr.hpp" />
<ClInclude Include="..\..\src\kiwano\core\RefBasePtr.hpp" />
<ClInclude Include="..\..\src\kiwano\math\Constants.h" />
<ClInclude Include="..\..\src\kiwano\math\EaseFunctions.h" />
<ClInclude Include="..\..\src\kiwano\math\Math.h" />
@ -102,6 +102,7 @@
<ClInclude Include="..\..\src\kiwano\utils\Json.h" />
<ClInclude Include="..\..\src\kiwano\utils\Logger.h" />
<ClInclude Include="..\..\src\kiwano\utils\ResourceCache.h" />
<ClInclude Include="..\..\src\kiwano\utils\ResourceLoader.h" />
<ClInclude Include="..\..\src\kiwano\utils\Task.h" />
<ClInclude Include="..\..\src\kiwano\utils\TaskScheduler.h" />
<ClInclude Include="..\..\src\kiwano\utils\Ticker.h" />
@ -133,8 +134,7 @@
<ClCompile Include="..\..\src\kiwano\base\Director.cpp" />
<ClCompile Include="..\..\src\kiwano\base\Module.cpp" />
<ClCompile Include="..\..\src\kiwano\base\ObjectBase.cpp" />
<ClCompile Include="..\..\src\kiwano\base\ObjectPool.cpp" />
<ClCompile Include="..\..\src\kiwano\base\RefCounter.cpp" />
<ClCompile Include="..\..\src\kiwano\base\RefObject.cpp" />
<ClCompile Include="..\..\src\kiwano\core\Allocator.cpp" />
<ClCompile Include="..\..\src\kiwano\core\Exception.cpp" />
<ClCompile Include="..\..\src\kiwano\core\Library.cpp" />
@ -180,6 +180,7 @@
<ClCompile Include="..\..\src\kiwano\utils\EventTicker.cpp" />
<ClCompile Include="..\..\src\kiwano\utils\Logger.cpp" />
<ClCompile Include="..\..\src\kiwano\utils\ResourceCache.cpp" />
<ClCompile Include="..\..\src\kiwano\utils\ResourceLoader.cpp" />
<ClCompile Include="..\..\src\kiwano\utils\Task.cpp" />
<ClCompile Include="..\..\src\kiwano\utils\TaskScheduler.cpp" />
<ClCompile Include="..\..\src\kiwano\utils\Ticker.cpp" />

View File

@ -65,9 +65,6 @@
<ClInclude Include="..\..\src\kiwano\math\Vec2.hpp">
<Filter>math</Filter>
</ClInclude>
<ClInclude Include="..\..\src\kiwano\core\SmartPtr.hpp">
<Filter>core</Filter>
</ClInclude>
<ClInclude Include="..\..\src\kiwano\kiwano.h" />
<ClInclude Include="..\..\src\kiwano\2d\GifSprite.h">
<Filter>2d</Filter>
@ -303,9 +300,6 @@
<ClInclude Include="..\..\src\kiwano\base\ObjectBase.h">
<Filter>base</Filter>
</ClInclude>
<ClInclude Include="..\..\src\kiwano\base\RefCounter.h">
<Filter>base</Filter>
</ClInclude>
<ClInclude Include="..\..\src\kiwano\event\Event.h">
<Filter>event</Filter>
</ClInclude>
@ -345,15 +339,24 @@
<ClInclude Include="..\..\src\kiwano\utils\ConfigIni.h">
<Filter>utils</Filter>
</ClInclude>
<ClInclude Include="..\..\src\kiwano\base\ObjectPool.h">
<Filter>base</Filter>
</ClInclude>
<ClInclude Include="..\..\src\kiwano\core\Defer.h">
<Filter>core</Filter>
</ClInclude>
<ClInclude Include="..\..\src\kiwano\2d\action\Action.h">
<Filter>2d\action</Filter>
</ClInclude>
<ClInclude Include="..\..\src\kiwano\base\RefObject.h">
<Filter>base</Filter>
</ClInclude>
<ClInclude Include="..\..\src\kiwano\core\RefBasePtr.hpp">
<Filter>core</Filter>
</ClInclude>
<ClInclude Include="..\..\src\kiwano\base\RefPtr.h">
<Filter>base</Filter>
</ClInclude>
<ClInclude Include="..\..\src\kiwano\utils\ResourceLoader.h">
<Filter>utils</Filter>
</ClInclude>
</ItemGroup>
<ItemGroup>
<ClCompile Include="..\..\src\kiwano\2d\Canvas.cpp">
@ -539,9 +542,6 @@
<ClCompile Include="..\..\src\kiwano\base\ObjectBase.cpp">
<Filter>base</Filter>
</ClCompile>
<ClCompile Include="..\..\src\kiwano\base\RefCounter.cpp">
<Filter>base</Filter>
</ClCompile>
<ClCompile Include="..\..\src\kiwano\event\Event.cpp">
<Filter>event</Filter>
</ClCompile>
@ -575,12 +575,15 @@
<ClCompile Include="..\..\src\kiwano\utils\ConfigIni.cpp">
<Filter>utils</Filter>
</ClCompile>
<ClCompile Include="..\..\src\kiwano\base\ObjectPool.cpp">
<Filter>base</Filter>
</ClCompile>
<ClCompile Include="..\..\src\kiwano\2d\action\Action.cpp">
<Filter>2d\action</Filter>
</ClCompile>
<ClCompile Include="..\..\src\kiwano\base\RefObject.cpp">
<Filter>base</Filter>
</ClCompile>
<ClCompile Include="..\..\src\kiwano\utils\ResourceLoader.cpp">
<Filter>utils</Filter>
</ClCompile>
</ItemGroup>
<ItemGroup>
<None Include="suppress_warning.ruleset" />

View File

@ -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()

View File

@ -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();

View File

@ -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<Sound>();
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<Sound>();
if (sound)
{

View File

@ -40,10 +40,6 @@ KGE_DECLARE_SMART_PTR(SoundPlayer);
class KGE_API SoundPlayer : public ObjectBase
{
public:
/// \~chinese
/// @brief 创建音频播放器
static SoundPlayerPtr Create();
SoundPlayer();
~SoundPlayer();

View File

@ -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)

View File

@ -38,17 +38,13 @@ using ImGuiPipeline = Function<void()>;
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();

View File

@ -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<MouseEvent>())
{
if (evt->IsType<MouseDownEvent>())
ImGuiIO& io = ImGui::GetIO();
if (evt->IsType<MouseEvent>())
{
MouseButton button = dynamic_cast<MouseDownEvent*>(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<MouseDownEvent>())
{
MouseButton button = dynamic_cast<MouseDownEvent*>(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<MouseUpEvent>())
{
MouseButton button = dynamic_cast<MouseUpEvent*>(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<MouseWheelEvent>())
{
float wheel = dynamic_cast<MouseWheelEvent*>(evt)->wheel;
io.MouseWheel += wheel;
}
}
else if (evt->IsType<MouseUpEvent>())
else if (evt->IsType<KeyEvent>())
{
MouseButton button = dynamic_cast<MouseUpEvent*>(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<MouseWheelEvent>())
{
float wheel = dynamic_cast<MouseWheelEvent*>(evt)->wheel;
io.MouseWheel += wheel;
}
}
else if (evt->IsType<KeyEvent>())
{
if (evt->IsType<KeyDownEvent>())
{
KeyCode key = dynamic_cast<KeyDownEvent*>(evt)->code;
io.KeysDown[(int)key] = true;
}
else if (evt->IsType<KeyUpEvent>())
{
KeyCode key = dynamic_cast<KeyUpEvent*>(evt)->code;
io.KeysDown[(int)key] = false;
}
else if (evt->IsType<KeyCharEvent>())
{
// You can also use ToAscii()+GetKeyboardState() to retrieve characters.
char ch = dynamic_cast<KeyCharEvent*>(evt)->value;
io.AddInputCharacter(static_cast<ImWchar>(ch));
if (evt->IsType<KeyDownEvent>())
{
KeyCode key = dynamic_cast<KeyDownEvent*>(evt)->code;
io.KeysDown[(int)key] = true;
}
else if (evt->IsType<KeyUpEvent>())
{
KeyCode key = dynamic_cast<KeyUpEvent*>(evt)->code;
io.KeysDown[(int)key] = false;
}
else if (evt->IsType<KeyCharEvent>())
{
// You can also use ToAscii()+GetKeyboardState() to retrieve characters.
char ch = dynamic_cast<KeyCharEvent*>(evt)->value;
io.AddInputCharacter(static_cast<ImWchar>(ch));
}
}
}
ctx.Next();
}
void ImGuiModule::UpdateMousePos()

View File

@ -34,9 +34,7 @@ namespace imgui
*/
class ImGuiModule
: public Singleton<ImGuiModule>
, public RenderModule
, public UpdateModule
, public EventModule
, public Module
{
friend Singleton<ImGuiModule>;
@ -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();

View File

@ -253,7 +253,7 @@ void HttpModule::NetworkThread()
return;
}
HttpResponsePtr response = new (std::nothrow) HttpResponse(request);
HttpResponsePtr response = MakePtr<HttpResponse>(request);
Perform(request, response);
response_mutex_.lock();

View File

@ -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)

View File

@ -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;

View File

@ -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<Fixture>();
if (ptr)
{
auto shape = std::make_unique<b2CircleShape>();
@ -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<Fixture>();
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<Point>& vertexs)
{
FixturePtr ptr = new (std::nothrow) Fixture;
FixturePtr ptr = MakePtr<Fixture>();
if (ptr)
{
Vector<b2Vec2> b2vertexs;
@ -82,7 +82,7 @@ FixturePtr Fixture::CreatePolygon(const Param& param, const Vector<Point>& verte
FixturePtr Fixture::CreateEdge(const Param& param, const Point& p1, const Point& p2)
{
FixturePtr ptr = new (std::nothrow) Fixture;
FixturePtr ptr = MakePtr<Fixture>();
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<Point>& vertices, bool loop)
{
FixturePtr ptr = new (std::nothrow) Fixture;
FixturePtr ptr = MakePtr<Fixture>();
if (ptr)
{
Vector<b2Vec2> b2vertices;

View File

@ -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)
{
}

View File

@ -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 初始化关节

View File

@ -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);

View File

@ -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 物理世界

View File

@ -31,11 +31,11 @@ class PhysicWorld::DebugDrawer : public b2Draw
public:
DebugDrawer(const Size& size)
{
canvas_ = Canvas::Create(size);
canvas_ = MakePtr<Canvas>(size);
ctx_ = canvas_->GetContext2D();
fill_brush_ = Brush::Create(Color::White);
line_brush_ = Brush::Create(Color::White);
fill_brush_ = MakePtr<Brush>(Color::White);
line_brush_ = MakePtr<Brush>(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()

View File

@ -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();

View File

@ -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<Actor>();
return ptr;
}
Actor::Actor()
: ComponentManager(this)
, visible_(true)
@ -264,8 +258,8 @@ bool Actor::HandleEvent(Event* evt)
{
hover_ = true;
MouseHoverEventPtr hover = memory::New<MouseHoverEvent>();
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<MouseOutEvent>();
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<MouseUpEvent*>(evt);
MouseClickEventPtr click = memory::New<MouseClickEvent>();
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<ActorPtr>& 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)

View File

@ -77,10 +77,6 @@ public:
/// @brief 角色更新回调函数
typedef Function<void(Duration)> UpdateCallback;
/// \~chinese
/// @brief ´´˝¨˝ÇÉŤ
static ActorPtr Create();
Actor();
virtual ~Actor();

View File

@ -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>();
texture_cached_ = MakePtr<Texture>();
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

View File

@ -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_;

View File

@ -54,10 +54,10 @@ DebugActor::DebugActor()
comma_locale_ = std::locale(std::locale(), new comma_numpunct);
background_brush_ = memory::New<Brush>();
background_brush_ = MakePtr<Brush>();
background_brush_->SetColor(Color::Rgba(0x000000, 0.7f));
BrushPtr fill_brush = memory::New<Brush>();
BrushPtr fill_brush = MakePtr<Brush>();
fill_brush->SetColor(Color::White);
debug_text_style_.font_family = "Arial";

View File

@ -25,38 +25,6 @@
namespace kiwano
{
GifSpritePtr GifSprite::Create(const String& file_path)
{
GifSpritePtr ptr = memory::New<GifSprite>();
if (ptr)
{
if (!ptr->Load(file_path))
return nullptr;
}
return ptr;
}
GifSpritePtr GifSprite::Create(const Resource& res)
{
GifSpritePtr ptr = memory::New<GifSprite>();
if (ptr)
{
if (!ptr->Load(res))
return nullptr;
}
return ptr;
}
GifSpritePtr GifSprite::Create(GifImagePtr gif)
{
GifSpritePtr ptr = memory::New<GifSprite>();
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<Texture>();
frame_to_render_ = MakePtr<Texture>();
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<Texture>();
saved_frame_ = MakePtr<Texture>();
frame_rt_->CreateTexture(*saved_frame_, frame_to_render_->GetSizeInPixels());
}
saved_frame_->CopyFrom(frame_to_render_);

View File

@ -48,22 +48,22 @@ public:
/// @brief GIF²¥·Å½áÊø»Øµ÷
using DoneCallback = Function<void()>;
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ͼƬ

View File

@ -25,12 +25,6 @@
namespace kiwano
{
LayerActorPtr LayerActor::Create()
{
LayerActorPtr ptr = memory::New<LayerActor>();
return ptr;
}
LayerActor::LayerActor()
: swallow_(false)
{

View File

@ -39,10 +39,6 @@ KGE_DECLARE_SMART_PTR(LayerActor);
class KGE_API LayerActor : public Actor
{
public:
/// \~chinese
/// @brief ´´˝¨Íź˛ă
static LayerActorPtr Create();
LayerActor();
virtual ~LayerActor();

View File

@ -25,40 +25,25 @@
namespace kiwano
{
ShapeActorPtr ShapeActor::Create(ShapePtr shape)
ShapeActor::ShapeActor() {}
ShapeActor::ShapeActor(ShapePtr shape)
{
ShapeActorPtr ptr = memory::New<ShapeActor>();
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<LineActor>();
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<RectActor>();
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<RoundedRectActor>();
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<CircleActor>();
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<EllipseActor>();
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<Point>& points)
{
PolygonActorPtr ptr = memory::New<PolygonActor>();
if (ptr)
{
ptr->SetVertices(points);
}
return ptr;
}
PolygonActor::PolygonActor() {}
PolygonActor::PolygonActor(const Vector<Point>& points)
{
SetVertices(points);
}
PolygonActor::~PolygonActor() {}
void PolygonActor::SetVertices(const Vector<Point>& 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());
}
}

View File

@ -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<Point>& points);
PolygonActor();
PolygonActor(const Vector<Point>& points);
virtual ~PolygonActor();
@ -338,7 +336,7 @@ inline void ShapeActor::SetStrokeColor(const Color& color)
{
if (!stroke_brush_)
{
stroke_brush_ = memory::New<Brush>();
stroke_brush_ = MakePtr<Brush>();
}
stroke_brush_->SetColor(color);
}
@ -347,7 +345,7 @@ inline void ShapeActor::SetFillColor(const Color& color)
{
if (!fill_brush_)
{
fill_brush_ = memory::New<Brush>();
fill_brush_ = MakePtr<Brush>();
}
fill_brush_->SetColor(color);
}

View File

@ -24,81 +24,58 @@
namespace kiwano
{
SpritePtr Sprite::Create(const String& file_path)
{
SpritePtr ptr = memory::New<Sprite>();
if (ptr)
{
if (!ptr->Load(file_path))
return nullptr;
}
return ptr;
}
SpritePtr Sprite::Create(const Resource& res)
{
SpritePtr ptr = memory::New<Sprite>();
if (ptr)
{
if (!ptr->Load(res))
return nullptr;
}
return ptr;
}
SpritePtr Sprite::Create(FramePtr frame)
{
SpritePtr ptr = memory::New<Sprite>();
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<Frame>(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<Frame>(res);
if (frame)
{
SetFrame(frame, autoresize);
return true;
}
Fail("Sprite::Load failed");
return false;
}

View File

@ -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();

View File

@ -25,12 +25,6 @@
namespace kiwano
{
StagePtr Stage::Create()
{
StagePtr ptr = memory::New<Stage>();
return ptr;
}
Stage::Stage()
{
SetStage(this);
@ -57,13 +51,13 @@ void Stage::RenderBorder(RenderContext& ctx)
if (!border_fill_brush_)
{
border_fill_brush_ = memory::New<Brush>();
border_fill_brush_ = MakePtr<Brush>();
border_fill_brush_->SetColor(Color(Color::Red, .4f));
}
if (!border_stroke_brush_)
{
border_stroke_brush_ = memory::New<Brush>();
border_stroke_brush_ = MakePtr<Brush>();
border_stroke_brush_->SetColor(Color(Color::Red, .8f));
}

View File

@ -43,10 +43,6 @@ class KGE_API Stage : public Actor
friend class Director;
public:
/// \~chinese
/// @brief 进入舞台时
static StagePtr Create();
Stage();
virtual ~Stage();

View File

@ -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<TextActor>();
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<TextLayout>();
}
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<Brush>(color));
}
}
@ -227,7 +228,7 @@ void TextActor::SetOutlineColor(const Color& outline_color)
}
else
{
SetFillBrush(Brush::Create(outline_color));
SetFillBrush(MakePtr<Brush>(outline_color));
}
}

View File

@ -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();

View File

@ -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<BoxTransition>();
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<EmergeTransition>();
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<FadeTransition>();
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<MoveTransition>();
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<RotationTransition>();
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);

View File

@ -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;

View File

@ -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

View File

@ -22,7 +22,6 @@
#include <kiwano/core/Common.h>
#include <kiwano/core/Cloneable.h>
#include <kiwano/base/ObjectBase.h>
#include <kiwano/core/SmartPtr.hpp>
#include <kiwano/core/Time.h>
#include <kiwano/core/IntrusiveList.h>
#include <kiwano/math/Math.h>
@ -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;

View File

@ -25,27 +25,24 @@ namespace kiwano
ActionDelay::ActionDelay(Duration delay)
{
SetEntity(ActionDelayEntity::Create(delay));
SetEntity(MakePtr<ActionDelayEntity>(delay));
}
ActionDelayEntityPtr ActionDelayEntity::Create(Duration delay)
ActionDelayEntity::ActionDelayEntity(Duration delay)
{
ActionDelayEntityPtr ptr = memory::New<ActionDelayEntity>();
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

View File

@ -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;
};
/** @} */

View File

@ -27,18 +27,7 @@ namespace kiwano
ActionGroup::ActionGroup(const Vector<ActionEntityPtr>& actions, bool parallel)
{
SetEntity(ActionGroupEntity::Create(actions, parallel));
}
ActionGroupEntityPtr ActionGroupEntity::Create(const Vector<ActionEntityPtr>& actions, bool parallel)
{
ActionGroupEntityPtr ptr = memory::New<ActionGroupEntity>();
if (ptr)
{
ptr->parallel_ = parallel;
ptr->AddActions(actions);
}
return ptr;
SetEntity(MakePtr<ActionGroupEntity>(actions, parallel));
}
ActionGroupEntity::ActionGroupEntity()
@ -46,9 +35,10 @@ ActionGroupEntity::ActionGroupEntity()
{
}
ActionGroupEntity::ActionGroupEntity(bool parallel)
ActionGroupEntity::ActionGroupEntity(const Vector<ActionEntityPtr>& actions, bool parallel)
: parallel_(parallel)
{
AddActions(actions);
}
ActionGroupEntity::~ActionGroupEntity() {}
@ -123,7 +113,7 @@ void ActionGroupEntity::AddActions(const Vector<ActionEntityPtr>& actions)
AddAction(action);
}
ActionEntityPtr ActionGroupEntity::Clone() const
ActionGroupEntity* ActionGroupEntity::Clone() const
{
Vector<ActionEntityPtr> 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<ActionEntityPtr> 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

View File

@ -47,15 +47,13 @@ public:
class KGE_API ActionGroupEntity : public ActionEntity
{
public:
ActionGroupEntity();
/// \~chinese
/// @brief 创建动画组合
/// @param actions 动画集合
/// @param parallel 同步执行
static ActionGroupEntityPtr Create(const Vector<ActionEntityPtr>& actions, bool parallel = false);
ActionGroupEntity();
ActionGroupEntity(bool parallel);
ActionGroupEntity(const Vector<ActionEntityPtr>& 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;

View File

@ -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;
}

View File

@ -55,7 +55,7 @@ public:
/// \~chinese
/// @brief 获取指定名称的动画
/// @param name 动画名称
ActionEntityPtr GetAction(const String& name);
ActionEntity* GetAction(const String& name);
/// \~chinese
/// @brief 获取所有动画

View File

@ -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<ActionMoveByEntity>();
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<ActionMoveToEntity>();
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<ActionJumpByEntity>();
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<ActionJumpToEntity>();
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<ActionScaleByEntity>();
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<ActionScaleToEntity>();
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<ActionFadeToEntity>();
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<ActionRotateByEntity>();
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<ActionRotateToEntity>();
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<ActionCustomEntity>();
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<ActionMoveByEntity>(duration, displacement));
}
ActionMoveTo::ActionMoveTo(Duration duration, const Point& distination)
{
SetEntity(ActionMoveToEntity::Create(duration, distination));
SetEntity(MakePtr<ActionMoveToEntity>(duration, distination));
}
ActionJumpBy::ActionJumpBy(Duration duration, const Vec2& displacement, float height, int count)
{
SetEntity(ActionJumpByEntity::Create(duration, displacement, height, count));
SetEntity(MakePtr<ActionJumpByEntity>(duration, displacement, height, count));
}
ActionJumpTo::ActionJumpTo(Duration duration, const Point& distination, float height, int count)
{
SetEntity(ActionJumpToEntity::Create(duration, distination, height, count));
SetEntity(MakePtr<ActionJumpToEntity>(duration, distination, height, count));
}
ActionScaleBy::ActionScaleBy(Duration duration, float scale_x, float scale_y)
{
SetEntity(ActionScaleByEntity::Create(duration, scale_x, scale_y));
SetEntity(MakePtr<ActionScaleByEntity>(duration, scale_x, scale_y));
}
ActionScaleBy::ActionScaleBy(Duration duration, Vec2 scale)
{
SetEntity(ActionScaleByEntity::Create(duration, scale.x, scale.y));
SetEntity(MakePtr<ActionScaleByEntity>(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<ActionScaleToEntity>(duration, scale_x, scale_y));
}
ActionScaleTo::ActionScaleTo(Duration duration, Vec2 scale)
{
SetEntity(ActionScaleToEntity::Create(duration, scale.x, scale.y));
SetEntity(MakePtr<ActionScaleToEntity>(duration, scale.x, scale.y));
}
ActionFadeTo::ActionFadeTo(Duration duration, float opacity)
{
SetEntity(ActionFadeToEntity::Create(duration, opacity));
SetEntity(MakePtr<ActionFadeToEntity>(duration, opacity));
}
ActionFadeIn::ActionFadeIn(Duration duration)
{
SetEntity(ActionFadeToEntity::Create(duration, 1.0f));
SetEntity(MakePtr<ActionFadeToEntity>(duration, 1.0f));
}
ActionFadeOut::ActionFadeOut(Duration duration)
{
SetEntity(ActionFadeToEntity::Create(duration, 0.0f));
SetEntity(MakePtr<ActionFadeToEntity>(duration, 0.0f));
}
ActionRotateBy::ActionRotateBy(Duration duration, float rotation)
{
SetEntity(ActionRotateByEntity::Create(duration, rotation));
SetEntity(MakePtr<ActionRotateByEntity>(duration, rotation));
}
ActionRotateTo::ActionRotateTo(Duration duration, float rotation)
{
SetEntity(ActionRotateToEntity::Create(duration, rotation));
SetEntity(MakePtr<ActionRotateToEntity>(duration, rotation));
}
ActionCustom::ActionCustom(Duration duration, TweenFunc tween_func)
{
SetEntity(ActionCustomEntity::Create(duration, tween_func));
SetEntity(MakePtr<ActionCustomEntity>(duration, tween_func));
}
} // namespace kiwano

View File

@ -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<ActionTweenEntity*>(static_cast<const ActionTweenEntity*>(ptr.Get()));
return static_cast<ActionTweenEntity*>(Action::Get());
}
/// \~chinese
/// @brief 设置动画实体
inline void SetEntity(ActionTweenEntityPtr tween_ptr)
{
this->ptr = static_cast<ActionEntity*>(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;

View File

@ -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<ActionWalkEntity>(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<ActionWalkEntity>();
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)

View File

@ -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;

View File

@ -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<AnimationEntity>();
if (ptr)
{
ptr->SetDuration(dur);
ptr->SetFrameSequence(frame_seq);
}
return ptr;
SetEntity(MakePtr<AnimationEntity>(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

View File

@ -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

View File

@ -23,10 +23,10 @@
#include <kiwano/2d/Stage.h>
#include <kiwano/2d/Transition.h>
#include <kiwano/base/Director.h>
#include <kiwano/render/RenderContext.h>
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<DebugActor>();
debug_actor_ = MakePtr<DebugActor>();
}
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

View File

@ -34,9 +34,7 @@ namespace kiwano
*/
class KGE_API Director
: public Singleton<Director>
, public UpdateModule
, public RenderModule
, public EventModule
, public Module
{
friend Singleton<Director>;
@ -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();

View File

@ -19,28 +19,118 @@
// THE SOFTWARE.
#include <kiwano/base/Module.h>
#include <kiwano/render/RenderContext.h>
namespace kiwano
{
Module::Module()
: flag_(0)
ModuleContext::ModuleContext(ModuleList& modules)
: index_(-1)
, modules_(modules)
{
}
RenderModule::RenderModule()
ModuleContext::~ModuleContext() {}
void ModuleContext::ResetIndex()
{
flag_ |= ModuleFlag<RenderModule>::value;
index_ = -1;
}
UpdateModule::UpdateModule()
void ModuleContext::Next()
{
flag_ |= ModuleFlag<UpdateModule>::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<EventModule>::value;
}
} // namespace kiwano

View File

@ -25,124 +25,126 @@ namespace kiwano
{
class RenderContext;
class Event;
class Module;
template <typename _CompTy>
struct ModuleFlag;
/// \~chinese
/// @brief 模块列表
typedef Vector<Module*> 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 <typename _CompTy>
_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<RenderModule>
{
static constexpr int value = KGE_DEFINE_COMPONENT_FLAG(0);
};
template <>
struct ModuleFlag<UpdateModule>
{
static constexpr int value = KGE_DEFINE_COMPONENT_FLAG(1);
};
template <>
struct ModuleFlag<EventModule>
{
static constexpr int value = KGE_DEFINE_COMPONENT_FLAG(2);
};
#undef KGE_DEFINE_COMPONENT_FLAG
} // namespace kiwano

View File

@ -18,25 +18,75 @@
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
#include <typeinfo>
#include <atomic>
#include <kiwano/base/ObjectBase.h>
#include <kiwano/base/ObjectPool.h>
#include <kiwano/utils/Logger.h>
#include <kiwano/utils/Json.h>
#include <typeinfo>
namespace kiwano
{
namespace
{
bool tracing_leaks = false;
Vector<ObjectBase*> tracing_objects;
uint32_t last_object_id = 0;
bool tracing_leaks = false;
Vector<ObjectBase*> tracing_objects;
std::atomic<uint64_t> 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;

View File

@ -21,20 +21,118 @@
#pragma once
#include <kiwano/macros.h>
#include <kiwano/core/Common.h>
#include <kiwano/core/Exception.h>
#include <kiwano/core/Serializable.h>
#include <kiwano/core/SmartPtr.hpp>
#include <kiwano/base/RefCounter.h>
#include <kiwano/base/RefObject.h>
#include <kiwano/base/RefPtr.h>
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<void(ObjectBase*, const ObjectStatus&)> 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_;
}

View File

@ -18,29 +18,84 @@
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
#include <kiwano/base/RefCounter.h>
#include <kiwano/base/RefObject.h>
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

View File

@ -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<uint32_t> ref_count_;
};
inline uint32_t RefCounter::GetRefCount() const
{
return ref_count_;
}
} // namespace kiwano

View File

@ -18,69 +18,57 @@
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
#include <kiwano/base/ObjectPool.h>
#pragma once
#include <kiwano/base/RefObject.h>
#include <kiwano/core/RefBasePtr.hpp>
namespace kiwano
{
List<ObjectPool*> 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<std::mutex> lock(mutex_);
objects_.push_back(obj);
}
}
}
bool ObjectPool::Contains(ObjectBase* obj) const
{
std::lock_guard<std::mutex> lock(const_cast<std::mutex&>(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<ObjectBase*> copied;
{
std::lock_guard<std::mutex> 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 <typename _Ty>
using RefPtr = RefBasePtr<_Ty, DefaultRefPtrPolicy>;
/// \~chinese
/// @brief 构造引用计数对象智能指针
template <typename _Ty, typename... _Args>
inline RefPtr<_Ty> MakePtr(_Args&&... args)
{
static_assert(std::is_base_of<RefObject, _Ty>::value, "_Ty must be derived from RefObject");
return RefPtr<_Ty>(new _Ty(std::forward<_Args>(args)...));
}
/// \~chinese
/// @brief 构造引用计数对象智能指针
template <typename _Ty>
inline RefPtr<_Ty> MakePtr(_Ty* ptr)
{
static_assert(std::is_base_of<RefObject, _Ty>::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> CLASS##Ptr;
#endif

View File

@ -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<Button>();
if (ptr)
{
ptr->SetClickCallback(click);
ptr->SetPressedCallback(pressed);
ptr->SetMouseOverCallback(mouse_over);
ptr->SetMouseOutCallback(mouse_out);
}
return ptr;
SetName("__KGE_BUTTON__");
}
Button::Button()

View File

@ -45,7 +45,7 @@ public:
/// \~chinese
/// @brief 创建按钮
/// @param click 按钮点击回调函数
static ButtonPtr Create(const Callback& click);
Button(const Callback& click);
/// \~chinese
/// @brief 创建按钮
@ -53,8 +53,7 @@ public:
/// @param pressed 按钮按下回调函数
/// @param mouse_over 按钮移入回调函数
/// @param mouse_out 按钮移出回调函数
static ButtonPtr Create(const Callback& click, const Callback& pressed, const Callback& mouse_over,
const Callback& mouse_out);
Button(const Callback& click, const Callback& pressed, const Callback& mouse_over, const Callback& mouse_out);
Button();

View File

@ -37,9 +37,9 @@ MemoryAllocator* GetGlobalAllocator()
return ::operator new(size);
}
virtual void Free(void* ptr, size_t size) override
virtual void Free(void* ptr) override
{
::operator delete(ptr, size);
::operator delete(ptr);
}
};

View File

@ -40,7 +40,7 @@ public:
/// \~chinese
/// @brief 释放内存
virtual void Free(void* ptr, size_t size) = 0;
virtual void Free(void* ptr) = 0;
};
/// \~chinese
@ -60,52 +60,12 @@ inline void* Alloc(size_t size)
/// \~chinese
/// @brief 使用当前内存分配器释放内存
inline void Free(void* ptr, size_t size)
inline void Free(void* ptr)
{
memory::GetAllocator()->Free(ptr, size);
}
/// \~chinese
/// @brief 构造对象
template <typename _Ty, typename... _Args>
inline _Ty* Construct(void* ptr, _Args&&... args)
{
return ::new (ptr) _Ty(std::forward<_Args>(args)...);
}
/// \~chinese
/// @brief 销毁对象
template <typename _Ty, typename... _Args>
inline void Destroy(_Ty* ptr)
{
ptr->~_Ty();
}
/// \~chinese
/// @brief 使用当前内存分配器创建对象
template <typename _Ty, typename... _Args>
inline _Ty* New(_Args&&... args)
{
void* ptr = memory::Alloc(sizeof(_Ty));
if (ptr)
{
return memory::Construct<_Ty>(ptr, std::forward<_Args>(args)...);
}
return nullptr;
}
/// \~chinese
/// @brief 使用当前内存分配器销毁对象
template <typename _Ty>
inline void Delete(_Ty* ptr)
{
if (ptr)
{
memory::Destroy<_Ty>(ptr);
memory::Free(ptr, sizeof(_Ty));
}
memory::GetAllocator()->Free(ptr);
}
} // namespace memory
/// \~chinese
/// @brief 分配器
@ -153,19 +113,19 @@ public:
inline void deallocate(void* ptr, size_t count)
{
memory::Free(ptr, sizeof(_Ty) * count);
memory::Free(ptr /*, sizeof(_Ty) * count */);
}
template <typename _UTy, typename... _Args>
inline void construct(_UTy* ptr, _Args&&... args)
inline void construct(_UTy* const ptr, _Args&&... args)
{
memory::Construct<_UTy>(ptr, std::forward<_Args>(args)...);
::new (const_cast<void*>(static_cast<const volatile void*>(ptr))) _Ty(std::forward<_Args>(args)...);
}
template <typename _UTy>
inline void destroy(_UTy* ptr)
{
memory::Destroy<_UTy>(ptr);
ptr->~_UTy();
}
size_t max_size() const noexcept
@ -215,5 +175,4 @@ bool operator!=(const Allocator<_Ty>&, const Allocator<_Other>&) noexcept
return false;
}
} // namespace memory
} // namespace kiwano

View File

@ -19,7 +19,6 @@
// THE SOFTWARE.
#pragma once
#include <kiwano/core/SmartPtr.hpp>
namespace kiwano
{
@ -28,7 +27,7 @@ template <typename _Ty>
class Cloneable
{
public:
virtual SmartPtr<_Ty> Clone() const = 0;
virtual _Ty* Clone() const = 0;
protected:
Cloneable() = default;

View File

@ -56,23 +56,28 @@ using WideStringStream = std::wstringstream;
/// \~chinese
/// @brief 线性数组容器
template <typename _Ty, typename... _Args>
using Vector = std::vector<_Ty, _Args...>;
template <typename _Ty, typename _Alloc = std::allocator<_Ty>>
using Vector = std::vector<_Ty, _Alloc>;
/// \~chinese
/// @brief 链表容器
template <typename _Ty, typename... _Args>
using List = std::list<_Ty, _Args...>;
template <typename _Ty, typename _Alloc = std::allocator<_Ty>>
using List = std::list<_Ty, _Alloc>;
/// \~chinese
/// @brief 双端队列容器
template <typename _Ty, typename _Alloc = std::allocator<_Ty>>
using Deque = std::deque<_Ty, _Alloc>;
/// \~chinese
/// @brief 队列容器
template <typename _Ty, typename... _Args>
using Queue = std::queue<_Ty, _Args...>;
template <typename _Ty, typename _Container = Deque<_Ty>>
using Queue = std::queue<_Ty, _Container>;
/// \~chinese
/// @brief 集合容器
template <typename _Ty, typename... _Args>
using Set = std::set<_Ty, _Args...>;
template <typename _Kty, typename _Compare = std::less<_Kty>, typename _Alloc = std::allocator<_Kty>>
using Set = std::set<_Kty, _Compare, _Alloc>;
/// \~chinese
/// @brief 对容器
@ -81,23 +86,25 @@ using Pair = std::pair<_Ty1, _Ty2>;
/// \~chinese
/// @brief 无序集合容器
template <typename _Ty, typename... _Args>
using UnorderedSet = std::unordered_set<_Ty, _Args...>;
template <typename _Kty, typename _Hash = std::hash<_Kty>, typename _Keq = std::equal_to<_Kty>,
typename _Alloc = std::allocator<_Kty>>
using UnorderedSet = std::unordered_set<_Kty, _Hash, _Keq, _Alloc>;
/// \~chinese
/// @brief 栈容器
template <typename _Ty, typename... _Args>
using Stack = std::stack<_Ty, _Args...>;
template <typename _Ty, typename _Container = Deque<_Ty>>
using Stack = std::stack<_Ty, _Container>;
/// \~chinese
/// @brief ×Ö·û´®ÈÝÆ÷
template <typename _Kty, typename _Ty, typename... _Args>
using Map = std::map<_Kty, _Ty, _Args...>;
/// @brief 排序关联容器
template <typename _Kty, typename _Ty, typename _Compare = std::less<_Kty>, typename _Alloc = std::allocator<Pair<const _Kty, _Ty>>>
using Map = std::map<_Kty, _Ty, _Compare, _Alloc>;
/// \~chinese
/// @brief ×Ö·û´®ÈÝÆ÷
template <typename _Kty, typename _Ty, typename... _Args>
using UnorderedMap = std::unordered_map<_Kty, _Ty, _Args...>;
/// @brief 非排序关联容器
template <typename _Kty, typename _Ty, typename _Hash = std::hash<_Kty>, typename _Keq = std::equal_to<_Kty>,
typename _Alloc = std::allocator<Pair<const _Kty, _Ty>>>
using UnorderedMap = std::unordered_map<_Kty, _Ty, _Hash, _Keq, _Alloc>;
/// \~chinese
/// @brief 不可拷贝对象

View File

@ -20,26 +20,9 @@
#pragma once
#include <kiwano/core/Common.h>
#include <kiwano/utils/Logger.h>
#include <stdexcept>
#include <system_error>
#define KGE_THROW(MESSAGE) \
do \
{ \
KGE_ERRORF("An exception occurred: %s", MESSAGE); \
kiwano::StackTracer().Print(); \
throw kiwano::RuntimeError(MESSAGE); \
} while (0)
#define KGE_THROW_SYSTEM_ERROR(ERRCODE, MESSAGE) \
do \
{ \
KGE_ERRORF("An exception occurred (%#x): %s", ERRCODE, MESSAGE); \
kiwano::StackTracer().Print(); \
throw kiwano::SystemError(std::error_code(kiwano::error_enum(ERRCODE)), MESSAGE); \
} while (0)
namespace kiwano
{
@ -104,12 +87,6 @@ inline std::error_condition make_error_condition(kiwano::error_enum errc) noexce
return std::error_condition(static_cast<int>(errc), kiwano::com_category());
}
#define KGE_THROW_IF_FAILED(HR, MESSAGE) \
if (FAILED(HR)) \
{ \
KGE_THROW_SYSTEM_ERROR(HR, MESSAGE); \
}
} // namespace kiwano
#endif // KGE_PLATFORM_WINDOWS

View File

@ -22,36 +22,16 @@
#include <utility>
#include <type_traits>
#include <kiwano/core/Common.h>
#include <kiwano/base/RefCounter.h>
namespace kiwano
{
/**
* \~chinese
* @brief
* @brief ÒýÓüÆÊýÖÇÄÜÖ¸Õë
*/
struct DefaultSmartPtrRefProxy
{
static inline void Retain(RefCounter* ptr)
{
if (ptr)
ptr->Retain();
}
static inline void Release(RefCounter* ptr)
{
if (ptr)
ptr->Release();
}
};
/**
* \~chinese
* @brief
*/
template <typename _Ty, typename _ProxyTy = DefaultSmartPtrRefProxy>
class SmartPtr
template <typename _Ty, typename _RefPolicy>
class RefBasePtr : protected _RefPolicy
{
public:
using value_type = _Ty;
@ -60,65 +40,66 @@ public:
using reference_type = _Ty&;
using const_reference_type = const _Ty&;
SmartPtr() noexcept
RefBasePtr() noexcept
: ptr_(nullptr)
{
}
SmartPtr(std::nullptr_t) noexcept
RefBasePtr(std::nullptr_t) noexcept
: ptr_(nullptr)
{
}
SmartPtr(pointer_type p)
RefBasePtr(pointer_type p)
: ptr_(p)
{
_ProxyTy::Retain(ptr_);
_RefPolicy::Retain(ptr_);
}
SmartPtr(const SmartPtr& other)
RefBasePtr(const RefBasePtr& other)
: ptr_(other.ptr_)
{
_ProxyTy::Retain(ptr_);
_RefPolicy::Retain(ptr_);
}
SmartPtr(SmartPtr&& other) noexcept
RefBasePtr(RefBasePtr&& other) noexcept
: ptr_(nullptr)
{
Swap(other);
}
~SmartPtr()
~RefBasePtr()
{
Tidy();
}
template <typename _UTy, typename std::enable_if<std::is_base_of<_Ty, _UTy>::value, int>::type = 0>
SmartPtr(const SmartPtr<_UTy, _ProxyTy>& other)
template <typename _UTy, typename std::enable_if<std::is_convertible<_UTy*, _Ty*>::value, int>::type = 0>
RefBasePtr(const RefBasePtr<_UTy, _RefPolicy>& other)
{
ptr_ = const_cast<pointer_type>(dynamic_cast<const_pointer_type>(other.Get()));
_ProxyTy::Retain(ptr_);
ptr_ = dynamic_cast<pointer_type>(other.Get());
_RefPolicy::Retain(ptr_);
}
inline pointer_type Get() noexcept
inline pointer_type Get() const noexcept
{
return ptr_;
}
inline const_pointer_type Get() const noexcept
inline pointer_type* GetAddressOfAndRelease()
{
return ptr_;
Tidy();
return &ptr_;
}
inline void Reset(pointer_type ptr = nullptr)
{
if (ptr)
SmartPtr(ptr).Swap(*this);
RefBasePtr(ptr).Swap(*this);
else
Tidy();
}
inline void Swap(SmartPtr& other) noexcept
inline void Swap(RefBasePtr& other) noexcept
{
std::swap(ptr_, other.ptr_);
}
@ -149,8 +130,7 @@ public:
inline pointer_type* operator&()
{
KGE_ASSERT(ptr_ == nullptr && "Memory leak");
return &ptr_;
return this->GetAddressOfAndRelease();
}
inline operator bool() const noexcept
@ -163,28 +143,36 @@ public:
return ptr_ == 0;
}
inline SmartPtr& operator=(const SmartPtr& other)
inline RefBasePtr& operator=(const RefBasePtr& other)
{
if (other.ptr_ != ptr_)
SmartPtr(other).Swap(*this);
RefBasePtr(other).Swap(*this);
return (*this);
}
inline SmartPtr& operator=(SmartPtr&& other) noexcept
inline RefBasePtr& operator=(RefBasePtr&& other) noexcept
{
if (other.ptr_ != ptr_)
other.Swap(*this);
return (*this);
}
inline SmartPtr& operator=(pointer_type p)
inline RefBasePtr& operator=(pointer_type p)
{
if (p != ptr_)
SmartPtr(p).Swap(*this);
RefBasePtr(p).Swap(*this);
return (*this);
}
inline SmartPtr& operator=(std::nullptr_t)
template <typename _UTy, typename std::enable_if<std::is_convertible<_UTy*, _Ty*>::value, int>::type = 0>
inline RefBasePtr& operator=(const RefBasePtr<_UTy, _RefPolicy>& other)
{
if (other.Get() != ptr_)
RefBasePtr(dynamic_cast<pointer_type>(other.Get())).Swap(*this);
return (*this);
}
inline RefBasePtr& operator=(std::nullptr_t)
{
Tidy();
return *this;
@ -193,7 +181,7 @@ public:
private:
void Tidy()
{
_ProxyTy::Release(ptr_);
_RefPolicy::Release(ptr_);
ptr_ = nullptr;
}
@ -201,84 +189,78 @@ private:
pointer_type ptr_;
};
template <class _Ty, class _UTy, class _ProxyTy>
inline bool operator==(const SmartPtr<_Ty, _ProxyTy>& lhs, const SmartPtr<_UTy, _ProxyTy>& rhs) noexcept
template <class _Ty, class _UTy, class _RefPolicy>
inline bool operator==(const RefBasePtr<_Ty, _RefPolicy>& lhs, const RefBasePtr<_UTy, _RefPolicy>& rhs) noexcept
{
return lhs.Get() == rhs.Get();
}
template <class _Ty, class _ProxyTy>
inline bool operator==(const SmartPtr<_Ty, _ProxyTy>& lhs, _Ty* rhs) noexcept
template <class _Ty, class _RefPolicy>
inline bool operator==(const RefBasePtr<_Ty, _RefPolicy>& lhs, _Ty* rhs) noexcept
{
return lhs.Get() == rhs;
}
template <class _Ty, class _ProxyTy>
inline bool operator==(_Ty* lhs, const SmartPtr<_Ty, _ProxyTy>& rhs) noexcept
template <class _Ty, class _RefPolicy>
inline bool operator==(_Ty* lhs, const RefBasePtr<_Ty, _RefPolicy>& rhs) noexcept
{
return lhs == rhs.Get();
}
template <class _Ty, class _ProxyTy>
inline bool operator==(const SmartPtr<_Ty, _ProxyTy>& lhs, std::nullptr_t) noexcept
template <class _Ty, class _RefPolicy>
inline bool operator==(const RefBasePtr<_Ty, _RefPolicy>& lhs, std::nullptr_t) noexcept
{
return !static_cast<bool>(lhs);
}
template <class _Ty, class _ProxyTy>
inline bool operator==(std::nullptr_t, const SmartPtr<_Ty, _ProxyTy>& rhs) noexcept
template <class _Ty, class _RefPolicy>
inline bool operator==(std::nullptr_t, const RefBasePtr<_Ty, _RefPolicy>& rhs) noexcept
{
return !static_cast<bool>(rhs);
}
template <class _Ty, class _UTy, class _ProxyTy>
inline bool operator!=(const SmartPtr<_Ty, _ProxyTy>& lhs, const SmartPtr<_UTy, _ProxyTy>& rhs) noexcept
template <class _Ty, class _UTy, class _RefPolicy>
inline bool operator!=(const RefBasePtr<_Ty, _RefPolicy>& lhs, const RefBasePtr<_UTy, _RefPolicy>& rhs) noexcept
{
return !(lhs == rhs);
}
template <class _Ty, class _ProxyTy>
inline bool operator!=(const SmartPtr<_Ty, _ProxyTy>& lhs, _Ty* rhs) noexcept
template <class _Ty, class _RefPolicy>
inline bool operator!=(const RefBasePtr<_Ty, _RefPolicy>& lhs, _Ty* rhs) noexcept
{
return lhs.Get() != rhs;
}
template <class _Ty, class _ProxyTy>
inline bool operator!=(_Ty* lhs, const SmartPtr<_Ty, _ProxyTy>& rhs) noexcept
template <class _Ty, class _RefPolicy>
inline bool operator!=(_Ty* lhs, const RefBasePtr<_Ty, _RefPolicy>& rhs) noexcept
{
return lhs != rhs.Get();
}
template <class _Ty, class _ProxyTy>
inline bool operator!=(const SmartPtr<_Ty, _ProxyTy>& lhs, std::nullptr_t) noexcept
template <class _Ty, class _RefPolicy>
inline bool operator!=(const RefBasePtr<_Ty, _RefPolicy>& lhs, std::nullptr_t) noexcept
{
return static_cast<bool>(lhs);
}
template <class _Ty, class _ProxyTy>
inline bool operator!=(std::nullptr_t, const SmartPtr<_Ty, _ProxyTy>& rhs) noexcept
template <class _Ty, class _RefPolicy>
inline bool operator!=(std::nullptr_t, const RefBasePtr<_Ty, _RefPolicy>& rhs) noexcept
{
return static_cast<bool>(rhs);
}
template <class _Ty, class _UTy, class _ProxyTy>
inline bool operator<(const SmartPtr<_Ty, _ProxyTy>& lhs, const SmartPtr<_UTy, _ProxyTy>& rhs) noexcept
template <class _Ty, class _UTy, class _RefPolicy>
inline bool operator<(const RefBasePtr<_Ty, _RefPolicy>& lhs, const RefBasePtr<_UTy, _RefPolicy>& rhs) noexcept
{
return lhs.Get() < rhs.Get();
}
// template class cannot specialize std::swap,
// so implement a swap function in kiwano namespace
template <class _Ty, class _ProxyTy>
inline void swap(SmartPtr<_Ty, _ProxyTy>& lhs, SmartPtr<_Ty, _ProxyTy>& rhs) noexcept
template <class _Ty, class _RefPolicy>
inline void swap(RefBasePtr<_Ty, _RefPolicy>& lhs, RefBasePtr<_Ty, _RefPolicy>& rhs) noexcept
{
lhs.Swap(rhs);
}
} // namespace kiwano
#ifndef KGE_DECLARE_SMART_PTR
#define KGE_DECLARE_SMART_PTR(CLASS) \
class CLASS; \
typedef ::kiwano::SmartPtr<CLASS> CLASS##Ptr;
#endif

View File

@ -18,13 +18,12 @@
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
#include <kiwano/core/Exception.h>
#include <kiwano/utils/Logger.h>
#include <kiwano/core/Time.h>
#include <regex>
#include <unordered_map>
#include <chrono>
#include <thread>
#include <kiwano/core/Time.h>
#include <kiwano/utils/Logger.h>
namespace kiwano
{

View File

@ -19,7 +19,8 @@
// THE SOFTWARE.
#pragma once
#include <kiwano/core/SmartPtr.hpp>
#include <kiwano/base/RefObject.h>
#include <kiwano/base/RefPtr.h>
#include <kiwano/event/EventType.h>
#include <kiwano/math/Math.h>
@ -39,7 +40,7 @@ KGE_DECLARE_SMART_PTR(Event);
/// \~chinese
/// @brief 事件
class KGE_API Event : public RefCounter
class KGE_API Event : public RefObject
{
public:
/// \~chinese
@ -74,13 +75,6 @@ private:
const EventType type_;
};
/// \~chinese
/// @brief 事件特性:判断是否是事件
template <typename _Ty>
struct IsBaseOfEvent : public std::bool_constant<std::is_base_of<Event, _Ty>::value || std::is_same<Event, _Ty>::value>
{
};
/// \~chinese
/// @brief 事件特性:判断事件类型是否相同
template <typename _Ty>
@ -88,7 +82,7 @@ struct IsSameEventType
{
inline bool operator()(const Event* evt) const
{
static_assert(kiwano::IsBaseOfEvent<_Ty>::value, "_Ty is not an event type.");
static_assert(std::is_base_of<Event, _Ty>::value, "_Ty is not an event type.");
return evt->GetType() == KGE_EVENT(_Ty);
}
};
@ -103,7 +97,7 @@ inline const EventType& Event::GetType() const
template <typename _Ty>
inline bool Event::IsType() const
{
static_assert(kiwano::IsBaseOfEvent<_Ty>::value, "_Ty is not an event type.");
static_assert(std::is_base_of<Event, _Ty>::value, "_Ty is not an event type.");
return IsSameEventType<_Ty>()(this);
}

View File

@ -58,14 +58,14 @@ EventListener* EventDispatcher::AddListener(EventListenerPtr listener)
EventListener* EventDispatcher::AddListener(const String& name, EventType type, EventListener::Callback callback)
{
EventListenerPtr listener = EventListener::Create(name, type, callback);
return AddListener(listener);
auto lis = MakePtr<EventListener>(name, type, callback);
return AddListener(lis);
}
EventListener* EventDispatcher::AddListener(EventType type, EventListener::Callback callback)
{
EventListenerPtr listener = EventListener::Create(type, callback);
return AddListener(listener);
auto lis = MakePtr<EventListener>(type, callback);
return AddListener(lis);
}
void EventDispatcher::StartListeners(const String& name)

View File

@ -59,7 +59,7 @@ public:
template <typename _EventTy>
EventListener* AddListener(EventListener::Callback callback)
{
static_assert(kiwano::IsBaseOfEvent<_EventTy>::value, "_EventTy is not an event type.");
static_assert(std::is_base_of<Event, _EventTy>::value, "_EventTy is not an event type.");
return AddListener(KGE_EVENT(_EventTy), callback);
}
@ -71,7 +71,7 @@ public:
template <typename _EventTy>
EventListener* AddListener(const String& name, EventListener::Callback callback)
{
static_assert(kiwano::IsBaseOfEvent<_EventTy>::value, "_EventTy is not an event type.");
static_assert(std::is_base_of<Event, _EventTy>::value, "_EventTy is not an event type.");
return AddListener(name, KGE_EVENT(_EventTy), callback);
}

View File

@ -24,29 +24,6 @@
namespace kiwano
{
EventListenerPtr EventListener::Create(EventType type, const Callback& callback)
{
EventListenerPtr ptr = memory::New<EventListener>();
if (ptr)
{
ptr->SetEventType(type);
ptr->SetCallback(callback);
}
return ptr;
}
EventListenerPtr EventListener::Create(const String& name, EventType type, const Callback& callback)
{
EventListenerPtr ptr = memory::New<EventListener>();
if (ptr)
{
ptr->SetName(name);
ptr->SetEventType(type);
ptr->SetCallback(callback);
}
return ptr;
}
EventListener::EventListener()
: type_()
, callback_()
@ -56,6 +33,19 @@ EventListener::EventListener()
{
}
EventListener::EventListener(EventType type, const Callback& callback)
: EventListener()
{
this->SetEventType(type);
this->SetCallback(callback);
}
EventListener::EventListener(const String& name, EventType type, const Callback& callback)
: EventListener(type, callback)
{
this->SetName(name);
}
EventListener::~EventListener() {}
void EventListener::Receive(Event* evt)

View File

@ -20,9 +20,8 @@
#pragma once
#include <kiwano/core/Common.h>
#include <kiwano/base/ObjectBase.h>
#include <kiwano/core/SmartPtr.hpp>
#include <kiwano/core/IntrusiveList.h>
#include <kiwano/base/ObjectBase.h>
#include <kiwano/event/Events.h>
namespace kiwano
@ -47,44 +46,21 @@ public:
/// @brief 监听器回调函数
using Callback = Function<void(Event*)>;
/// \~chinese
/// @brief 创建监听器
/// @param type 监听的事件类型
/// @param callback 回调函数
static EventListenerPtr Create(EventType type, const Callback& callback);
/// \~chinese
/// @brief 创建监听器
/// @param name 监听器名称
/// @param type 监听的事件类型
/// @param callback 回调函数
static EventListenerPtr Create(const String& name, EventType type, const Callback& callback);
/// \~chinese
/// @brief 创建监听器
/// @tparam _EventTy 事件类型
/// @param callback 回调函数
template <typename _EventTy>
static inline EventListenerPtr Create(const Callback& callback)
{
static_assert(kiwano::IsBaseOfEvent<_EventTy>::value, "_EventTy is not an event type.");
return EventListener::Create(KGE_EVENT(_EventTy), callback);
}
/// \~chinese
/// @brief 创建监听器
/// @tparam _EventTy 事件类型
/// @param name 监听器名称
/// @param callback 回调函数
template <typename _EventTy>
static inline EventListenerPtr Create(const String& name, const Callback& callback)
{
static_assert(kiwano::IsBaseOfEvent<_EventTy>::value, "_EventTy is not an event type.");
return EventListener::Create(name, KGE_EVENT(_EventTy), callback);
}
EventListener();
/// \~chinese
/// @brief 创建监听器
/// @param type 监听的事件类型
/// @param callback 回调函数
EventListener(EventType type, const Callback& callback);
/// \~chinese
/// @brief 创建监听器
/// @param name 监听器名称
/// @param type 监听的事件类型
/// @param callback 回调函数
EventListener(const String& name, EventType type, const Callback& callback);
virtual ~EventListener();
/// \~chinese
@ -142,7 +118,7 @@ public:
template <typename _EventTy>
inline void SetEventType()
{
static_assert(kiwano::IsBaseOfEvent<_EventTy>::value, "_EventTy is not an event type.");
static_assert(std::is_base_of<Event, _EventTy>::value, "_EventTy is not an event type.");
SetEventType(KGE_EVENT(_EventTy));
}

View File

@ -46,14 +46,14 @@
#include <kiwano/core/Common.h>
#include <kiwano/core/Defer.h>
#include <kiwano/core/Resource.h>
#include <kiwano/core/SmartPtr.hpp>
#include <kiwano/core/RefBasePtr.hpp>
#include <kiwano/core/Time.h>
//
// base
//
#include <kiwano/base/RefCounter.h>
#include <kiwano/base/RefObject.h>
#include <kiwano/base/ObjectBase.h>
#include <kiwano/base/Director.h>
#include <kiwano/base/Module.h>
@ -128,6 +128,7 @@
#include <kiwano/utils/Logger.h>
#include <kiwano/utils/ResourceCache.h>
#include <kiwano/utils/ResourceLoader.h>
#include <kiwano/utils/UserData.h>
#include <kiwano/utils/Timer.h>
#include <kiwano/utils/Ticker.h>

View File

@ -23,7 +23,6 @@
#include <kiwano/base/Director.h>
#include <kiwano/render/Renderer.h>
#include <kiwano/render/TextureCache.h>
#include <kiwano/utils/ResourceCache.h>
#include <kiwano/utils/Logger.h>
namespace kiwano
@ -51,7 +50,7 @@ void Application::Run(RunnerPtr runner)
running_ = true;
is_paused_ = false;
runner_ = runner;
timer_ = Timer::Create();
timer_ = MakePtr<Timer>();
// Initialize runner
runner->InitSettings();
@ -122,7 +121,6 @@ void Application::Destroy()
// Clear user resources
Director::GetInstance().ClearStages();
ResourceCache::GetInstance().Clear();
for (auto iter = modules_.rbegin(); iter != modules_.rend(); ++iter)
{
@ -162,13 +160,8 @@ void Application::DispatchEvent(Event* evt)
if (!running_ /* Dispatch events even if application is paused */)
return;
for (auto comp : modules_)
{
if (auto event_comp = comp->Cast<EventModule>())
{
event_comp->HandleEvent(evt);
}
}
auto ctx = EventModuleContext(modules_, evt);
ctx.Next();
}
void Application::Update(Duration dt)
@ -176,51 +169,24 @@ void Application::Update(Duration dt)
if (!running_ || is_paused_)
return;
// Before update
for (auto comp : modules_)
{
if (auto update_comp = comp->Cast<UpdateModule>())
{
update_comp->BeforeUpdate();
}
}
auto ctx = UpdateModuleContext(modules_, dt);
ctx.Next();
// perform functions
if (!functions_to_perform_.empty())
{
if (!functions_to_perform_.empty())
{
perform_mutex_.lock();
auto functions = std::move(functions_to_perform_);
perform_mutex_.unlock();
perform_mutex_.lock();
auto functions = std::move(functions_to_perform_);
perform_mutex_.unlock();
while (!functions.empty())
while (!functions.empty())
{
auto& func = functions.front();
if (func)
{
auto& func = functions.front();
if (func)
{
func();
}
functions.pop();
func();
}
}
}
// Updating
Duration scaled_dt = dt * time_scale_;
for (auto comp : modules_)
{
if (auto update_comp = comp->Cast<UpdateModule>())
{
update_comp->OnUpdate(scaled_dt);
}
}
// After update
for (auto rit = modules_.rbegin(); rit != modules_.rend(); ++rit)
{
if (auto update_comp = (*rit)->Cast<UpdateModule>())
{
update_comp->AfterUpdate();
functions.pop();
}
}
}
@ -233,33 +199,9 @@ void Application::Render()
Renderer& renderer = Renderer::GetInstance();
renderer.Clear();
// Before render
for (auto comp : modules_)
{
if (auto render_comp = comp->Cast<RenderModule>())
{
render_comp->BeforeRender();
}
}
// Rendering
renderer.BeginDraw();
for (auto comp : modules_)
{
if (auto render_comp = comp->Cast<RenderModule>())
{
render_comp->OnRender(renderer.GetContext());
}
}
renderer.EndDraw();
// After render
for (auto rit = modules_.rbegin(); rit != modules_.rend(); ++rit)
{
if (auto render_comp = (*rit)->Cast<RenderModule>())
{
render_comp->AfterRender();
}
auto ctx = RenderModuleContext(modules_, renderer.GetContext());
ctx.Next();
}
renderer.Present();

View File

@ -42,7 +42,8 @@ extern KGE_API int GetVersion();
* \~chinese
* @brief
*/
class KGE_API Application : public Singleton<Application>
class KGE_API Application
: public Singleton<Application>
{
friend Singleton<Application>;
@ -169,7 +170,7 @@ private:
float time_scale_;
RunnerPtr runner_;
TimerPtr timer_;
List<Module*> modules_;
ModuleList modules_;
std::mutex perform_mutex_;
Queue<Function<void()>> functions_to_perform_;
};

View File

@ -34,21 +34,6 @@ Input::Input()
Input::~Input() {}
void Input::AfterUpdate()
{
if (want_update_keys_)
{
want_update_keys_ = false;
::memcpy(keys_[Prev].data(), keys_[Current].data(), KEY_NUM * sizeof(bool));
}
if (want_update_buttons_)
{
want_update_buttons_ = false;
buttons_[Prev] = buttons_[Current];
}
}
bool Input::IsDown(KeyCode key) const
{
if (key == KeyCode::Unknown || key == KeyCode::Last)
@ -129,8 +114,27 @@ void Input::UpdateMousePos(const Point& pos)
mouse_pos_ = pos;
}
void Input::HandleEvent(Event* evt)
void Input::OnUpdate(UpdateModuleContext& ctx)
{
ctx.Next();
if (want_update_keys_)
{
want_update_keys_ = false;
::memcpy(keys_[Prev].data(), keys_[Current].data(), KEY_NUM * sizeof(bool));
}
if (want_update_buttons_)
{
want_update_buttons_ = false;
buttons_[Prev] = buttons_[Current];
}
}
void Input::HandleEvent(EventModuleContext& ctx)
{
Event* evt = ctx.evt;
if (evt->IsType<MouseEvent>())
{
if (evt->IsType<MouseMoveEvent>())
@ -158,4 +162,5 @@ void Input::HandleEvent(Event* evt)
}
}
}
} // namespace kiwano

View File

@ -33,10 +33,9 @@ namespace kiwano
* \~chinese
* @brief
*/
class KGE_API Input
class KGE_API Input final
: public Singleton<Input>
, public UpdateModule
, public EventModule
, public Module
{
friend Singleton<Input>;
@ -104,13 +103,9 @@ public:
Point GetMousePos() const;
public:
void SetupModule() override {}
void OnUpdate(UpdateModuleContext& ctx) override;
void DestroyModule() override {}
void AfterUpdate() override;
void HandleEvent(Event* evt) override;
void HandleEvent(EventModuleContext& ctx) override;
~Input();

View File

@ -28,45 +28,9 @@
namespace kiwano
{
RunnerPtr Runner::Create(Settings settings)
Runner::Runner(const Settings& settings)
: settings_(settings)
{
RunnerPtr ptr = memory::New<Runner>();
if (ptr)
{
ptr->SetSettings(settings);
}
return ptr;
}
RunnerPtr Runner::Create(Settings settings, Function<void()> on_ready, Function<void()> on_destroy)
{
class CallbackRunner : public Runner
{
public:
void OnReady() override
{
if (on_ready)
on_ready();
}
void OnDestroy() override
{
if (on_destroy)
on_destroy();
}
Function<void()> on_ready;
Function<void()> on_destroy;
};
SmartPtr<CallbackRunner> ptr = memory::New<CallbackRunner>();
if (ptr)
{
ptr->on_ready = on_ready;
ptr->on_destroy = on_destroy;
ptr->SetSettings(settings);
}
return ptr;
}
Runner::Runner() {}
@ -91,6 +55,7 @@ void Runner::InitSettings()
Renderer::GetInstance().SetVSyncEnabled(settings_.vsync_enabled);
// Use defaut modules
Application::GetInstance().Use(Renderer::GetInstance());
Application::GetInstance().Use(Input::GetInstance());
Application::GetInstance().Use(Director::GetInstance());
@ -104,7 +69,7 @@ void Runner::InitSettings()
// Create frame ticker
if (!settings_.frame_interval.IsZero())
{
frame_ticker_ = Ticker::Create(settings_.frame_interval, -1);
frame_ticker_ = MakePtr<Ticker>(settings_.frame_interval, -1);
}
}

View File

@ -62,20 +62,13 @@ struct Settings
class KGE_API Runner : public ObjectBase
{
public:
/// \~chinese
/// @brief 创建程序运行器
/// @param main_window 主窗口
static RunnerPtr Create(Settings settings);
/// \~chinese
/// @brief 创建程序运行器
/// @param main_window 主窗口
/// @param on_ready 应用程序初始化完成后执行的回调函数
/// @param on_destroy 应用程序销毁时执行的回调函数
static RunnerPtr Create(Settings settings, Function<void()> on_ready, Function<void()> on_destroy = nullptr);
Runner();
/// \~chinese
/// @brief 创建程序运行器
/// @param main_window 主窗口
Runner(const Settings& settings);
virtual ~Runner();
/// \~chinese
@ -99,16 +92,12 @@ public:
/// @param dt 时间间隔
/// @details 重载该函数以控制程序主循环
/// @return 返回false退出主循环否则继续运行主循环
virtual bool MainLoop(Duration dt);
bool MainLoop(Duration dt);
/// \~chinese
/// @brief 获取窗口
WindowPtr GetWindow() const;
/// \~chinese
/// @brief 设置窗口
void SetWindow(WindowPtr window);
/// \~chinese
/// @brief 获取设置
Settings GetSettings() const;
@ -126,6 +115,10 @@ protected:
/// @brief 修改设置
void SetSettings(Settings settings);
/// \~chinese
/// @brief 设置窗口
void SetWindow(WindowPtr window);
private:
friend class Application;

View File

@ -21,20 +21,20 @@
#pragma once
#include <type_traits>
#include <kiwano/core/Common.h>
#include <kiwano/core/SmartPtr.hpp>
#include <kiwano/core/RefBasePtr.hpp>
#include <Unknwnbase.h>
namespace kiwano
{
struct ComPtrProxy
struct ComPtrPolicy
{
static inline void Retain(IUnknown* ptr)
inline void Retain(IUnknown* ptr)
{
if (ptr)
ptr->AddRef();
}
static inline void Release(IUnknown* ptr)
inline void Release(IUnknown* ptr)
{
if (ptr)
ptr->Release();
@ -43,6 +43,6 @@ struct ComPtrProxy
// ComPtr<> is a smart pointer for COM
template <typename _Ty, typename = typename std::enable_if<std::is_base_of<IUnknown, _Ty>::value, int>::type>
using ComPtr = SmartPtr<_Ty, ComPtrProxy>;
using ComPtr = RefBasePtr<_Ty, ComPtrPolicy>;
} // namespace kiwano

View File

@ -25,7 +25,6 @@
#include <memory>
#include <array>
#include <kiwano/core/Keys.h>
#include <kiwano/core/Exception.h>
#include <kiwano/utils/Logger.h>
#include <kiwano/event/Events.h>
#include <kiwano/platform/Application.h>
@ -90,7 +89,7 @@ private:
WindowPtr Window::Create(const WindowConfig& config)
{
WindowWin32ImplPtr ptr = memory::New<WindowWin32Impl>();
WindowWin32ImplPtr ptr = MakePtr<WindowWin32Impl>();
if (ptr)
{
ptr->Init(config);

View File

@ -18,7 +18,6 @@
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
#include <kiwano/core/Exception.h>
#include <kiwano/utils/Logger.h>
#include <kiwano/platform/win32/libraries.h>

View File

@ -59,34 +59,22 @@ RadialGradientStyle::RadialGradientStyle(const Point& center, const Vec2& offset
{
}
BrushPtr Brush::Create(const Color& color)
Brush::Brush(const Color& color)
: Brush()
{
BrushPtr ptr = memory::New<Brush>();
if (ptr)
{
ptr->SetColor(color);
}
return ptr;
SetColor(color);
}
BrushPtr Brush::Create(const LinearGradientStyle& style)
Brush::Brush(const LinearGradientStyle& style)
: Brush()
{
BrushPtr ptr = memory::New<Brush>();
if (ptr)
{
ptr->SetStyle(style);
}
return ptr;
SetStyle(style);
}
BrushPtr Brush::Create(const RadialGradientStyle& style)
Brush::Brush(const RadialGradientStyle& style)
: Brush()
{
BrushPtr ptr = memory::New<Brush>();
if (ptr)
{
ptr->SetStyle(style);
}
return ptr;
SetStyle(style);
}
Brush::Brush()

View File

@ -92,17 +92,17 @@ public:
/// \~chinese
/// @brief 创建纯色画刷
/// @param color 画刷颜色
static BrushPtr Create(const Color& color);
Brush(const Color& color);
/// \~chinese
/// @brief 创建线性渐变样式
/// @param style 线性渐变样式
static BrushPtr Create(const LinearGradientStyle& style);
Brush(const LinearGradientStyle& style);
/// \~chinese
/// @brief 创建径向渐变样式
/// @param style 径向渐变样式
static BrushPtr Create(const RadialGradientStyle& style);
Brush(const RadialGradientStyle& style);
Brush();

View File

@ -20,7 +20,6 @@
#pragma once
#include <kiwano/core/Common.h>
#include <kiwano/macros.h>
namespace kiwano
{

View File

@ -19,7 +19,6 @@
// THE SOFTWARE.
#include <kiwano/render/DirectX/D2DDeviceResources.h>
#include <kiwano/utils/Logger.h>
#pragma comment(lib, "d2d1.lib")
#pragma comment(lib, "dwrite.lib")
@ -70,6 +69,12 @@ public:
HRESULT CreateTextLayout(_Out_ ComPtr<IDWriteTextLayout>& text_layout, _In_ LPCWSTR text, UINT32 length,
_In_ ComPtr<IDWriteTextFormat> text_format) override;
HRESULT CreateFontCollectionFromFiles(_Out_ ComPtr<IDWriteFontCollection>& font_collection,
const Vector<String>& file_paths) override;
HRESULT CreateFontCollectionFromResources(_Out_ ComPtr<IDWriteFontCollection>& font_collection,
const Vector<Resource>& resources) override;
HRESULT SetDpi(float dpi) override;
HRESULT SetLogicalSize(float width, float height) override;
@ -93,6 +98,10 @@ private:
float dpi_;
ComPtr<IDXGISwapChain> dxgi_swap_chain_;
ComPtr<IFontCollectionLoader> font_collection_loader_;
ComPtr<IResourceFontFileLoader> res_font_file_loader_;
ComPtr<IResourceFontCollectionLoader> res_font_collection_loader_;
};
@ -173,13 +182,34 @@ STDMETHODIMP D2DDeviceResources::QueryInterface(const IID& riid, void** object)
void D2DDeviceResources::DiscardResources()
{
factory_.Reset();
device_.Reset();
device_context_.Reset();
target_bitmap_.Reset();
if (dwrite_factory_)
{
if (font_collection_loader_)
{
dwrite_factory_->UnregisterFontCollectionLoader(font_collection_loader_.Get());
font_collection_loader_.Reset();
}
if (res_font_file_loader_)
{
dwrite_factory_->UnregisterFontFileLoader(res_font_file_loader_.Get());
res_font_file_loader_.Reset();
}
if (res_font_collection_loader_)
{
dwrite_factory_->UnregisterFontCollectionLoader(res_font_collection_loader_.Get());
res_font_collection_loader_.Reset();
}
}
target_bitmap_.Reset();
device_context_.Reset();
device_.Reset();
imaging_factory_.Reset();
dwrite_factory_.Reset();
imaging_factory_.Reset();
factory_.Reset();
}
HRESULT D2DDeviceResources::CreateDeviceIndependentResources()
@ -225,6 +255,38 @@ HRESULT D2DDeviceResources::CreateDeviceIndependentResources()
dwrite_factory_ = dwrite_factory;
}
}
// FontFileLoader and FontCollectionLoader
if (SUCCEEDED(hr))
{
hr = IFontCollectionLoader::Create(&font_collection_loader_);
if (SUCCEEDED(hr))
{
hr = dwrite_factory->RegisterFontCollectionLoader(font_collection_loader_.Get());
}
}
// ResourceFontFileLoader and ResourceFontCollectionLoader
if (SUCCEEDED(hr))
{
hr = IResourceFontFileLoader::Create(&res_font_file_loader_);
if (SUCCEEDED(hr))
{
hr = dwrite_factory->RegisterFontFileLoader(res_font_file_loader_.Get());
}
if (SUCCEEDED(hr))
{
hr = IResourceFontCollectionLoader::Create(&res_font_collection_loader_, res_font_file_loader_.Get());
if (SUCCEEDED(hr))
{
hr = dwrite_factory->RegisterFontCollectionLoader(res_font_collection_loader_.Get());
}
}
}
return hr;
}
@ -450,6 +512,43 @@ HRESULT D2DDeviceResources::CreateTextLayout(_Out_ ComPtr<IDWriteTextLayout>& te
return hr;
}
HRESULT D2DDeviceResources::CreateFontCollectionFromFiles(ComPtr<IDWriteFontCollection>& font_collection,
const Vector<String>& file_paths)
{
if (!dwrite_factory_ || !font_collection_loader_)
return E_UNEXPECTED;
LPVOID key = nullptr;
uint32_t key_size = 0;
HRESULT hr = font_collection_loader_->AddFilePaths(file_paths, &key, &key_size);
if (SUCCEEDED(hr))
{
hr =
dwrite_factory_->CreateCustomFontCollection(font_collection_loader_.Get(), key, key_size, &font_collection);
}
return hr;
}
HRESULT D2DDeviceResources::CreateFontCollectionFromResources(ComPtr<IDWriteFontCollection>& font_collection,
const Vector<Resource>& resources)
{
if (!dwrite_factory_ || !res_font_collection_loader_)
return E_UNEXPECTED;
LPVOID key = nullptr;
uint32_t key_size = 0;
HRESULT hr = res_font_collection_loader_->AddResources(resources, &key, &key_size);
if (SUCCEEDED(hr))
{
hr = dwrite_factory_->CreateCustomFontCollection(res_font_collection_loader_.Get(), key, key_size, &font_collection);
}
return hr;
}
} // namespace directx
} // namespace graphics
} // namespace kiwano

View File

@ -20,9 +20,7 @@
#pragma once
#include <kiwano/render/DirectX/helper.h>
#include <d2d1.h>
#include <d2d1_1.h>
#include <dwrite.h>
#include <kiwano/render/DirectX/FontCollectionLoader.h>
namespace kiwano
{
@ -58,6 +56,12 @@ public:
virtual HRESULT CreateTextLayout(_Out_ ComPtr<IDWriteTextLayout> & text_layout, _In_ LPCWSTR text, UINT32 length,
_In_ ComPtr<IDWriteTextFormat> text_format) = 0;
virtual HRESULT CreateFontCollectionFromFiles(_Out_ ComPtr<IDWriteFontCollection> & font_collection,
const Vector<String>& file_paths) = 0;
virtual HRESULT CreateFontCollectionFromResources(_Out_ ComPtr<IDWriteFontCollection> & font_collection,
const Vector<Resource>& resources) = 0;
virtual HRESULT SetDpi(float dpi) = 0;
virtual HRESULT SetLogicalSize(float width, float height) = 0;

View File

@ -20,7 +20,6 @@
#include <kiwano/utils/Logger.h>
#include <kiwano/render/DirectX/D3D11DeviceResources.h>
#include <memory>
KGE_SUPPRESS_WARNING_PUSH
KGE_SUPPRESS_WARNING(4800) // Implicit conversion from 'type' to bool

View File

@ -20,7 +20,8 @@
#pragma once
#include <kiwano/core/Resource.h>
#include <kiwano/render/DirectX/D2DDeviceResources.h>
#include <kiwano/render/DirectX/helper.h>
#include <dwrite.h>
namespace kiwano
{

View File

@ -18,16 +18,18 @@
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
#include <kiwano/core/Exception.h>
#include <kiwano/utils/Logger.h>
#include <kiwano/event/WindowEvent.h>
#include <kiwano/platform/FileSystem.h>
#include <kiwano/platform/Application.h>
#include <kiwano/render/ShapeMaker.h>
#include <kiwano/render/DirectX/RendererImpl.h>
#include <kiwano/render/DirectX/NativePtr.h>
#include <memory>
#define KGE_SET_STATUS_IF_FAILED(ERRCODE, OBJ, MESSAGE) \
if (FAILED(ERRCODE)) \
{ \
OBJ.Fail(strings::Format("%s failed (%#x): %s", __FUNCTION__, ERRCODE, MESSAGE)); \
}
namespace kiwano
{
@ -93,11 +95,10 @@ void RendererImpl::MakeContextForWindow(WindowPtr window)
}
}
// Initialize other device resources
if (SUCCEEDED(hr))
{
RenderContextImplPtr ctx = memory::New<RenderContextImpl>();
RenderContextImplPtr ctx = MakePtr<RenderContextImpl>();
hr = ctx->CreateDeviceResources(d2d_res_->GetFactory(), d2d_res_->GetDeviceContext());
if (SUCCEEDED(hr))
@ -106,38 +107,6 @@ void RendererImpl::MakeContextForWindow(WindowPtr window)
}
}
// FontFileLoader and FontCollectionLoader
if (SUCCEEDED(hr))
{
hr = IFontCollectionLoader::Create(&font_collection_loader_);
if (SUCCEEDED(hr))
{
hr = d2d_res_->GetDWriteFactory()->RegisterFontCollectionLoader(font_collection_loader_.Get());
}
}
// ResourceFontFileLoader and ResourceFontCollectionLoader
if (SUCCEEDED(hr))
{
hr = IResourceFontFileLoader::Create(&res_font_file_loader_);
if (SUCCEEDED(hr))
{
hr = d2d_res_->GetDWriteFactory()->RegisterFontFileLoader(res_font_file_loader_.Get());
}
if (SUCCEEDED(hr))
{
hr = IResourceFontCollectionLoader::Create(&res_font_collection_loader_, res_font_file_loader_.Get());
if (SUCCEEDED(hr))
{
hr = d2d_res_->GetDWriteFactory()->RegisterFontCollectionLoader(res_font_collection_loader_.Get());
}
}
}
KGE_THROW_IF_FAILED(hr, "Create render resources failed");
}
@ -147,14 +116,9 @@ void RendererImpl::Destroy()
if (d2d_res_)
{
d2d_res_->GetDWriteFactory()->UnregisterFontFileLoader(res_font_file_loader_.Get());
res_font_file_loader_.Reset();
d2d_res_->GetDWriteFactory()->UnregisterFontCollectionLoader(res_font_collection_loader_.Get());
res_font_collection_loader_.Reset();
render_ctx_.Reset();
d2d_res_->DiscardResources();
d2d_res_.Reset();
}
if (d3d_res_)
@ -194,8 +158,10 @@ void RendererImpl::CreateTexture(Texture& texture, const String& file_path)
if (!FileSystem::GetInstance().IsFileExists(file_path))
{
KGE_WARNF("Texture file '%s' not found!", file_path.c_str());
hr = HRESULT_FROM_WIN32(ERROR_FILE_NOT_FOUND);
KGE_SET_STATUS_IF_FAILED(hr, texture,
strings::Format("Texture file '%s' not found!", file_path.c_str()).c_str());
return;
}
if (SUCCEEDED(hr))
@ -234,10 +200,7 @@ void RendererImpl::CreateTexture(Texture& texture, const String& file_path)
}
}
if (FAILED(hr))
{
KGE_THROW_IF_FAILED(hr, "Load texture failed");
}
KGE_SET_STATUS_IF_FAILED(hr, texture, "Load texture failed");
}
void RendererImpl::CreateTexture(Texture& texture, const Resource& resource)
@ -289,10 +252,7 @@ void RendererImpl::CreateTexture(Texture& texture, const Resource& resource)
}
}
if (FAILED(hr))
{
KGE_WARNF("Load texture failed with HRESULT of %08X!", hr);
}
KGE_SET_STATUS_IF_FAILED(hr, texture, "Load texture failed");
}
void RendererImpl::CreateGifImage(GifImage& gif, const String& file_path)
@ -305,8 +265,10 @@ void RendererImpl::CreateGifImage(GifImage& gif, const String& file_path)
if (!FileSystem::GetInstance().IsFileExists(file_path))
{
KGE_WARNF("Gif texture file '%s' not found!", file_path.c_str());
hr = HRESULT_FROM_WIN32(ERROR_FILE_NOT_FOUND);
KGE_SET_STATUS_IF_FAILED(hr, gif,
strings::Format("Gif texture file '%s' not found!", file_path.c_str()).c_str());
return;
}
if (SUCCEEDED(hr))
@ -322,10 +284,7 @@ void RendererImpl::CreateGifImage(GifImage& gif, const String& file_path)
}
}
if (FAILED(hr))
{
KGE_WARNF("Load GIF texture failed with HRESULT of %08X!", hr);
}
KGE_SET_STATUS_IF_FAILED(hr, gif, "Load GIF texture failed");
}
void RendererImpl::CreateGifImage(GifImage& gif, const Resource& resource)
@ -354,10 +313,7 @@ void RendererImpl::CreateGifImage(GifImage& gif, const Resource& resource)
}
}
if (FAILED(hr))
{
KGE_WARNF("Load GIF texture failed with HRESULT of %08X!", hr);
}
KGE_SET_STATUS_IF_FAILED(hr, gif, "Load GIF texture failed");
}
void RendererImpl::CreateGifImageFrame(GifImage::Frame& frame, const GifImage& gif, size_t frame_index)
@ -394,7 +350,7 @@ void RendererImpl::CreateGifImageFrame(GifImage::Frame& frame, const GifImage& g
if (SUCCEEDED(hr))
{
frame.texture = memory::New<Texture>();
frame.texture = MakePtr<Texture>();
NativePtr::Set(frame.texture, bitmap);
frame.texture->SetSize({ bitmap->GetSize().width, bitmap->GetSize().height });
@ -518,10 +474,7 @@ void RendererImpl::CreateGifImageFrame(GifImage::Frame& frame, const GifImage& g
}
}
if (FAILED(hr))
{
KGE_WARNF("Load GIF frame failed with HRESULT of %08X!", hr);
}
KGE_SET_STATUS_IF_FAILED(hr, const_cast<GifImage&>(gif), "Load GIF frame failed");
}
void RendererImpl::CreateFontCollection(Font& font, const String& file_path)
@ -536,33 +489,26 @@ void RendererImpl::CreateFontCollection(Font& font, const String& file_path)
{
if (!FileSystem::GetInstance().IsFileExists(file_path))
{
KGE_WARNF("Font file '%s' not found!", file_path.c_str());
hr = HRESULT_FROM_WIN32(ERROR_FILE_NOT_FOUND);
KGE_SET_STATUS_IF_FAILED(hr, font, strings::Format("Font file '%s' not found!", file_path.c_str()).c_str());
return;
}
}
if (SUCCEEDED(hr))
{
LPVOID key = nullptr;
uint32_t key_size = 0;
String full_path = FileSystem::GetInstance().GetFullPathForFile(file_path);
String full_path = FileSystem::GetInstance().GetFullPathForFile(file_path);
hr = font_collection_loader_->AddFilePaths({ full_path }, &key, &key_size);
ComPtr<IDWriteFontCollection> font_collection;
hr = d2d_res_->CreateFontCollectionFromFiles(font_collection, { full_path });
if (SUCCEEDED(hr))
{
ComPtr<IDWriteFontCollection> font_collection;
hr = d2d_res_->GetDWriteFactory()->CreateCustomFontCollection(font_collection_loader_.Get(), key, key_size,
&font_collection);
if (SUCCEEDED(hr))
{
NativePtr::Set(font, font_collection);
}
NativePtr::Set(font, font_collection);
}
}
KGE_THROW_IF_FAILED(hr, "Create font collection failed");
KGE_SET_STATUS_IF_FAILED(hr, font, "Create font collection failed");
}
void RendererImpl::CreateFontCollection(Font& font, const Resource& res)
@ -575,25 +521,16 @@ void RendererImpl::CreateFontCollection(Font& font, const Resource& res)
if (SUCCEEDED(hr))
{
LPVOID key = nullptr;
uint32_t key_size = 0;
hr = res_font_collection_loader_->AddResources(Vector<Resource>{ res }, &key, &key_size);
ComPtr<IDWriteFontCollection> font_collection;
hr = d2d_res_->CreateFontCollectionFromResources(font_collection, Vector<Resource>{ res });
if (SUCCEEDED(hr))
{
ComPtr<IDWriteFontCollection> font_collection;
hr = d2d_res_->GetDWriteFactory()->CreateCustomFontCollection(res_font_collection_loader_.Get(), key,
key_size, &font_collection);
if (SUCCEEDED(hr))
{
NativePtr::Set(font, font_collection);
}
NativePtr::Set(font, font_collection);
}
}
KGE_THROW_IF_FAILED(hr, "Create font collection failed");
KGE_SET_STATUS_IF_FAILED(hr, font, "Create font collection failed");
}
void RendererImpl::CreateTextLayout(TextLayout& layout, const String& content, const TextStyle& style)
@ -637,7 +574,7 @@ void RendererImpl::CreateTextLayout(TextLayout& layout, const String& content, c
}
}
KGE_THROW_IF_FAILED(hr, "Create text layout failed");
KGE_SET_STATUS_IF_FAILED(hr, layout, "Create text layout failed");
}
void RendererImpl::CreateLineShape(Shape& shape, const Point& begin_pos, const Point& end_pos)
@ -673,7 +610,7 @@ void RendererImpl::CreateLineShape(Shape& shape, const Point& begin_pos, const P
}
}
KGE_THROW_IF_FAILED(hr, "Create ID2D1PathGeometry failed");
KGE_SET_STATUS_IF_FAILED(hr, shape, "Create ID2D1PathGeometry failed");
}
void RendererImpl::CreateRectShape(Shape& shape, const Rect& rect)
@ -695,7 +632,7 @@ void RendererImpl::CreateRectShape(Shape& shape, const Rect& rect)
NativePtr::Set(shape, output);
}
KGE_THROW_IF_FAILED(hr, "Create ID2D1RectangleGeometry failed");
KGE_SET_STATUS_IF_FAILED(hr, shape, "Create ID2D1RectangleGeometry failed");
}
void RendererImpl::CreateRoundedRectShape(Shape& shape, const Rect& rect, const Vec2& radius)
@ -718,7 +655,7 @@ void RendererImpl::CreateRoundedRectShape(Shape& shape, const Rect& rect, const
NativePtr::Set(shape, output);
}
KGE_THROW_IF_FAILED(hr, "Create ID2D1RoundedRectangleGeometry failed");
KGE_SET_STATUS_IF_FAILED(hr, shape, "Create ID2D1RoundedRectangleGeometry failed");
}
void RendererImpl::CreateEllipseShape(Shape& shape, const Point& center, const Vec2& radius)
@ -741,7 +678,7 @@ void RendererImpl::CreateEllipseShape(Shape& shape, const Point& center, const V
NativePtr::Set(shape, output);
}
KGE_THROW_IF_FAILED(hr, "Create ID2D1EllipseGeometry failed");
KGE_SET_STATUS_IF_FAILED(hr, shape, "Create ID2D1EllipseGeometry failed");
}
void RendererImpl::CreateShapeSink(ShapeMaker& maker)
@ -760,13 +697,13 @@ void RendererImpl::CreateShapeSink(ShapeMaker& maker)
if (SUCCEEDED(hr))
{
ShapePtr shape = memory::New<Shape>();
ShapePtr shape = MakePtr<Shape>();
NativePtr::Set(shape, geometry);
maker.SetShape(shape);
}
}
KGE_THROW_IF_FAILED(hr, "Create ID2D1PathGeometry failed");
KGE_SET_STATUS_IF_FAILED(hr, maker, "Create ID2D1PathGeometry failed");
}
void RendererImpl::CreateBrush(Brush& brush, const Color& color)
@ -800,7 +737,7 @@ void RendererImpl::CreateBrush(Brush& brush, const Color& color)
}
}
KGE_THROW_IF_FAILED(hr, "Create ID2D1SolidBrush failed");
KGE_SET_STATUS_IF_FAILED(hr, brush, "Create ID2D1SolidBrush failed");
}
void RendererImpl::CreateBrush(Brush& brush, const LinearGradientStyle& style)
@ -832,7 +769,7 @@ void RendererImpl::CreateBrush(Brush& brush, const LinearGradientStyle& style)
}
}
KGE_THROW_IF_FAILED(hr, "Create ID2D1LinearGradientBrush failed");
KGE_SET_STATUS_IF_FAILED(hr, brush, "Create ID2D1LinearGradientBrush failed");
}
void RendererImpl::CreateBrush(Brush& brush, const RadialGradientStyle& style)
@ -865,7 +802,7 @@ void RendererImpl::CreateBrush(Brush& brush, const RadialGradientStyle& style)
}
}
KGE_THROW_IF_FAILED(hr, "Create ID2D1RadialGradientBrush failed");
KGE_SET_STATUS_IF_FAILED(hr, brush, "Create ID2D1RadialGradientBrush failed");
}
void RendererImpl::CreateBrush(Brush& brush, TexturePtr texture)
@ -892,7 +829,7 @@ void RendererImpl::CreateBrush(Brush& brush, TexturePtr texture)
}
}
KGE_THROW_IF_FAILED(hr, "Create ID2D1RadialGradientBrush failed");
KGE_SET_STATUS_IF_FAILED(hr, brush, "Create ID2D1RadialGradientBrush failed");
}
void RendererImpl::CreateStrokeStyle(StrokeStyle& stroke_style)
@ -931,12 +868,12 @@ void RendererImpl::CreateStrokeStyle(StrokeStyle& stroke_style)
}
}
KGE_THROW_IF_FAILED(hr, "Create ID2D1StrokeStyle failed");
KGE_SET_STATUS_IF_FAILED(hr, stroke_style, "Create ID2D1StrokeStyle failed");
}
RenderContextPtr RendererImpl::CreateTextureRenderContext(Texture& texture, const Size* desired_size)
{
RenderContextImplPtr ptr = memory::New<RenderContextImpl>();
RenderContextImplPtr ptr = MakePtr<RenderContextImpl>();
HRESULT hr = S_OK;
if (!d2d_res_)

View File

@ -21,10 +21,8 @@
#pragma once
#include <kiwano/render/Renderer.h>
#include <kiwano/render/DirectX/D3DDeviceResources.h>
#include <kiwano/render/DirectX/FontCollectionLoader.h>
#include <kiwano/render/DirectX/RenderContextImpl.h>
namespace kiwano
{
@ -92,9 +90,6 @@ private:
ComPtr<ID2DDeviceResources> d2d_res_;
ComPtr<ID3DDeviceResources> d3d_res_;
ComPtr<IFontCollectionLoader> font_collection_loader_;
ComPtr<IResourceFontFileLoader> res_font_file_loader_;
ComPtr<IResourceFontCollectionLoader> res_font_collection_loader_;
};

View File

@ -82,7 +82,7 @@ HRESULT ITextRenderer::Create(_Out_ ITextRenderer** ppTextRenderer, _In_ ID2D1Re
if (ppTextRenderer)
{
TextRenderer* pTextRenderer = memory::New<TextRenderer>();
TextRenderer* pTextRenderer = new (std::nothrow) TextRenderer;
if (pTextRenderer)
{
hr = pTextRenderer->CreateDeviceResources(pRT);

View File

@ -20,10 +20,11 @@
#pragma once
#include <kiwano/math/Math.h>
#include <kiwano/core/Exception.h>
#include <kiwano/utils/Logger.h>
#include <kiwano/render/Color.h>
#include <kiwano/platform/win32/ComPtr.hpp>
#include <d2d1.h>
#include <d2d1_1.h>
namespace kiwano
{

View File

@ -24,26 +24,14 @@
namespace kiwano
{
FontPtr Font::Create(const String& file)
Font::Font(const String& file)
{
FontPtr ptr = memory::New<Font>();
if (ptr)
{
if (!ptr->Load(file))
return nullptr;
}
return ptr;
Load(file);
}
FontPtr Font::Create(const Resource& resource)
Font::Font(const Resource& resource)
{
FontPtr ptr = memory::New<Font>();
if (ptr)
{
if (!ptr->Load(resource))
return nullptr;
}
return ptr;
Load(resource);
}
Font::Font() {}

View File

@ -44,11 +44,11 @@ class Font : public NativeObject
public:
/// \~chinese
/// @brief ´´½¨×ÖÌå
static FontPtr Create(const String& file);
Font(const String& file);
/// \~chinese
/// @brief ´´½¨×ÖÌå
static FontPtr Create(const Resource& resource);
Font(const Resource& resource);
Font();

View File

@ -24,36 +24,19 @@
namespace kiwano
{
FramePtr Frame::Create(const String& file_path)
Frame::Frame(const String& file_path)
{
FramePtr ptr = memory::New<Frame>();
if (ptr)
{
if (!ptr->Load(file_path))
return nullptr;
}
return ptr;
Load(file_path);
}
FramePtr Frame::Create(const Resource& res)
Frame::Frame(const Resource& res)
{
FramePtr ptr = memory::New<Frame>();
if (ptr)
{
if (!ptr->Load(res))
return nullptr;
}
return ptr;
Load(res);
}
FramePtr Frame::Create(TexturePtr texture)
Frame::Frame(TexturePtr texture)
{
FramePtr ptr = memory::New<Frame>();
if (ptr)
{
ptr->SetTexture(texture);
}
return ptr;
SetTexture(texture);
}
Frame::Frame() {}

Some files were not shown because too many files have changed in this diff Show More