Window.cpp 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442
  1. #include <utility>
  2. #include "GL/glew.h"
  3. #include "GLFW/glfw3.h"
  4. #include "data/Array.h"
  5. #include "data/HashMap.h"
  6. #include "rendering/Window.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. for(Button& b : buttons) {
  257. b.tick();
  258. }
  259. }
  260. void Window::postTick() {
  261. lastMousePosition = mousePosition;
  262. }
  263. void Window::Input::setLimit(int l) {
  264. inputLimit = l;
  265. while(input.getLength() > inputLimit) {
  266. input.removeBySwap(inputLimit);
  267. }
  268. }
  269. void Window::Input::reset() {
  270. input.clear();
  271. inputCursor = 0;
  272. }
  273. void Window::Input::enable() {
  274. inputActive = true;
  275. }
  276. void Window::Input::disable() {
  277. inputActive = false;
  278. }
  279. static uint32 read(int& index, const char* s) {
  280. if(s[index] == '\0') {
  281. return '\0';
  282. }
  283. return s[index++];
  284. }
  285. static uint32 readUnicode(int& index, const char* s) {
  286. uint32 c = read(index, s);
  287. if((c & 0xE0) == 0xC0) {
  288. c = ((c & 0x1F) << 6) | (read(index, s) & 0x3F);
  289. } else if((c & 0xF0) == 0xE0) {
  290. c = ((c & 0xF) << 12) | ((read(index, s) & 0x3F) << 6);
  291. c |= read(index, s) & 0x3F;
  292. } else if((c & 0xF8) == 0xF0) {
  293. c = ((c & 0x7) << 18) | ((read(index, s) & 0x3F) << 12);
  294. c |= (read(index, s) & 0x3F) << 6;
  295. c |= read(index, s) & 0x3F;
  296. }
  297. return c;
  298. }
  299. void Window::Input::fill(const char* s) {
  300. int index = 0;
  301. reset();
  302. while(true) {
  303. uint32 c = readUnicode(index, s);
  304. if(c == '\0') {
  305. break;
  306. }
  307. addUnicode(c);
  308. }
  309. }
  310. int Window::Input::getCursor() {
  311. return inputCursor;
  312. }
  313. void Window::Input::setCursor(int index) {
  314. if(index < 0) {
  315. inputCursor = 0;
  316. } else if(index > input.getLength()) {
  317. inputCursor = input.getLength();
  318. } else {
  319. inputCursor = index;
  320. }
  321. }
  322. const List<uint32>& Window::Input::getUnicode() {
  323. return input;
  324. }
  325. Window::Controls::ButtonId Window::Controls::add(const ButtonName& name) {
  326. ButtonId id = buttons.getLength();
  327. buttons.add(name);
  328. return id;
  329. }
  330. void Window::Controls::bindKey(ButtonId id, int key) {
  331. keyToButtonId.add(key, id);
  332. }
  333. void Window::Controls::bindGamepad(ButtonId id, int gamepadButton) {
  334. gamepadToButtonId.add(gamepadButton, id);
  335. }
  336. void Window::Controls::bindMouse(ButtonId id, int mouseButton) {
  337. mouseToButtonId.add(mouseButton, id);
  338. }
  339. Vector2 Window::Controls::getLastMousePosition() {
  340. return lastMousePosition;
  341. }
  342. Vector2 Window::Controls::getMousePosition() {
  343. return mousePosition;
  344. }
  345. Vector2 Window::Controls::getLeftGamepadAxis() {
  346. return Vector2(lastControllerState.axes[GLFW_GAMEPAD_AXIS_LEFT_X],
  347. lastControllerState.axes[GLFW_GAMEPAD_AXIS_LEFT_Y]);
  348. }
  349. Vector2 Window::Controls::getRightGamepadAxis() {
  350. return Vector2(lastControllerState.axes[GLFW_GAMEPAD_AXIS_RIGHT_X],
  351. lastControllerState.axes[GLFW_GAMEPAD_AXIS_RIGHT_Y]);
  352. }
  353. float Window::Controls::getLeftGamepadTrigger() {
  354. return lastControllerState.axes[GLFW_GAMEPAD_AXIS_LEFT_TRIGGER];
  355. }
  356. float Window::Controls::getRightGamepadTrigger() {
  357. return lastControllerState.axes[GLFW_GAMEPAD_AXIS_RIGHT_TRIGGER];
  358. }
  359. static const Button& getButton(Window::Controls::ButtonId id) {
  360. if(id < 0 || id >= buttons.getLength()) {
  361. return fallbackButton;
  362. }
  363. return buttons[id];
  364. }
  365. bool Window::Controls::isDown(ButtonId id) {
  366. return getButton(id).downTime > 0;
  367. }
  368. int Window::Controls::getDownTime(ButtonId id) {
  369. return getButton(id).downTime;
  370. }
  371. bool Window::Controls::wasReleased(ButtonId id) {
  372. return getButton(id).released;
  373. }
  374. const Window::Controls::ButtonName& Window::Controls::getName(ButtonId id) {
  375. return getButton(id).name;
  376. }