A 2D tile-based sandbox game.
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.

main.cc 7.0KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264
  1. #include <time.h>
  2. #include <unistd.h>
  3. #include <vector>
  4. #include <memory>
  5. #include <chrono>
  6. #include <ratio>
  7. #include <SDL2/SDL.h>
  8. #include <SDL2/SDL_image.h>
  9. #include <string.h>
  10. #include <imgui.h>
  11. #include <imgui_sdl/imgui_sdl.h>
  12. #include <swan/swan.h>
  13. using namespace Swan;
  14. #define errassert(expr, str, errfn) do { \
  15. if (!(expr)) { \
  16. panic << (str) << ": " << errfn(); \
  17. return EXIT_FAILURE; \
  18. } \
  19. } while (0)
  20. #define sdlassert(expr, str) errassert(expr, str, SDL_GetError);
  21. #define imgassert(expr, str) errassert(expr, str, IMG_GetError);
  22. // ImGUI and SDL have different numbers for mouse buttons
  23. int sdlButtonToImGuiButton(uint8_t button) {
  24. switch (button) {
  25. case SDL_BUTTON_LEFT:
  26. return 0;
  27. case SDL_BUTTON_RIGHT:
  28. return 1;
  29. case SDL_BUTTON_MIDDLE:
  30. return 2;
  31. case SDL_BUTTON_X1:
  32. return 3;
  33. case SDL_BUTTON_X2:
  34. return 4;
  35. default:
  36. warn << "Unknown mouse button: " << button;
  37. return 4; // Let's call that X2?
  38. }
  39. }
  40. int main(int argc, char **argv) {
  41. uint32_t winflags = SDL_WINDOW_SHOWN | SDL_WINDOW_RESIZABLE | SDL_WINDOW_ALLOW_HIGHDPI;
  42. uint32_t renderflags = SDL_RENDERER_ACCELERATED | SDL_RENDERER_PRESENTVSYNC;
  43. float gui_scale = 1;
  44. for (int i = 1; i < argc; ++i) {
  45. if (strcmp(argv[i], "--lodpi") == 0) {
  46. winflags &= ~SDL_WINDOW_ALLOW_HIGHDPI;
  47. } else if (strcmp(argv[i], "--fullscreen") == 0) {
  48. winflags |= SDL_WINDOW_FULLSCREEN_DESKTOP;
  49. } else if (strcmp(argv[i], "--no-vsync") == 0) {
  50. renderflags &= ~SDL_RENDERER_PRESENTVSYNC;
  51. } else if (strcmp(argv[i], "--vulkan") == 0) {
  52. winflags |= SDL_WINDOW_VULKAN;
  53. } else if (strcmp(argv[i], "--sw-render") == 0) {
  54. renderflags &= ~SDL_RENDERER_ACCELERATED;
  55. renderflags |= SDL_RENDERER_SOFTWARE;
  56. } else if (strcmp(argv[i], "--2x") == 0) {
  57. gui_scale = 2;
  58. } else {
  59. warn << "Unknown argument: " << argv[i];
  60. }
  61. }
  62. sdlassert(SDL_Init(SDL_INIT_VIDEO) >= 0, "Could not initialize SDL");
  63. Deferred<SDL_Quit> sdl;
  64. int imgflags = IMG_INIT_PNG;
  65. imgassert(IMG_Init(imgflags) == imgflags, "Could not initialize SDL_Image");
  66. Deferred<IMG_Quit> sdl_image;
  67. // Create the window
  68. CPtr<SDL_Window, SDL_DestroyWindow> window(
  69. SDL_CreateWindow(
  70. "Project: SWAN",
  71. SDL_WINDOWPOS_UNDEFINED, SDL_WINDOWPOS_UNDEFINED,
  72. (int)(640 * gui_scale), (int)(480 * gui_scale), winflags));
  73. // Load and display application icon
  74. CPtr<SDL_Surface, SDL_FreeSurface> icon(
  75. IMG_Load("assets/icon.png"));
  76. sdlassert(icon, "Could not load icon");
  77. SDL_SetWindowIcon(window.get(), icon.get());
  78. CPtr<SDL_Renderer, SDL_DestroyRenderer> renderer(
  79. SDL_CreateRenderer(window.get(), -1, renderflags));
  80. sdlassert(renderer, "Could not create renderer");
  81. SDL_SetRenderDrawBlendMode(renderer.get(), SDL_BLENDMODE_BLEND);
  82. SDL_SetRenderDrawColor(renderer.get(), 0, 0, 0, 255);
  83. Win win(window.get(), renderer.get(), gui_scale);
  84. // Init ImGUI and ImGUI_SDL
  85. IMGUI_CHECKVERSION();
  86. CPtr<ImGuiContext, ImGui::DestroyContext> context(
  87. ImGui::CreateContext());
  88. ImGuiSDL::Initialize(renderer.get(), (int)win.getPixSize().x, (int)win.getPixSize().y);
  89. Deferred<ImGuiSDL::Deinitialize> imgui_sdl;
  90. info << "Initialized with window size " << win.getPixSize();
  91. // ImGuiIO is to glue SDL and ImGUI together
  92. ImGuiIO& imgui_io = ImGui::GetIO();
  93. imgui_io.BackendPlatformName = "imgui_sdl + Project: SWAN";
  94. // Create a world
  95. Game game(win);
  96. std::vector<std::string> mods{ "core.mod" };
  97. game.createWorld("core::default", mods);
  98. PerfCounter pcounter;
  99. auto prev_time = std::chrono::steady_clock::now();
  100. float fps_acc = 0;
  101. float tick_acc = 0;
  102. int fcount = 0;
  103. int slow_frames = 0;
  104. while (1) {
  105. RTClock total_time_clock;
  106. SDL_Event evt;
  107. while (SDL_PollEvent(&evt)) {
  108. switch (evt.type) {
  109. case SDL_QUIT:
  110. goto exit;
  111. break;
  112. case SDL_WINDOWEVENT:
  113. if (evt.window.event == SDL_WINDOWEVENT_RESIZED) {
  114. imgui_io.DisplaySize.x = (float)evt.window.data1;
  115. imgui_io.DisplaySize.y = (float)evt.window.data2;
  116. win.onResize(evt.window.data1, evt.window.data2);
  117. }
  118. break;
  119. case SDL_KEYDOWN:
  120. game.onKeyDown(evt.key.keysym);
  121. break;
  122. case SDL_KEYUP:
  123. game.onKeyUp(evt.key.keysym);
  124. break;
  125. case SDL_MOUSEMOTION:
  126. imgui_io.MousePos.x = (float)evt.motion.x;
  127. imgui_io.MousePos.y = (float)evt.motion.y;
  128. if (!imgui_io.WantCaptureMouse)
  129. game.onMouseMove(evt.motion.x, evt.motion.y);
  130. break;
  131. case SDL_MOUSEBUTTONDOWN:
  132. imgui_io.MouseDown[sdlButtonToImGuiButton(evt.button.button)] = true;
  133. if (!imgui_io.WantCaptureMouse)
  134. game.onMouseDown(evt.button.x, evt.button.y, evt.button.button);
  135. break;
  136. case SDL_MOUSEBUTTONUP:
  137. imgui_io.MouseDown[sdlButtonToImGuiButton(evt.button.button)] = false;
  138. if (!imgui_io.WantCaptureMouse)
  139. game.onMouseUp(evt.button.x, evt.button.y, evt.button.button);
  140. break;
  141. case SDL_MOUSEWHEEL:
  142. imgui_io.MouseWheel += (float)evt.wheel.y;
  143. if (!imgui_io.WantCaptureMouse)
  144. game.onScrollWheel(evt.wheel.y);
  145. break;
  146. }
  147. }
  148. auto now = std::chrono::steady_clock::now();
  149. std::chrono::duration<float> dur(now - prev_time);
  150. prev_time = now;
  151. float dt = dur.count();
  152. // Display FPS
  153. fps_acc += dt;
  154. fcount += 1;
  155. if (fps_acc >= 4) {
  156. info << "FPS: " << fcount / 4.0;
  157. fps_acc -= 4;
  158. fcount = 0;
  159. }
  160. // We want to warn if one frame takes over 0.1 seconds...
  161. if (dt > 0.1) {
  162. if (slow_frames == 0)
  163. warn << "Delta time too high! (" << dt << "s)";
  164. slow_frames += 1;
  165. // And we never want to do physics as if our one frame is greater than
  166. // 0.5 seconds.
  167. if (dt > 0.5)
  168. dt = 0.5;
  169. } else if (slow_frames > 0) {
  170. if (slow_frames > 1)
  171. warn << slow_frames << " consecutive slow frames.";
  172. slow_frames = 0;
  173. }
  174. // Simple case: we can keep up, only need one physics update
  175. RTClock update_clock;
  176. if (dt <= 1 / 25.0) {
  177. pcounter.countGameUpdatesPerFrame(1);
  178. game.update(dt);
  179. // Complex case: run multiple steps this iteration
  180. } else {
  181. int count = (int)ceil(dt / (1/30.0));
  182. pcounter.countGameUpdatesPerFrame(count);
  183. float delta = dt / (float)count;
  184. info << "Delta time " << dt << "s. Running " << count << " updates in one frame, with a delta as if we had " << 1.0 / delta << " FPS.";
  185. for (int i = 0; i < count; ++i)
  186. game.update(delta);
  187. }
  188. pcounter.countGameUpdate(update_clock.duration());
  189. // Tick at a consistent TICK_RATE
  190. tick_acc += dt;
  191. while (tick_acc >= 1.0 / TICK_RATE) {
  192. tick_acc -= 1.0 / TICK_RATE;
  193. RTClock tick_clock;
  194. game.tick(1.0 / TICK_RATE);
  195. pcounter.countGameTick(tick_clock.duration());
  196. }
  197. {
  198. auto [r, g, b, a] = game.backgroundColor();
  199. RenderDrawColor c(renderer.get(), r, g, b, a);
  200. SDL_RenderClear(renderer.get());
  201. }
  202. // ImGUI
  203. imgui_io.DeltaTime = dt;
  204. ImGui::NewFrame();
  205. RTClock draw_clock;
  206. game.draw();
  207. pcounter.countGameDraw(draw_clock.duration());
  208. pcounter.countFrameTime(total_time_clock.duration());
  209. pcounter.render();
  210. // Render ImGUI
  211. ImGui::Render();
  212. ImGuiSDL::Render(ImGui::GetDrawData());
  213. RTClock present_clock;
  214. SDL_RenderPresent(renderer.get());
  215. pcounter.countRenderPresent(present_clock.duration());
  216. pcounter.countTotalTime(total_time_clock.duration());
  217. }
  218. exit:
  219. return EXIT_SUCCESS;
  220. }