Files
Archimedes/include/utils/Window/WindowGLFW/WindowGLFW.h
2025-04-19 15:08:39 -05:00

130 lines
3.9 KiB
C++

#include "pch.hpp"
#ifdef WINDOW_GLFW
#undef WINDOW_GLFW
#include "utils/Window/WindowEvents.h"
#include <GLFW/glfw3.h>
namespace Archimedes {
class Window;
class WindowGLFW {
public:
WindowGLFW(Window* p, const std::function<void(Event*)>& sendEvent) {
data.window = p;
data.sendEvent = sendEvent;
glfwSetErrorCallback([](int e, const char* m){
std::cout << "GLFW Error: " << m << std::endl;
});
if(!glfwInit()) {
std::cout << "glfwInit failed!\n";
std::abort();
}
w = glfwCreateWindow(640, 480, "Archimedes", NULL, NULL);
if(!w) {
glfwTerminate();
std::abort();
}
glfwMakeContextCurrent(w);
glfwSwapInterval(1);
glfwSetWindowUserPointer(w, &data);
glfwSetWindowSizeCallback(w, [](GLFWwindow* window, int w, int h){
WindowData& d = *(WindowData*) glfwGetWindowUserPointer(window);
d.sendEvent(new WindowResizeEvent(w, h));
});
glfwSetWindowCloseCallback(w, [](GLFWwindow* window){
WindowData& d = *(WindowData*) glfwGetWindowUserPointer(window);
d.sendEvent(new WindowCloseEvent(d.window));
});
glfwSetKeyCallback(w, [](GLFWwindow* window, int key, int scancode, int action, int mods){
WindowData& d = *(WindowData*) glfwGetWindowUserPointer(window);
switch(action) {
case GLFW_PRESS:
d.sendEvent(new WindowKeyPressedEvent(key, 0));
break;
case GLFW_RELEASE:
d.sendEvent(new WindowKeyReleasedEvent(key));
break;
case GLFW_REPEAT:
d.sendEvent(new WindowKeyPressedEvent(key, 1));
break;
}
});
glfwSetMouseButtonCallback(w, [](GLFWwindow* window, int button, int action, int mods){
WindowData& d = *(WindowData*) glfwGetWindowUserPointer(window);
switch(action) {
case GLFW_PRESS:
d.sendEvent(new WindowMouseButtonPressedEvent(button));
break;
case GLFW_RELEASE:
d.sendEvent(new WindowMouseButtonReleasedEvent(button));
break;
}
});
glfwSetScrollCallback(w, [](GLFWwindow* window, double dx, double dy){
WindowData& d = *(WindowData*) glfwGetWindowUserPointer(window);
d.sendEvent(new WindowScrollEvent(dx, dy));
});
glfwSetCursorPosCallback(w, [](GLFWwindow* window, double dx, double dy){
WindowData& d = *(WindowData*) glfwGetWindowUserPointer(window);
d.sendEvent(new WindowMouseMovedEvent(dx, dy));
});
}
~WindowGLFW() {
glfwTerminate();
}
bool shouldClose() {
return glfwWindowShouldClose(w);
}
void doFrame() { restoreContext(); glfwSwapBuffers(w); }
void pollEvents() { glfwPollEvents(); }
void restoreContext() { glfwMakeContextCurrent(w); }
void getSize(int& w, int& h) {
glfwGetFramebufferSize(this->w, &w, &h);
}
GLFWwindow* getWindow() { return w; }
WindowData data;
private:
GLFWwindow* w;
};
typedef WindowGLFW WindowImpl;
}
#endif