Application.cpp 8.1 KB

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