refactor: add Window interface

This commit is contained in:
MihailRis
2025-04-02 14:59:53 +03:00
parent cd5c6a889c
commit 9694a59649
31 changed files with 859 additions and 923 deletions
-189
View File
@@ -1,189 +0,0 @@
#include "Events.hpp"
#include <GL/glew.h>
#include <GLFW/glfw3.h>
#include <string.h>
#include "debug/Logger.hpp"
#include "util/stringutil.hpp"
#include "Window.hpp"
static debug::Logger logger("events");
inline constexpr short _MOUSE_KEYS_OFFSET = 1024;
namespace {
bool keys[KEYS_BUFFER_SIZE] = {};
uint frames[KEYS_BUFFER_SIZE] = {};
uint current_frame = 0;
bool cursor_drag = false;
bool cursor_locked = false;
std::unordered_map<keycode, util::HandlersList<>> key_callbacks;
}
int Events::scroll = 0;
glm::vec2 Events::delta = {};
glm::vec2 Events::cursor = {};
std::vector<uint> Events::codepoints;
std::vector<keycode> Events::pressedKeys;
Bindings Events::bindings {};
int Events::getScroll() {
return scroll;
}
bool Events::pressed(keycode keycode) {
return pressed(static_cast<int>(keycode));
}
bool Events::pressed(int keycode) {
if (keycode < 0 || keycode >= KEYS_BUFFER_SIZE) {
return false;
}
return keys[keycode];
}
bool Events::jpressed(keycode keycode) {
return jpressed(static_cast<int>(keycode));
}
bool Events::jpressed(int keycode) {
return Events::pressed(keycode) && frames[keycode] == current_frame;
}
bool Events::clicked(mousecode button) {
return clicked(static_cast<int>(button));
}
bool Events::clicked(int button) {
return Events::pressed(_MOUSE_KEYS_OFFSET + button);
}
bool Events::jclicked(mousecode button) {
return jclicked(static_cast<int>(button));
}
bool Events::jclicked(int button) {
return Events::jpressed(_MOUSE_KEYS_OFFSET + button);
}
void Events::toggleCursor() {
cursor_drag = false;
cursor_locked = !cursor_locked;
Window::setCursorMode(
cursor_locked ? GLFW_CURSOR_DISABLED : GLFW_CURSOR_NORMAL
);
}
void Events::pollEvents() {
current_frame++;
delta.x = 0.f;
delta.y = 0.f;
scroll = 0;
codepoints.clear();
pressedKeys.clear();
glfwPollEvents();
for (auto& entry : bindings.getAll()) {
auto& binding = entry.second;
if (!binding.enabled) {
binding.state = false;
continue;
}
binding.justChange = false;
bool newstate = false;
switch (binding.type) {
case inputtype::keyboard:
newstate = pressed(binding.code);
break;
case inputtype::mouse:
newstate = clicked(binding.code);
break;
}
if (newstate) {
if (!binding.state) {
binding.state = true;
binding.justChange = true;
binding.onactived.notify();
}
} else {
if (binding.state) {
binding.state = false;
binding.justChange = true;
}
}
}
}
Binding* Events::getBinding(const std::string& name) {
return bindings.get(name);
}
Binding& Events::requireBinding(const std::string& name) {
if (const auto found = getBinding(name)) {
return *found;
}
throw std::runtime_error("binding '" + name + "' does not exist");
}
void Events::bind(const std::string& name, inputtype type, keycode code) {
bind(name, type, static_cast<int>(code));
}
void Events::bind(const std::string& name, inputtype type, mousecode code) {
bind(name, type, static_cast<int>(code));
}
void Events::bind(const std::string& name, inputtype type, int code) {
bindings.bind(name, type, code);
}
void Events::rebind(const std::string& name, inputtype type, int code) {
requireBinding(name) = Binding(type, code);
}
bool Events::active(const std::string& name) {
return bindings.active(name);
}
bool Events::jactive(const std::string& name) {
return bindings.jactive(name);
}
void Events::setKey(int key, bool b) {
::keys[key] = b;
::frames[key] = current_frame;
if (b) {
const auto& callbacks = ::key_callbacks.find(static_cast<keycode>(key));
if (callbacks != ::key_callbacks.end()) {
callbacks->second.notify();
}
}
}
void Events::setButton(int button, bool b) {
setKey(_MOUSE_KEYS_OFFSET + button, b);
}
void Events::setPosition(float xpos, float ypos) {
if (::cursor_drag) {
Events::delta.x += xpos - Events::cursor.x;
Events::delta.y += ypos - Events::cursor.y;
} else {
::cursor_drag = true;
}
Events::cursor.x = xpos;
Events::cursor.y = ypos;
}
observer_handler Events::addKeyCallback(keycode key, KeyCallback callback) {
return ::key_callbacks[key].add(std::move(callback));
}
bool Events::isCursorLocked() {
return cursor_locked;
}
-54
View File
@@ -1,54 +0,0 @@
#pragma once
#include <string>
#include <unordered_map>
#include <vector>
#include "delegates.hpp"
#include "typedefs.hpp"
#include "input.hpp"
inline constexpr short KEYS_BUFFER_SIZE = 1036;
namespace Events {
extern int scroll;
extern glm::vec2 delta;
extern glm::vec2 cursor;
extern std::vector<uint> codepoints;
extern std::vector<keycode> pressedKeys;
extern Bindings bindings;
void pollEvents();
int getScroll();
bool pressed(keycode keycode);
bool pressed(int keycode);
bool jpressed(keycode keycode);
bool jpressed(int keycode);
bool clicked(mousecode button);
bool clicked(int button);
bool jclicked(mousecode button);
bool jclicked(int button);
void toggleCursor();
Binding* getBinding(const std::string& name);
Binding& requireBinding(const std::string& name);
void bind(const std::string& name, inputtype type, keycode code);
void bind(const std::string& name, inputtype type, mousecode code);
void bind(const std::string& name, inputtype type, int code);
void rebind(const std::string& name, inputtype type, int code);
bool active(const std::string& name);
bool jactive(const std::string& name);
observer_handler addKeyCallback(keycode key, KeyCallback callback);
void setKey(int key, bool b);
void setButton(int button, bool b);
void setPosition(float xpos, float ypos);
bool isCursorLocked();
};
-568
View File
@@ -1,568 +0,0 @@
#include "Window.hpp"
#include <GL/glew.h>
#include <GLFW/glfw3.h>
#include <chrono>
#include <iostream>
#include <thread>
#include <unordered_set>
#include "debug/Logger.hpp"
#include "graphics/core/ImageData.hpp"
#include "graphics/core/Texture.hpp"
#include "settings.hpp"
#include "util/ObjectsKeeper.hpp"
#include "Events.hpp"
#include "util/platform.hpp"
static debug::Logger logger("window");
namespace {
GLFWwindow* window = nullptr;
DisplaySettings* settings = nullptr;
std::stack<glm::vec4> scissorStack;
glm::vec4 scissorArea;
int framerate = -1;
double prevSwap = 0.0;
bool fullscreen = false;
CursorShape cursor = CursorShape::ARROW;
int posX = 0;
int posY = 0;
}
uint Window::width = 0;
uint Window::height = 0;
static util::ObjectsKeeper observers_keeper;
static std::unordered_set<std::string> extensionsCache;
static const char* gl_error_name(int error) {
switch (error) {
case GL_DEBUG_TYPE_ERROR: return "ERROR";
case GL_DEBUG_TYPE_DEPRECATED_BEHAVIOR: return "DEPRECATED_BEHAVIOR";
case GL_DEBUG_TYPE_UNDEFINED_BEHAVIOR: return "UNDEFINED_BEHAVIOR";
case GL_DEBUG_TYPE_PORTABILITY: return "PORTABILITY";
case GL_DEBUG_TYPE_PERFORMANCE: return "PERFORMANCE";
case GL_DEBUG_TYPE_OTHER: return "OTHER";
}
return "UNKNOWN";
}
static const char* gl_severity_name(int severity) {
switch (severity) {
case GL_DEBUG_SEVERITY_LOW: return "LOW";
case GL_DEBUG_SEVERITY_MEDIUM: return "MEDIUM";
case GL_DEBUG_SEVERITY_HIGH: return "HIGH";
case GL_DEBUG_SEVERITY_NOTIFICATION: return "NOTIFICATION";
}
return "UNKNOWN";
}
static void GLAPIENTRY gl_message_callback(
GLenum source,
GLenum type,
GLuint id,
GLenum severity,
GLsizei length,
const GLchar* message,
const void* userParam
) {
if (severity == GL_DEBUG_SEVERITY_NOTIFICATION) {
return;
}
if (!ENGINE_DEBUG_BUILD && severity != GL_DEBUG_SEVERITY_HIGH) {
return;
}
std::cerr << "GL:" << gl_error_name(type) << ":"
<< gl_severity_name(severity) << ": " << message << std::endl;
}
static void cursor_position_callback(GLFWwindow*, double xpos, double ypos) {
Events::setPosition(xpos, ypos);
}
static void mouse_button_callback(GLFWwindow*, int button, int action, int) {
Events::setButton(button, action == GLFW_PRESS);
}
static void key_callback(
GLFWwindow*, int key, int /*scancode*/, int action, int /*mode*/
) {
if (key == GLFW_KEY_UNKNOWN) return;
if (action == GLFW_PRESS) {
Events::setKey(key, true);
Events::pressedKeys.push_back(static_cast<keycode>(key));
} else if (action == GLFW_RELEASE) {
Events::setKey(key, false);
} else if (action == GLFW_REPEAT) {
Events::pressedKeys.push_back(static_cast<keycode>(key));
}
}
static void scroll_callback(GLFWwindow*, double xoffset, double yoffset) {
Events::scroll += yoffset;
}
static void character_callback(GLFWwindow*, unsigned int codepoint) {
Events::codepoints.push_back(codepoint);
}
static void window_size_callback(GLFWwindow*, int width, int height) {
if (width && height) {
glViewport(0, 0, width, height);
Window::width = width;
Window::height = height;
if (!Window::isFullscreen() && !Window::isMaximized()) {
Window::getSettings()->width.set(width);
Window::getSettings()->height.set(height);
}
}
Window::resetScissor();
}
bool Window::isMaximized() {
return glfwGetWindowAttrib(window, GLFW_MAXIMIZED);
}
bool Window::isIconified() {
return glfwGetWindowAttrib(window, GLFW_ICONIFIED);
}
bool Window::isFocused() {
return glfwGetWindowAttrib(window, GLFW_FOCUSED);
}
static const char* glfw_error_name(int error) {
switch (error) {
case GLFW_NO_ERROR:
return "no error";
case GLFW_NOT_INITIALIZED:
return "not initialized";
case GLFW_NO_CURRENT_CONTEXT:
return "no current context";
case GLFW_INVALID_ENUM:
return "invalid enum";
case GLFW_INVALID_VALUE:
return "invalid value";
case GLFW_OUT_OF_MEMORY:
return "out of memory";
case GLFW_API_UNAVAILABLE:
return "api unavailable";
case GLFW_VERSION_UNAVAILABLE:
return "version unavailable";
case GLFW_PLATFORM_ERROR:
return "platform error";
case GLFW_FORMAT_UNAVAILABLE:
return "format unavailable";
case GLFW_NO_WINDOW_CONTEXT:
return "no window context";
default:
return "unknown error";
}
}
static void glfw_error_callback(int error, const char* description) {
auto logline = logger.error();
logline << "GLFW error [0x" << std::hex << error << " - "
<< glfw_error_name(error) << "]";
if (description) {
logline << ": " << description;
}
}
static GLFWcursor* standard_cursors[static_cast<int>(CursorShape::LAST) + 1] = {};
class GLFWInput : public Input {
public:
void pollEvents() override {
Events::pollEvents();
}
const char* getClipboardText() const override {
return glfwGetClipboardString(::window);
}
int getScroll() override {
return Events::getScroll();
}
bool pressed(keycode keycode) const override {
return Events::pressed(keycode);
}
bool jpressed(keycode keycode) const override {
return Events::jpressed(keycode);
}
bool clicked(mousecode mousecode) const override {
return Events::clicked(mousecode);
}
bool jclicked(mousecode mousecode) const override {
return Events::jclicked(mousecode);
}
CursorState getCursor() const override {
return {
Events::isCursorLocked(),
Events::cursor,
Events::delta
};
}
void toggleCursor() override {
Events::toggleCursor();
}
Bindings& getBindings() override {
return Events::bindings;
}
const Bindings& getBindings() const override {
return Events::bindings;
}
observer_handler addKeyCallback(keycode key, KeyCallback callback) override {
return Events::addKeyCallback(key, std::move(callback));
}
const std::vector<keycode>& getPressedKeys() const override {
return Events::pressedKeys;
}
const std::vector<uint>& getCodepoints() const override {
return Events::codepoints;
}
};
static_assert(!std::is_abstract<GLFWInput>());
std::unique_ptr<Input> Window::initialize(DisplaySettings* settings) {
::settings = settings;
Window::width = settings->width.get();
Window::height = settings->height.get();
std::string title = "VoxelCore v" +
std::to_string(ENGINE_VERSION_MAJOR) + "." +
std::to_string(ENGINE_VERSION_MINOR);
if (ENGINE_DEBUG_BUILD) {
title += " [debug]";
}
glfwSetErrorCallback(glfw_error_callback);
if (glfwInit() == GLFW_FALSE) {
logger.error() << "failed to initialize GLFW";
return nullptr;
}
glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 3);
glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 3);
#ifdef __APPLE__
glfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE);
glfwWindowHint(GLFW_OPENGL_FORWARD_COMPAT, GL_TRUE);
glfwWindowHint(GLFW_COCOA_RETINA_FRAMEBUFFER, GLFW_FALSE);
#else
glfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_ANY_PROFILE);
#endif
glfwWindowHint(GLFW_RESIZABLE, GL_TRUE);
glfwWindowHint(GLFW_SAMPLES, settings->samples.get());
window = glfwCreateWindow(width, height, title.c_str(), nullptr, nullptr);
if (window == nullptr) {
logger.error() << "failed to create GLFW window";
glfwTerminate();
return nullptr;
}
glfwMakeContextCurrent(window);
glewExperimental = GL_TRUE;
GLenum glewErr = glewInit();
if (glewErr != GLEW_OK) {
if (glewErr == GLEW_ERROR_NO_GLX_DISPLAY) {
// see issue #240
logger.warning()
<< "glewInit() returned GLEW_ERROR_NO_GLX_DISPLAY; ignored";
} else {
logger.error() << "failed to initialize GLEW:\n"
<< glewGetErrorString(glewErr);
return nullptr;
}
}
if (isGlExtensionSupported("GL_KHR_debug")) {
glEnable(GL_DEBUG_OUTPUT);
glDebugMessageCallback(gl_message_callback, nullptr);
}
glViewport(0, 0, width, height);
glClearColor(0.0f, 0.0f, 0.0f, 1);
glEnable(GL_BLEND);
glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
GLint maxTextureSize[1] {static_cast<GLint>(Texture::MAX_RESOLUTION)};
glGetIntegerv(GL_MAX_TEXTURE_SIZE, maxTextureSize);
if (maxTextureSize[0] > 0) {
Texture::MAX_RESOLUTION = maxTextureSize[0];
logger.info() << "max texture size is " << Texture::MAX_RESOLUTION;
}
glfwSetKeyCallback(window, key_callback);
glfwSetMouseButtonCallback(window, mouse_button_callback);
glfwSetCursorPosCallback(window, cursor_position_callback);
glfwSetWindowSizeCallback(window, window_size_callback);
glfwSetCharCallback(window, character_callback);
glfwSetScrollCallback(window, scroll_callback);
observers_keeper = util::ObjectsKeeper();
observers_keeper.keepAlive(settings->fullscreen.observe(
[](bool value) {
if (value != isFullscreen()) {
toggleFullscreen();
}
},
true
));
glfwSwapInterval(1);
setFramerate(settings->framerate.get());
const GLubyte* vendor = glGetString(GL_VENDOR);
const GLubyte* renderer = glGetString(GL_RENDERER);
logger.info() << "GL Vendor: " << reinterpret_cast<const char*>(vendor);
logger.info() << "GL Renderer: " << reinterpret_cast<const char*>(renderer);
logger.info() << "GLFW: " << glfwGetVersionString();
glm::vec2 scale;
glfwGetMonitorContentScale(glfwGetPrimaryMonitor(), &scale.x, &scale.y);
logger.info() << "monitor content scale: " << scale.x << "x" << scale.y;
input_util::initialize();
for (int i = 0; i <= static_cast<int>(CursorShape::LAST); i++) {
int cursor = GLFW_ARROW_CURSOR + i;
// GLFW 3.3 does not support some cursors
if (GLFW_VERSION_MAJOR <= 3 && GLFW_VERSION_MINOR <= 3 && cursor > GLFW_VRESIZE_CURSOR) {
break;
}
standard_cursors[i] = glfwCreateStandardCursor(cursor);
}
return std::make_unique<GLFWInput>();
}
void Window::clear() {
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
}
void Window::clearDepth() {
glClear(GL_DEPTH_BUFFER_BIT);
}
void Window::setBgColor(glm::vec3 color) {
glClearColor(color.r, color.g, color.b, 1.0f);
}
void Window::setBgColor(glm::vec4 color) {
glClearColor(color.r, color.g, color.b, color.a);
}
void Window::viewport(int x, int y, int width, int height) {
glViewport(x, y, width, height);
}
void Window::setCursorMode(int mode) {
glfwSetInputMode(window, GLFW_CURSOR, mode);
}
void Window::resetScissor() {
scissorArea = glm::vec4(0.0f, 0.0f, width, height);
scissorStack = std::stack<glm::vec4>();
glDisable(GL_SCISSOR_TEST);
}
void Window::pushScissor(glm::vec4 area) {
if (scissorStack.empty()) {
glEnable(GL_SCISSOR_TEST);
}
scissorStack.push(scissorArea);
area.z += glm::ceil(area.x);
area.w += glm::ceil(area.y);
area.x = glm::max(area.x, scissorArea.x);
area.y = glm::max(area.y, scissorArea.y);
area.z = glm::min(area.z, scissorArea.z);
area.w = glm::min(area.w, scissorArea.w);
if (area.z < 0.0f || area.w < 0.0f) {
glScissor(0, 0, 0, 0);
} else {
glScissor(
area.x,
Window::height - area.w,
std::max(0, static_cast<int>(glm::ceil(area.z - area.x))),
std::max(0, static_cast<int>(glm::ceil(area.w - area.y)))
);
}
scissorArea = area;
}
void Window::popScissor() {
if (scissorStack.empty()) {
logger.warning() << "extra Window::popScissor call";
return;
}
glm::vec4 area = scissorStack.top();
scissorStack.pop();
if (area.z < 0.0f || area.w < 0.0f) {
glScissor(0, 0, 0, 0);
} else {
glScissor(
area.x,
Window::height - area.w,
std::max(0, int(area.z - area.x)),
std::max(0, int(area.w - area.y))
);
}
if (scissorStack.empty()) {
glDisable(GL_SCISSOR_TEST);
}
scissorArea = area;
}
void Window::terminate() {
observers_keeper = util::ObjectsKeeper();
for (int i = 0; i <= static_cast<int>(CursorShape::LAST); i++) {
glfwDestroyCursor(standard_cursors[i]);
}
glfwTerminate();
}
bool Window::isShouldClose() {
return glfwWindowShouldClose(window);
}
void Window::setShouldClose(bool flag) {
glfwSetWindowShouldClose(window, flag);
}
void Window::setFramerate(int framerate) {
if ((framerate != -1) != (::framerate != -1)) {
glfwSwapInterval(framerate == -1);
}
::framerate = framerate;
}
void Window::toggleFullscreen() {
fullscreen = !fullscreen;
GLFWmonitor* monitor = glfwGetPrimaryMonitor();
const GLFWvidmode* mode = glfwGetVideoMode(monitor);
if (Events::isCursorLocked()){
Events::toggleCursor();
}
if (fullscreen) {
glfwGetWindowPos(window, &posX, &posY);
glfwSetWindowMonitor(
window, monitor, 0, 0, mode->width, mode->height, GLFW_DONT_CARE
);
} else {
glfwSetWindowMonitor(
window,
nullptr,
posX,
posY,
settings->width.get(),
settings->height.get(),
GLFW_DONT_CARE
);
}
double xPos, yPos;
glfwGetCursorPos(window, &xPos, &yPos);
Events::setPosition(xPos, yPos);
}
bool Window::isFullscreen() {
return fullscreen;
}
void Window::swapBuffers() {
glfwSwapBuffers(window);
Window::resetScissor();
if (framerate > 0) {
auto elapsedTime = time() - prevSwap;
auto frameTime = 1.0 / framerate;
if (elapsedTime < frameTime) {
platform::sleep(
static_cast<size_t>((frameTime - elapsedTime) * 1000)
);
}
}
prevSwap = time();
}
double Window::time() {
return glfwGetTime();
}
DisplaySettings* Window::getSettings() {
return settings;
}
void Window::setCursor(CursorShape shape) {
if (cursor == shape) {
return;
}
cursor = shape;
// NULL cursor is valid for GLFW
glfwSetCursor(window, standard_cursors[static_cast<int>(shape)]);
}
std::unique_ptr<ImageData> Window::takeScreenshot() {
auto data = std::make_unique<ubyte[]>(width * height * 3);
glPixelStorei(GL_PACK_ALIGNMENT, 1);
glReadPixels(0, 0, width, height, GL_RGB, GL_UNSIGNED_BYTE, data.get());
return std::make_unique<ImageData>(
ImageFormat::rgb888, width, height, data.release()
);
}
void Window::setClipboardText(const char* text) {
glfwSetClipboardString(window, text);
}
void Window::setIcon(const ImageData* image) {
GLFWimage icon {
static_cast<int>(image->getWidth()),
static_cast<int>(image->getHeight()),
image->getData()};
glfwSetWindowIcon(window, 1, &icon);
}
static void initGlExtensionsCache() {
if (!extensionsCache.empty()) {
return;
}
GLint numExtensions = 0;
glGetIntegerv(GL_NUM_EXTENSIONS, &numExtensions);
for (GLint i = 0; i < numExtensions; ++i) {
const char *ext = reinterpret_cast<const char *>(glGetStringi(GL_EXTENSIONS, i));
if (ext) {
extensionsCache.insert(ext);
}
}
}
bool Window::isGlExtensionSupported(const char *extension) {
if (!extension || !*extension) {
return false;
}
initGlExtensionsCache();
return extensionsCache.find(extension) != extensionsCache.end();
}
+39 -30
View File
@@ -12,43 +12,52 @@ class ImageData;
class Input;
struct DisplaySettings;
namespace Window {
extern uint width;
extern uint height;
class Window {
public:
Window(glm::ivec2 size) : size(std::move(size)) {}
std::unique_ptr<Input> initialize(DisplaySettings* settings);
void terminate();
virtual ~Window() = default;
virtual void swapBuffers() = 0;
void viewport(int x, int y, int width, int height);
void setCursorMode(int mode);
bool isShouldClose();
void setShouldClose(bool flag);
void swapBuffers();
void setFramerate(int interval);
void toggleFullscreen();
bool isFullscreen();
bool isMaximized();
bool isFocused();
bool isIconified();
virtual bool isMaximized() const = 0;
virtual bool isFocused() const = 0;
virtual bool isIconified() const = 0;
void pushScissor(glm::vec4 area);
void popScissor();
void resetScissor();
virtual bool isShouldClose() const = 0;
virtual void setShouldClose(bool flag) = 0;
void setCursor(CursorShape shape);
virtual void setCursor(CursorShape shape) = 0;
virtual void toggleFullscreen() = 0;
virtual bool isFullscreen() const = 0;
virtual void setIcon(const ImageData* image) = 0;
virtual void pushScissor(glm::vec4 area) = 0;
virtual void popScissor() = 0;
virtual void resetScissor() = 0;
virtual double time() = 0;
virtual void setFramerate(int framerate) = 0;
// TODO: move somewhere
virtual std::unique_ptr<ImageData> takeScreenshot() = 0;
const glm::ivec2& getSize() const {
return size;
}
protected:
glm::ivec2 size;
};
namespace display {
std::tuple<
std::unique_ptr<Window>,
std::unique_ptr<Input>
> initialize(DisplaySettings* settings);
void clear();
void clearDepth();
void setBgColor(glm::vec3 color);
void setBgColor(glm::vec4 color);
double time();
void setClipboardText(const char* text);
DisplaySettings* getSettings();
void setIcon(const ImageData* image);
inline glm::vec2 size() {
return glm::vec2(width, height);
}
std::unique_ptr<ImageData> takeScreenshot();
};
+683
View File
@@ -0,0 +1,683 @@
#include "window/Window.hpp"
#include <GL/glew.h>
#include <GLFW/glfw3.h>
#include <unordered_set>
#include <chrono>
#include "debug/Logger.hpp"
#include "graphics/core/ImageData.hpp"
#include "graphics/core/Texture.hpp"
#include "settings.hpp"
#include "util/ObjectsKeeper.hpp"
#include "util/platform.hpp"
#include "window/input.hpp"
static debug::Logger logger("window");
static std::unordered_set<std::string> extensions_cache;
static void init_gl_extensions_cache() {
if (!extensions_cache.empty()) {
return;
}
GLint numExtensions = 0;
glGetIntegerv(GL_NUM_EXTENSIONS, &numExtensions);
for (GLint i = 0; i < numExtensions; ++i) {
const char *ext = reinterpret_cast<const char *>(glGetStringi(GL_EXTENSIONS, i));
if (ext) {
extensions_cache.insert(ext);
}
}
}
static bool is_gl_extension_supported(const char *extension) {
if (!extension || !*extension) {
return false;
}
init_gl_extensions_cache();
return extensions_cache.find(extension) != extensions_cache.end();
}
static const char* gl_error_name(int error) {
switch (error) {
case GL_DEBUG_TYPE_ERROR: return "ERROR";
case GL_DEBUG_TYPE_DEPRECATED_BEHAVIOR: return "DEPRECATED_BEHAVIOR";
case GL_DEBUG_TYPE_UNDEFINED_BEHAVIOR: return "UNDEFINED_BEHAVIOR";
case GL_DEBUG_TYPE_PORTABILITY: return "PORTABILITY";
case GL_DEBUG_TYPE_PERFORMANCE: return "PERFORMANCE";
case GL_DEBUG_TYPE_OTHER: return "OTHER";
}
return "UNKNOWN";
}
static const char* gl_severity_name(int severity) {
switch (severity) {
case GL_DEBUG_SEVERITY_LOW: return "LOW";
case GL_DEBUG_SEVERITY_MEDIUM: return "MEDIUM";
case GL_DEBUG_SEVERITY_HIGH: return "HIGH";
case GL_DEBUG_SEVERITY_NOTIFICATION: return "NOTIFICATION";
}
return "UNKNOWN";
}
static void GLAPIENTRY gl_message_callback(
GLenum source,
GLenum type,
GLuint id,
GLenum severity,
GLsizei length,
const GLchar* message,
const void* userParam
) {
if (severity == GL_DEBUG_SEVERITY_NOTIFICATION) {
return;
}
if (!ENGINE_DEBUG_BUILD && severity != GL_DEBUG_SEVERITY_HIGH) {
return;
}
logger.warning() << "GL:" << gl_error_name(type) << ":"
<< gl_severity_name(severity) << ": " << message;
}
static const char* glfw_error_name(int error) {
switch (error) {
case GLFW_NO_ERROR:
return "no error";
case GLFW_NOT_INITIALIZED:
return "not initialized";
case GLFW_NO_CURRENT_CONTEXT:
return "no current context";
case GLFW_INVALID_ENUM:
return "invalid enum";
case GLFW_INVALID_VALUE:
return "invalid value";
case GLFW_OUT_OF_MEMORY:
return "out of memory";
case GLFW_API_UNAVAILABLE:
return "api unavailable";
case GLFW_VERSION_UNAVAILABLE:
return "version unavailable";
case GLFW_PLATFORM_ERROR:
return "platform error";
case GLFW_FORMAT_UNAVAILABLE:
return "format unavailable";
case GLFW_NO_WINDOW_CONTEXT:
return "no window context";
default:
return "unknown error";
}
}
static void glfw_error_callback(int error, const char* description) {
auto logline = logger.error();
logline << "GLFW error [0x" << std::hex << error << " - "
<< glfw_error_name(error) << "]";
if (description) {
logline << ": " << description;
}
}
inline constexpr short KEYS_BUFFER_SIZE = 1036;
inline constexpr short _MOUSE_KEYS_OFFSET = 1024;
static GLFWcursor* standard_cursors[static_cast<int>(CursorShape::LAST) + 1] = {};
class GLFWInput : public Input {
public:
int scroll = 0;
uint currentFrame = 0;
uint frames[KEYS_BUFFER_SIZE] {};
std::vector<uint> codepoints;
std::vector<keycode> pressedKeys;
Bindings bindings;
bool keys[KEYS_BUFFER_SIZE] {};
std::unordered_map<keycode, util::HandlersList<>> keyCallbacks;
GLFWInput(GLFWwindow* window)
: window(window) {
}
void pollEvents() override {
delta.x = 0.0f;
delta.y = 0.0f;
scroll = 0;
currentFrame++;
codepoints.clear();
pressedKeys.clear();
glfwPollEvents();
for (auto& entry : bindings.getAll()) {
auto& binding = entry.second;
if (!binding.enabled) {
binding.state = false;
continue;
}
binding.justChange = false;
bool newstate = false;
switch (binding.type) {
case inputtype::keyboard:
newstate = pressed(static_cast<keycode>(binding.code));
break;
case inputtype::mouse:
newstate = clicked(static_cast<mousecode>(binding.code));
break;
}
if (newstate) {
if (!binding.state) {
binding.state = true;
binding.justChange = true;
binding.onactived.notify();
}
} else {
if (binding.state) {
binding.state = false;
binding.justChange = true;
}
}
}
}
void onKeyCallback(int key, bool pressed) {
bool prevPressed = keys[key];
keys[key] = pressed;
frames[key] = currentFrame;
if (pressed && !prevPressed) {
const auto& callbacks = keyCallbacks.find(static_cast<keycode>(key));
if (callbacks != keyCallbacks.end()) {
callbacks->second.notify();
}
}
if (pressed) {
pressedKeys.push_back(static_cast<keycode>(key));
}
}
void onMouseCallback(int button, bool pressed) {
int key = button + _MOUSE_KEYS_OFFSET;
onKeyCallback(key, pressed);
}
const char* getClipboardText() const override {
return glfwGetClipboardString(window);
}
void setClipboardText(const char* text) override {
glfwSetClipboardString(window, text);
}
int getScroll() override {
return scroll;
}
bool pressed(keycode key) const override {
int keycode = static_cast<int>(key);
if (keycode < 0 || keycode >= KEYS_BUFFER_SIZE) {
return false;
}
return keys[keycode];
}
bool jpressed(keycode keycode) const override {
return pressed(keycode) &&
frames[static_cast<int>(keycode)] == currentFrame;
}
bool clicked(mousecode code) const override {
return pressed(
static_cast<keycode>(_MOUSE_KEYS_OFFSET + static_cast<int>(code))
);
}
bool jclicked(mousecode code) const override {
return clicked(code) &&
frames[static_cast<int>(code) + _MOUSE_KEYS_OFFSET] ==
currentFrame;
}
CursorState getCursor() const override {
return {isCursorLocked(), cursor, delta};
}
bool isCursorLocked() const override {
return cursorLocked;
}
void toggleCursor() override {
cursorDrag = false;
if (cursorLocked) {
glfwSetInputMode(window, GLFW_CURSOR, GLFW_CURSOR_NORMAL);
} else {
glfwSetInputMode(window, GLFW_CURSOR, GLFW_CURSOR_DISABLED);
}
cursorLocked = !cursorLocked;
}
void setCursorPosition(double xpos, double ypos) {
if (cursorDrag) {
delta.x += xpos - cursor.x;
delta.y += ypos - cursor.y;
} else {
cursorDrag = true;
}
cursor.x = xpos;
cursor.y = ypos;
}
Bindings& getBindings() override {
return bindings;
}
const Bindings& getBindings() const override {
return bindings;
}
observer_handler addKeyCallback(keycode key, KeyCallback callback) override {
return keyCallbacks[key].add(std::move(callback));
}
const std::vector<keycode>& getPressedKeys() const override {
return pressedKeys;
}
const std::vector<uint>& getCodepoints() const override {
return codepoints;
}
private:
GLFWwindow* window;
bool cursorLocked = false;
bool cursorDrag = false;
glm::vec2 delta;
glm::vec2 cursor;
};
static_assert(!std::is_abstract<GLFWInput>());
class GLFWWindow : public Window {
public:
GLFWInput& input;
DisplaySettings* settings;
GLFWWindow(
GLFWInput& glfwInput,
GLFWwindow* window,
DisplaySettings* settings,
int width,
int height
)
: Window({width, height}),
input(glfwInput),
settings(settings),
window(window) {
}
~GLFWWindow() {
for (int i = 0; i <= static_cast<int>(CursorShape::LAST); i++) {
glfwDestroyCursor(standard_cursors[i]);
}
glfwTerminate();
}
double time() override {
return glfwGetTime();
}
void swapBuffers() override {
glfwSwapBuffers(window);
resetScissor();
if (framerate > 0) {
auto elapsedTime = time() - prevSwap;
auto frameTime = 1.0 / framerate;
if (elapsedTime < frameTime) {
platform::sleep(
static_cast<size_t>((frameTime - elapsedTime) * 1000)
);
}
}
prevSwap = time();
}
bool isMaximized() const override {
return glfwGetWindowAttrib(window, GLFW_MAXIMIZED);
}
bool isFocused() const override {
return glfwGetWindowAttrib(window, GLFW_FOCUSED);
}
bool isIconified() const override {
return glfwGetWindowAttrib(window, GLFW_ICONIFIED);
}
bool isShouldClose() const override {
return glfwWindowShouldClose(window);
}
void setShouldClose(bool flag) override {
glfwSetWindowShouldClose(window, flag);
}
void setCursor(CursorShape shape) override {
if (cursor == shape) {
return;
}
cursor = shape;
// NULL cursor is valid for GLFW
glfwSetCursor(window, standard_cursors[static_cast<int>(shape)]);
}
void toggleFullscreen() override {
fullscreen = !fullscreen;
GLFWmonitor* monitor = glfwGetPrimaryMonitor();
const GLFWvidmode* mode = glfwGetVideoMode(monitor);
if (input.isCursorLocked()){
input.toggleCursor();
}
if (fullscreen) {
glfwGetWindowPos(window, &posX, &posY);
glfwSetWindowMonitor(
window, monitor, 0, 0, mode->width, mode->height, GLFW_DONT_CARE
);
} else {
glfwSetWindowMonitor(
window,
nullptr,
posX,
posY,
settings->width.get(),
settings->height.get(),
GLFW_DONT_CARE
);
}
double xPos, yPos;
glfwGetCursorPos(window, &xPos, &yPos);
input.setCursorPosition(xPos, yPos);
}
bool isFullscreen() const override {
return fullscreen;
}
void setIcon(const ImageData* image) override {
if (image == nullptr) {
glfwSetWindowIcon(window, 0, nullptr);
return;
}
GLFWimage icon {
static_cast<int>(image->getWidth()),
static_cast<int>(image->getHeight()),
image->getData()};
glfwSetWindowIcon(window, 1, &icon);
}
void setSize(int width, int height) {
glViewport(0, 0, width, height);
size = {width, height};
if (!isFullscreen() && !isMaximized()) {
settings->width.set(width);
settings->height.set(height);
}
}
void pushScissor(glm::vec4 area) override {
if (scissorStack.empty()) {
glEnable(GL_SCISSOR_TEST);
}
scissorStack.push(scissorArea);
area.z += glm::ceil(area.x);
area.w += glm::ceil(area.y);
area.x = glm::max(area.x, scissorArea.x);
area.y = glm::max(area.y, scissorArea.y);
area.z = glm::min(area.z, scissorArea.z);
area.w = glm::min(area.w, scissorArea.w);
if (area.z < 0.0f || area.w < 0.0f) {
glScissor(0, 0, 0, 0);
} else {
glScissor(
area.x,
size.y - area.w,
std::max(0, static_cast<int>(glm::ceil(area.z - area.x))),
std::max(0, static_cast<int>(glm::ceil(area.w - area.y)))
);
}
scissorArea = area;
}
void resetScissor() override {
scissorArea = glm::vec4(0.0f, 0.0f, size.x, size.y);
scissorStack = std::stack<glm::vec4>();
glDisable(GL_SCISSOR_TEST);
}
void popScissor() override {
if (scissorStack.empty()) {
logger.warning() << "extra Window::popScissor call";
return;
}
glm::vec4 area = scissorStack.top();
scissorStack.pop();
if (area.z < 0.0f || area.w < 0.0f) {
glScissor(0, 0, 0, 0);
} else {
glScissor(
area.x,
size.y - area.w,
std::max(0, static_cast<int>(area.z - area.x)),
std::max(0, static_cast<int>(area.w - area.y))
);
}
if (scissorStack.empty()) {
glDisable(GL_SCISSOR_TEST);
}
scissorArea = area;
}
std::unique_ptr<ImageData> takeScreenshot() override {
auto data = std::make_unique<ubyte[]>(size.x * size.y * 3);
glPixelStorei(GL_PACK_ALIGNMENT, 1);
glReadPixels(0, 0, size.x, size.y, GL_RGB, GL_UNSIGNED_BYTE, data.get());
return std::make_unique<ImageData>(
ImageFormat::rgb888, size.x, size.y, data.release()
);
}
void setFramerate(int framerate) override {
if ((framerate != -1) != (this->framerate != -1)) {
glfwSwapInterval(framerate == -1);
}
this->framerate = framerate;
}
private:
GLFWwindow* window;
CursorShape cursor = CursorShape::ARROW;
bool fullscreen = false;
int framerate = -1;
std::stack<glm::vec4> scissorStack;
glm::vec4 scissorArea;
double prevSwap = 0.0;
int posX = 0;
int posY = 0;
};
static_assert(!std::is_abstract<GLFWWindow>());
static void mouse_button_callback(GLFWwindow* window, int button, int action, int) {
auto handler = static_cast<GLFWWindow*>(glfwGetWindowUserPointer(window));
handler->input.onMouseCallback(button, action == GLFW_PRESS);
}
static void character_callback(GLFWwindow* window, unsigned int codepoint) {
auto handler = static_cast<GLFWWindow*>(glfwGetWindowUserPointer(window));
handler->input.codepoints.push_back(codepoint);
}
static void key_callback(
GLFWwindow* window, int key, int /*scancode*/, int action, int /*mode*/
) {
auto handler = static_cast<GLFWWindow*>(glfwGetWindowUserPointer(window));
auto& input = handler->input;
if (key == GLFW_KEY_UNKNOWN) {
return;
}
if (action == GLFW_PRESS) {
input.onKeyCallback(key, true);
} else if (action == GLFW_RELEASE) {
input.onKeyCallback(key, false);
} else if (action == GLFW_REPEAT) {
input.onKeyCallback(key, true);
}
}
static void window_size_callback(GLFWwindow* window, int width, int height) {
auto handler = static_cast<GLFWWindow*>(glfwGetWindowUserPointer(window));
if (width && height) {
handler->setSize(width, height);
}
handler->resetScissor();
}
static void scroll_callback(GLFWwindow* window, double, double yoffset) {
auto handler = static_cast<GLFWWindow*>(glfwGetWindowUserPointer(window));
handler->input.scroll += yoffset;
}
static void cursor_pos_callback(GLFWwindow* window, double xpos, double ypos) {
auto handler = static_cast<GLFWWindow*>(glfwGetWindowUserPointer(window));
handler->input.setCursorPosition(xpos, ypos);
}
std::tuple<
std::unique_ptr<Window>,
std::unique_ptr<Input>
> display::initialize(DisplaySettings* settings) {
int width = settings->width.get();
int height = settings->height.get();
std::string title = "VoxelCore v" +
std::to_string(ENGINE_VERSION_MAJOR) + "." +
std::to_string(ENGINE_VERSION_MINOR);
if (ENGINE_DEBUG_BUILD) {
title += " [debug]";
}
glfwSetErrorCallback(glfw_error_callback);
if (glfwInit() == GLFW_FALSE) {
logger.error() << "failed to initialize GLFW";
return {nullptr, nullptr};
}
glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 3);
glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 3);
#ifdef __APPLE__
glfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE);
glfwWindowHint(GLFW_OPENGL_FORWARD_COMPAT, GL_TRUE);
glfwWindowHint(GLFW_COCOA_RETINA_FRAMEBUFFER, GLFW_FALSE);
#else
glfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_ANY_PROFILE);
#endif
glfwWindowHint(GLFW_RESIZABLE, GL_TRUE);
glfwWindowHint(GLFW_SAMPLES, settings->samples.get());
auto window = glfwCreateWindow(width, height, title.c_str(), nullptr, nullptr);
if (window == nullptr) {
logger.error() << "failed to create GLFW window";
glfwTerminate();
return {nullptr, nullptr};
}
glfwMakeContextCurrent(window);
glewExperimental = GL_TRUE;
GLenum glewErr = glewInit();
if (glewErr != GLEW_OK) {
if (glewErr == GLEW_ERROR_NO_GLX_DISPLAY) {
// see issue #240
logger.warning()
<< "glewInit() returned GLEW_ERROR_NO_GLX_DISPLAY; ignored";
} else {
logger.error() << "failed to initialize GLEW:\n"
<< glewGetErrorString(glewErr);
glfwTerminate();
return {nullptr, nullptr};
}
}
if (is_gl_extension_supported("GL_KHR_debug")) {
glEnable(GL_DEBUG_OUTPUT);
glDebugMessageCallback(gl_message_callback, nullptr);
}
glViewport(0, 0, width, height);
glClearColor(0.0f, 0.0f, 0.0f, 1);
glEnable(GL_BLEND);
glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
GLint maxTextureSize[1] {static_cast<GLint>(Texture::MAX_RESOLUTION)};
glGetIntegerv(GL_MAX_TEXTURE_SIZE, maxTextureSize);
if (maxTextureSize[0] > 0) {
Texture::MAX_RESOLUTION = maxTextureSize[0];
logger.info() << "max texture size is " << Texture::MAX_RESOLUTION;
}
glfwSetKeyCallback(window, key_callback);
glfwSetMouseButtonCallback(window, mouse_button_callback);
glfwSetCursorPosCallback(window, cursor_pos_callback);
glfwSetWindowSizeCallback(window, window_size_callback);
glfwSetCharCallback(window, character_callback);
glfwSetScrollCallback(window, scroll_callback);
glfwSwapInterval(1);
const GLubyte* vendor = glGetString(GL_VENDOR);
const GLubyte* renderer = glGetString(GL_RENDERER);
logger.info() << "GL Vendor: " << reinterpret_cast<const char*>(vendor);
logger.info() << "GL Renderer: " << reinterpret_cast<const char*>(renderer);
logger.info() << "GLFW: " << glfwGetVersionString();
glm::vec2 scale;
glfwGetMonitorContentScale(glfwGetPrimaryMonitor(), &scale.x, &scale.y);
logger.info() << "monitor content scale: " << scale.x << "x" << scale.y;
input_util::initialize();
for (int i = 0; i <= static_cast<int>(CursorShape::LAST); i++) {
int cursor = GLFW_ARROW_CURSOR + i;
// GLFW 3.3 does not support some cursors
if (GLFW_VERSION_MAJOR <= 3 && GLFW_VERSION_MINOR <= 3 && cursor > GLFW_VRESIZE_CURSOR) {
break;
}
standard_cursors[i] = glfwCreateStandardCursor(cursor);
}
auto inputPtr = std::make_unique<GLFWInput>(window);
auto windowPtr = std::make_unique<GLFWWindow>(
*inputPtr, window, settings, width, height
);
glfwSetWindowUserPointer(window, windowPtr.get());
return {std::move(windowPtr), std::move(inputPtr)};
}
void display::clear() {
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
}
void display::clearDepth() {
glClear(GL_DEPTH_BUFFER_BIT);
}
void display::setBgColor(glm::vec3 color) {
glClearColor(color.r, color.g, color.b, 1.0f);
}
void display::setBgColor(glm::vec4 color) {
glClearColor(color.r, color.g, color.b, color.a);
}
+2
View File
@@ -258,6 +258,7 @@ public:
virtual void pollEvents() = 0;
virtual const char* getClipboardText() const = 0;
virtual void setClipboardText(const char* str) = 0;
virtual int getScroll() = 0;
@@ -269,6 +270,7 @@ public:
virtual CursorState getCursor() const = 0;
virtual bool isCursorLocked() const = 0;
virtual void toggleCursor() = 0;
virtual Bindings& getBindings() = 0;