Window.cpp 11 KB

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