Window.cpp 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433
  1. #include <utility>
  2. #include "GL/glew.h"
  3. #include "GLFW/glfw3.h"
  4. #include "rendering/Window.h"
  5. #include "utils/Array.h"
  6. #include "utils/HashMap.h"
  7. static GLFWwindow* window = nullptr;
  8. static Clock fps;
  9. static Clock tps;
  10. static IntVector2 size{0, 0};
  11. static bool sizeChanged = false;
  12. static List<uint32> input;
  13. static int inputCursor = 0;
  14. static int inputLimit = 256;
  15. static bool inputActive = false;
  16. struct Button final {
  17. Window::Controls::ButtonName name;
  18. int key;
  19. int downTime;
  20. int upEvents;
  21. int downEvents;
  22. int controllerUp;
  23. int controllerDown;
  24. bool released;
  25. Button(const Window::Controls::ButtonName& name)
  26. : name(name), key(0), downTime(0), upEvents(0), downEvents(0),
  27. controllerUp(0), controllerDown(0), released(false) {
  28. }
  29. void tick() {
  30. bool down = (downEvents > 0) || (controllerDown > 0);
  31. bool up = (upEvents == downEvents) && (controllerUp == controllerDown);
  32. if(released) {
  33. downTime = 0;
  34. }
  35. downTime += down;
  36. released = down && up;
  37. downEvents -= upEvents;
  38. upEvents = 0;
  39. controllerDown -= controllerUp;
  40. controllerUp = 0;
  41. }
  42. };
  43. static Button fallbackButton{"unknown"};
  44. static List<Button> buttons;
  45. static HashMap<int, Window::Controls::ButtonId> keyToButtonId;
  46. static HashMap<int, Window::Controls::ButtonId> gamepadToButtonId;
  47. static HashMap<int, Window::Controls::ButtonId> mouseToButtonId;
  48. static Vector2 lastMousePosition;
  49. static Vector2 mousePosition;
  50. static int activeController = -1;
  51. static GLFWgamepadstate lastControllerState;
  52. static void onButton(HashMap<int, Window::Controls::ButtonId>& map, int key,
  53. int action) {
  54. Window::Controls::ButtonId* b = map.search(key);
  55. if(b == nullptr) {
  56. return;
  57. }
  58. Window::Controls::ButtonId id = *b;
  59. if(id < 0 || id >= buttons.getLength()) {
  60. return;
  61. }
  62. if(action == GLFW_RELEASE) {
  63. buttons[id].upEvents++;
  64. } else if(action == GLFW_PRESS) {
  65. buttons[id].downEvents++;
  66. }
  67. }
  68. static void addError(Error& e) {
  69. const char* description = nullptr;
  70. int errorCode = glfwGetError(&description);
  71. if(errorCode == GLFW_NO_ERROR) {
  72. return;
  73. }
  74. e.message.append(": ").append(description);
  75. }
  76. static void handleInputKey(int key, int action) {
  77. if(action == GLFW_RELEASE) {
  78. return;
  79. }
  80. switch(key) {
  81. case GLFW_KEY_BACKSPACE:
  82. if(input.getLength() > inputCursor - 1 && inputCursor > 0) {
  83. input.remove(inputCursor - 1);
  84. inputCursor--;
  85. }
  86. break;
  87. case GLFW_KEY_LEFT: inputCursor -= inputCursor > 0; break;
  88. case GLFW_KEY_RIGHT:
  89. inputCursor += inputCursor < input.getLength();
  90. break;
  91. }
  92. }
  93. static void onKey(GLFWwindow*, int key, int scancode, int action, int mods) {
  94. (void)scancode;
  95. (void)mods;
  96. if(inputActive) {
  97. handleInputKey(key, action);
  98. } else {
  99. onButton(keyToButtonId, key, action);
  100. }
  101. }
  102. static void addUnicode(uint32 codepoint) {
  103. if(input.getLength() >= inputLimit) {
  104. return;
  105. }
  106. input.add(codepoint);
  107. for(int i = input.getLength() - 1; i > inputCursor; i--) {
  108. std::swap(input[i], input[i - 1]);
  109. }
  110. inputCursor++;
  111. }
  112. static void onChar(GLFWwindow*, uint32 codepoint) {
  113. if(inputActive) {
  114. addUnicode(codepoint);
  115. }
  116. }
  117. static void onResize(GLFWwindow*, int width, int height) {
  118. sizeChanged = true;
  119. size[0] = width;
  120. size[1] = height;
  121. }
  122. static void onMouse(GLFWwindow*, int button, int action, int mods) {
  123. (void)mods;
  124. onButton(mouseToButtonId, button, action);
  125. }
  126. static void onMouseMove(GLFWwindow*, double x, double y) {
  127. mousePosition = Vector2(x, y);
  128. }
  129. Error Window::open(const WindowOptions& o) {
  130. if(!glfwInit()) {
  131. Error e{"could not initialize GLFW"};
  132. addError(e);
  133. return e;
  134. }
  135. glfwDefaultWindowHints();
  136. glfwWindowHint(GLFW_VISIBLE, false);
  137. glfwWindowHint(GLFW_RESIZABLE, true);
  138. glfwWindowHint(GLFW_DECORATED, !o.fullscreen);
  139. glfwWindowHint(GLFW_DOUBLEBUFFER, true);
  140. if(o.es) {
  141. glfwWindowHint(GLFW_CLIENT_API, GLFW_OPENGL_ES_API);
  142. } else {
  143. glfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE);
  144. }
  145. glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, o.majorVersion);
  146. glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, o.minorVersion);
  147. GLFWmonitor* m = o.fullscreen ? glfwGetPrimaryMonitor() : nullptr;
  148. window = glfwCreateWindow(o.size[0], o.size[1], o.name, m, nullptr);
  149. if(window == nullptr) {
  150. Error e{"could not create window"};
  151. addError(e);
  152. close();
  153. return e;
  154. }
  155. size = o.size;
  156. glfwSetKeyCallback(window, onKey);
  157. glfwSetCharCallback(window, onChar);
  158. glfwSetFramebufferSizeCallback(window, onResize);
  159. glfwSetMouseButtonCallback(window, onMouse);
  160. glfwSetCursorPosCallback(window, onMouseMove);
  161. glfwMakeContextCurrent(window);
  162. glfwSwapInterval(o.vsync);
  163. GLenum err = glewInit();
  164. if(err != GLEW_OK) {
  165. Error e{"could not initialize GLEW: "};
  166. e.message.append(glewGetErrorString(err));
  167. close();
  168. return e;
  169. }
  170. return {};
  171. }
  172. void Window::close() {
  173. if(window != nullptr) {
  174. glfwDestroyWindow(window);
  175. window = nullptr;
  176. }
  177. glfwTerminate();
  178. }
  179. float Window::getTicksPerSecond() {
  180. return tps.getUpdatesPerSecond();
  181. }
  182. float Window::getFramesPerSecond() {
  183. return fps.getUpdatesPerSecond();
  184. }
  185. const IntVector2& Window::getSize() {
  186. return size;
  187. }
  188. bool Window::hasSizeChanged() {
  189. return sizeChanged;
  190. }
  191. void Window::trapCursor() {
  192. glfwSetInputMode(window, GLFW_CURSOR, GLFW_CURSOR_DISABLED);
  193. }
  194. void Window::freeCursor() {
  195. glfwSetInputMode(window, GLFW_CURSOR, GLFW_CURSOR_NORMAL);
  196. }
  197. void Window::show() {
  198. glfwShowWindow(window);
  199. }
  200. bool Window::shouldClose() {
  201. return glfwWindowShouldClose(window);
  202. }
  203. Clock::Nanos Window::startFrame() {
  204. return fps.update();
  205. }
  206. static bool searchForGamepad() {
  207. if(activeController != -1) {
  208. return true;
  209. }
  210. for(int i = GLFW_JOYSTICK_1; i <= GLFW_JOYSTICK_LAST; i++) {
  211. if(glfwJoystickIsGamepad(i)) {
  212. activeController = i;
  213. return true;
  214. }
  215. }
  216. return false;
  217. }
  218. static void checkGamepad() {
  219. GLFWgamepadstate state;
  220. if(!glfwGetGamepadState(activeController, &state)) {
  221. activeController = -1;
  222. return;
  223. }
  224. for(int i = 0; i <= GLFW_GAMEPAD_BUTTON_LAST; i++) {
  225. Window::Controls::ButtonId* idp = gamepadToButtonId.search(i);
  226. if(idp == nullptr) {
  227. continue;
  228. }
  229. Window::Controls::ButtonId id = *idp;
  230. if(id < 0 || id >= buttons.getLength()) {
  231. continue;
  232. }
  233. if(!lastControllerState.buttons[i] && state.buttons[i]) {
  234. buttons[id].controllerDown++;
  235. } else if(lastControllerState.buttons[i] && !state.buttons[i]) {
  236. buttons[id].controllerUp++;
  237. }
  238. }
  239. lastControllerState = state;
  240. }
  241. void Window::endFrame() {
  242. glfwSwapBuffers(window);
  243. sizeChanged = false;
  244. glfwPollEvents();
  245. if(searchForGamepad()) {
  246. checkGamepad();
  247. }
  248. }
  249. void Window::tick() {
  250. tps.update();
  251. lastMousePosition = mousePosition;
  252. for(Button& b : buttons) {
  253. b.tick();
  254. }
  255. }
  256. void Window::Input::setLimit(int l) {
  257. inputLimit = l;
  258. while(input.getLength() > inputLimit) {
  259. input.removeBySwap(inputLimit);
  260. }
  261. }
  262. void Window::Input::reset() {
  263. input.clear();
  264. inputCursor = 0;
  265. }
  266. void Window::Input::enable() {
  267. inputActive = true;
  268. }
  269. void Window::Input::disable() {
  270. inputActive = false;
  271. }
  272. static uint32 read(int& index, const char* s) {
  273. if(s[index] == '\0') {
  274. return '\0';
  275. }
  276. return s[index++];
  277. }
  278. static uint32 readUnicode(int& index, const char* s) {
  279. uint32 c = read(index, s);
  280. if((c & 0xE0) == 0xC0) {
  281. c = ((c & 0x1F) << 6) | (read(index, s) & 0x3F);
  282. } else if((c & 0xF0) == 0xE0) {
  283. c = ((c & 0xF) << 12) | ((read(index, s) & 0x3F) << 6);
  284. c |= read(index, s) & 0x3F;
  285. } else if((c & 0xF8) == 0xF0) {
  286. c = ((c & 0x7) << 18) | ((read(index, s) & 0x3F) << 12);
  287. c |= (read(index, s) & 0x3F) << 6;
  288. c |= read(index, s) & 0x3F;
  289. }
  290. return c;
  291. }
  292. void Window::Input::fill(const char* s) {
  293. int index = 0;
  294. reset();
  295. while(true) {
  296. uint32 c = readUnicode(index, s);
  297. if(c == '\0') {
  298. break;
  299. }
  300. addUnicode(c);
  301. }
  302. }
  303. int Window::Input::getCursor() {
  304. return inputCursor;
  305. }
  306. void Window::Input::setCursor(int index) {
  307. if(index < 0) {
  308. inputCursor = 0;
  309. } else if(index > input.getLength()) {
  310. inputCursor = input.getLength();
  311. } else {
  312. inputCursor = index;
  313. }
  314. }
  315. const List<uint32>& Window::Input::getUnicode() {
  316. return input;
  317. }
  318. Window::Controls::ButtonId Window::Controls::add(const ButtonName& name) {
  319. ButtonId id = buttons.getLength();
  320. buttons.add(name);
  321. return id;
  322. }
  323. void Window::Controls::bindKey(ButtonId id, int key) {
  324. keyToButtonId.add(key, id);
  325. }
  326. void Window::Controls::bindGamepad(ButtonId id, int gamepadButton) {
  327. gamepadToButtonId.add(gamepadButton, id);
  328. }
  329. void Window::Controls::bindMouse(ButtonId id, int mouseButton) {
  330. mouseToButtonId.add(mouseButton, id);
  331. }
  332. Vector2 Window::Controls::getLastMousePosition() {
  333. return lastMousePosition;
  334. }
  335. Vector2 Window::Controls::getMousePosition() {
  336. return mousePosition;
  337. }
  338. Vector2 Window::Controls::getLeftGamepadAxis() {
  339. return Vector2(lastControllerState.axes[GLFW_GAMEPAD_AXIS_LEFT_X],
  340. lastControllerState.axes[GLFW_GAMEPAD_AXIS_LEFT_Y]);
  341. }
  342. Vector2 Window::Controls::getRightGamepadAxis() {
  343. return Vector2(lastControllerState.axes[GLFW_GAMEPAD_AXIS_RIGHT_X],
  344. lastControllerState.axes[GLFW_GAMEPAD_AXIS_RIGHT_Y]);
  345. }
  346. float Window::Controls::getLeftGamepadTrigger() {
  347. return lastControllerState.axes[GLFW_GAMEPAD_AXIS_LEFT_TRIGGER];
  348. }
  349. float Window::Controls::getRightGamepadTrigger() {
  350. return lastControllerState.axes[GLFW_GAMEPAD_AXIS_RIGHT_TRIGGER];
  351. }
  352. static const Button& getButton(Window::Controls::ButtonId id) {
  353. if(id < 0 || id >= buttons.getLength()) {
  354. return fallbackButton;
  355. }
  356. return buttons[id];
  357. }
  358. bool Window::Controls::isDown(ButtonId id) {
  359. return getButton(id).downTime > 0;
  360. }
  361. int Window::Controls::getDownTime(ButtonId id) {
  362. return getButton(id).downTime;
  363. }
  364. bool Window::Controls::wasReleased(ButtonId id) {
  365. return getButton(id).released;
  366. }
  367. const Window::Controls::ButtonName& Window::Controls::getName(ButtonId id) {
  368. return getButton(id).name;
  369. }