Window.cpp 2.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374
  1. #include <iostream>
  2. #include "rendering/wrapper/Window.h"
  3. Window::Window(WindowSize& size, Controller& controller, const Options& options) : window(nullptr), size(size),
  4. controller(controller) {
  5. glfwDefaultWindowHints();
  6. glfwWindowHint(GLFW_VISIBLE, 0);
  7. glfwWindowHint(GLFW_RESIZABLE, 1);
  8. glfwWindowHint(GLFW_DECORATED, !options.fullscreen);
  9. glfwWindowHint(GLFW_DOUBLEBUFFER, 1);
  10. glfwWindowHint(GLFW_CLIENT_API, GLFW_OPENGL_ES_API);
  11. glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 3);
  12. glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 0);
  13. GLFWmonitor* monitor = options.fullscreen ? glfwGetPrimaryMonitor() : nullptr;
  14. window = glfwCreateWindow(size.width, size.height, options.name, monitor, nullptr);
  15. if(window == nullptr) {
  16. std::cout << "could not create window\n";
  17. return;
  18. }
  19. glfwSetInputMode(window, GLFW_CURSOR, GLFW_CURSOR_HIDDEN);
  20. glfwMakeContextCurrent(window);
  21. glfwSwapInterval(options.vsync);
  22. glfwSetWindowUserPointer(window, this);
  23. glfwSetFramebufferSizeCallback(window, [](GLFWwindow* glfwWindow, int newWidth, int newHeight) {
  24. glViewport(0, 0, newWidth, newHeight);
  25. void* data = glfwGetWindowUserPointer(glfwWindow);
  26. if(data == nullptr) {
  27. return;
  28. }
  29. Window& w = *static_cast<Window*> (data);
  30. w.size.width = newWidth;
  31. w.size.height = newHeight;
  32. });
  33. glfwSetKeyCallback(window, [](GLFWwindow* glfwWindow, int key, int, int action, int) {
  34. void* data = glfwGetWindowUserPointer(glfwWindow);
  35. if(data == nullptr) {
  36. return;
  37. }
  38. Window& w = *static_cast<Window*> (data);
  39. if(action == GLFW_PRESS) {
  40. w.controller.press(key);
  41. } else if(action == GLFW_RELEASE) {
  42. w.controller.release(key);
  43. }
  44. });
  45. }
  46. Window::~Window() {
  47. if(window != nullptr) {
  48. glfwDestroyWindow(window);
  49. }
  50. }
  51. bool Window::hasError() const {
  52. return window == nullptr;
  53. }
  54. void Window::show() {
  55. glfwShowWindow(window);
  56. }
  57. bool Window::shouldClose() const {
  58. return glfwWindowShouldClose(window);
  59. }
  60. void Window::swapBuffers() {
  61. glfwSwapBuffers(window);
  62. glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
  63. }