Window.cpp 11 KB

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