2
0

Application.cpp 8.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343
  1. // SPDX-FileCopyrightText: 2021 Jorrit Rouwe
  2. // SPDX-License-Identifier: MIT
  3. #include <TestFramework.h>
  4. #include <Application/Application.h>
  5. #include <UI/UIManager.h>
  6. #include <Application/DebugUI.h>
  7. #include <Utils/Log.h>
  8. #include <Utils/CustomMemoryHook.h>
  9. #include <Jolt/Core/FPException.h>
  10. #include <Jolt/Core/Factory.h>
  11. #include <Jolt/RegisterTypes.h>
  12. #include <Renderer/DebugRendererImp.h>
  13. #include <crtdbg.h>
  14. // Constructor
  15. Application::Application() :
  16. mDebugRenderer(nullptr),
  17. mRenderer(nullptr),
  18. mKeyboard(nullptr),
  19. mMouse(nullptr),
  20. mUI(nullptr),
  21. mDebugUI(nullptr)
  22. {
  23. #if defined(_DEBUG)
  24. // Enable leak detection
  25. _CrtSetDbgFlag(_CRTDBG_ALLOC_MEM_DF | _CRTDBG_LEAK_CHECK_DF);
  26. #endif
  27. // Register trace implementation
  28. Trace = TraceImpl;
  29. #ifdef JPH_ENABLE_ASSERTS
  30. // Register assert failed handler
  31. AssertFailed = [](const char *inExpression, const char *inMessage, const char *inFile, uint inLine)
  32. {
  33. Trace("%s (%d): Assert Failed: %s", inFile, inLine, inMessage != nullptr? inMessage : inExpression);
  34. return true;
  35. };
  36. #endif // JPH_ENABLE_ASSERTS
  37. // Create factory
  38. Factory::sInstance = new Factory;
  39. // Register physics types with the factory
  40. RegisterTypes();
  41. {
  42. // Disable allocation checking
  43. DisableCustomMemoryHook dcmh;
  44. // Create renderer
  45. mRenderer = new Renderer;
  46. mRenderer->Initialize();
  47. // Create font
  48. Font *font = new Font(mRenderer);
  49. font->Create("Arial", 24);
  50. mFont = font;
  51. // Init debug renderer
  52. mDebugRenderer = new DebugRendererImp(mRenderer, mFont);
  53. // Init keyboard
  54. mKeyboard = new Keyboard;
  55. mKeyboard->Initialize(mRenderer);
  56. // Init mouse
  57. mMouse = new Mouse;
  58. mMouse->Initialize(mRenderer);
  59. // Init UI
  60. mUI = new UIManager(mRenderer);
  61. mUI->SetVisible(false);
  62. // Init debug UI
  63. mDebugUI = new DebugUI(mUI, mFont);
  64. }
  65. // Get initial time
  66. mLastUpdateTicks = GetProcessorTickCount();
  67. }
  68. // Destructor
  69. Application::~Application()
  70. {
  71. {
  72. // Disable allocation checking
  73. DisableCustomMemoryHook dcmh;
  74. delete mDebugUI;
  75. delete mUI;
  76. delete mMouse;
  77. delete mKeyboard;
  78. delete mDebugRenderer;
  79. mFont = nullptr;
  80. delete mRenderer;
  81. }
  82. delete Factory::sInstance;
  83. Factory::sInstance = nullptr;
  84. }
  85. // Clear debug lines / triangles / texts that have been accumulated
  86. void Application::ClearDebugRenderer()
  87. {
  88. JPH_PROFILE_FUNCTION();
  89. static_cast<DebugRendererImp *>(mDebugRenderer)->Clear();
  90. mDebugRendererCleared = true;
  91. }
  92. // Main loop
  93. void Application::Run()
  94. {
  95. // Set initial camera position
  96. ResetCamera();
  97. // Main message loop
  98. MSG msg;
  99. memset(&msg, 0, sizeof(msg));
  100. while (WM_QUIT != msg.message)
  101. {
  102. if (PeekMessage(&msg, nullptr, 0, 0, PM_REMOVE))
  103. {
  104. JPH_PROFILE("DispatchMessage");
  105. TranslateMessage(&msg);
  106. DispatchMessage(&msg);
  107. }
  108. else
  109. {
  110. // Get new input
  111. mKeyboard->Poll();
  112. mMouse->Poll();
  113. // Handle keyboard input
  114. for (int key = mKeyboard->GetFirstKey(); key != 0; key = mKeyboard->GetNextKey())
  115. switch (key)
  116. {
  117. case DIK_P:
  118. mIsPaused = !mIsPaused;
  119. break;
  120. case DIK_O:
  121. mSingleStep = true;
  122. break;
  123. case DIK_T:
  124. // Dump timing info to file
  125. JPH_PROFILE_DUMP();
  126. break;
  127. case DIK_ESCAPE:
  128. mDebugUI->ToggleVisibility();
  129. break;
  130. }
  131. // Calculate delta time
  132. uint64 ticks = GetProcessorTickCount();
  133. uint64 delta = ticks - mLastUpdateTicks;
  134. mLastUpdateTicks = ticks;
  135. float clock_delta_time = float(delta) / float(GetProcessorTicksPerSecond());
  136. float world_delta_time = !mIsPaused || mSingleStep? clock_delta_time : 0.0f;
  137. mSingleStep = false;
  138. // Clear debug lines if we're going to step
  139. if (world_delta_time > 0.0f)
  140. ClearDebugRenderer();
  141. // Update the camera position
  142. if (!mUI->IsVisible())
  143. UpdateCamera(clock_delta_time);
  144. // Start rendering
  145. mRenderer->BeginFrame(mWorldCamera, GetWorldScale());
  146. {
  147. JPH_PROFILE("RenderFrame");
  148. if (!RenderFrame(world_delta_time))
  149. break;
  150. }
  151. // Draw coordinate axis
  152. if (mDebugRendererCleared)
  153. mDebugRenderer->DrawCoordinateSystem(Mat44::sIdentity());
  154. // For next frame: mark that we haven't cleared debug stuff
  155. mDebugRendererCleared = false;
  156. // Draw debug information
  157. static_cast<DebugRendererImp *>(mDebugRenderer)->Draw();
  158. // Draw the frame rate counter
  159. DrawFPS(clock_delta_time);
  160. if (mUI->IsVisible())
  161. {
  162. // Send mouse input to UI
  163. bool left_pressed = mMouse->IsLeftPressed();
  164. if (left_pressed && !mLeftMousePressed)
  165. mUI->MouseDown(mMouse->GetX(), mMouse->GetY());
  166. else if (!left_pressed && mLeftMousePressed)
  167. mUI->MouseUp(mMouse->GetX(), mMouse->GetY());
  168. mLeftMousePressed = left_pressed;
  169. mUI->MouseMove(mMouse->GetX(), mMouse->GetY());
  170. {
  171. // Disable allocation checking
  172. DisableCustomMemoryHook dcmh;
  173. // Update and draw the menu
  174. mUI->Update(clock_delta_time);
  175. mUI->Draw();
  176. }
  177. }
  178. else
  179. {
  180. // Menu not visible, cancel any mouse operations
  181. mUI->MouseCancel();
  182. }
  183. // Show the frame
  184. mRenderer->EndFrame();
  185. // Notify of next frame
  186. JPH_PROFILE_NEXTFRAME();
  187. }
  188. }
  189. }
  190. void Application::GetCameraLocalHeadingAndPitch(float &outHeading, float &outPitch)
  191. {
  192. outHeading = ATan2(mLocalCamera.mForward.GetZ(), mLocalCamera.mForward.GetX());
  193. outPitch = ATan2(mLocalCamera.mForward.GetY(), Vec3(mLocalCamera.mForward.GetX(), 0, mLocalCamera.mForward.GetZ()).Length());
  194. }
  195. void Application::ConvertCameraLocalToWorld(float inCameraHeading, float inCameraPitch)
  196. {
  197. // Convert local to world space using the camera pivot
  198. Mat44 pivot = GetCameraPivot(inCameraHeading, inCameraPitch);
  199. mWorldCamera = mLocalCamera;
  200. mWorldCamera.mPos = pivot * mLocalCamera.mPos;
  201. mWorldCamera.mForward = pivot.Multiply3x3(mLocalCamera.mForward);
  202. mWorldCamera.mUp = pivot.Multiply3x3(mLocalCamera.mUp);
  203. }
  204. void Application::ResetCamera()
  205. {
  206. // Get local space camera state
  207. mLocalCamera = CameraState();
  208. GetInitialCamera(mLocalCamera);
  209. // Convert to world space
  210. float heading, pitch;
  211. GetCameraLocalHeadingAndPitch(heading, pitch);
  212. ConvertCameraLocalToWorld(heading, pitch);
  213. }
  214. // Update camera position
  215. void Application::UpdateCamera(float inDeltaTime)
  216. {
  217. JPH_PROFILE_FUNCTION();
  218. // Determine speed
  219. float speed = GetWorldScale() * mWorldCamera.mFarPlane / 50.0f * inDeltaTime;
  220. bool shift = mKeyboard->IsKeyPressed(DIK_LSHIFT) || mKeyboard->IsKeyPressed(DIK_RSHIFT);
  221. bool control = mKeyboard->IsKeyPressed(DIK_LCONTROL) || mKeyboard->IsKeyPressed(DIK_RCONTROL);
  222. bool alt = mKeyboard->IsKeyPressed(DIK_LALT) || mKeyboard->IsKeyPressed(DIK_RALT);
  223. if (shift) speed *= 10.0f;
  224. else if (control) speed /= 25.0f;
  225. else if (alt) speed = 0.0f;
  226. // Position
  227. Vec3 right = mLocalCamera.mForward.Cross(mLocalCamera.mUp);
  228. if (mKeyboard->IsKeyPressed(DIK_A)) mLocalCamera.mPos -= speed * right;
  229. if (mKeyboard->IsKeyPressed(DIK_D)) mLocalCamera.mPos += speed * right;
  230. if (mKeyboard->IsKeyPressed(DIK_W)) mLocalCamera.mPos += speed * mLocalCamera.mForward;
  231. if (mKeyboard->IsKeyPressed(DIK_S)) mLocalCamera.mPos -= speed * mLocalCamera.mForward;
  232. // Forward
  233. float heading, pitch;
  234. GetCameraLocalHeadingAndPitch(heading, pitch);
  235. heading += DegreesToRadians(mMouse->GetDX() * 0.5f);
  236. pitch = Clamp(pitch - DegreesToRadians(mMouse->GetDY() * 0.5f), -0.49f * JPH_PI, 0.49f * JPH_PI);
  237. mLocalCamera.mForward = Vec3(Cos(pitch) * Cos(heading), Sin(pitch), Cos(pitch) * Sin(heading));
  238. // Convert to world space
  239. ConvertCameraLocalToWorld(heading, pitch);
  240. }
  241. void Application::DrawFPS(float inDeltaTime)
  242. {
  243. JPH_PROFILE_FUNCTION();
  244. // Don't divide by zero
  245. if (inDeltaTime <= 0.0f)
  246. return;
  247. // Switch tho ortho mode
  248. mRenderer->SetOrthoMode();
  249. // Update stats
  250. mTotalDeltaTime += inDeltaTime;
  251. mNumFrames++;
  252. if (mNumFrames > 10)
  253. {
  254. mFPS = mNumFrames / mTotalDeltaTime;
  255. mNumFrames = 0;
  256. mTotalDeltaTime = 0.0f;
  257. }
  258. // Create string
  259. String fps = StringFormat("%.1f", (double)mFPS);
  260. // Get size of text on screen
  261. Float2 text_size = mFont->MeasureText(fps);
  262. int text_w = int(text_size.x * mFont->GetCharHeight());
  263. int text_h = int(text_size.y * mFont->GetCharHeight());
  264. // Draw FPS counter
  265. int x = (mRenderer->GetWindowWidth() - text_w) / 2 - 20;
  266. int y = 10;
  267. mUI->DrawQuad(x - 5, y - 3, text_w + 10, text_h + 6, UITexturedQuad(), Color(0, 0, 0, 128));
  268. mUI->DrawText(x, y, fps, mFont);
  269. // Draw status string
  270. if (!mStatusString.empty())
  271. mUI->DrawText(5, 5, mStatusString, mFont);
  272. // Draw paused string if the app is paused
  273. if (mIsPaused)
  274. {
  275. string_view paused_str = "P: Unpause, ESC: Menu";
  276. Float2 pause_size = mFont->MeasureText(paused_str);
  277. mUI->DrawText(mRenderer->GetWindowWidth() - 5 - int(pause_size.x * mFont->GetCharHeight()), 5, paused_str, mFont);
  278. }
  279. // Restore state
  280. mRenderer->SetProjectionMode();
  281. }