Application.cpp 8.4 KB

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