Window.cpp 11 KB

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