2
0

Application.cpp 8.5 KB

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