Game.cpp 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600
  1. // ----------------------------------------------------------------
  2. // From Game Programming in C++ by Sanjay Madhav
  3. // Copyright (C) 2017 Sanjay Madhav. All rights reserved.
  4. //
  5. // Released under the BSD License
  6. // See LICENSE in root directory for full details.
  7. // ----------------------------------------------------------------
  8. #include "Game.h"
  9. #include <algorithm>
  10. #include "Renderer.h"
  11. #include "AudioSystem.h"
  12. #include "PhysWorld.h"
  13. #include "Actor.h"
  14. #include "UIScreen.h"
  15. #include "HUD.h"
  16. #include "MeshComponent.h"
  17. #include "FollowActor.h"
  18. #include "PlaneActor.h"
  19. #include "TargetActor.h"
  20. #include "BallActor.h"
  21. #include "PauseMenu.h"
  22. #include <SDL/SDL.h>
  23. #include <SDL/SDL_ttf.h>
  24. #include "Font.h"
  25. #include <fstream>
  26. #include <sstream>
  27. #include <rapidjson/document.h>
  28. #include "Skeleton.h"
  29. #include "Animation.h"
  30. Game::Game()
  31. :mRenderer(nullptr)
  32. ,mAudioSystem(nullptr)
  33. ,mPhysWorld(nullptr)
  34. ,mGameState(EGameplay)
  35. ,mUpdatingActors(false)
  36. {
  37. }
  38. bool Game::Initialize()
  39. {
  40. if (SDL_Init(SDL_INIT_VIDEO|SDL_INIT_AUDIO) != 0)
  41. {
  42. SDL_Log("Unable to initialize SDL: %s", SDL_GetError());
  43. return false;
  44. }
  45. // Create the renderer
  46. mRenderer = new Renderer(this);
  47. if (!mRenderer->Initialize(1024.0f, 768.0f))
  48. {
  49. SDL_Log("Failed to initialize renderer");
  50. delete mRenderer;
  51. mRenderer = nullptr;
  52. return false;
  53. }
  54. // Create the audio system
  55. mAudioSystem = new AudioSystem(this);
  56. if (!mAudioSystem->Initialize())
  57. {
  58. SDL_Log("Failed to initialize audio system");
  59. mAudioSystem->Shutdown();
  60. delete mAudioSystem;
  61. mAudioSystem = nullptr;
  62. return false;
  63. }
  64. // Create the physics world
  65. mPhysWorld = new PhysWorld(this);
  66. // Initialize SDL_ttf
  67. if (TTF_Init() != 0)
  68. {
  69. SDL_Log("Failed to initialize SDL_ttf");
  70. return false;
  71. }
  72. LoadData();
  73. mTicksCount = SDL_GetTicks();
  74. return true;
  75. }
  76. void Game::RunLoop()
  77. {
  78. while (mGameState != EQuit)
  79. {
  80. ProcessInput();
  81. UpdateGame();
  82. GenerateOutput();
  83. }
  84. }
  85. void Game::AddPlane(PlaneActor* plane)
  86. {
  87. mPlanes.emplace_back(plane);
  88. }
  89. void Game::RemovePlane(PlaneActor* plane)
  90. {
  91. auto iter = std::find(mPlanes.begin(), mPlanes.end(), plane);
  92. mPlanes.erase(iter);
  93. }
  94. void Game::ProcessInput()
  95. {
  96. SDL_Event event;
  97. while (SDL_PollEvent(&event))
  98. {
  99. switch (event.type)
  100. {
  101. case SDL_QUIT:
  102. mGameState = EQuit;
  103. break;
  104. // This fires when a key's initially pressed
  105. case SDL_KEYDOWN:
  106. if (!event.key.repeat)
  107. {
  108. if (mGameState == EGameplay)
  109. {
  110. HandleKeyPress(event.key.keysym.sym);
  111. }
  112. else if (!mUIStack.empty())
  113. {
  114. mUIStack.back()->
  115. HandleKeyPress(event.key.keysym.sym);
  116. }
  117. }
  118. break;
  119. case SDL_MOUSEBUTTONDOWN:
  120. if (mGameState == EGameplay)
  121. {
  122. HandleKeyPress(event.button.button);
  123. }
  124. else if (!mUIStack.empty())
  125. {
  126. mUIStack.back()->
  127. HandleKeyPress(event.button.button);
  128. }
  129. break;
  130. default:
  131. break;
  132. }
  133. }
  134. const Uint8* state = SDL_GetKeyboardState(NULL);
  135. if (mGameState == EGameplay)
  136. {
  137. for (auto actor : mActors)
  138. {
  139. if (actor->GetState() == Actor::EActive)
  140. {
  141. actor->ProcessInput(state);
  142. }
  143. }
  144. }
  145. else if (!mUIStack.empty())
  146. {
  147. mUIStack.back()->ProcessInput(state);
  148. }
  149. }
  150. void Game::HandleKeyPress(int key)
  151. {
  152. switch (key)
  153. {
  154. case SDLK_ESCAPE:
  155. // Create pause menu
  156. new PauseMenu(this);
  157. break;
  158. case '-':
  159. {
  160. // Reduce master volume
  161. float volume = mAudioSystem->GetBusVolume("bus:/");
  162. volume = Math::Max(0.0f, volume - 0.1f);
  163. mAudioSystem->SetBusVolume("bus:/", volume);
  164. break;
  165. }
  166. case '=':
  167. {
  168. // Increase master volume
  169. float volume = mAudioSystem->GetBusVolume("bus:/");
  170. volume = Math::Min(1.0f, volume + 0.1f);
  171. mAudioSystem->SetBusVolume("bus:/", volume);
  172. break;
  173. }
  174. case '1':
  175. {
  176. // Load English text
  177. LoadText("Assets/English.gptext");
  178. break;
  179. }
  180. case '2':
  181. {
  182. // Load Russian text
  183. LoadText("Assets/Russian.gptext");
  184. break;
  185. }
  186. case SDL_BUTTON_LEFT:
  187. {
  188. break;
  189. }
  190. default:
  191. break;
  192. }
  193. }
  194. void Game::UpdateGame()
  195. {
  196. // Compute delta time
  197. // Wait until 16ms has elapsed since last frame
  198. while (!SDL_TICKS_PASSED(SDL_GetTicks(), mTicksCount + 16))
  199. ;
  200. float deltaTime = (SDL_GetTicks() - mTicksCount) / 1000.0f;
  201. if (deltaTime > 0.05f)
  202. {
  203. deltaTime = 0.05f;
  204. }
  205. mTicksCount = SDL_GetTicks();
  206. if (mGameState == EGameplay)
  207. {
  208. // Update all actors
  209. mUpdatingActors = true;
  210. for (auto actor : mActors)
  211. {
  212. actor->Update(deltaTime);
  213. }
  214. mUpdatingActors = false;
  215. // Move any pending actors to mActors
  216. for (auto pending : mPendingActors)
  217. {
  218. pending->ComputeWorldTransform();
  219. mActors.emplace_back(pending);
  220. }
  221. mPendingActors.clear();
  222. // Add any dead actors to a temp vector
  223. std::vector<Actor*> deadActors;
  224. for (auto actor : mActors)
  225. {
  226. if (actor->GetState() == Actor::EDead)
  227. {
  228. deadActors.emplace_back(actor);
  229. }
  230. }
  231. // Delete dead actors (which removes them from mActors)
  232. for (auto actor : deadActors)
  233. {
  234. delete actor;
  235. }
  236. }
  237. // Update audio system
  238. mAudioSystem->Update(deltaTime);
  239. // Update UI screens
  240. for (auto ui : mUIStack)
  241. {
  242. if (ui->GetState() == UIScreen::EActive)
  243. {
  244. ui->Update(deltaTime);
  245. }
  246. }
  247. // Delete any UIScreens that are closed
  248. auto iter = mUIStack.begin();
  249. while (iter != mUIStack.end())
  250. {
  251. if ((*iter)->GetState() == UIScreen::EClosing)
  252. {
  253. delete *iter;
  254. iter = mUIStack.erase(iter);
  255. }
  256. else
  257. {
  258. ++iter;
  259. }
  260. }
  261. }
  262. void Game::GenerateOutput()
  263. {
  264. mRenderer->Draw();
  265. }
  266. void Game::LoadData()
  267. {
  268. LoadFont("Assets/Carlito-Regular.ttf");
  269. // Load English text
  270. LoadText("Assets/English.gptext");
  271. // Create actors
  272. Actor* a = nullptr;
  273. Quaternion q;
  274. //MeshComponent* mc = nullptr;
  275. // Setup floor
  276. const float start = -1250.0f;
  277. const float size = 250.0f;
  278. for (int i = 0; i < 10; i++)
  279. {
  280. for (int j = 0; j < 10; j++)
  281. {
  282. a = new PlaneActor(this);
  283. a->SetPosition(Vector3(start + i * size, start + j * size, -100.0f));
  284. }
  285. }
  286. // Left/right walls
  287. q = Quaternion(Vector3::UnitX, Math::PiOver2);
  288. for (int i = 0; i < 10; i++)
  289. {
  290. a = new PlaneActor(this);
  291. a->SetPosition(Vector3(start + i * size, start - size, 0.0f));
  292. a->SetRotation(q);
  293. a = new PlaneActor(this);
  294. a->SetPosition(Vector3(start + i * size, -start + size, 0.0f));
  295. a->SetRotation(q);
  296. }
  297. q = Quaternion::Concatenate(q, Quaternion(Vector3::UnitZ, Math::PiOver2));
  298. // Forward/back walls
  299. for (int i = 0; i < 10; i++)
  300. {
  301. a = new PlaneActor(this);
  302. a->SetPosition(Vector3(start - size, start + i * size, 0.0f));
  303. a->SetRotation(q);
  304. a = new PlaneActor(this);
  305. a->SetPosition(Vector3(-start + size, start + i * size, 0.0f));
  306. a->SetRotation(q);
  307. }
  308. // Setup lights
  309. mRenderer->SetAmbientLight(Vector3(0.2f, 0.2f, 0.2f));
  310. DirectionalLight& dir = mRenderer->GetDirectionalLight();
  311. dir.mDirection = Vector3(0.0f, -0.707f, -0.707f);
  312. dir.mDiffuseColor = Vector3(0.78f, 0.88f, 1.0f);
  313. dir.mSpecColor = Vector3(0.8f, 0.8f, 0.8f);
  314. // UI elements
  315. mHUD = new HUD(this);
  316. // Start music
  317. mMusicEvent = mAudioSystem->PlayEvent("event:/Music");
  318. // Enable relative mouse mode for camera look
  319. SDL_SetRelativeMouseMode(SDL_TRUE);
  320. // Make an initial call to get relative to clear out
  321. SDL_GetRelativeMouseState(nullptr, nullptr);
  322. // Different camera actors
  323. mFollowActor = new FollowActor(this);
  324. // Create target actors
  325. a = new TargetActor(this);
  326. a->SetPosition(Vector3(1450.0f, 0.0f, 100.0f));
  327. a = new TargetActor(this);
  328. a->SetPosition(Vector3(1450.0f, 0.0f, 400.0f));
  329. a = new TargetActor(this);
  330. a->SetPosition(Vector3(1450.0f, -500.0f, 200.0f));
  331. a = new TargetActor(this);
  332. a->SetPosition(Vector3(1450.0f, 500.0f, 200.0f));
  333. a = new TargetActor(this);
  334. a->SetPosition(Vector3(0.0f, -1450.0f, 200.0f));
  335. a->SetRotation(Quaternion(Vector3::UnitZ, Math::PiOver2));
  336. a = new TargetActor(this);
  337. a->SetPosition(Vector3(0.0f, 1450.0f, 200.0f));
  338. a->SetRotation(Quaternion(Vector3::UnitZ, -Math::PiOver2));
  339. }
  340. void Game::UnloadData()
  341. {
  342. // Delete actors
  343. // Because ~Actor calls RemoveActor, have to use a different style loop
  344. while (!mActors.empty())
  345. {
  346. delete mActors.back();
  347. }
  348. // Clear the UI stack
  349. while (!mUIStack.empty())
  350. {
  351. delete mUIStack.back();
  352. mUIStack.pop_back();
  353. }
  354. if (mRenderer)
  355. {
  356. mRenderer->UnloadData();
  357. }
  358. // Unload fonts
  359. for (auto f : mFonts)
  360. {
  361. f.second->Unload();
  362. delete f.second;
  363. }
  364. // Unload skeletons
  365. for (auto s : mSkeletons)
  366. {
  367. delete s.second;
  368. }
  369. // Unload animations
  370. for (auto a : mAnims)
  371. {
  372. delete a.second;
  373. }
  374. }
  375. void Game::Shutdown()
  376. {
  377. UnloadData();
  378. TTF_Quit();
  379. delete mPhysWorld;
  380. if (mRenderer)
  381. {
  382. mRenderer->Shutdown();
  383. }
  384. if (mAudioSystem)
  385. {
  386. mAudioSystem->Shutdown();
  387. }
  388. SDL_Quit();
  389. }
  390. void Game::AddActor(Actor* actor)
  391. {
  392. // If we're updating actors, need to add to pending
  393. if (mUpdatingActors)
  394. {
  395. mPendingActors.emplace_back(actor);
  396. }
  397. else
  398. {
  399. mActors.emplace_back(actor);
  400. }
  401. }
  402. void Game::RemoveActor(Actor* actor)
  403. {
  404. // Is it in pending actors?
  405. auto iter = std::find(mPendingActors.begin(), mPendingActors.end(), actor);
  406. if (iter != mPendingActors.end())
  407. {
  408. // Swap to end of vector and pop off (avoid erase copies)
  409. std::iter_swap(iter, mPendingActors.end() - 1);
  410. mPendingActors.pop_back();
  411. }
  412. // Is it in actors?
  413. iter = std::find(mActors.begin(), mActors.end(), actor);
  414. if (iter != mActors.end())
  415. {
  416. // Swap to end of vector and pop off (avoid erase copies)
  417. std::iter_swap(iter, mActors.end() - 1);
  418. mActors.pop_back();
  419. }
  420. }
  421. void Game::PushUI(UIScreen* screen)
  422. {
  423. mUIStack.emplace_back(screen);
  424. }
  425. void Game::LoadFont(const std::string& fileName)
  426. {
  427. Font* font = new Font(this);
  428. if (font->Load(fileName))
  429. {
  430. mFonts.emplace(fileName, font);
  431. }
  432. else
  433. {
  434. font->Unload();
  435. delete font;
  436. }
  437. }
  438. Font* Game::GetFont(const std::string& fileName)
  439. {
  440. auto iter = mFonts.find(fileName);
  441. if (iter != mFonts.end())
  442. {
  443. return iter->second;
  444. }
  445. else
  446. {
  447. return nullptr;
  448. }
  449. }
  450. void Game::LoadText(const std::string& fileName)
  451. {
  452. // Clear the existing map, if already loaded
  453. mText.clear();
  454. // Try to open the file
  455. std::ifstream file(fileName);
  456. if (!file.is_open())
  457. {
  458. SDL_Log("Text file %s not found", fileName.c_str());
  459. return;
  460. }
  461. // Read the entire file to a string stream
  462. std::stringstream fileStream;
  463. fileStream << file.rdbuf();
  464. std::string contents = fileStream.str();
  465. // Open this file in rapidJSON
  466. rapidjson::StringStream jsonStr(contents.c_str());
  467. rapidjson::Document doc;
  468. doc.ParseStream(jsonStr);
  469. if (!doc.IsObject())
  470. {
  471. SDL_Log("Text file %s is not valid JSON", fileName.c_str());
  472. return;
  473. }
  474. // Parse the text map
  475. const rapidjson::Value& actions = doc["TextMap"];
  476. for (rapidjson::Value::ConstMemberIterator itr = actions.MemberBegin();
  477. itr != actions.MemberEnd(); ++itr)
  478. {
  479. if (itr->name.IsString() && itr->value.IsString())
  480. {
  481. mText.emplace(itr->name.GetString(),
  482. itr->value.GetString());
  483. }
  484. }
  485. }
  486. const std::string& Game::GetText(const std::string& key)
  487. {
  488. static std::string errorMsg("**KEY NOT FOUND**");
  489. // Find this text in the map, if it exists
  490. auto iter = mText.find(key);
  491. if (iter != mText.end())
  492. {
  493. return iter->second;
  494. }
  495. else
  496. {
  497. return errorMsg;
  498. }
  499. }
  500. Skeleton* Game::GetSkeleton(const std::string& fileName)
  501. {
  502. auto iter = mSkeletons.find(fileName);
  503. if (iter != mSkeletons.end())
  504. {
  505. return iter->second;
  506. }
  507. else
  508. {
  509. Skeleton* sk = new Skeleton();
  510. if (sk->Load(fileName))
  511. {
  512. mSkeletons.emplace(fileName, sk);
  513. }
  514. else
  515. {
  516. delete sk;
  517. sk = nullptr;
  518. }
  519. return sk;
  520. }
  521. }
  522. Animation* Game::GetAnimation(const std::string& fileName)
  523. {
  524. auto iter = mAnims.find(fileName);
  525. if (iter != mAnims.end())
  526. {
  527. return iter->second;
  528. }
  529. else
  530. {
  531. Animation* anim = new Animation();
  532. if (anim->Load(fileName))
  533. {
  534. mAnims.emplace(fileName, anim);
  535. }
  536. else
  537. {
  538. delete anim;
  539. anim = nullptr;
  540. }
  541. return anim;
  542. }
  543. }