Application.cpp 8.2 KB

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