Application.cpp 8.6 KB

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