window.cpp 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119
  1. #include "window.h"
  2. #include <logs/assert.h>
  3. #include "callbacks.h"
  4. void pika::PikaWindow::create()
  5. {
  6. context.wind = glfwCreateWindow(640, 480, "Pika", NULL, NULL);
  7. windowState.hasFocus = true;
  8. PIKA_PERMA_ASSERT(context.wind, "problem initializing window");
  9. glfwMakeContextCurrent(context.wind);
  10. glfwSetWindowUserPointer(context.wind, this);
  11. glfwSetMouseButtonCallback(context.wind, mouseCallback);
  12. glfwSetWindowFocusCallback(context.wind, windowFocusCallback);
  13. glfwSetKeyCallback(context.wind, keyCallback);
  14. timer = std::chrono::high_resolution_clock::now();
  15. }
  16. bool pika::PikaWindow::shouldClose()
  17. {
  18. return glfwWindowShouldClose(context.wind);
  19. }
  20. void pika::PikaWindow::update()
  21. {
  22. #pragma region deltaTime
  23. auto end = std::chrono::high_resolution_clock::now();
  24. deltaTime = (std::chrono::duration_cast<std::chrono::microseconds>(end - timer)).count() / 1000000.0f;
  25. timer = end;
  26. if (deltaTime > 1.f / 10) { deltaTime = 1.f / 10; }
  27. #pragma endregion
  28. #pragma region input
  29. auto processInputBefore = [](pika::Button &b)
  30. {
  31. b.setTyped(false);
  32. };
  33. processInputBefore(input.lMouse);
  34. processInputBefore(input.rMouse);
  35. for (int i = 0; i < Button::BUTTONS_COUNT; i++)
  36. {
  37. processInputBefore(input.buttons[i]);
  38. }
  39. #pragma endregion
  40. glfwPollEvents();
  41. glfwSwapBuffers(context.wind);
  42. #pragma region window state
  43. {
  44. int w = 0;
  45. int h = 0;
  46. glfwGetWindowSize(context.wind, &w, &h);
  47. windowState.w = w;
  48. windowState.h = h;
  49. }
  50. #pragma endregion
  51. #pragma region input
  52. double mouseX = 0;
  53. double mouseY = 0;
  54. glfwGetCursorPos(context.wind, &mouseX, &mouseY);
  55. input.mouseX = (int)mouseX;
  56. input.mouseY = (int)mouseY;
  57. auto processInput = [](pika::Button &b)
  58. {
  59. if (!b.lastState() && b.held())
  60. {
  61. b.setPressed(true);
  62. }
  63. else
  64. {
  65. b.setPressed(false);
  66. }
  67. if (b.lastState() && !b.held())
  68. {
  69. b.setReleased(true);
  70. }
  71. else
  72. {
  73. b.setReleased(false);
  74. }
  75. b.setLastState(b.held());
  76. };
  77. processInput(input.lMouse);
  78. processInput(input.rMouse);
  79. for (int i = 0; i < Button::BUTTONS_COUNT; i++)
  80. {
  81. processInput(input.buttons[i]);
  82. }
  83. #pragma endregion
  84. }