💿🐜 Antkeeper source code https://antkeeper.com
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

729 lines
18 KiB

  1. /*
  2. * Copyright (C) 2021 Christopher J. Howard
  3. *
  4. * This file is part of Antkeeper source code.
  5. *
  6. * Antkeeper source code is free software: you can redistribute it and/or modify
  7. * it under the terms of the GNU General Public License as published by
  8. * the Free Software Foundation, either version 3 of the License, or
  9. * (at your option) any later version.
  10. *
  11. * Antkeeper source code is distributed in the hope that it will be useful,
  12. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  13. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  14. * GNU General Public License for more details.
  15. *
  16. * You should have received a copy of the GNU General Public License
  17. * along with Antkeeper source code. If not, see <http://www.gnu.org/licenses/>.
  18. */
  19. #include "animation/frame-scheduler.hpp"
  20. #include "application.hpp"
  21. #include "debug/logger.hpp"
  22. #include "debug/performance-sampler.hpp"
  23. #include "event/event-dispatcher.hpp"
  24. #include "event/window-events.hpp"
  25. #include "input/scancode.hpp"
  26. #include "input/sdl-game-controller-tables.hpp"
  27. #include "input/sdl-scancode-table.hpp"
  28. #include "resources/image.hpp"
  29. #include <SDL2/SDL.h>
  30. #include <glad/glad.h>
  31. #include <stdexcept>
  32. #include <utility>
  33. #include <thread>
  34. #include <stb/stb_image_write.h>
  35. #include <iostream>
  36. #include <iomanip>
  37. application::application():
  38. closed(false),
  39. exit_status(EXIT_SUCCESS),
  40. current_state{std::string(), nullptr, nullptr},
  41. queued_state{std::string(), nullptr, nullptr},
  42. update_callback(nullptr),
  43. render_callback(nullptr),
  44. fullscreen(true),
  45. vsync(true),
  46. cursor_visible(true),
  47. display_dimensions({0, 0}),
  48. window_dimensions({0, 0}),
  49. viewport_dimensions({0, 0}),
  50. mouse_position({0, 0}),
  51. update_rate(60.0),
  52. logger(nullptr),
  53. sdl_window(nullptr),
  54. sdl_gl_context(nullptr)
  55. {
  56. // Setup logging
  57. logger = new debug::logger();
  58. // Get SDL compiled version
  59. SDL_version sdl_compiled_version;
  60. SDL_VERSION(&sdl_compiled_version);
  61. std::string sdl_compiled_version_string = std::to_string(sdl_compiled_version.major) + "." + std::to_string(sdl_compiled_version.minor) + "." + std::to_string(sdl_compiled_version.patch);
  62. logger->log("Compiled against SDL " + sdl_compiled_version_string);
  63. // Get SDL linked version
  64. SDL_version sdl_linked_version;
  65. SDL_GetVersion(&sdl_linked_version);
  66. std::string sdl_linked_version_string = std::to_string(sdl_linked_version.major) + "." + std::to_string(sdl_linked_version.minor) + "." + std::to_string(sdl_linked_version.patch);
  67. logger->log("Linking against SDL " + sdl_linked_version_string);
  68. // Init SDL
  69. logger->push_task("Initializing SDL");
  70. if (SDL_Init(SDL_INIT_VIDEO) != 0)
  71. {
  72. logger->pop_task(EXIT_FAILURE);
  73. throw std::runtime_error("Failed to initialize SDL");
  74. }
  75. else
  76. {
  77. logger->pop_task(EXIT_SUCCESS);
  78. }
  79. // Load default OpenGL library
  80. logger->push_task("Loading OpenGL library");
  81. if (SDL_GL_LoadLibrary(nullptr) != 0)
  82. {
  83. logger->pop_task(EXIT_FAILURE);
  84. }
  85. else
  86. {
  87. logger->pop_task(EXIT_SUCCESS);
  88. }
  89. // Set window creation hints
  90. SDL_GL_SetAttribute(SDL_GL_ACCELERATED_VISUAL, 1);
  91. SDL_GL_SetAttribute(SDL_GL_CONTEXT_MAJOR_VERSION, 3);
  92. SDL_GL_SetAttribute(SDL_GL_CONTEXT_MINOR_VERSION, 3);
  93. SDL_GL_SetAttribute(SDL_GL_DOUBLEBUFFER, 1);
  94. SDL_GL_SetAttribute(SDL_GL_DEPTH_SIZE, 24);
  95. // Get display dimensions
  96. SDL_DisplayMode sdl_desktop_display_mode;
  97. if (SDL_GetDesktopDisplayMode(0, &sdl_desktop_display_mode) != 0)
  98. {
  99. logger->error("Failed to get desktop display mode: \"" + std::string(SDL_GetError()) + "\"");
  100. throw std::runtime_error("Failed to detect desktop display mode");
  101. }
  102. else
  103. {
  104. logger->log("Detected " + std::to_string(sdl_desktop_display_mode.w) + "x" + std::to_string(sdl_desktop_display_mode.h) + " display");
  105. display_dimensions = {sdl_desktop_display_mode.w, sdl_desktop_display_mode.h};
  106. }
  107. // Create a hidden fullscreen window
  108. logger->push_task("Creating " + std::to_string(display_dimensions[0]) + "x" + std::to_string(display_dimensions[1]) + " window");
  109. sdl_window = SDL_CreateWindow
  110. (
  111. "",
  112. SDL_WINDOWPOS_CENTERED, SDL_WINDOWPOS_CENTERED,
  113. display_dimensions[0], display_dimensions[1],
  114. SDL_WINDOW_OPENGL | SDL_WINDOW_FULLSCREEN_DESKTOP | SDL_WINDOW_ALLOW_HIGHDPI | SDL_WINDOW_HIDDEN
  115. );
  116. if (!sdl_window)
  117. {
  118. logger->pop_task(EXIT_FAILURE);
  119. throw std::runtime_error("Failed to create SDL window");
  120. }
  121. else
  122. {
  123. logger->pop_task(EXIT_SUCCESS);
  124. }
  125. // Create OpenGL context
  126. logger->push_task("Creating OpenGL 3.3 context");
  127. sdl_gl_context = SDL_GL_CreateContext(sdl_window);
  128. if (!sdl_gl_context)
  129. {
  130. logger->pop_task(EXIT_FAILURE);
  131. throw std::runtime_error("Failed to create OpenGL context");
  132. }
  133. else
  134. {
  135. logger->pop_task(EXIT_SUCCESS);
  136. }
  137. // Update window size and viewport size
  138. SDL_GetWindowSize(sdl_window, &window_dimensions[0], &window_dimensions[1]);
  139. SDL_GL_GetDrawableSize(sdl_window, &viewport_dimensions[0], &viewport_dimensions[1]);
  140. // Load OpenGL functions via GLAD
  141. logger->push_task("Loading OpenGL functions");
  142. if (!gladLoadGLLoader((GLADloadproc)SDL_GL_GetProcAddress))
  143. {
  144. logger->pop_task(EXIT_FAILURE);
  145. throw std::runtime_error("Failed to load OpenGL functions");
  146. }
  147. else
  148. {
  149. logger->pop_task(EXIT_SUCCESS);
  150. }
  151. // Set v-sync mode
  152. int swap_interval = (vsync) ? 1 : 0;
  153. logger->push_task((swap_interval) ? "Enabling v-sync" : "Disabling v-sync");
  154. if (SDL_GL_SetSwapInterval(swap_interval) != 0)
  155. {
  156. logger->pop_task(EXIT_FAILURE);
  157. }
  158. else
  159. {
  160. logger->pop_task(EXIT_SUCCESS);
  161. }
  162. // Init SDL joystick and game controller subsystems
  163. logger->push_task("Initializing SDL Joystick and Game Controller subsystems");
  164. if (SDL_InitSubSystem(SDL_INIT_JOYSTICK | SDL_INIT_GAMECONTROLLER) != 0)
  165. {
  166. logger->pop_task(EXIT_FAILURE);
  167. }
  168. else
  169. {
  170. logger->pop_task(EXIT_SUCCESS);
  171. }
  172. // Load SDL game controller mappings
  173. /*
  174. logger->push_task("Loading SDL game controller mappings from database");
  175. std::string gamecontrollerdb_path = data_path + "controls/gamecontrollerdb.txt";
  176. if (SDL_GameControllerAddMappingsFromFile(gamecontrollerdb_path.c_str()) == -1)
  177. {
  178. logger->pop_task(EXIT_FAILURE);
  179. }
  180. else
  181. {
  182. logger->pop_task(EXIT_SUCCESS);
  183. }
  184. */
  185. // Setup rasterizer
  186. rasterizer = new gl::rasterizer();
  187. // Setup events
  188. event_dispatcher = new ::event_dispatcher();
  189. // Setup input
  190. keyboard = new input::keyboard();
  191. keyboard->set_event_dispatcher(event_dispatcher);
  192. mouse = new input::mouse();
  193. mouse->set_event_dispatcher(event_dispatcher);
  194. // Setup frame scheduler
  195. frame_scheduler = new ::frame_scheduler();
  196. frame_scheduler->set_update_callback(std::bind(&application::update, this, std::placeholders::_1, std::placeholders::_2));
  197. frame_scheduler->set_render_callback(std::bind(&application::render, this, std::placeholders::_1));
  198. frame_scheduler->set_update_rate(update_rate);
  199. frame_scheduler->set_max_frame_duration(0.25);
  200. // Setup performance sampling
  201. performance_sampler = new debug::performance_sampler();
  202. performance_sampler->set_sample_size(15);
  203. }
  204. application::~application()
  205. {
  206. // Destroy the OpenGL context
  207. SDL_GL_DeleteContext(sdl_gl_context);
  208. // Destroy the SDL window
  209. SDL_DestroyWindow(sdl_window);
  210. // Shutdown SDL
  211. SDL_QuitSubSystem(SDL_INIT_VIDEO | SDL_INIT_JOYSTICK | SDL_INIT_GAMECONTROLLER);
  212. SDL_Quit();
  213. }
  214. void application::close(int status)
  215. {
  216. closed = true;
  217. exit_status = status;
  218. }
  219. int application::execute(bootloader_type bootloader)
  220. {
  221. try
  222. {
  223. // Execute bootloader
  224. if (bootloader)
  225. {
  226. exit_status = bootloader(this);
  227. if (exit_status != EXIT_SUCCESS)
  228. {
  229. return exit_status;
  230. }
  231. }
  232. // Show window
  233. SDL_ShowWindow(sdl_window);
  234. // Clear window
  235. rasterizer->clear_framebuffer(true, false, false);
  236. SDL_GL_SwapWindow(sdl_window);
  237. // Perform initial update
  238. update(0.0, 0.0);
  239. // Reset frame scheduler
  240. frame_scheduler->reset();
  241. // Schedule frames until closed
  242. while (!closed)
  243. {
  244. // Tick frame scheduler
  245. frame_scheduler->tick();
  246. // Sample frame duration
  247. performance_sampler->sample(frame_scheduler->get_frame_duration());
  248. }
  249. // Exit current state
  250. change_state({std::string(), nullptr, nullptr});
  251. }
  252. catch (const std::exception& e)
  253. {
  254. // Print exception to logger
  255. logger->error(std::string("Unhandled exception: \"") + e.what() + std::string("\""));
  256. // Show error message box with unhandled exception
  257. SDL_ShowSimpleMessageBox
  258. (
  259. SDL_MESSAGEBOX_ERROR,
  260. "Unhandled Exception",
  261. e.what(),
  262. sdl_window
  263. );
  264. // Set exit status to failure
  265. exit_status = EXIT_FAILURE;
  266. }
  267. return exit_status;
  268. }
  269. void application::change_state(const application::state& next_state)
  270. {
  271. // Exit current state
  272. if (current_state.exit)
  273. {
  274. logger->push_task("Exiting application state \"" + current_state.name + "\"");
  275. try
  276. {
  277. current_state.exit();
  278. }
  279. catch (...)
  280. {
  281. logger->pop_task(EXIT_FAILURE);
  282. throw;
  283. }
  284. logger->pop_task(EXIT_SUCCESS);
  285. }
  286. current_state = next_state;
  287. // Enter next state
  288. if (current_state.enter)
  289. {
  290. logger->push_task("Entering application state \"" + current_state.name + "\"");
  291. try
  292. {
  293. current_state.enter();
  294. }
  295. catch (...)
  296. {
  297. logger->pop_task(EXIT_FAILURE);
  298. throw;
  299. }
  300. logger->pop_task(EXIT_SUCCESS);
  301. }
  302. // Enter queued state (if any)
  303. if (queued_state.enter != nullptr || queued_state.exit != nullptr)
  304. {
  305. // Make a copy of the queued state
  306. application::state queued_state_copy = queued_state;
  307. // Clear the queued state
  308. queued_state = {std::string(), nullptr, nullptr};
  309. // Enter the queued state
  310. change_state(queued_state_copy);
  311. }
  312. }
  313. void application::queue_state(const application::state& next_state)
  314. {
  315. queued_state = next_state;
  316. logger->log("Queued application state \"" + queued_state.name + "\"");
  317. }
  318. std::shared_ptr<image> application::capture_frame() const
  319. {
  320. int w = viewport_dimensions[0];
  321. int h = viewport_dimensions[1];
  322. std::shared_ptr<image> frame = std::make_shared<image>();
  323. frame->format(3, false);
  324. frame->resize(w, h);
  325. // Read pixel data from framebuffer into image
  326. glReadBuffer(GL_BACK);
  327. glReadPixels(0, 0, w, h, GL_RGB, GL_UNSIGNED_BYTE, frame->get_pixels());
  328. return std::move(frame);
  329. }
  330. void application::save_frame(const std::string& path) const
  331. {
  332. logger->push_task("Saving screenshot to \"" + path + "\"");
  333. auto frame = capture_frame();
  334. std::thread
  335. (
  336. [frame, path]
  337. {
  338. stbi_flip_vertically_on_write(1);
  339. stbi_write_png(path.c_str(), frame->get_width(), frame->get_height(), frame->get_channels(), frame->get_pixels(), frame->get_width() * frame->get_channels());
  340. }
  341. ).detach();
  342. logger->pop_task(EXIT_SUCCESS);
  343. }
  344. void application::set_update_callback(const update_callback_type& callback)
  345. {
  346. update_callback = callback;
  347. }
  348. void application::set_render_callback(const render_callback_type& callback)
  349. {
  350. render_callback = callback;
  351. }
  352. void application::set_update_rate(double frequency)
  353. {
  354. update_rate = frequency;
  355. frame_scheduler->set_update_rate(update_rate);
  356. }
  357. void application::set_title(const std::string& title)
  358. {
  359. SDL_SetWindowTitle(sdl_window, title.c_str());
  360. }
  361. void application::set_cursor_visible(bool visible)
  362. {
  363. SDL_ShowCursor((visible) ? SDL_ENABLE : SDL_DISABLE);
  364. cursor_visible = visible;
  365. }
  366. void application::set_relative_mouse_mode(bool enabled)
  367. {
  368. if (enabled)
  369. {
  370. SDL_GetMouseState(&mouse_position[0], &mouse_position[1]);
  371. SDL_ShowCursor(SDL_DISABLE);
  372. SDL_SetRelativeMouseMode(SDL_TRUE);
  373. }
  374. else
  375. {
  376. SDL_SetRelativeMouseMode(SDL_FALSE);
  377. SDL_WarpMouseInWindow(sdl_window, mouse_position[0], mouse_position[1]);
  378. if (cursor_visible)
  379. SDL_ShowCursor(SDL_ENABLE);
  380. }
  381. }
  382. void application::resize_window(int width, int height)
  383. {
  384. int x = (display_dimensions[0] >> 1) - (width >> 1);
  385. int y = (display_dimensions[1] >> 1) - (height >> 1);
  386. // Resize and center window
  387. SDL_SetWindowPosition(sdl_window, x, y);
  388. SDL_SetWindowSize(sdl_window, width, height);
  389. window_resized();
  390. }
  391. void application::set_fullscreen(bool fullscreen)
  392. {
  393. if (this->fullscreen != fullscreen)
  394. {
  395. this->fullscreen = fullscreen;
  396. if (fullscreen)
  397. {
  398. SDL_HideWindow(sdl_window);
  399. SDL_SetWindowFullscreen(sdl_window, SDL_WINDOW_FULLSCREEN_DESKTOP);
  400. SDL_ShowWindow(sdl_window);
  401. }
  402. else
  403. {
  404. SDL_SetWindowFullscreen(sdl_window, 0);
  405. SDL_SetWindowBordered(sdl_window, SDL_TRUE);
  406. SDL_SetWindowResizable(sdl_window, SDL_TRUE);
  407. }
  408. }
  409. }
  410. void application::set_vsync(bool vsync)
  411. {
  412. if (this->vsync != vsync)
  413. {
  414. this->vsync = vsync;
  415. SDL_GL_SetSwapInterval((vsync) ? 1 : 0);
  416. }
  417. }
  418. void application::set_window_opacity(float opacity)
  419. {
  420. SDL_SetWindowOpacity(sdl_window, opacity);
  421. }
  422. void application::swap_buffers()
  423. {
  424. SDL_GL_SwapWindow(sdl_window);
  425. }
  426. void application::update(double t, double dt)
  427. {
  428. translate_sdl_events();
  429. event_dispatcher->update(t);
  430. if (update_callback)
  431. {
  432. update_callback(t, dt);
  433. }
  434. /*
  435. static int frame = 0;
  436. if (frame % 60 == 0)
  437. {
  438. std::cout << std::fixed;
  439. std::cout << std::setprecision(2);
  440. std::cout << performance_sampler->mean_frame_duration() * 1000.0 << "\n";
  441. }
  442. ++frame;
  443. */
  444. }
  445. void application::render(double alpha)
  446. {
  447. /*
  448. std::cout << std::fixed;
  449. std::cout << std::setprecision(2);
  450. std::cout << performance_sampler->mean_frame_duration() * 1000.0 << std::endl;
  451. */
  452. if (render_callback)
  453. {
  454. render_callback(alpha);
  455. }
  456. SDL_GL_SwapWindow(sdl_window);
  457. }
  458. void application::translate_sdl_events()
  459. {
  460. // Mouse motion event accumulators
  461. bool mouse_motion = false;
  462. int mouse_x;
  463. int mouse_y;
  464. int mouse_dx = 0;
  465. int mouse_dy = 0;
  466. SDL_Event sdl_event;
  467. while (SDL_PollEvent(&sdl_event))
  468. {
  469. switch (sdl_event.type)
  470. {
  471. case SDL_KEYDOWN:
  472. case SDL_KEYUP:
  473. {
  474. if (sdl_event.key.repeat == 0)
  475. {
  476. input::scancode scancode = input::scancode::unknown;
  477. if (sdl_event.key.keysym.scancode <= SDL_SCANCODE_APP2)
  478. {
  479. scancode = input::sdl_scancode_table[sdl_event.key.keysym.scancode];
  480. }
  481. if (sdl_event.type == SDL_KEYDOWN)
  482. keyboard->press(scancode);
  483. else
  484. keyboard->release(scancode);
  485. }
  486. break;
  487. }
  488. case SDL_MOUSEMOTION:
  489. {
  490. // More than one mouse motion event is often generated per frame, and may be a source of lag.
  491. // Mouse events are accumulated here to prevent excess function calls and allocations
  492. mouse_motion = true;
  493. mouse_x = sdl_event.motion.x;
  494. mouse_y = sdl_event.motion.y;
  495. mouse_dx += sdl_event.motion.xrel;
  496. mouse_dy += sdl_event.motion.yrel;
  497. break;
  498. }
  499. case SDL_MOUSEBUTTONDOWN:
  500. {
  501. mouse->press(sdl_event.button.button, sdl_event.button.x, sdl_event.button.y);
  502. break;
  503. }
  504. case SDL_MOUSEBUTTONUP:
  505. {
  506. mouse->release(sdl_event.button.button, sdl_event.button.x, sdl_event.button.y);
  507. break;
  508. }
  509. case SDL_MOUSEWHEEL:
  510. {
  511. int direction = (sdl_event.wheel.direction == SDL_MOUSEWHEEL_FLIPPED) ? -1 : 1;
  512. mouse->scroll(sdl_event.wheel.x * direction, sdl_event.wheel.y * direction);
  513. break;
  514. }
  515. case SDL_CONTROLLERBUTTONDOWN:
  516. {
  517. if (sdl_event.cbutton.button != SDL_CONTROLLER_BUTTON_INVALID)
  518. {
  519. if (auto it = game_controller_map.find(sdl_event.cdevice.which); it != game_controller_map.end())
  520. {
  521. input::game_controller_button button = input::sdl_button_table[sdl_event.cbutton.button];
  522. it->second->press(button);
  523. }
  524. }
  525. break;
  526. }
  527. case SDL_CONTROLLERBUTTONUP:
  528. {
  529. if (sdl_event.cbutton.button != SDL_CONTROLLER_BUTTON_INVALID)
  530. {
  531. if (auto it = game_controller_map.find(sdl_event.cdevice.which); it != game_controller_map.end())
  532. {
  533. input::game_controller_button button = input::sdl_button_table[sdl_event.cbutton.button];
  534. it->second->release(button);
  535. }
  536. }
  537. break;
  538. }
  539. case SDL_CONTROLLERAXISMOTION:
  540. {
  541. if (sdl_event.caxis.axis != SDL_CONTROLLER_AXIS_INVALID)
  542. {
  543. if (auto it = game_controller_map.find(sdl_event.cdevice.which); it != game_controller_map.end())
  544. {
  545. input::game_controller_axis axis = input::sdl_axis_table[sdl_event.caxis.axis];
  546. float value = sdl_event.caxis.value;
  547. value /= (value < 0.0f) ? 32768.0f : 32767.0f;
  548. it->second->move(axis, value);
  549. }
  550. }
  551. break;
  552. }
  553. case SDL_CONTROLLERDEVICEADDED:
  554. {
  555. if (SDL_IsGameController(sdl_event.cdevice.which))
  556. {
  557. SDL_GameController* sdl_controller = SDL_GameControllerOpen(sdl_event.cdevice.which);
  558. std::string controller_name = SDL_GameControllerNameForIndex(sdl_event.cdevice.which);
  559. if (sdl_controller)
  560. {
  561. if (auto it = game_controller_map.find(sdl_event.cdevice.which); it != game_controller_map.end())
  562. {
  563. logger->log("Reconnected game controller \"" + controller_name + "\"");
  564. it->second->connect(true);
  565. }
  566. else
  567. {
  568. logger->log("Connected game controller \"" + controller_name + "\"");
  569. input::game_controller* controller = new input::game_controller();
  570. controller->set_event_dispatcher(event_dispatcher);
  571. game_controllers.push_back(controller);
  572. game_controller_map[sdl_event.cdevice.which] = controller;
  573. controller->connect(false);
  574. }
  575. }
  576. else
  577. {
  578. logger->error("Failed to connected game controller \"" + controller_name + "\"");
  579. }
  580. }
  581. break;
  582. }
  583. case SDL_CONTROLLERDEVICEREMOVED:
  584. {
  585. SDL_GameController* sdl_controller = SDL_GameControllerFromInstanceID(sdl_event.cdevice.which);
  586. if (sdl_controller)
  587. {
  588. SDL_GameControllerClose(sdl_controller);
  589. logger->log("Disconnected game controller");
  590. if (auto it = game_controller_map.find(sdl_event.cdevice.which); it != game_controller_map.end())
  591. {
  592. it->second->disconnect();
  593. }
  594. }
  595. break;
  596. }
  597. case SDL_WINDOWEVENT:
  598. {
  599. if (sdl_event.window.event == SDL_WINDOWEVENT_RESIZED)
  600. {
  601. window_resized();
  602. }
  603. break;
  604. }
  605. case SDL_QUIT:
  606. {
  607. close(EXIT_SUCCESS);
  608. break;
  609. }
  610. }
  611. }
  612. // Process accumulated mouse motion events
  613. if (mouse_motion)
  614. {
  615. mouse->move(mouse_x, mouse_y, mouse_dx, mouse_dy);
  616. }
  617. }
  618. void application::window_resized()
  619. {
  620. // Update window size and viewport size
  621. SDL_GetWindowSize(sdl_window, &window_dimensions[0], &window_dimensions[1]);
  622. SDL_GL_GetDrawableSize(sdl_window, &viewport_dimensions[0], &viewport_dimensions[1]);
  623. rasterizer->context_resized(viewport_dimensions[0], viewport_dimensions[1]);
  624. window_resized_event event;
  625. event.w = window_dimensions[0];
  626. event.h = window_dimensions[1];
  627. event_dispatcher->queue(event);
  628. }