refactor Singleton

This commit is contained in:
Nomango 2019-07-30 15:27:01 +08:00
parent 762a764917
commit d153f31a74
27 changed files with 137 additions and 118 deletions

View File

@ -79,7 +79,7 @@ namespace kiwano
return false; return false;
} }
hr = Audio::Instance().CreateVoice(&voice_, transcoder.GetWaveFormatEx()); hr = Audio::Instance()->CreateVoice(&voice_, transcoder.GetWaveFormatEx());
if (FAILED(hr)) if (FAILED(hr))
{ {
if (wave_data_) if (wave_data_)

View File

@ -39,9 +39,9 @@ namespace kiwano
//ImGui::StyleColorsClassic(); //ImGui::StyleColorsClassic();
// Setup Platform/Renderer bindings // Setup Platform/Renderer bindings
Init(app->GetWindow()->GetHandle()); Init(Window::Instance()->GetHandle());
target_window_ = Renderer::Instance().GetTargetWindow(); target_window_ = Renderer::Instance()->GetTargetWindow();
} }
void ImGuiModule::DestroyComponent() void ImGuiModule::DestroyComponent()
@ -58,9 +58,9 @@ namespace kiwano
io.DeltaTime = dt; io.DeltaTime = dt;
// Read keyboard modifiers inputs // Read keyboard modifiers inputs
io.KeyCtrl = Input::Instance().IsDown(KeyCode::Ctrl); io.KeyCtrl = Input::Instance()->IsDown(KeyCode::Ctrl);
io.KeyShift = Input::Instance().IsDown(KeyCode::Shift); io.KeyShift = Input::Instance()->IsDown(KeyCode::Shift);
io.KeyAlt = Input::Instance().IsDown(KeyCode::Alt); io.KeyAlt = Input::Instance()->IsDown(KeyCode::Alt);
io.KeySuper = false; io.KeySuper = false;
// io.KeysDown[], io.MousePos, io.MouseDown[], io.MouseWheel: filled by the WndProc handler below. // io.KeysDown[], io.MousePos, io.MouseDown[], io.MouseWheel: filled by the WndProc handler below.
@ -207,7 +207,7 @@ namespace kiwano
KGE_ASSERT(io.Fonts->IsBuilt() && "Font atlas not built!"); KGE_ASSERT(io.Fonts->IsBuilt() && "Font atlas not built!");
// Setup display size (every frame to accommodate for window resizing) // Setup display size (every frame to accommodate for window resizing)
Size display_size = Renderer::Instance().GetOutputSize(); Size display_size = Renderer::Instance()->GetOutputSize();
io.DisplaySize = ImVec2(display_size.x, display_size.y); io.DisplaySize = ImVec2(display_size.x, display_size.y);
ImGui::NewFrame(); ImGui::NewFrame();
@ -232,7 +232,7 @@ namespace kiwano
::SetCursorPos(pos.x, pos.y); ::SetCursorPos(pos.x, pos.y);
} }
Point pos = Input::Instance().GetMousePos(); Point pos = Input::Instance()->GetMousePos();
io.MousePos = ImVec2(pos.x, pos.y); io.MousePos = ImVec2(pos.x, pos.y);
} }
@ -254,7 +254,7 @@ namespace kiwano
case ImGuiMouseCursor_Hand: cursor = MouseCursor::Hand; break; case ImGuiMouseCursor_Hand: cursor = MouseCursor::Hand; break;
} }
Window::Instance().SetMouseCursor(cursor); Window::Instance()->SetMouseCursor(cursor);
} }
void ImGuiModule::UpdateGamepads() void ImGuiModule::UpdateGamepads()
{ {

View File

@ -6,7 +6,7 @@
#include "imgui_impl_dx11.h" #include "imgui_impl_dx11.h"
inline bool ImGui_Impl_Init(::kiwano::Renderer& renderer) { return ImGui_ImplDX11_Init(renderer.GetD3DDeviceResources()->GetDevice(), renderer.GetD3DDeviceResources()->GetDeviceContext()); } inline bool ImGui_Impl_Init(::kiwano::Renderer* renderer) { return ImGui_ImplDX11_Init(renderer->GetD3DDeviceResources()->GetDevice(), renderer->GetD3DDeviceResources()->GetDeviceContext()); }
inline void ImGui_Impl_Shutdown() { ImGui_ImplDX11_Shutdown(); } inline void ImGui_Impl_Shutdown() { ImGui_ImplDX11_Shutdown(); }
inline void ImGui_Impl_NewFrame() { ImGui_ImplDX11_NewFrame(); } inline void ImGui_Impl_NewFrame() { ImGui_ImplDX11_NewFrame(); }
inline void ImGui_Impl_RenderDrawData(ImDrawData* draw_data) { ImGui_ImplDX11_RenderDrawData(draw_data); } inline void ImGui_Impl_RenderDrawData(ImDrawData* draw_data) { ImGui_ImplDX11_RenderDrawData(draw_data); }
@ -18,7 +18,7 @@ inline bool ImGui_Impl_CreateDeviceObjects() { return ImGui_ImplDX11_Cre
#include "imgui_impl_dx10.h" #include "imgui_impl_dx10.h"
inline bool ImGui_Impl_Init(::kiwano::Renderer& renderer) { return ImGui_ImplDX10_Init(renderer.GetD3DDeviceResources()->GetDevice()); } inline bool ImGui_Impl_Init(::kiwano::Renderer* renderer) { return ImGui_ImplDX10_Init(renderer->GetD3DDeviceResources()->GetDevice()); }
inline void ImGui_Impl_Shutdown() { ImGui_ImplDX10_Shutdown(); } inline void ImGui_Impl_Shutdown() { ImGui_ImplDX10_Shutdown(); }
inline void ImGui_Impl_NewFrame() { ImGui_ImplDX10_NewFrame(); } inline void ImGui_Impl_NewFrame() { ImGui_ImplDX10_NewFrame(); }
inline void ImGui_Impl_RenderDrawData(ImDrawData* draw_data) { ImGui_ImplDX10_RenderDrawData(draw_data); } inline void ImGui_Impl_RenderDrawData(ImDrawData* draw_data) { ImGui_ImplDX10_RenderDrawData(draw_data); }

View File

@ -30,7 +30,7 @@ namespace kiwano
: cache_expired_(false) : cache_expired_(false)
, stroke_width_(1.0f) , stroke_width_(1.0f)
{ {
auto ctx = Renderer::Instance().GetD2DDeviceResources()->GetDeviceContext(); auto ctx = Renderer::Instance()->GetD2DDeviceResources()->GetDeviceContext();
ThrowIfFailed( ThrowIfFailed(
ctx->CreateCompatibleRenderTarget(&render_target_) ctx->CreateCompatibleRenderTarget(&render_target_)
@ -98,7 +98,7 @@ namespace kiwano
if (bitmap_cached_) if (bitmap_cached_)
{ {
Rect bitmap_rect(0.f, 0.f, bitmap_cached_->GetSize().width, bitmap_cached_->GetSize().height); Rect bitmap_rect(0.f, 0.f, bitmap_cached_->GetSize().width, bitmap_cached_->GetSize().height);
Renderer::Instance().DrawBitmap( Renderer::Instance()->DrawBitmap(
bitmap_cached_, bitmap_cached_,
bitmap_rect, bitmap_rect,
bitmap_rect bitmap_rect
@ -123,7 +123,7 @@ namespace kiwano
void Canvas::SetOutlineJoinStyle(StrokeStyle outline_join) void Canvas::SetOutlineJoinStyle(StrokeStyle outline_join)
{ {
outline_join_style_ = Renderer::Instance().GetD2DDeviceResources()->GetStrokeStyle(outline_join); outline_join_style_ = Renderer::Instance()->GetD2DDeviceResources()->GetStrokeStyle(outline_join);
} }
void Canvas::SetTextStyle(Font const& font, TextStyle const & text_style) void Canvas::SetTextStyle(Font const& font, TextStyle const & text_style)
@ -136,7 +136,7 @@ namespace kiwano
text_style_.outline, text_style_.outline,
DX::ConvertToColorF(text_style_.outline_color), DX::ConvertToColorF(text_style_.outline_color),
text_style_.outline_width, text_style_.outline_width,
Renderer::Instance().GetD2DDeviceResources()->GetStrokeStyle(text_style_.outline_stroke) Renderer::Instance()->GetD2DDeviceResources()->GetStrokeStyle(text_style_.outline_stroke)
); );
// clear text format // clear text format
@ -272,7 +272,7 @@ namespace kiwano
if (!text_format_) if (!text_format_)
{ {
ThrowIfFailed( ThrowIfFailed(
Renderer::Instance().GetD2DDeviceResources()->CreateTextFormat( Renderer::Instance()->GetD2DDeviceResources()->CreateTextFormat(
text_format_, text_format_,
text_font_, text_font_,
text_style_ text_style_
@ -283,7 +283,7 @@ namespace kiwano
ComPtr<IDWriteTextLayout> text_layout; ComPtr<IDWriteTextLayout> text_layout;
Size layout_size; Size layout_size;
ThrowIfFailed( ThrowIfFailed(
Renderer::Instance().GetD2DDeviceResources()->CreateTextLayout( Renderer::Instance()->GetD2DDeviceResources()->CreateTextLayout(
text_layout, text_layout,
layout_size, layout_size,
text, text,
@ -392,7 +392,7 @@ namespace kiwano
current_geometry_ = nullptr; current_geometry_ = nullptr;
ThrowIfFailed( ThrowIfFailed(
Renderer::Instance().GetD2DDeviceResources()->GetFactory()->CreatePathGeometry(&current_geometry_) Renderer::Instance()->GetD2DDeviceResources()->GetFactory()->CreatePathGeometry(&current_geometry_)
); );
ThrowIfFailed( ThrowIfFailed(

View File

@ -51,12 +51,12 @@ namespace kiwano
void DebugNode::OnRender() void DebugNode::OnRender()
{ {
Renderer::Instance().SetTransform(Matrix{}); Renderer::Instance()->SetTransform(Matrix{});
Renderer::Instance().GetSolidColorBrush()->SetColor(D2D1::ColorF(0.0f, 0.0f, 0.0f, 0.5f)); Renderer::Instance()->GetSolidColorBrush()->SetColor(D2D1::ColorF(0.0f, 0.0f, 0.0f, 0.5f));
Renderer::Instance().GetD2DDeviceResources()->GetDeviceContext()->FillRectangle( Renderer::Instance()->GetD2DDeviceResources()->GetDeviceContext()->FillRectangle(
D2D1_RECT_F{ 10, 10, 30 + debug_text_->GetLayoutSize().x, 30 + debug_text_->GetLayoutSize().y }, D2D1_RECT_F{ 10, 10, 30 + debug_text_->GetLayoutSize().x, 30 + debug_text_->GetLayoutSize().y },
Renderer::Instance().GetSolidColorBrush() Renderer::Instance()->GetSolidColorBrush()
); );
} }
@ -77,9 +77,9 @@ namespace kiwano
ss << "Objects: " << Object::__GetTracingObjects().size() << std::endl; ss << "Objects: " << Object::__GetTracingObjects().size() << std::endl;
#endif #endif
ss << "Render: " << Renderer::Instance().GetStatus().duration.Milliseconds() << "ms" << std::endl; ss << "Render: " << Renderer::Instance()->GetStatus().duration.Milliseconds() << "ms" << std::endl;
ss << "Primitives / sec: " << Renderer::Instance().GetStatus().primitives * frame_time_.size() << std::endl; ss << "Primitives / sec: " << Renderer::Instance()->GetStatus().primitives * frame_time_.size() << std::endl;
PROCESS_MEMORY_COUNTERS_EX pmc; PROCESS_MEMORY_COUNTERS_EX pmc;
GetProcessMemoryInfo(GetCurrentProcess(), (PROCESS_MEMORY_COUNTERS*)&pmc, sizeof(pmc)); GetProcessMemoryInfo(GetCurrentProcess(), (PROCESS_MEMORY_COUNTERS*)&pmc, sizeof(pmc));

View File

@ -128,7 +128,7 @@ namespace kiwano
ComPtr<ID2D1PathGeometry> path_geo; ComPtr<ID2D1PathGeometry> path_geo;
ComPtr<ID2D1GeometrySink> path_sink; ComPtr<ID2D1GeometrySink> path_sink;
HRESULT hr = Renderer::Instance().GetD2DDeviceResources()->GetFactory()->CreatePathGeometry(&path_geo); HRESULT hr = Renderer::Instance()->GetD2DDeviceResources()->GetFactory()->CreatePathGeometry(&path_geo);
if (SUCCEEDED(hr)) if (SUCCEEDED(hr))
{ {
@ -185,7 +185,7 @@ namespace kiwano
void RectangleGeometry::SetRect(Rect const & rect) void RectangleGeometry::SetRect(Rect const & rect)
{ {
ComPtr<ID2D1RectangleGeometry> geo; ComPtr<ID2D1RectangleGeometry> geo;
auto factory = Renderer::Instance().GetD2DDeviceResources()->GetFactory(); auto factory = Renderer::Instance()->GetD2DDeviceResources()->GetFactory();
if (SUCCEEDED(factory->CreateRectangleGeometry(DX::ConvertToRectF(rect), &geo))) if (SUCCEEDED(factory->CreateRectangleGeometry(DX::ConvertToRectF(rect), &geo)))
{ {
@ -226,7 +226,7 @@ namespace kiwano
void CircleGeometry::SetCircle(Point const & center, float radius) void CircleGeometry::SetCircle(Point const & center, float radius)
{ {
ComPtr<ID2D1EllipseGeometry> geo; ComPtr<ID2D1EllipseGeometry> geo;
auto factory = Renderer::Instance().GetD2DDeviceResources()->GetFactory(); auto factory = Renderer::Instance()->GetD2DDeviceResources()->GetFactory();
if (SUCCEEDED(factory->CreateEllipseGeometry( if (SUCCEEDED(factory->CreateEllipseGeometry(
D2D1::Ellipse( D2D1::Ellipse(
@ -274,7 +274,7 @@ namespace kiwano
void EllipseGeometry::SetEllipse(Point const & center, float radius_x, float radius_y) void EllipseGeometry::SetEllipse(Point const & center, float radius_x, float radius_y)
{ {
ComPtr<ID2D1EllipseGeometry> geo; ComPtr<ID2D1EllipseGeometry> geo;
auto factory = Renderer::Instance().GetD2DDeviceResources()->GetFactory(); auto factory = Renderer::Instance()->GetD2DDeviceResources()->GetFactory();
if (SUCCEEDED(factory->CreateEllipseGeometry( if (SUCCEEDED(factory->CreateEllipseGeometry(
D2D1::Ellipse( D2D1::Ellipse(
@ -306,7 +306,7 @@ namespace kiwano
{ {
current_geometry_ = nullptr; current_geometry_ = nullptr;
auto factory = Renderer::Instance().GetD2DDeviceResources()->GetFactory(); auto factory = Renderer::Instance()->GetD2DDeviceResources()->GetFactory();
ThrowIfFailed( ThrowIfFailed(
factory->CreatePathGeometry(&current_geometry_) factory->CreatePathGeometry(&current_geometry_)
@ -422,7 +422,7 @@ namespace kiwano
void RoundedRectGeometry::SetRoundedRect(Rect const & rect, float radius_x, float radius_y) void RoundedRectGeometry::SetRoundedRect(Rect const & rect, float radius_x, float radius_y)
{ {
ComPtr<ID2D1RoundedRectangleGeometry> geo; ComPtr<ID2D1RoundedRectangleGeometry> geo;
auto factory = Renderer::Instance().GetD2DDeviceResources()->GetFactory(); auto factory = Renderer::Instance()->GetD2DDeviceResources()->GetFactory();
if (SUCCEEDED(factory->CreateRoundedRectangleGeometry( if (SUCCEEDED(factory->CreateRoundedRectangleGeometry(
D2D1::RoundedRect( D2D1::RoundedRect(

View File

@ -70,12 +70,12 @@ namespace kiwano
{ {
if (geometry_ && geometry_->geo_) if (geometry_ && geometry_->geo_)
{ {
Renderer::Instance().FillGeometry( Renderer::Instance()->FillGeometry(
geometry_->geo_.Get(), geometry_->geo_.Get(),
fill_color_ fill_color_
); );
Renderer::Instance().DrawGeometry( Renderer::Instance()->DrawGeometry(
geometry_->geo_, geometry_->geo_,
stroke_color_, stroke_color_,
stroke_width_, stroke_width_,

View File

@ -36,8 +36,8 @@ namespace kiwano
, frame_position_{} , frame_position_{}
, bg_color_{} , bg_color_{}
{ {
factory_ = Renderer::Instance().GetD2DDeviceResources()->GetWICImagingFactory(); factory_ = Renderer::Instance()->GetD2DDeviceResources()->GetWICImagingFactory();
auto ctx = Renderer::Instance().GetD2DDeviceResources()->GetDeviceContext(); auto ctx = Renderer::Instance()->GetD2DDeviceResources()->GetDeviceContext();
ThrowIfFailed( ThrowIfFailed(
ctx->CreateCompatibleRenderTarget(&frame_rt_) ctx->CreateCompatibleRenderTarget(&frame_rt_)
@ -157,7 +157,7 @@ namespace kiwano
if (SUCCEEDED(frame_rt_->GetBitmap(&frame_to_render))) if (SUCCEEDED(frame_rt_->GetBitmap(&frame_to_render)))
{ {
Rect bounds = GetBounds(); Rect bounds = GetBounds();
Renderer::Instance().DrawBitmap(frame_to_render, bounds, bounds); Renderer::Instance()->DrawBitmap(frame_to_render, bounds, bounds);
} }
} }
} }
@ -192,7 +192,7 @@ namespace kiwano
if (SUCCEEDED(hr)) if (SUCCEEDED(hr))
{ {
auto ctx = Renderer::Instance().GetD2DDeviceResources()->GetDeviceContext(); auto ctx = Renderer::Instance()->GetD2DDeviceResources()->GetDeviceContext();
// Create a D2DBitmap from IWICBitmapSource // Create a D2DBitmap from IWICBitmapSource
raw_frame_.Reset(); raw_frame_.Reset();

View File

@ -69,11 +69,11 @@ namespace kiwano
return false; return false;
} }
#endif #endif
hr = Renderer::Instance().GetD2DDeviceResources()->CreateBitmapFromFile(bitmap, res.GetFileName()); hr = Renderer::Instance()->GetD2DDeviceResources()->CreateBitmapFromFile(bitmap, res.GetFileName());
} }
else else
{ {
hr = Renderer::Instance().GetD2DDeviceResources()->CreateBitmapFromResource(bitmap, res); hr = Renderer::Instance()->GetD2DDeviceResources()->CreateBitmapFromResource(bitmap, res);
} }
if (FAILED(hr)) if (FAILED(hr))

View File

@ -27,7 +27,7 @@ namespace kiwano
Layer::Layer() Layer::Layer()
: swallow_(false) : swallow_(false)
{ {
SetSize(Renderer::Instance().GetOutputSize()); SetSize(Renderer::Instance()->GetOutputSize());
auto handler = MakeClosure(this, &Layer::HandleMessages); auto handler = MakeClosure(this, &Layer::HandleMessages);

View File

@ -638,8 +638,8 @@ namespace kiwano
void VisualNode::PrepareRender() void VisualNode::PrepareRender()
{ {
Renderer::Instance().SetTransform(transform_matrix_); Renderer::Instance()->SetTransform(transform_matrix_);
Renderer::Instance().SetOpacity(displayed_opacity_); Renderer::Instance()->SetOpacity(displayed_opacity_);
} }
} }

View File

@ -29,7 +29,7 @@ namespace kiwano
scene_ = this; scene_ = this;
SetAnchor(0, 0); SetAnchor(0, 0);
SetSize(Renderer::Instance().GetOutputSize()); SetSize(Renderer::Instance()->GetOutputSize());
} }
Scene::~Scene() Scene::~Scene()

View File

@ -99,7 +99,7 @@ namespace kiwano
{ {
if (image_) if (image_)
{ {
Renderer::Instance().DrawImage(image_, GetBounds()); Renderer::Instance()->DrawImage(image_, GetBounds());
} }
} }
} }

View File

@ -303,14 +303,14 @@ namespace kiwano
if (text_layout_) if (text_layout_)
{ {
Renderer::Instance().SetTextStyle( Renderer::Instance()->SetTextStyle(
style_.color, style_.color,
style_.outline, style_.outline,
style_.outline_color, style_.outline_color,
style_.outline_width, style_.outline_width,
style_.outline_stroke style_.outline_stroke
); );
Renderer::Instance().DrawTextLayout(text_layout_); Renderer::Instance()->DrawTextLayout(text_layout_);
} }
} }
@ -327,7 +327,7 @@ namespace kiwano
return; return;
ThrowIfFailed( ThrowIfFailed(
Renderer::Instance().GetD2DDeviceResources()->CreateTextFormat( Renderer::Instance()->GetD2DDeviceResources()->CreateTextFormat(
text_format_, text_format_,
font_, font_,
style_ style_
@ -335,7 +335,7 @@ namespace kiwano
); );
ThrowIfFailed( ThrowIfFailed(
Renderer::Instance().GetD2DDeviceResources()->CreateTextLayout( Renderer::Instance()->GetD2DDeviceResources()->CreateTextLayout(
text_layout_, text_layout_,
layout_size_, layout_size_,
text_, text_,

View File

@ -66,18 +66,18 @@ namespace kiwano
if (in_scene_) if (in_scene_)
{ {
ThrowIfFailed( ThrowIfFailed(
Renderer::Instance().CreateLayer(in_layer_) Renderer::Instance()->CreateLayer(in_layer_)
); );
} }
if (out_scene_) if (out_scene_)
{ {
ThrowIfFailed( ThrowIfFailed(
Renderer::Instance().CreateLayer(out_layer_) Renderer::Instance()->CreateLayer(out_layer_)
); );
} }
window_size_ = Renderer::Instance().GetOutputSize(); window_size_ = Renderer::Instance()->GetOutputSize();
out_layer_prop_ = in_layer_prop_ = LayerProperties{ Rect(Point(), window_size_),1.f }; out_layer_prop_ = in_layer_prop_ = LayerProperties{ Rect(Point(), window_size_),1.f };
} }
@ -101,34 +101,34 @@ namespace kiwano
void Transition::Render() void Transition::Render()
{ {
auto& renderer = Renderer::Instance(); auto renderer = Renderer::Instance();
if (out_scene_) if (out_scene_)
{ {
renderer.PushClip( renderer->PushClip(
out_scene_->GetTransformMatrix(), out_scene_->GetTransformMatrix(),
window_size_ window_size_
); );
renderer.PushLayer(out_layer_, out_layer_prop_); renderer->PushLayer(out_layer_, out_layer_prop_);
out_scene_->Render(); out_scene_->Render();
renderer.PopLayer(); renderer->PopLayer();
renderer.PopClip(); renderer->PopClip();
} }
if (in_scene_) if (in_scene_)
{ {
renderer.PushClip( renderer->PushClip(
in_scene_->GetTransformMatrix(), in_scene_->GetTransformMatrix(),
window_size_ window_size_
); );
renderer.PushLayer(in_layer_, in_layer_prop_); renderer->PushLayer(in_layer_, in_layer_prop_);
in_scene_->Render(); in_scene_->Render();
renderer.PopLayer(); renderer->PopLayer();
renderer.PopClip(); renderer->PopClip();
} }
} }

View File

@ -27,18 +27,18 @@
#ifndef KGE_LOG #ifndef KGE_LOG
# ifdef KGE_DEBUG # ifdef KGE_DEBUG
# define KGE_LOG(FORMAT, ...) kiwano::Logger::Instance().Messagef((FORMAT ## "\n"), __VA_ARGS__) # define KGE_LOG(FORMAT, ...) kiwano::Logger::Instance()->Messagef((FORMAT ## "\n"), __VA_ARGS__)
# else # else
# define KGE_LOG __noop # define KGE_LOG __noop
# endif # endif
#endif #endif
#ifndef KGE_WARNING_LOG #ifndef KGE_WARNING_LOG
# define KGE_WARNING_LOG(FORMAT, ...) kiwano::Logger::Instance().Warningf((FORMAT ## "\n"), __VA_ARGS__) # define KGE_WARNING_LOG(FORMAT, ...) kiwano::Logger::Instance()->Warningf((FORMAT ## "\n"), __VA_ARGS__)
#endif #endif
#ifndef KGE_ERROR_LOG #ifndef KGE_ERROR_LOG
# define KGE_ERROR_LOG(FORMAT, ...) kiwano::Logger::Instance().Errorf((FORMAT ## "\n"), __VA_ARGS__) # define KGE_ERROR_LOG(FORMAT, ...) kiwano::Logger::Instance()->Errorf((FORMAT ## "\n"), __VA_ARGS__)
#endif #endif
namespace kiwano namespace kiwano
@ -274,7 +274,7 @@ namespace kiwano
inline std::wostream& Logger::DefaultOutputColor(std::wostream& out) inline std::wostream& Logger::DefaultOutputColor(std::wostream& out)
{ {
::SetConsoleTextAttribute(::GetStdHandle(STD_OUTPUT_HANDLE), Logger::Instance().default_stdout_color_); ::SetConsoleTextAttribute(::GetStdHandle(STD_OUTPUT_HANDLE), Logger::Instance()->default_stdout_color_);
return out; return out;
} }
} }

View File

@ -19,25 +19,41 @@
// THE SOFTWARE. // THE SOFTWARE.
#pragma once #pragma once
#include <memory>
#include <mutex>
// Class that will implement the singleton mode, // Class that will implement the singleton mode,
// must use the macro in its delare file // must use the macro in its delare file
#ifndef KGE_DECLARE_SINGLETON #ifndef KGE_DECLARE_SINGLETON
#define KGE_DECLARE_SINGLETON( CLASS ) \ #define KGE_DECLARE_SINGLETON( CLASS ) \
friend class ::kiwano::Singleton< CLASS > friend ::kiwano::Singleton< CLASS >; \
friend ::std::default_delete< CLASS >
#endif #endif
namespace kiwano namespace kiwano
{ {
template <typename _Ty> template <typename _Ty>
class Singleton struct Singleton
{ {
public: public:
static inline _Ty& Instance() static inline _Ty* Instance()
{ {
static _Ty instance; // Thread-safe if (!instance_)
return instance; {
std::call_once(once_, Init);
}
return instance_.get();
}
static inline void Init()
{
if (!instance_) instance_.reset(new (std::nothrow) _Ty);
}
static inline void Destroy()
{
instance_.reset();
} }
protected: protected:
@ -47,5 +63,15 @@ namespace kiwano
Singleton(const Singleton&) = delete; Singleton(const Singleton&) = delete;
Singleton& operator=(const Singleton&) = delete; Singleton& operator=(const Singleton&) = delete;
private:
static std::once_flag once_;
static std::unique_ptr<_Ty> instance_;
}; };
template <typename _Ty>
std::once_flag Singleton<_Ty>::once_;
template <typename _Ty>
std::unique_ptr<_Ty> Singleton<_Ty>::instance_;
} }

View File

@ -49,17 +49,14 @@ namespace kiwano
Application::Application() Application::Application()
: end_(true) : end_(true)
, inited_(false) , inited_(false)
, main_window_(nullptr)
, time_scale_(1.f) , time_scale_(1.f)
{ {
ThrowIfFailed( ThrowIfFailed(
::CoInitialize(nullptr) ::CoInitialize(nullptr)
); );
main_window_ = &Window::Instance(); Use(Renderer::Instance());
Use(Input::Instance());
Use(&Renderer::Instance());
Use(&Input::Instance());
} }
Application::~Application() Application::~Application()
@ -72,7 +69,7 @@ namespace kiwano
void Application::Init(const Options& options) void Application::Init(const Options& options)
{ {
ThrowIfFailed( ThrowIfFailed(
main_window_->Create( Window::Instance()->Create(
options.title, options.title,
options.width, options.width,
options.height, options.height,
@ -82,8 +79,8 @@ namespace kiwano
) )
); );
Renderer::Instance().SetClearColor(options.clear_color); Renderer::Instance()->SetClearColor(options.clear_color);
Renderer::Instance().SetVSyncEnabled(options.vsync); Renderer::Instance()->SetVSyncEnabled(options.vsync);
// Setup all components // Setup all components
for (Component* c : components_) for (Component* c : components_)
@ -94,7 +91,7 @@ namespace kiwano
// Everything is ready // Everything is ready
OnStart(); OnStart();
HWND hwnd = main_window_->GetHandle(); HWND hwnd = Window::Instance()->GetHandle();
// disable imm // disable imm
::ImmAssociateContext(hwnd, nullptr); ::ImmAssociateContext(hwnd, nullptr);
@ -107,7 +104,7 @@ namespace kiwano
void Application::Run() void Application::Run()
{ {
HWND hwnd = main_window_->GetHandle(); HWND hwnd = Window::Instance()->GetHandle();
if (!hwnd) if (!hwnd)
throw std::exception("Calling Application::Run before Application::Init"); throw std::exception("Calling Application::Run before Application::Init");
@ -115,7 +112,7 @@ namespace kiwano
if (hwnd) if (hwnd)
{ {
end_ = false; end_ = false;
main_window_->Prepare(); Window::Instance()->Prepare();
MSG msg = {}; MSG msg = {};
while (::GetMessageW(&msg, nullptr, 0, 0) && !end_) while (::GetMessageW(&msg, nullptr, 0, 0) && !end_)
@ -221,12 +218,12 @@ namespace kiwano
if (show) if (show)
{ {
debug_node_ = new DebugNode; debug_node_ = new DebugNode;
Renderer::Instance().SetCollectingStatus(true); Renderer::Instance()->SetCollectingStatus(true);
} }
else else
{ {
debug_node_.Reset(); debug_node_.Reset();
Renderer::Instance().SetCollectingStatus(false); Renderer::Instance()->SetCollectingStatus(false);
} }
} }
@ -448,7 +445,7 @@ namespace kiwano
app->curr_scene_->Dispatch(evt); app->curr_scene_->Dispatch(evt);
} }
app->GetWindow()->UpdateWindowRect(); Window::Instance()->UpdateWindowRect();
} }
} }
break; break;
@ -472,7 +469,7 @@ namespace kiwano
{ {
bool active = (LOWORD(wparam) != WA_INACTIVE); bool active = (LOWORD(wparam) != WA_INACTIVE);
app->GetWindow()->SetActive(active); Window::Instance()->SetActive(active);
if (app->curr_scene_) if (app->curr_scene_)
{ {

View File

@ -117,9 +117,6 @@ namespace kiwano
// 获取当前场景 // 获取当前场景
ScenePtr GetCurrentScene(); ScenePtr GetCurrentScene();
// »ñÈ¡Ö÷´°¿Ú
inline Window* GetWindow() const { return main_window_; }
// 设置时间缩放因子 // 设置时间缩放因子
void SetTimeScale( void SetTimeScale(
float scale_factor float scale_factor
@ -153,7 +150,6 @@ namespace kiwano
NodePtr debug_node_; NodePtr debug_node_;
TransitionPtr transition_; TransitionPtr transition_;
Window* main_window_;
Array<Component*> components_; Array<Component*> components_;
}; };
} }

View File

@ -21,7 +21,7 @@
#include "render.h" #include "render.h"
#include "../2d/Image.h" #include "../2d/Image.h"
#include "../base/logs.h" #include "../base/logs.h"
#include "../platform/Application.h" #include "../base/window.h"
namespace kiwano namespace kiwano
{ {
@ -45,7 +45,7 @@ namespace kiwano
{ {
KGE_LOG(L"Creating device resources"); KGE_LOG(L"Creating device resources");
hwnd_ = app->GetWindow()->GetHandle(); hwnd_ = Window::Instance()->GetHandle();
ThrowIfFailed(hwnd_ ? S_OK : E_FAIL); ThrowIfFailed(hwnd_ ? S_OK : E_FAIL);
@ -87,7 +87,7 @@ namespace kiwano
CreateDeviceResources() CreateDeviceResources()
); );
output_size_ = app->GetWindow()->GetSize(); output_size_ = Window::Instance()->GetSize();
} }
void Renderer::DestroyComponent() void Renderer::DestroyComponent()

View File

@ -112,7 +112,7 @@ namespace kiwano
if (evt.type == Event::MouseHover) if (evt.type == Event::MouseHover)
{ {
SetStatus(Status::Hover); SetStatus(Status::Hover);
Window::Instance().SetMouseCursor(MouseCursor::Hand); Window::Instance()->SetMouseCursor(MouseCursor::Hand);
if (mouse_over_callback_) if (mouse_over_callback_)
mouse_over_callback_(); mouse_over_callback_();
@ -120,7 +120,7 @@ namespace kiwano
else if (evt.type == Event::MouseOut) else if (evt.type == Event::MouseOut)
{ {
SetStatus(Status::Normal); SetStatus(Status::Normal);
Window::Instance().SetMouseCursor(MouseCursor::Arrow); Window::Instance()->SetMouseCursor(MouseCursor::Arrow);
if (mouse_out_callback_) if (mouse_out_callback_)
mouse_out_callback_(); mouse_out_callback_();

View File

@ -59,7 +59,7 @@ public:
ImGui::End(); ImGui::End();
// Ð޸Ĵ°¿Ú±³¾°É« // Ð޸Ĵ°¿Ú±³¾°É«
Renderer::Instance().SetClearColor(clear_color); Renderer::Instance()->SetClearColor(clear_color);
} }
void AnotherWindow() void AnotherWindow()

View File

@ -11,7 +11,7 @@ public:
ImGuiApp() ImGuiApp()
{ {
// 添加 ImGui 组件 // 添加 ImGui 组件
Use(&ImGuiModule::Instance()); Use(ImGuiModule::Instance());
// 初始化 // 初始化
Options options(L"ImGui Demo", 1280, 800); Options options(L"ImGui Demo", 1280, 800);

View File

@ -21,30 +21,30 @@ public:
void OnUpdate(Duration dt) override void OnUpdate(Duration dt) override
{ {
// 获取输入设备 // 获取输入设备
auto& input = Input::Instance(); auto input = Input::Instance();
// 按下左右键 // 按下左右键
if (input.IsDown(KeyCode::Left)) if (input->IsDown(KeyCode::Left))
{ {
this->Move(-2, 0); this->Move(-2, 0);
} }
else if (input.IsDown(KeyCode::Right)) else if (input->IsDown(KeyCode::Right))
{ {
this->Move(2, 0); this->Move(2, 0);
} }
// 按下上下键 // 按下上下键
if (input.IsDown(KeyCode::Up)) if (input->IsDown(KeyCode::Up))
{ {
this->Move(0, -2); this->Move(0, -2);
} }
else if (input.IsDown(KeyCode::Down)) else if (input->IsDown(KeyCode::Down))
{ {
this->Move(0, 2); this->Move(0, 2);
} }
// 按下鼠标左键,顺时针旋转角色 // 按下鼠标左键,顺时针旋转角色
if (input.IsDown(MouseButton::Left)) if (input->IsDown(MouseButton::Left))
{ {
// 获取当前旋转角度 // 获取当前旋转角度
float rotation = this->GetRotation(); float rotation = this->GetRotation();
@ -53,7 +53,7 @@ public:
} }
// 点击鼠标右键,隐藏或显示角色 // 点击鼠标右键,隐藏或显示角色
if (input.WasPressed(MouseButton::Right)) if (input->WasPressed(MouseButton::Right))
{ {
// 获取当前显示状态 // 获取当前显示状态
bool visible = this->IsVisible(); bool visible = this->IsVisible();

View File

@ -63,20 +63,20 @@ public:
state_text->SetText(playing ? L"当前状态:正在播放" : L"当前状态:停止播放"); state_text->SetText(playing ? L"当前状态:正在播放" : L"当前状态:停止播放");
// 获取输入设备 // 获取输入设备
auto& input = Input::Instance(); auto input = Input::Instance();
// 按空格键暂停或继续 // 按空格键暂停或继续
if (input.WasPressed(KeyCode::Space)) if (input->WasPressed(KeyCode::Space))
{ {
bgmusic->IsPlaying() ? bgmusic->Pause() : bgmusic->Resume(); bgmusic->IsPlaying() ? bgmusic->Pause() : bgmusic->Resume();
} }
// 按上下键调整音量 // 按上下键调整音量
if (input.WasPressed(KeyCode::Up)) if (input->WasPressed(KeyCode::Up))
{ {
bgmusic->SetVolume(volume + 0.1f); bgmusic->SetVolume(volume + 0.1f);
} }
else if (input.WasPressed(KeyCode::Down)) else if (input->WasPressed(KeyCode::Down))
{ {
bgmusic->SetVolume(volume - 0.1f); bgmusic->SetVolume(volume - 0.1f);
} }

View File

@ -33,13 +33,13 @@ public:
void OnEnter() override void OnEnter() override
{ {
// 进入场景时打开控制台 // 进入场景时打开控制台
Logger::Instance().ShowConsole(true); Logger::Instance()->ShowConsole(true);
} }
void OnExit() override void OnExit() override
{ {
// 退出场景时关闭控制台 // 退出场景时关闭控制台
Logger::Instance().ShowConsole(false); Logger::Instance()->ShowConsole(false);
} }
void OnKeyDown(Event const& e) void OnKeyDown(Event const& e)
@ -66,7 +66,7 @@ public:
void SendGetRequest() void SendGetRequest()
{ {
// 发送 GET 请求 // 发送 GET 请求
Logger::Instance().Println(L"Start to send GET request..."); Logger::Instance()->Println(L"Start to send GET request...");
HttpRequestPtr request = new HttpRequest; HttpRequestPtr request = new HttpRequest;
// 设置请求 URL // 设置请求 URL
@ -77,13 +77,13 @@ public:
request->SetResponseCallback(MakeClosure(this, &Demo5::Complete)); request->SetResponseCallback(MakeClosure(this, &Demo5::Complete));
// 发送 HTTP 请求 // 发送 HTTP 请求
HttpClient::Instance().Send(request); HttpClient::Instance()->Send(request);
} }
void SendPostRequest() void SendPostRequest()
{ {
// 发送 POST 请求 // 发送 POST 请求
Logger::Instance().Println(L"Start to send POST request..."); Logger::Instance()->Println(L"Start to send POST request...");
// 创建 JSON 格式的 POST 数据 // 创建 JSON 格式的 POST 数据
Json request_data = { Json request_data = {
@ -102,13 +102,13 @@ public:
request->SetJsonData(request_data); request->SetJsonData(request_data);
request->SetResponseCallback(MakeClosure(this, &Demo5::Complete)); request->SetResponseCallback(MakeClosure(this, &Demo5::Complete));
HttpClient::Instance().Send(request); HttpClient::Instance()->Send(request);
} }
void SendPutRequest() void SendPutRequest()
{ {
// 发送 PUT 请求 // 发送 PUT 请求
Logger::Instance().Println(L"Start to send PUT request..."); Logger::Instance()->Println(L"Start to send PUT request...");
// 创建 JSON 格式的 PUT 数据 // 创建 JSON 格式的 PUT 数据
Json request_data = Json::array({ 1, 2, 3 }); Json request_data = Json::array({ 1, 2, 3 });
@ -120,20 +120,20 @@ public:
request->SetJsonData(request_data); request->SetJsonData(request_data);
request->SetResponseCallback(MakeClosure(this, &Demo5::Complete)); request->SetResponseCallback(MakeClosure(this, &Demo5::Complete));
HttpClient::Instance().Send(request); HttpClient::Instance()->Send(request);
} }
void SendDeleteRequest() void SendDeleteRequest()
{ {
// 发送 DELETE 请求 // 发送 DELETE 请求
Logger::Instance().Println(L"Start to send DELETE request..."); Logger::Instance()->Println(L"Start to send DELETE request...");
HttpRequestPtr request = new HttpRequest; HttpRequestPtr request = new HttpRequest;
request->SetUrl(L"http://httpbin.org/delete"); request->SetUrl(L"http://httpbin.org/delete");
request->SetType(HttpRequest::Type::Delete); request->SetType(HttpRequest::Type::Delete);
request->SetResponseCallback(MakeClosure(this, &Demo5::Complete)); request->SetResponseCallback(MakeClosure(this, &Demo5::Complete));
HttpClient::Instance().Send(request); HttpClient::Instance()->Send(request);
} }
void Complete(HttpRequestPtr request, HttpResponsePtr response) void Complete(HttpRequestPtr request, HttpResponsePtr response)

View File

@ -32,10 +32,10 @@ public:
DemoApp() DemoApp()
{ {
// 使用 Audio 组件 // 使用 Audio 组件
Use(&Audio::Instance()); Use(Audio::Instance());
// 使用 HttpClient 组件 // 使用 HttpClient 组件
Use(&HttpClient::Instance()); Use(HttpClient::Instance());
Options options(L"Kiwano示例程序", WINDOW_WIDTH, WINDOW_HEIGHT); Options options(L"Kiwano示例程序", WINDOW_WIDTH, WINDOW_HEIGHT);
Init(options); Init(options);
@ -53,7 +53,7 @@ public:
s_CurrIndex = index; s_CurrIndex = index;
String title = s_Demos[index].title; String title = s_Demos[index].title;
GetWindow()->SetTitle(L"KiwanoʾÀý³ÌÐò - " + title); Window::Instance()->SetTitle(L"KiwanoʾÀý³ÌÐò - " + title);
ScenePtr scene = s_Demos[index].Create(); ScenePtr scene = s_Demos[index].Create();
EnterScene(scene); EnterScene(scene);