Extra2D/include/platform/window_module.h

182 lines
3.6 KiB
C
Raw Normal View History

#pragma once
#include <SDL.h>
#include <config/app_config.h>
#include <config/window_config.h>
#include <functional>
#include <module/module.h>
#include <module/module_registry.h>
#include <type_traits>
#include <types/math/size.h>
#include <types/math/vec2.h>
namespace extra2d {
/**
* @brief
*/
using ResizeCb = std::function<void(int32 w, int32 h)>;
using CloseCb = std::function<void()>;
/**
* @brief -
*
* SDL2 OpenGL
* 使 Module
*/
class WindowModule : public Module {
// 自动注册到模块系统,优先级为 0最先初始化
E2D_REGISTER_MODULE(WindowModule, "Window", 0)
public:
WindowModule();
~WindowModule() override;
// 禁止拷贝
WindowModule(const WindowModule &) = delete;
WindowModule &operator=(const WindowModule &) = delete;
// 允许移动
WindowModule(WindowModule &&) noexcept;
WindowModule &operator=(WindowModule &&) noexcept;
// Module 接口实现
bool init() override;
void shutdown() override;
/**
* @brief 使
*/
bool create(const WindowCfg &cfg);
/**
* @brief
* @return true false 退
*/
bool pollEvents();
/**
* @brief
*/
void swapBuffers();
/**
* @brief SDL
*/
SDL_Window *handle() const { return window_; }
/**
* @brief OpenGL
*/
SDL_GLContext glContext() const { return glCtx_; }
/**
* @brief
*/
Size getSize() const;
/**
* @brief
*/
Vec2 getPosition() const;
/**
* @brief
*/
void setSize(int32 w, int32 h);
/**
* @brief
*/
void setTitle(const std::string &title);
/**
* @brief
*/
void setFullscreen(bool fullscreen);
/**
* @brief
*/
bool isFullscreen() const;
/**
* @brief
*/
void setVsync(bool vsync);
/**
* @brief
*/
bool isVsync() const;
/**
* @brief /
*/
void setVisible(bool visible);
/**
* @brief
*/
bool isVisible() const;
/**
* @brief
*/
void setOnClose(CloseCb cb) { onClose_ = std::move(cb); }
/**
* @brief
*/
void setOnResize(ResizeCb cb) { onResize_ = std::move(cb); }
/**
* @brief
*/
void requestClose() { shouldClose_ = true; }
/**
* @brief
*/
bool shouldClose() const { return shouldClose_; }
private:
void handleWindowEvent(const SDL_WindowEvent &evt);
/**
* @brief
* @tparam ConfigT
* @param config
*
* AppConfig
*/
template <typename ConfigT> void onModuleConfig(const ConfigT &config) {
// 只处理 AppConfig 类型
if constexpr (std::is_same_v<ConfigT, AppConfig>) {
WindowCfg cfg;
cfg.title = config.title;
cfg.width = config.width;
cfg.height = config.height;
cfg.fullscreen = config.fullscreen;
cfg.resizable = config.resizable;
cfg.vsync = config.vsync;
cfg.glMajor = config.glMajor;
cfg.glMinor = config.glMinor;
if (create(cfg)) {
setVisible(true);
}
}
}
SDL_Window *window_ = nullptr;
SDL_GLContext glCtx_ = nullptr;
bool shouldClose_ = false;
bool vsync_ = true;
CloseCb onClose_;
ResizeCb onResize_;
};
} // namespace extra2d