Application.cpp 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433
  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/Factory.h>
  11. #include <Jolt/RegisterTypes.h>
  12. #include <Renderer/DebugRendererImp.h>
  13. #ifdef JPH_PLATFORM_WINDOWS
  14. #include <crtdbg.h>
  15. #include <Input/Win/KeyboardWin.h>
  16. #include <Input/Win/MouseWin.h>
  17. #include <Window/ApplicationWindowWin.h>
  18. #elif defined(JPH_PLATFORM_LINUX)
  19. #include <Input/Linux/KeyboardLinux.h>
  20. #include <Input/Linux/MouseLinux.h>
  21. #include <Window/ApplicationWindowLinux.h>
  22. #elif defined(JPH_PLATFORM_MACOS)
  23. #include <Input/MacOS/KeyboardMacOS.h>
  24. #include <Input/MacOS/MouseMacOS.h>
  25. #include <Window/ApplicationWindowMacOS.h>
  26. #endif
  27. JPH_GCC_SUPPRESS_WARNING("-Wswitch")
  28. // Constructor
  29. Application::Application(const char *inApplicationName, [[maybe_unused]] const String &inCommandLine) :
  30. mDebugRenderer(nullptr),
  31. mRenderer(nullptr),
  32. mKeyboard(nullptr),
  33. mMouse(nullptr),
  34. mUI(nullptr),
  35. mDebugUI(nullptr)
  36. {
  37. #if defined(JPH_PLATFORM_WINDOWS) && defined(_DEBUG)
  38. // Enable leak detection
  39. _CrtSetDbgFlag(_CRTDBG_ALLOC_MEM_DF | _CRTDBG_LEAK_CHECK_DF);
  40. #endif
  41. // Register trace implementation
  42. Trace = TraceImpl;
  43. #ifdef JPH_ENABLE_ASSERTS
  44. // Register assert failed handler
  45. AssertFailed = [](const char *inExpression, const char *inMessage, const char *inFile, uint inLine)
  46. {
  47. Trace("%s (%d): Assert Failed: %s", inFile, inLine, inMessage != nullptr? inMessage : inExpression);
  48. return true;
  49. };
  50. #endif // JPH_ENABLE_ASSERTS
  51. // Create factory
  52. Factory::sInstance = new Factory;
  53. // Register physics types with the factory
  54. RegisterTypes();
  55. {
  56. // Disable allocation checking
  57. DisableCustomMemoryHook dcmh;
  58. // Create window
  59. #ifdef JPH_PLATFORM_WINDOWS
  60. mWindow = new ApplicationWindowWin;
  61. #elif defined(JPH_PLATFORM_LINUX)
  62. mWindow = new ApplicationWindowLinux;
  63. #elif defined(JPH_PLATFORM_MACOS)
  64. mWindow = new ApplicationWindowMacOS;
  65. #else
  66. #error No window defined
  67. #endif
  68. mWindow->Initialize(inApplicationName);
  69. // Create renderer
  70. mRenderer = Renderer::sCreate();
  71. mRenderer->Initialize(mWindow);
  72. // Create font
  73. Font *font = new Font(mRenderer);
  74. font->Create("Roboto-Regular", 24);
  75. mFont = font;
  76. // Init debug renderer
  77. mDebugRenderer = new DebugRendererImp(mRenderer, mFont);
  78. // Init keyboard
  79. #ifdef JPH_PLATFORM_WINDOWS
  80. mKeyboard = new KeyboardWin;
  81. #elif defined(JPH_PLATFORM_LINUX)
  82. mKeyboard = new KeyboardLinux;
  83. #elif defined(JPH_PLATFORM_MACOS)
  84. mKeyboard = new KeyboardMacOS;
  85. #else
  86. #error No keyboard defined
  87. #endif
  88. mKeyboard->Initialize(mWindow);
  89. // Init mouse
  90. #ifdef JPH_PLATFORM_WINDOWS
  91. mMouse = new MouseWin;
  92. #elif defined(JPH_PLATFORM_LINUX)
  93. mMouse = new MouseLinux;
  94. #elif defined(JPH_PLATFORM_MACOS)
  95. mMouse = new MouseMacOS;
  96. #else
  97. #error No mouse defined
  98. #endif
  99. mMouse->Initialize(mWindow);
  100. // Init UI
  101. mUI = new UIManager(mRenderer);
  102. mUI->SetVisible(false);
  103. // Init debug UI
  104. mDebugUI = new DebugUI(mUI, mFont);
  105. }
  106. // Get initial time
  107. mLastUpdateTime = chrono::high_resolution_clock::now();
  108. }
  109. // Destructor
  110. Application::~Application()
  111. {
  112. {
  113. // Disable allocation checking
  114. DisableCustomMemoryHook dcmh;
  115. delete mDebugUI;
  116. delete mUI;
  117. delete mMouse;
  118. delete mKeyboard;
  119. delete mDebugRenderer;
  120. mFont = nullptr;
  121. delete mRenderer;
  122. delete mWindow;
  123. }
  124. // Unregisters all types with the factory and cleans up the default material
  125. UnregisterTypes();
  126. delete Factory::sInstance;
  127. Factory::sInstance = nullptr;
  128. }
  129. String Application::sCreateCommandLine(int inArgC, char **inArgV)
  130. {
  131. String command_line;
  132. for (int i = 0; i < inArgC; ++i)
  133. {
  134. if (i > 0)
  135. command_line += " ";
  136. command_line += inArgV[i];
  137. }
  138. return command_line;
  139. }
  140. // Clear debug lines / triangles / texts that have been accumulated
  141. void Application::ClearDebugRenderer()
  142. {
  143. JPH_PROFILE_FUNCTION();
  144. static_cast<DebugRendererImp *>(mDebugRenderer)->Clear();
  145. mDebugRendererCleared = true;
  146. }
  147. // Main loop
  148. void Application::Run()
  149. {
  150. // Set initial camera position
  151. ResetCamera();
  152. // Enter the main loop
  153. mWindow->MainLoop([this]() { return RenderFrame(); });
  154. }
  155. bool Application::RenderFrame()
  156. {
  157. // Get new input
  158. mKeyboard->Poll();
  159. mMouse->Poll();
  160. // Handle keyboard input
  161. for (EKey key = mKeyboard->GetFirstKey(); key != EKey::Invalid; key = mKeyboard->GetNextKey())
  162. switch (key)
  163. {
  164. case EKey::P:
  165. mIsPaused = !mIsPaused;
  166. break;
  167. case EKey::O:
  168. mSingleStep = true;
  169. break;
  170. case EKey::T:
  171. // Dump timing info to file
  172. JPH_PROFILE_DUMP();
  173. break;
  174. case EKey::Escape:
  175. mDebugUI->ToggleVisibility();
  176. break;
  177. }
  178. // Calculate delta time
  179. chrono::high_resolution_clock::time_point time = chrono::high_resolution_clock::now();
  180. chrono::microseconds delta = chrono::duration_cast<chrono::microseconds>(time - mLastUpdateTime);
  181. mLastUpdateTime = time;
  182. float clock_delta_time = 1.0e-6f * delta.count();
  183. float world_delta_time = 0.0f;
  184. if (mRequestedDeltaTime <= 0.0f)
  185. {
  186. // If no fixed frequency update is requested, update with variable time step
  187. world_delta_time = !mIsPaused || mSingleStep? clock_delta_time : 0.0f;
  188. mResidualDeltaTime = 0.0f;
  189. }
  190. else
  191. {
  192. // Else use fixed time steps
  193. if (mSingleStep)
  194. {
  195. // Single step
  196. world_delta_time = mRequestedDeltaTime;
  197. }
  198. else if (!mIsPaused)
  199. {
  200. // Calculate how much time has passed since the last render
  201. world_delta_time = clock_delta_time + mResidualDeltaTime;
  202. if (world_delta_time < mRequestedDeltaTime)
  203. {
  204. // Too soon, set the residual time and don't update
  205. mResidualDeltaTime = world_delta_time;
  206. world_delta_time = 0.0f;
  207. }
  208. else
  209. {
  210. // Update and clamp the residual time to a full update to avoid spiral of death
  211. mResidualDeltaTime = min(mRequestedDeltaTime, world_delta_time - mRequestedDeltaTime);
  212. world_delta_time = mRequestedDeltaTime;
  213. }
  214. }
  215. }
  216. mSingleStep = false;
  217. // Clear debug lines if we're going to step
  218. if (world_delta_time > 0.0f)
  219. ClearDebugRenderer();
  220. {
  221. JPH_PROFILE("UpdateFrame");
  222. if (!UpdateFrame(world_delta_time))
  223. return false;
  224. }
  225. // Draw coordinate axis
  226. if (mDebugRendererCleared)
  227. mDebugRenderer->DrawCoordinateSystem(RMat44::sIdentity());
  228. // For next frame: mark that we haven't cleared debug stuff
  229. mDebugRendererCleared = false;
  230. // Update the camera position
  231. if (!mUI->IsVisible())
  232. UpdateCamera(clock_delta_time);
  233. // Start rendering
  234. if (!mRenderer->BeginFrame(mWorldCamera, GetWorldScale()))
  235. return true;
  236. // Draw from light
  237. static_cast<DebugRendererImp *>(mDebugRenderer)->DrawShadowPass();
  238. // Start drawing normally
  239. mRenderer->EndShadowPass();
  240. // Draw debug information
  241. static_cast<DebugRendererImp *>(mDebugRenderer)->Draw();
  242. // Draw the frame rate counter
  243. DrawFPS(clock_delta_time);
  244. if (mUI->IsVisible())
  245. {
  246. // Send mouse input to UI
  247. bool left_pressed = mMouse->IsLeftPressed();
  248. if (left_pressed && !mLeftMousePressed)
  249. mUI->MouseDown(mMouse->GetX(), mMouse->GetY());
  250. else if (!left_pressed && mLeftMousePressed)
  251. mUI->MouseUp(mMouse->GetX(), mMouse->GetY());
  252. mLeftMousePressed = left_pressed;
  253. mUI->MouseMove(mMouse->GetX(), mMouse->GetY());
  254. {
  255. // Disable allocation checking
  256. DisableCustomMemoryHook dcmh;
  257. // Update and draw the menu
  258. mUI->Update(clock_delta_time);
  259. mUI->Draw();
  260. }
  261. }
  262. else
  263. {
  264. // Menu not visible, cancel any mouse operations
  265. mUI->MouseCancel();
  266. }
  267. // Show the frame
  268. mRenderer->EndFrame();
  269. // Notify of next frame
  270. JPH_PROFILE_NEXTFRAME();
  271. return true;
  272. }
  273. void Application::GetCameraLocalHeadingAndPitch(float &outHeading, float &outPitch)
  274. {
  275. outHeading = ATan2(mLocalCamera.mForward.GetZ(), mLocalCamera.mForward.GetX());
  276. outPitch = ATan2(mLocalCamera.mForward.GetY(), Vec3(mLocalCamera.mForward.GetX(), 0, mLocalCamera.mForward.GetZ()).Length());
  277. }
  278. void Application::ConvertCameraLocalToWorld(float inCameraHeading, float inCameraPitch)
  279. {
  280. // Convert local to world space using the camera pivot
  281. RMat44 pivot = GetCameraPivot(inCameraHeading, inCameraPitch);
  282. mWorldCamera = mLocalCamera;
  283. mWorldCamera.mPos = pivot * mLocalCamera.mPos;
  284. mWorldCamera.mForward = pivot.Multiply3x3(mLocalCamera.mForward);
  285. mWorldCamera.mUp = pivot.Multiply3x3(mLocalCamera.mUp);
  286. }
  287. void Application::ResetCamera()
  288. {
  289. // Get local space camera state
  290. mLocalCamera = CameraState();
  291. GetInitialCamera(mLocalCamera);
  292. // Convert to world space
  293. float heading, pitch;
  294. GetCameraLocalHeadingAndPitch(heading, pitch);
  295. ConvertCameraLocalToWorld(heading, pitch);
  296. }
  297. // Update camera position
  298. void Application::UpdateCamera(float inDeltaTime)
  299. {
  300. JPH_PROFILE_FUNCTION();
  301. // Determine speed
  302. float speed = 20.0f * GetWorldScale() * inDeltaTime;
  303. bool shift = mKeyboard->IsKeyPressed(EKey::LShift) || mKeyboard->IsKeyPressed(EKey::RShift);
  304. bool control = mKeyboard->IsKeyPressed(EKey::LControl) || mKeyboard->IsKeyPressed(EKey::RControl);
  305. bool alt = mKeyboard->IsKeyPressed(EKey::LAlt) || mKeyboard->IsKeyPressed(EKey::RAlt);
  306. if (shift) speed *= 10.0f;
  307. else if (control) speed /= 25.0f;
  308. else if (alt) speed = 0.0f;
  309. // Position
  310. Vec3 right = mLocalCamera.mForward.Cross(mLocalCamera.mUp);
  311. if (mKeyboard->IsKeyPressed(EKey::A)) mLocalCamera.mPos -= speed * right;
  312. if (mKeyboard->IsKeyPressed(EKey::D)) mLocalCamera.mPos += speed * right;
  313. if (mKeyboard->IsKeyPressed(EKey::W)) mLocalCamera.mPos += speed * mLocalCamera.mForward;
  314. if (mKeyboard->IsKeyPressed(EKey::S)) mLocalCamera.mPos -= speed * mLocalCamera.mForward;
  315. // Forward
  316. float heading, pitch;
  317. GetCameraLocalHeadingAndPitch(heading, pitch);
  318. heading += DegreesToRadians(mMouse->GetDX() * 0.5f);
  319. pitch = Clamp(pitch - DegreesToRadians(mMouse->GetDY() * 0.5f), -0.49f * JPH_PI, 0.49f * JPH_PI);
  320. mLocalCamera.mForward = Vec3(Cos(pitch) * Cos(heading), Sin(pitch), Cos(pitch) * Sin(heading));
  321. // Convert to world space
  322. ConvertCameraLocalToWorld(heading, pitch);
  323. }
  324. void Application::DrawFPS(float inDeltaTime)
  325. {
  326. JPH_PROFILE_FUNCTION();
  327. // Don't divide by zero
  328. if (inDeltaTime <= 0.0f)
  329. return;
  330. // Switch tho ortho mode
  331. mRenderer->SetOrthoMode();
  332. // Update stats
  333. mTotalDeltaTime += inDeltaTime;
  334. mNumFrames++;
  335. if (mNumFrames > 10)
  336. {
  337. mFPS = mNumFrames / mTotalDeltaTime;
  338. mNumFrames = 0;
  339. mTotalDeltaTime = 0.0f;
  340. }
  341. // Create string
  342. String fps = StringFormat("%.1f", (double)mFPS);
  343. // Get size of text on screen
  344. Float2 text_size = mFont->MeasureText(fps);
  345. int text_w = int(text_size.x * mFont->GetCharHeight());
  346. int text_h = int(text_size.y * mFont->GetCharHeight());
  347. // Draw FPS counter
  348. int x = (mWindow->GetWindowWidth() - text_w) / 2 - 20;
  349. int y = 10;
  350. mUI->DrawQuad(x - 5, y - 3, text_w + 10, text_h + 6, UITexturedQuad(), Color(0, 0, 0, 128));
  351. mUI->DrawText(x, y, fps, mFont);
  352. // Draw status string
  353. if (!mStatusString.empty())
  354. mUI->DrawText(5, 5, mStatusString, mFont);
  355. // Draw paused string if the app is paused
  356. if (mIsPaused)
  357. {
  358. string_view paused_str = "P: Unpause, ESC: Menu";
  359. Float2 pause_size = mFont->MeasureText(paused_str);
  360. mUI->DrawText(mWindow->GetWindowWidth() - 5 - int(pause_size.x * mFont->GetCharHeight()), 5, paused_str, mFont);
  361. }
  362. // Restore state
  363. mRenderer->SetProjectionMode();
  364. }