diff --git a/Extra2D/include/extra2d/app/application.h b/Extra2D/include/extra2d/app/application.h index 1ea91d9..3c8d409 100644 --- a/Extra2D/include/extra2d/app/application.h +++ b/Extra2D/include/extra2d/app/application.h @@ -1,11 +1,10 @@ #pragma once -#include +#include #include #include #include -#include -#include +#include namespace extra2d { @@ -21,123 +20,119 @@ class InputModule; */ class Application { public: - static Application& get(); + static Application &get(); - Application(const Application&) = delete; - Application& operator=(const Application&) = delete; + Application(const Application &) = delete; + Application &operator=(const Application &) = delete; - /** - * @brief 注册模块 - * @tparam T 模块类型 - * @tparam Args 构造函数参数 - * @return 模块指针 - */ - template - T* use(Args&&... args) { - return Registry::instance().use(std::forward(args)...); - } - - /** - * @brief 获取模块 - * @tparam T 模块类型 - * @return 模块指针 - */ - template - T* get() const { - return Registry::instance().get(); - } - - /** - * @brief 初始化 - * @return 初始化成功返回 true - */ - bool init(); - - /** - * @brief 初始化(带配置) - * @param config 应用配置 - * @return 初始化成功返回 true - */ - bool init(const AppConfig& config); - - /** - * @brief 关闭 - */ - void shutdown(); - - /** - * @brief 运行主循环 - */ - void run(); - - /** - * @brief 请求退出 - */ - void quit(); - - /** - * @brief 暂停 - */ - void pause(); - - /** - * @brief 恢复 - */ - void resume(); - - bool isPaused() const { return paused_; } - bool isRunning() const { return running_; } - - /** - * @brief 获取窗口 - * @return 窗口指针 - */ - IWindow* window(); - - /** - * @brief 获取渲染器 - * @return 渲染器指针 - */ - RenderBackend* renderer(); - - /** - * @brief 获取输入 - * @return 输入指针 - */ - IInput* input(); - - /** - * @brief 进入场景 - * @param scene 场景指针 - */ - void enterScene(Ptr scene); - - float deltaTime() const { return deltaTime_; } - float totalTime() const { return totalTime_; } - int fps() const { return currentFps_; } + /** + * @brief 注册模块 + * @tparam T 模块类型 + * @tparam Args 构造函数参数 + * @return 模块指针 + */ + template T *use(Args &&...args) { + return Registry::instance().use(std::forward(args)...); + } + + /** + * @brief 获取模块 + * @tparam T 模块类型 + * @return 模块指针 + */ + template T *get() const { return Registry::instance().get(); } + + /** + * @brief 初始化 + * @return 初始化成功返回 true + */ + bool init(); + + /** + * @brief 初始化(带配置) + * @param config 应用配置 + * @return 初始化成功返回 true + */ + bool init(const AppConfig &config); + + /** + * @brief 关闭 + */ + void shutdown(); + + /** + * @brief 运行主循环 + */ + void run(); + + /** + * @brief 请求退出 + */ + void quit(); + + /** + * @brief 暂停 + */ + void pause(); + + /** + * @brief 恢复 + */ + void resume(); + + bool isPaused() const { return paused_; } + bool isRunning() const { return running_; } + + /** + * @brief 获取窗口 + * @return 窗口指针 + */ + IWindow *window(); + + /** + * @brief 获取渲染器 + * @return 渲染器指针 + */ + RenderBackend *renderer(); + + /** + * @brief 获取输入 + * @return 输入指针 + */ + IInput *input(); + + /** + * @brief 进入场景 + * @param scene 场景指针 + */ + void enterScene(Ptr scene); + + float deltaTime() const { return deltaTime_; } + float totalTime() const { return totalTime_; } + int fps() const { return currentFps_; } private: - Application(); - ~Application(); - - void mainLoop(); - void update(); - void render(); - void registerCoreServices(); - - bool initialized_ = false; - bool running_ = false; - bool paused_ = false; - bool shouldQuit_ = false; - - float deltaTime_ = 0.0f; - float totalTime_ = 0.0f; - double lastFrameTime_ = 0.0; - int frameCount_ = 0; - float fpsTimer_ = 0.0f; - int currentFps_ = 0; - - AppConfig appConfig_; + Application(); + ~Application(); + + void mainLoop(); + void update(); + void render(); + void configureCameraService(); + + bool initialized_ = false; + bool running_ = false; + bool paused_ = false; + bool shouldQuit_ = false; + + float deltaTime_ = 0.0f; + float totalTime_ = 0.0f; + double lastFrameTime_ = 0.0; + int frameCount_ = 0; + float fpsTimer_ = 0.0f; + int currentFps_ = 0; + + AppConfig appConfig_; }; } // namespace extra2d diff --git a/Extra2D/include/extra2d/core/service_locator.h b/Extra2D/include/extra2d/core/service_locator.h index e2735fd..31f6492 100644 --- a/Extra2D/include/extra2d/core/service_locator.h +++ b/Extra2D/include/extra2d/core/service_locator.h @@ -1,27 +1,26 @@ #pragma once +#include #include #include +#include +#include +#include +#include #include #include -#include -#include -#include -#include -#include namespace extra2d { /** * @brief 服务工厂函数类型 */ -template -using ServiceFactory = std::function()>; +template using ServiceFactory = std::function()>; /** * @brief 服务定位器 * 实现依赖注入和服务发现模式,解耦模块间依赖 - * + * * 特性: * - 类型安全的服务注册和获取 * - 支持服务工厂延迟创建 @@ -31,222 +30,273 @@ using ServiceFactory = std::function()>; */ class ServiceLocator { public: - /** - * @brief 获取单例实例 - * @return 服务定位器实例引用 - */ - static ServiceLocator& instance(); + /** + * @brief 获取单例实例 + * @return 服务定位器实例引用 + */ + static ServiceLocator &instance(); - ServiceLocator(const ServiceLocator&) = delete; - ServiceLocator& operator=(const ServiceLocator&) = delete; + ServiceLocator(const ServiceLocator &) = delete; + ServiceLocator &operator=(const ServiceLocator &) = delete; - /** - * @brief 注册服务实例 - * @tparam T 服务接口类型 - * @param service 服务实例 - */ - template - void registerService(SharedPtr service) { - static_assert(std::is_base_of_v, - "T must derive from IService"); - - std::lock_guard lock(mutex_); - auto typeId = std::type_index(typeid(T)); - services_[typeId] = std::static_pointer_cast(service); - orderedServices_.push_back(service); - sortServices(); + /** + * @brief 注册服务实例 + * @tparam T 服务接口类型 + * @param service 服务实例 + */ + template void registerService(SharedPtr service) { + static_assert(std::is_base_of_v, + "T must derive from IService"); + + std::lock_guard lock(mutex_); + auto typeId = std::type_index(typeid(T)); + services_[typeId] = std::static_pointer_cast(service); + orderedServices_.push_back(service); + sortServices(); + } + + /** + * @brief 注册服务工厂 + * @tparam T 服务接口类型 + * @param factory 服务工厂函数 + */ + template void registerFactory(ServiceFactory factory) { + static_assert(std::is_base_of_v, + "T must derive from IService"); + + std::lock_guard lock(mutex_); + auto typeId = std::type_index(typeid(T)); + factories_[typeId] = [factory]() -> SharedPtr { + return std::static_pointer_cast(factory()); + }; + + // 立即创建服务实例并添加到有序列表 + auto service = factories_[typeId](); + services_[typeId] = service; + orderedServices_.push_back(service); + sortServices(); + } + + /** + * @brief 获取服务实例 + * @tparam T 服务接口类型 + * @return 服务实例,不存在返回 nullptr + */ + template SharedPtr getService() const { + static_assert(std::is_base_of_v, + "T must derive from IService"); + + std::lock_guard lock(mutex_); + auto typeId = std::type_index(typeid(T)); + + auto it = services_.find(typeId); + if (it != services_.end()) { + return std::static_pointer_cast(it->second); } - /** - * @brief 注册服务工厂 - * @tparam T 服务接口类型 - * @param factory 服务工厂函数 - */ - template - void registerFactory(ServiceFactory factory) { - static_assert(std::is_base_of_v, - "T must derive from IService"); - - std::lock_guard lock(mutex_); - auto typeId = std::type_index(typeid(T)); - factories_[typeId] = [factory]() -> SharedPtr { - return std::static_pointer_cast(factory()); - }; + auto factoryIt = factories_.find(typeId); + if (factoryIt != factories_.end()) { + auto service = factoryIt->second(); + services_[typeId] = service; + return std::static_pointer_cast(service); } - /** - * @brief 获取服务实例 - * @tparam T 服务接口类型 - * @return 服务实例,不存在返回 nullptr - */ - template - SharedPtr getService() const { - static_assert(std::is_base_of_v, - "T must derive from IService"); - - std::lock_guard lock(mutex_); - auto typeId = std::type_index(typeid(T)); - - auto it = services_.find(typeId); - if (it != services_.end()) { - return std::static_pointer_cast(it->second); - } - - auto factoryIt = factories_.find(typeId); - if (factoryIt != factories_.end()) { - auto service = factoryIt->second(); - services_[typeId] = service; - return std::static_pointer_cast(service); - } - - return nullptr; + return nullptr; + } + + /** + * @brief 尝试获取服务实例(不创建) + * @tparam T 服务接口类型 + * @return 服务实例,不存在返回 nullptr + */ + template SharedPtr tryGetService() const { + static_assert(std::is_base_of_v, + "T must derive from IService"); + + std::lock_guard lock(mutex_); + auto typeId = std::type_index(typeid(T)); + auto it = services_.find(typeId); + if (it != services_.end()) { + return std::static_pointer_cast(it->second); + } + return nullptr; + } + + /** + * @brief 检查服务是否已注册 + * @tparam T 服务接口类型 + * @return 已注册返回 true + */ + template bool hasService() const { + std::lock_guard lock(mutex_); + auto typeId = std::type_index(typeid(T)); + return services_.find(typeId) != services_.end() || + factories_.find(typeId) != factories_.end(); + } + + /** + * @brief 注销服务 + * @tparam T 服务接口类型 + */ + template void unregisterService() { + std::lock_guard lock(mutex_); + auto typeId = std::type_index(typeid(T)); + + auto it = services_.find(typeId); + if (it != services_.end()) { + auto service = it->second; + services_.erase(it); + + auto orderIt = + std::find(orderedServices_.begin(), orderedServices_.end(), service); + if (orderIt != orderedServices_.end()) { + orderedServices_.erase(orderIt); + } } - /** - * @brief 尝试获取服务实例(不创建) - * @tparam T 服务接口类型 - * @return 服务实例,不存在返回 nullptr - */ - template - SharedPtr tryGetService() const { - static_assert(std::is_base_of_v, - "T must derive from IService"); - - std::lock_guard lock(mutex_); - auto typeId = std::type_index(typeid(T)); - auto it = services_.find(typeId); - if (it != services_.end()) { - return std::static_pointer_cast(it->second); - } - return nullptr; - } + factories_.erase(typeId); + } - /** - * @brief 检查服务是否已注册 - * @tparam T 服务接口类型 - * @return 已注册返回 true - */ - template - bool hasService() const { - std::lock_guard lock(mutex_); - auto typeId = std::type_index(typeid(T)); - return services_.find(typeId) != services_.end() || - factories_.find(typeId) != factories_.end(); - } + /** + * @brief 初始化所有已注册的服务 + * @return 所有服务初始化成功返回 true + */ + bool initializeAll(); - /** - * @brief 注销服务 - * @tparam T 服务接口类型 - */ - template - void unregisterService() { - std::lock_guard lock(mutex_); - auto typeId = std::type_index(typeid(T)); - - auto it = services_.find(typeId); - if (it != services_.end()) { - auto service = it->second; - services_.erase(it); - - auto orderIt = std::find(orderedServices_.begin(), - orderedServices_.end(), service); - if (orderIt != orderedServices_.end()) { - orderedServices_.erase(orderIt); - } - } - - factories_.erase(typeId); - } + /** + * @brief 关闭所有服务 + */ + void shutdownAll(); - /** - * @brief 初始化所有已注册的服务 - * @return 所有服务初始化成功返回 true - */ - bool initializeAll(); + /** + * @brief 更新所有服务 + * @param deltaTime 帧间隔时间 + */ + void updateAll(float deltaTime); - /** - * @brief 关闭所有服务 - */ - void shutdownAll(); + /** + * @brief 暂停所有服务 + */ + void pauseAll(); - /** - * @brief 更新所有服务 - * @param deltaTime 帧间隔时间 - */ - void updateAll(float deltaTime); + /** + * @brief 恢复所有服务 + */ + void resumeAll(); - /** - * @brief 暂停所有服务 - */ - void pauseAll(); + /** + * @brief 获取所有服务(按优先级排序) + * @return 服务列表 + */ + std::vector> getAllServices() const; - /** - * @brief 恢复所有服务 - */ - void resumeAll(); + /** + * @brief 清空所有服务和工厂 + */ + void clear(); - /** - * @brief 获取所有服务(按优先级排序) - * @return 服务列表 - */ - std::vector> getAllServices() const; - - /** - * @brief 清空所有服务和工厂 - */ - void clear(); - - /** - * @brief 获取已注册服务数量 - * @return 服务数量 - */ - size_t size() const { return services_.size(); } + /** + * @brief 获取已注册服务数量 + * @return 服务数量 + */ + size_t size() const { return services_.size(); } private: - ServiceLocator() = default; - ~ServiceLocator() = default; + ServiceLocator() = default; + ~ServiceLocator() = default; - /** - * @brief 按优先级排序服务 - */ - void sortServices(); + /** + * @brief 按优先级排序服务 + */ + void sortServices(); - mutable std::unordered_map> services_; - std::unordered_map()>> factories_; - std::vector> orderedServices_; - mutable std::mutex mutex_; + mutable std::unordered_map> services_; + std::unordered_map()>> + factories_; + std::vector> orderedServices_; + mutable std::mutex mutex_; }; /** * @brief 服务注册器 * 用于静态注册服务 */ -template -class ServiceRegistrar { +template class ServiceRegistrar { public: - explicit ServiceRegistrar(ServiceFactory factory = nullptr) { - if (factory) { - ServiceLocator::instance().registerFactory(factory); - } else { - ServiceLocator::instance().registerFactory( - []() -> SharedPtr { - return makeShared(); - } - ); - } + explicit ServiceRegistrar(ServiceFactory factory = nullptr) { + if (factory) { + ServiceLocator::instance().registerFactory(factory); + } else { + ServiceLocator::instance().registerFactory( + []() -> SharedPtr { + return makeShared(); + }); } + } }; -} +/** + * @brief 服务注册元数据模板 + * 使用模板元编程实现编译期服务注册 + * 通过静态成员变量的初始化触发注册 + */ +template struct ServiceAutoReg { + /** + * @brief 注册标记,访问此变量时触发服务注册 + */ + static const bool registered; -#define E2D_REGISTER_SERVICE(Interface, Implementation) \ - namespace { \ - static ::extra2d::ServiceRegistrar \ - E2D_CONCAT(service_registrar_, __LINE__); \ - } + /** + * @brief 执行实际的服务注册 + * @return true 表示注册成功 + */ + static bool doRegister() { + ::extra2d::ServiceLocator::instance().registerFactory( + []() -> ::extra2d::SharedPtr { + return ::extra2d::makeShared(); + }); + return true; + } +}; -#define E2D_REGISTER_SERVICE_FACTORY(Interface, Factory) \ - namespace { \ - static ::extra2d::ServiceRegistrar \ - E2D_CONCAT(service_factory_registrar_, __LINE__)(Factory); \ +// 静态成员定义,在此处触发注册 +template +const bool ServiceAutoReg::registered = + ServiceAutoReg::doRegister(); + +/** + * @brief 服务注册元数据(带自定义工厂) + */ +template struct ServiceAutoRegFactory { + template struct Impl { + static const bool registered; + + static bool doRegister(Factory factory) { + ::extra2d::ServiceLocator::instance().registerFactory(factory); + return true; } + }; +}; + +template +template +const bool ServiceAutoRegFactory::Impl::registered = + ServiceAutoRegFactory::Impl::doRegister(Factory{}); + +/** + * @brief 自动注册服务宏(元数据驱动) + * 在服务实现类中使用,通过模板元编程实现自动注册 + * 比静态对象更可靠,不易被编译器优化 + */ +#define E2D_AUTO_REGISTER_SERVICE(Interface, Implementation) \ + static inline const bool E2D_CONCAT(_service_reg_, __LINE__) = \ + ServiceAutoReg::registered + +/** + * @brief 带自定义工厂的自动注册服务宏(元数据驱动) + */ +#define E2D_AUTO_REGISTER_SERVICE_FACTORY(Interface, Factory) \ + static inline const bool E2D_CONCAT(_service_factory_reg_, __LINE__) = \ + ServiceAutoRegFactory::Impl::registered + +} // namespace extra2d diff --git a/Extra2D/include/extra2d/services/camera_service.h b/Extra2D/include/extra2d/services/camera_service.h index 948a187..f2acf89 100644 --- a/Extra2D/include/extra2d/services/camera_service.h +++ b/Extra2D/include/extra2d/services/camera_service.h @@ -1,6 +1,7 @@ #pragma once #include +#include #include #include @@ -106,6 +107,9 @@ public: private: Camera camera_; ViewportAdapter viewportAdapter_; + + // 服务注册元数据 + E2D_AUTO_REGISTER_SERVICE(ICameraService, CameraService); }; } diff --git a/Extra2D/include/extra2d/services/event_service.h b/Extra2D/include/extra2d/services/event_service.h index 7b91819..7235aff 100644 --- a/Extra2D/include/extra2d/services/event_service.h +++ b/Extra2D/include/extra2d/services/event_service.h @@ -1,6 +1,7 @@ #pragma once #include +#include #include #include @@ -68,6 +69,9 @@ public: private: EventQueue queue_; EventDispatcher dispatcher_; + + // 服务注册元数据 + E2D_AUTO_REGISTER_SERVICE(IEventService, EventService); }; } diff --git a/Extra2D/include/extra2d/services/logger_service.h b/Extra2D/include/extra2d/services/logger_service.h index 12a1245..b0edcaa 100644 --- a/Extra2D/include/extra2d/services/logger_service.h +++ b/Extra2D/include/extra2d/services/logger_service.h @@ -1,6 +1,7 @@ #pragma once #include +#include #include #include #include @@ -120,10 +121,13 @@ public: private: void output(LogLevel level, const char* msg); const char* getLevelString(LogLevel level); - + LogLevel level_; class Impl; UniquePtr impl_; + + // 服务注册元数据 + E2D_AUTO_REGISTER_SERVICE(ILogger, ConsoleLogger); }; } // namespace extra2d diff --git a/Extra2D/include/extra2d/services/scene_service.h b/Extra2D/include/extra2d/services/scene_service.h index 742893a..0f30608 100644 --- a/Extra2D/include/extra2d/services/scene_service.h +++ b/Extra2D/include/extra2d/services/scene_service.h @@ -1,6 +1,7 @@ #pragma once #include +#include #include namespace extra2d { @@ -86,6 +87,9 @@ public: private: SceneManager manager_; + + // 服务注册元数据 + E2D_AUTO_REGISTER_SERVICE(ISceneService, SceneService); }; } diff --git a/Extra2D/include/extra2d/services/timer_service.h b/Extra2D/include/extra2d/services/timer_service.h index 65a9762..bf2d65d 100644 --- a/Extra2D/include/extra2d/services/timer_service.h +++ b/Extra2D/include/extra2d/services/timer_service.h @@ -1,6 +1,7 @@ #pragma once #include +#include #include namespace extra2d { @@ -48,6 +49,9 @@ public: private: TimerManager manager_; + + // 服务注册元数据 + E2D_AUTO_REGISTER_SERVICE(ITimerService, TimerService); }; } diff --git a/Extra2D/src/app/application.cpp b/Extra2D/src/app/application.cpp index 784c67c..3b767d5 100644 --- a/Extra2D/src/app/application.cpp +++ b/Extra2D/src/app/application.cpp @@ -14,8 +14,6 @@ #include -#include - namespace extra2d { static double getTimeSeconds() { @@ -57,66 +55,49 @@ bool Application::init(const AppConfig &config) { appConfig_ = config; - // 首先注册日志服务(模块初始化可能需要它) - auto &locator = ServiceLocator::instance(); - if (!locator.hasService()) { - auto logger = makeShared(); - locator.registerService(std::static_pointer_cast(logger)); - } - // 初始化所有模块(拓扑排序) + // 服务通过 E2D_AUTO_REGISTER_SERVICE 宏自动注册 if (!Registry::instance().init()) { return false; } - // 模块初始化完成后,注册其他核心服务 - registerCoreServices(); + // 配置相机服务(需要窗口信息) + configureCameraService(); + + // 初始化所有服务 + ServiceLocator::instance().initializeAll(); initialized_ = true; running_ = true; return true; } -void Application::registerCoreServices() { - auto &locator = ServiceLocator::instance(); - - if (!locator.hasService()) { - auto service = makeShared(); - locator.registerService(std::static_pointer_cast(service)); - } - - if (!locator.hasService()) { - auto service = makeShared(); - locator.registerService(std::static_pointer_cast(service)); - } - - if (!locator.hasService()) { - auto service = makeShared(); - locator.registerService(std::static_pointer_cast(service)); - } - +void Application::configureCameraService() { auto *winMod = get(); - if (winMod && winMod->win() && !locator.hasService()) { - auto cameraService = makeShared(); - auto *win = winMod->win(); - cameraService->setViewport(0, static_cast(win->width()), - static_cast(win->height()), 0); - ViewportConfig vpConfig; - vpConfig.logicWidth = static_cast(win->width()); - vpConfig.logicHeight = static_cast(win->height()); - vpConfig.mode = ViewportMode::AspectRatio; - cameraService->setViewportConfig(vpConfig); - cameraService->updateViewport(win->width(), win->height()); - locator.registerService( - std::static_pointer_cast(cameraService)); - - win->onResize([cameraService](int width, int height) { - cameraService->updateViewport(width, height); - cameraService->applyViewportAdapter(); - }); + if (!winMod || !winMod->win()) { + return; } - locator.initializeAll(); + auto cameraService = ServiceLocator::instance().getService(); + if (!cameraService) { + return; + } + + auto *win = winMod->win(); + cameraService->setViewport(0, static_cast(win->width()), + static_cast(win->height()), 0); + + ViewportConfig vpConfig; + vpConfig.logicWidth = static_cast(win->width()); + vpConfig.logicHeight = static_cast(win->height()); + vpConfig.mode = ViewportMode::AspectRatio; + cameraService->setViewportConfig(vpConfig); + cameraService->updateViewport(win->width(), win->height()); + + win->onResize([cameraService](int width, int height) { + cameraService->updateViewport(width, height); + cameraService->applyViewportAdapter(); + }); } void Application::shutdown() { @@ -125,6 +106,7 @@ void Application::shutdown() { VRAMMgr::get().printStats(); + ServiceLocator::instance().shutdownAll(); ServiceLocator::instance().clear(); Registry::instance().shutdown(); Registry::instance().clear(); diff --git a/Extra2D/src/services/camera_service.cpp b/Extra2D/src/services/camera_service.cpp index 0748f03..f611289 100644 --- a/Extra2D/src/services/camera_service.cpp +++ b/Extra2D/src/services/camera_service.cpp @@ -3,126 +3,97 @@ namespace extra2d { CameraService::CameraService() { - info_.name = "CameraService"; - info_.priority = ServicePriority::Camera; - info_.enabled = true; + info_.name = "CameraService"; + info_.priority = ServicePriority::Camera; + info_.enabled = true; } CameraService::CameraService(float left, float right, float bottom, float top) : camera_(left, right, bottom, top) { - info_.name = "CameraService"; - info_.priority = ServicePriority::Camera; - info_.enabled = true; + info_.name = "CameraService"; + info_.priority = ServicePriority::Camera; + info_.enabled = true; } -ServiceInfo CameraService::getServiceInfo() const { - return info_; -} +ServiceInfo CameraService::getServiceInfo() const { return info_; } bool CameraService::initialize() { - camera_.setViewportAdapter(&viewportAdapter_); - setState(ServiceState::Running); - return true; + camera_.setViewportAdapter(&viewportAdapter_); + setState(ServiceState::Running); + return true; } -void CameraService::shutdown() { - setState(ServiceState::Stopped); +void CameraService::shutdown() { setState(ServiceState::Stopped); } + +void CameraService::setPosition(const Vec2 &position) { + camera_.setPos(position); } -void CameraService::setPosition(const Vec2& position) { - camera_.setPos(position); +void CameraService::setPosition(float x, float y) { camera_.setPos(x, y); } + +Vec2 CameraService::getPosition() const { return camera_.getPosition(); } + +void CameraService::setRotation(float degrees) { camera_.setRotation(degrees); } + +float CameraService::getRotation() const { return camera_.getRotation(); } + +void CameraService::setZoom(float zoom) { camera_.setZoom(zoom); } + +float CameraService::getZoom() const { return camera_.getZoom(); } + +void CameraService::setViewport(float left, float right, float bottom, + float top) { + camera_.setViewport(left, right, bottom, top); } -void CameraService::setPosition(float x, float y) { - camera_.setPos(x, y); -} - -Vec2 CameraService::getPosition() const { - return camera_.getPosition(); -} - -void CameraService::setRotation(float degrees) { - camera_.setRotation(degrees); -} - -float CameraService::getRotation() const { - return camera_.getRotation(); -} - -void CameraService::setZoom(float zoom) { - camera_.setZoom(zoom); -} - -float CameraService::getZoom() const { - return camera_.getZoom(); -} - -void CameraService::setViewport(float left, float right, float bottom, float top) { - camera_.setViewport(left, right, bottom, top); -} - -Rect CameraService::getViewport() const { - return camera_.getViewport(); -} +Rect CameraService::getViewport() const { return camera_.getViewport(); } glm::mat4 CameraService::getViewMatrix() const { - return camera_.getViewMatrix(); + return camera_.getViewMatrix(); } glm::mat4 CameraService::getProjectionMatrix() const { - return camera_.getProjectionMatrix(); + return camera_.getProjectionMatrix(); } glm::mat4 CameraService::getViewProjectionMatrix() const { - return camera_.getViewProjectionMatrix(); + return camera_.getViewProjectionMatrix(); } -Vec2 CameraService::screenToWorld(const Vec2& screenPos) const { - return camera_.screenToWorld(screenPos); +Vec2 CameraService::screenToWorld(const Vec2 &screenPos) const { + return camera_.screenToWorld(screenPos); } -Vec2 CameraService::worldToScreen(const Vec2& worldPos) const { - return camera_.worldToScreen(worldPos); +Vec2 CameraService::worldToScreen(const Vec2 &worldPos) const { + return camera_.worldToScreen(worldPos); } -void CameraService::move(const Vec2& offset) { - camera_.move(offset); +void CameraService::move(const Vec2 &offset) { camera_.move(offset); } + +void CameraService::move(float x, float y) { camera_.move(x, y); } + +void CameraService::setBounds(const Rect &bounds) { camera_.setBounds(bounds); } + +void CameraService::clearBounds() { camera_.clearBounds(); } + +void CameraService::lookAt(const Vec2 &target) { camera_.lookAt(target); } + +void CameraService::setViewportConfig(const ViewportConfig &config) { + viewportAdapter_.setConfig(config); } -void CameraService::move(float x, float y) { - camera_.move(x, y); -} - -void CameraService::setBounds(const Rect& bounds) { - camera_.setBounds(bounds); -} - -void CameraService::clearBounds() { - camera_.clearBounds(); -} - -void CameraService::lookAt(const Vec2& target) { - camera_.lookAt(target); -} - -void CameraService::setViewportConfig(const ViewportConfig& config) { - viewportAdapter_.setConfig(config); -} - -const ViewportConfig& CameraService::getViewportConfig() const { - return viewportAdapter_.getConfig(); +const ViewportConfig &CameraService::getViewportConfig() const { + return viewportAdapter_.getConfig(); } void CameraService::updateViewport(int screenWidth, int screenHeight) { - viewportAdapter_.update(screenWidth, screenHeight); + viewportAdapter_.update(screenWidth, screenHeight); } -const ViewportResult& CameraService::getViewportResult() const { - return viewportAdapter_.getResult(); +const ViewportResult &CameraService::getViewportResult() const { + return viewportAdapter_.getResult(); } -void CameraService::applyViewportAdapter() { - camera_.applyViewportAdapter(); -} +void CameraService::applyViewportAdapter() { camera_.applyViewportAdapter(); } -} +} // namespace extra2d diff --git a/Extra2D/src/services/event_service.cpp b/Extra2D/src/services/event_service.cpp index 9551b75..8212dd1 100644 --- a/Extra2D/src/services/event_service.cpp +++ b/Extra2D/src/services/event_service.cpp @@ -3,78 +3,63 @@ namespace extra2d { EventService::EventService() { - info_.name = "EventService"; - info_.priority = ServicePriority::Event; - info_.enabled = true; + info_.name = "EventService"; + info_.priority = ServicePriority::Event; + info_.enabled = true; } -ServiceInfo EventService::getServiceInfo() const { - return info_; -} +ServiceInfo EventService::getServiceInfo() const { return info_; } bool EventService::initialize() { - setState(ServiceState::Running); - return true; + setState(ServiceState::Running); + return true; } void EventService::shutdown() { - queue_.clear(); - dispatcher_.removeAllListeners(); - setState(ServiceState::Stopped); + queue_.clear(); + dispatcher_.removeAllListeners(); + setState(ServiceState::Stopped); } void EventService::update(float deltaTime) { - if (getState() == ServiceState::Running) { - processQueue(); - } + if (getState() == ServiceState::Running) { + processQueue(); + } } -void EventService::pushEvent(const Event& event) { - queue_.push(event); -} +void EventService::pushEvent(const Event &event) { queue_.push(event); } -void EventService::pushEvent(Event&& event) { - queue_.push(std::move(event)); -} +void EventService::pushEvent(Event &&event) { queue_.push(std::move(event)); } -bool EventService::pollEvent(Event& event) { - return queue_.poll(event); -} +bool EventService::pollEvent(Event &event) { return queue_.poll(event); } -ListenerId EventService::addListener(EventType type, EventDispatcher::EventCallback callback) { - return dispatcher_.addListener(type, callback); +ListenerId EventService::addListener(EventType type, + EventDispatcher::EventCallback callback) { + return dispatcher_.addListener(type, callback); } void EventService::removeListener(ListenerId id) { - dispatcher_.removeListener(id); + dispatcher_.removeListener(id); } void EventService::removeAllListeners(EventType type) { - dispatcher_.removeAllListeners(type); + dispatcher_.removeAllListeners(type); } -void EventService::removeAllListeners() { - dispatcher_.removeAllListeners(); -} +void EventService::removeAllListeners() { dispatcher_.removeAllListeners(); } -void EventService::dispatch(Event& event) { - dispatcher_.dispatch(event); -} +void EventService::dispatch(Event &event) { dispatcher_.dispatch(event); } -void EventService::processQueue() { - dispatcher_.processQueue(queue_); -} +void EventService::processQueue() { dispatcher_.processQueue(queue_); } size_t EventService::getListenerCount(EventType type) const { - return dispatcher_.getListenerCount(type); + return dispatcher_.getListenerCount(type); } size_t EventService::getTotalListenerCount() const { - return dispatcher_.getTotalListenerCount(); + return dispatcher_.getTotalListenerCount(); } -size_t EventService::getQueueSize() const { - return queue_.size(); -} +size_t EventService::getQueueSize() const { return queue_.size(); } -} +} // namespace extra2d diff --git a/Extra2D/src/services/logger_service.cpp b/Extra2D/src/services/logger_service.cpp index 8305dd7..032364c 100644 --- a/Extra2D/src/services/logger_service.cpp +++ b/Extra2D/src/services/logger_service.cpp @@ -1,10 +1,7 @@ -#include -#include -#include -#include #include -#include -#include +#include +#include +#include #include namespace extra2d { @@ -12,160 +9,183 @@ namespace extra2d { // ConsoleLogger 实现 class ConsoleLogger::Impl { public: - std::mutex mutex_; + std::mutex mutex_; }; -ConsoleLogger::ConsoleLogger() : level_(LogLevel::Info), impl_(std::make_unique()) { - info_.name = "ConsoleLogger"; - info_.priority = ServicePriority::Core; +ConsoleLogger::ConsoleLogger() + : level_(LogLevel::Info), impl_(std::make_unique()) { + info_.name = "ConsoleLogger"; + info_.priority = ServicePriority::Core; } ConsoleLogger::~ConsoleLogger() = default; bool ConsoleLogger::initialize() { - setState(ServiceState::Running); - return true; + setState(ServiceState::Running); + return true; } -void ConsoleLogger::shutdown() { - setState(ServiceState::Stopped); -} +void ConsoleLogger::shutdown() { setState(ServiceState::Stopped); } -void ConsoleLogger::setLevel(LogLevel level) { - level_ = level; -} +void ConsoleLogger::setLevel(LogLevel level) { level_ = level; } -LogLevel ConsoleLogger::getLevel() const { - return level_; -} +LogLevel ConsoleLogger::getLevel() const { return level_; } bool ConsoleLogger::isEnabled(LogLevel level) const { - return static_cast(level) >= static_cast(level_); + return static_cast(level) >= static_cast(level_); } -void ConsoleLogger::log(LogLevel level, const char* fmt, ...) { - if (!isEnabled(level)) return; - - char buffer[1024]; - va_list args; - va_start(args, fmt); - vsnprintf(buffer, sizeof(buffer), fmt, args); - va_end(args); - - output(level, buffer); +void ConsoleLogger::log(LogLevel level, const char *fmt, ...) { + if (!isEnabled(level)) + return; + + char buffer[1024]; + va_list args; + va_start(args, fmt); + vsnprintf(buffer, sizeof(buffer), fmt, args); + va_end(args); + + output(level, buffer); } -void ConsoleLogger::log(LogLevel level, const std::string& msg) { - if (!isEnabled(level)) return; - output(level, msg.c_str()); +void ConsoleLogger::log(LogLevel level, const std::string &msg) { + if (!isEnabled(level)) + return; + output(level, msg.c_str()); } -void ConsoleLogger::trace(const char* fmt, ...) { - if (!isEnabled(LogLevel::Trace)) return; - char buffer[1024]; - va_list args; - va_start(args, fmt); - vsnprintf(buffer, sizeof(buffer), fmt, args); - va_end(args); - output(LogLevel::Trace, buffer); +void ConsoleLogger::trace(const char *fmt, ...) { + if (!isEnabled(LogLevel::Trace)) + return; + char buffer[1024]; + va_list args; + va_start(args, fmt); + vsnprintf(buffer, sizeof(buffer), fmt, args); + va_end(args); + output(LogLevel::Trace, buffer); } -void ConsoleLogger::debug(const char* fmt, ...) { - if (!isEnabled(LogLevel::Debug)) return; - char buffer[1024]; - va_list args; - va_start(args, fmt); - vsnprintf(buffer, sizeof(buffer), fmt, args); - va_end(args); - output(LogLevel::Debug, buffer); +void ConsoleLogger::debug(const char *fmt, ...) { + if (!isEnabled(LogLevel::Debug)) + return; + char buffer[1024]; + va_list args; + va_start(args, fmt); + vsnprintf(buffer, sizeof(buffer), fmt, args); + va_end(args); + output(LogLevel::Debug, buffer); } -void ConsoleLogger::info(const char* fmt, ...) { - if (!isEnabled(LogLevel::Info)) return; - char buffer[1024]; - va_list args; - va_start(args, fmt); - vsnprintf(buffer, sizeof(buffer), fmt, args); - va_end(args); - output(LogLevel::Info, buffer); +void ConsoleLogger::info(const char *fmt, ...) { + if (!isEnabled(LogLevel::Info)) + return; + char buffer[1024]; + va_list args; + va_start(args, fmt); + vsnprintf(buffer, sizeof(buffer), fmt, args); + va_end(args); + output(LogLevel::Info, buffer); } -void ConsoleLogger::warn(const char* fmt, ...) { - if (!isEnabled(LogLevel::Warn)) return; - char buffer[1024]; - va_list args; - va_start(args, fmt); - vsnprintf(buffer, sizeof(buffer), fmt, args); - va_end(args); - output(LogLevel::Warn, buffer); +void ConsoleLogger::warn(const char *fmt, ...) { + if (!isEnabled(LogLevel::Warn)) + return; + char buffer[1024]; + va_list args; + va_start(args, fmt); + vsnprintf(buffer, sizeof(buffer), fmt, args); + va_end(args); + output(LogLevel::Warn, buffer); } -void ConsoleLogger::error(const char* fmt, ...) { - if (!isEnabled(LogLevel::Error)) return; - char buffer[1024]; - va_list args; - va_start(args, fmt); - vsnprintf(buffer, sizeof(buffer), fmt, args); - va_end(args); - output(LogLevel::Error, buffer); +void ConsoleLogger::error(const char *fmt, ...) { + if (!isEnabled(LogLevel::Error)) + return; + char buffer[1024]; + va_list args; + va_start(args, fmt); + vsnprintf(buffer, sizeof(buffer), fmt, args); + va_end(args); + output(LogLevel::Error, buffer); } -void ConsoleLogger::fatal(const char* fmt, ...) { - if (!isEnabled(LogLevel::Fatal)) return; - char buffer[1024]; - va_list args; - va_start(args, fmt); - vsnprintf(buffer, sizeof(buffer), fmt, args); - va_end(args); - output(LogLevel::Fatal, buffer); +void ConsoleLogger::fatal(const char *fmt, ...) { + if (!isEnabled(LogLevel::Fatal)) + return; + char buffer[1024]; + va_list args; + va_start(args, fmt); + vsnprintf(buffer, sizeof(buffer), fmt, args); + va_end(args); + output(LogLevel::Fatal, buffer); } -void ConsoleLogger::output(LogLevel level, const char* msg) { - std::lock_guard lock(impl_->mutex_); - - auto now = std::chrono::system_clock::now(); - auto time = std::chrono::system_clock::to_time_t(now); - auto ms = std::chrono::duration_cast( - now.time_since_epoch()) % 1000; - - std::tm tm; +void ConsoleLogger::output(LogLevel level, const char *msg) { + std::lock_guard lock(impl_->mutex_); + + auto now = std::chrono::system_clock::now(); + auto time = std::chrono::system_clock::to_time_t(now); + auto ms = std::chrono::duration_cast( + now.time_since_epoch()) % + 1000; + + std::tm tm; #ifdef _WIN32 - localtime_s(&tm, &time); + localtime_s(&tm, &time); #else - localtime_r(&time, &tm); + localtime_r(&time, &tm); #endif - - const char* levelStr = getLevelString(level); - - // 颜色代码 - const char* color = ""; - const char* reset = "\033[0m"; - - switch (level) { - case LogLevel::Trace: color = "\033[90m"; break; - case LogLevel::Debug: color = "\033[36m"; break; - case LogLevel::Info: color = "\033[32m"; break; - case LogLevel::Warn: color = "\033[33m"; break; - case LogLevel::Error: color = "\033[31m"; break; - case LogLevel::Fatal: color = "\033[35m"; break; - default: break; - } - - printf("%s[%02d:%02d:%02d.%03d] [%s] %s%s\n", - color, tm.tm_hour, tm.tm_min, tm.tm_sec, (int)ms.count(), - levelStr, msg, reset); + + const char *levelStr = getLevelString(level); + + // 颜色代码 + const char *color = ""; + const char *reset = "\033[0m"; + + switch (level) { + case LogLevel::Trace: + color = "\033[90m"; + break; + case LogLevel::Debug: + color = "\033[36m"; + break; + case LogLevel::Info: + color = "\033[32m"; + break; + case LogLevel::Warn: + color = "\033[33m"; + break; + case LogLevel::Error: + color = "\033[31m"; + break; + case LogLevel::Fatal: + color = "\033[35m"; + break; + default: + break; + } + + printf("%s[%02d:%02d:%02d.%03d] [%s] %s%s\n", color, tm.tm_hour, tm.tm_min, + tm.tm_sec, (int)ms.count(), levelStr, msg, reset); } -const char* ConsoleLogger::getLevelString(LogLevel level) { - switch (level) { - case LogLevel::Trace: return "TRACE"; - case LogLevel::Debug: return "DEBUG"; - case LogLevel::Info: return "INFO"; - case LogLevel::Warn: return "WARN"; - case LogLevel::Error: return "ERROR"; - case LogLevel::Fatal: return "FATAL"; - default: return "UNKNOWN"; - } +const char *ConsoleLogger::getLevelString(LogLevel level) { + switch (level) { + case LogLevel::Trace: + return "TRACE"; + case LogLevel::Debug: + return "DEBUG"; + case LogLevel::Info: + return "INFO"; + case LogLevel::Warn: + return "WARN"; + case LogLevel::Error: + return "ERROR"; + case LogLevel::Fatal: + return "FATAL"; + default: + return "UNKNOWN"; + } } } // namespace extra2d diff --git a/Extra2D/src/services/scene_service.cpp b/Extra2D/src/services/scene_service.cpp index 2ef197a..854f1bd 100644 --- a/Extra2D/src/services/scene_service.cpp +++ b/Extra2D/src/services/scene_service.cpp @@ -3,109 +3,92 @@ namespace extra2d { SceneService::SceneService() { - info_.name = "SceneService"; - info_.priority = ServicePriority::Scene; - info_.enabled = true; + info_.name = "SceneService"; + info_.priority = ServicePriority::Scene; + info_.enabled = true; } -ServiceInfo SceneService::getServiceInfo() const { - return info_; -} +ServiceInfo SceneService::getServiceInfo() const { return info_; } bool SceneService::initialize() { - setState(ServiceState::Running); - return true; + setState(ServiceState::Running); + return true; } void SceneService::shutdown() { - manager_.end(); - setState(ServiceState::Stopped); + manager_.end(); + setState(ServiceState::Stopped); } void SceneService::update(float deltaTime) { - if (getState() == ServiceState::Running) { - manager_.update(deltaTime); - } + if (getState() == ServiceState::Running) { + manager_.update(deltaTime); + } } void SceneService::runWithScene(Ptr scene) { - manager_.runWithScene(scene); + manager_.runWithScene(scene); } void SceneService::replaceScene(Ptr scene) { - manager_.replaceScene(scene); + manager_.replaceScene(scene); } -void SceneService::pushScene(Ptr scene) { - manager_.pushScene(scene); -} +void SceneService::pushScene(Ptr scene) { manager_.pushScene(scene); } -void SceneService::popScene() { - manager_.popScene(); -} +void SceneService::popScene() { manager_.popScene(); } -void SceneService::popToRootScene() { - manager_.popToRootScene(); -} +void SceneService::popToRootScene() { manager_.popToRootScene(); } -void SceneService::popToScene(const std::string& name) { - manager_.popToScene(name); +void SceneService::popToScene(const std::string &name) { + manager_.popToScene(name); } Ptr SceneService::getCurrentScene() const { - return manager_.getCurrentScene(); + return manager_.getCurrentScene(); } Ptr SceneService::getPreviousScene() const { - return manager_.getPreviousScene(); + return manager_.getPreviousScene(); } Ptr SceneService::getRootScene() const { - return manager_.getRootScene(); + return manager_.getRootScene(); } -Ptr SceneService::getSceneByName(const std::string& name) const { - return manager_.getSceneByName(name); +Ptr SceneService::getSceneByName(const std::string &name) const { + return manager_.getSceneByName(name); } -size_t SceneService::getSceneCount() const { - return manager_.getSceneCount(); +size_t SceneService::getSceneCount() const { return manager_.getSceneCount(); } + +bool SceneService::isEmpty() const { return manager_.isEmpty(); } + +bool SceneService::hasScene(const std::string &name) const { + return manager_.hasScene(name); } -bool SceneService::isEmpty() const { - return manager_.isEmpty(); +void SceneService::render(RenderBackend &renderer) { + manager_.render(renderer); } -bool SceneService::hasScene(const std::string& name) const { - return manager_.hasScene(name); -} - -void SceneService::render(RenderBackend& renderer) { - manager_.render(renderer); -} - -void SceneService::collectRenderCommands(std::vector& commands) { - manager_.collectRenderCommands(commands); +void SceneService::collectRenderCommands(std::vector &commands) { + manager_.collectRenderCommands(commands); } bool SceneService::isTransitioning() const { - return manager_.isTransitioning(); + return manager_.isTransitioning(); } -void SceneService::setTransitionCallback(SceneManager::TransitionCallback callback) { - manager_.setTransitionCallback(callback); +void SceneService::setTransitionCallback( + SceneManager::TransitionCallback callback) { + manager_.setTransitionCallback(callback); } -void SceneService::end() { - manager_.end(); -} +void SceneService::end() { manager_.end(); } -void SceneService::purgeCachedScenes() { - manager_.purgeCachedScenes(); -} +void SceneService::purgeCachedScenes() { manager_.purgeCachedScenes(); } -void SceneService::enterScene(Ptr scene) { - manager_.enterScene(scene); -} +void SceneService::enterScene(Ptr scene) { manager_.enterScene(scene); } -} +} // namespace extra2d diff --git a/Extra2D/src/services/timer_service.cpp b/Extra2D/src/services/timer_service.cpp index 8674c3f..b3fe050 100644 --- a/Extra2D/src/services/timer_service.cpp +++ b/Extra2D/src/services/timer_service.cpp @@ -3,57 +3,50 @@ namespace extra2d { TimerService::TimerService() { - info_.name = "TimerService"; - info_.priority = ServicePriority::Timer; - info_.enabled = true; + info_.name = "TimerService"; + info_.priority = ServicePriority::Timer; + info_.enabled = true; } -ServiceInfo TimerService::getServiceInfo() const { - return info_; -} +ServiceInfo TimerService::getServiceInfo() const { return info_; } bool TimerService::initialize() { - setState(ServiceState::Running); - return true; + setState(ServiceState::Running); + return true; } void TimerService::shutdown() { - manager_.clear(); - setState(ServiceState::Stopped); + manager_.clear(); + setState(ServiceState::Stopped); } void TimerService::update(float deltaTime) { - if (getState() == ServiceState::Running) { - manager_.update(deltaTime); - } + if (getState() == ServiceState::Running) { + manager_.update(deltaTime); + } } uint32 TimerService::addTimer(float delay, Timer::Callback callback) { - return manager_.addTimer(delay, callback); + return manager_.addTimer(delay, callback); } -uint32 TimerService::addRepeatingTimer(float interval, Timer::Callback callback) { - return manager_.addRepeatingTimer(interval, callback); +uint32 TimerService::addRepeatingTimer(float interval, + Timer::Callback callback) { + return manager_.addRepeatingTimer(interval, callback); } void TimerService::cancelTimer(uint32 timerId) { - manager_.cancelTimer(timerId); + manager_.cancelTimer(timerId); } -void TimerService::pauseTimer(uint32 timerId) { - manager_.pauseTimer(timerId); -} +void TimerService::pauseTimer(uint32 timerId) { manager_.pauseTimer(timerId); } void TimerService::resumeTimer(uint32 timerId) { - manager_.resumeTimer(timerId); + manager_.resumeTimer(timerId); } -void TimerService::clear() { - manager_.clear(); -} +void TimerService::clear() { manager_.clear(); } -size_t TimerService::getTimerCount() const { - return manager_.getTimerCount(); -} +size_t TimerService::getTimerCount() const { return manager_.getTimerCount(); } -} +} // namespace extra2d