Game.cpp 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530
  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 "FPSActor.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. Game::Game()
  29. :mRenderer(nullptr)
  30. ,mAudioSystem(nullptr)
  31. ,mPhysWorld(nullptr)
  32. ,mGameState(EGameplay)
  33. ,mUpdatingActors(false)
  34. {
  35. }
  36. bool Game::Initialize()
  37. {
  38. if (SDL_Init(SDL_INIT_VIDEO|SDL_INIT_AUDIO) != 0)
  39. {
  40. SDL_Log("Unable to initialize SDL: %s", SDL_GetError());
  41. return false;
  42. }
  43. // Create the renderer
  44. mRenderer = new Renderer(this);
  45. if (!mRenderer->Initialize(1024.0f, 768.0f))
  46. {
  47. SDL_Log("Failed to initialize renderer");
  48. delete mRenderer;
  49. mRenderer = nullptr;
  50. return false;
  51. }
  52. // Create the audio system
  53. mAudioSystem = new AudioSystem(this);
  54. if (!mAudioSystem->Initialize())
  55. {
  56. SDL_Log("Failed to initialize audio system");
  57. mAudioSystem->Shutdown();
  58. delete mAudioSystem;
  59. mAudioSystem = nullptr;
  60. return false;
  61. }
  62. // Create the physics world
  63. mPhysWorld = new PhysWorld(this);
  64. // Initialize SDL_ttf
  65. if (TTF_Init() != 0)
  66. {
  67. SDL_Log("Failed to initialize SDL_ttf");
  68. return false;
  69. }
  70. LoadData();
  71. mTicksCount = SDL_GetTicks();
  72. return true;
  73. }
  74. void Game::RunLoop()
  75. {
  76. while (mGameState != EQuit)
  77. {
  78. ProcessInput();
  79. UpdateGame();
  80. GenerateOutput();
  81. }
  82. }
  83. void Game::AddPlane(PlaneActor* plane)
  84. {
  85. mPlanes.emplace_back(plane);
  86. }
  87. void Game::RemovePlane(PlaneActor* plane)
  88. {
  89. auto iter = std::find(mPlanes.begin(), mPlanes.end(), plane);
  90. mPlanes.erase(iter);
  91. }
  92. void Game::ProcessInput()
  93. {
  94. SDL_Event event;
  95. while (SDL_PollEvent(&event))
  96. {
  97. switch (event.type)
  98. {
  99. case SDL_QUIT:
  100. mGameState = EQuit;
  101. break;
  102. // This fires when a key's initially pressed
  103. case SDL_KEYDOWN:
  104. if (!event.key.repeat)
  105. {
  106. if (mGameState == EGameplay)
  107. {
  108. HandleKeyPress(event.key.keysym.sym);
  109. }
  110. else if (!mUIStack.empty())
  111. {
  112. mUIStack.back()->
  113. HandleKeyPress(event.key.keysym.sym);
  114. }
  115. }
  116. break;
  117. case SDL_MOUSEBUTTONDOWN:
  118. if (mGameState == EGameplay)
  119. {
  120. HandleKeyPress(event.button.button);
  121. }
  122. else if (!mUIStack.empty())
  123. {
  124. mUIStack.back()->
  125. HandleKeyPress(event.button.button);
  126. }
  127. break;
  128. default:
  129. break;
  130. }
  131. }
  132. const Uint8* state = SDL_GetKeyboardState(NULL);
  133. if (mGameState == EGameplay)
  134. {
  135. for (auto actor : mActors)
  136. {
  137. if (actor->GetState() == Actor::EActive)
  138. {
  139. actor->ProcessInput(state);
  140. }
  141. }
  142. }
  143. else if (!mUIStack.empty())
  144. {
  145. mUIStack.back()->ProcessInput(state);
  146. }
  147. }
  148. void Game::HandleKeyPress(int key)
  149. {
  150. switch (key)
  151. {
  152. case SDLK_ESCAPE:
  153. // Create pause menu
  154. new PauseMenu(this);
  155. break;
  156. case '-':
  157. {
  158. // Reduce master volume
  159. float volume = mAudioSystem->GetBusVolume("bus:/");
  160. volume = Math::Max(0.0f, volume - 0.1f);
  161. mAudioSystem->SetBusVolume("bus:/", volume);
  162. break;
  163. }
  164. case '=':
  165. {
  166. // Increase master volume
  167. float volume = mAudioSystem->GetBusVolume("bus:/");
  168. volume = Math::Min(1.0f, volume + 0.1f);
  169. mAudioSystem->SetBusVolume("bus:/", volume);
  170. break;
  171. }
  172. case '1':
  173. {
  174. // Load English text
  175. LoadText("Assets/English.gptext");
  176. break;
  177. }
  178. case '2':
  179. {
  180. // Load Russian text
  181. LoadText("Assets/Russian.gptext");
  182. break;
  183. }
  184. case SDL_BUTTON_LEFT:
  185. {
  186. // Fire weapon
  187. mFPSActor->Shoot();
  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. // Load English text
  269. LoadText("Assets/English.gptext");
  270. // Create actors
  271. Actor* a = nullptr;
  272. Quaternion q;
  273. //MeshComponent* mc = nullptr;
  274. // Setup floor
  275. const float start = -1250.0f;
  276. const float size = 250.0f;
  277. for (int i = 0; i < 10; i++)
  278. {
  279. for (int j = 0; j < 10; j++)
  280. {
  281. a = new PlaneActor(this);
  282. a->SetPosition(Vector3(start + i * size, start + j * size, -100.0f));
  283. }
  284. }
  285. // Left/right walls
  286. q = Quaternion(Vector3::UnitX, Math::PiOver2);
  287. for (int i = 0; i < 10; i++)
  288. {
  289. a = new PlaneActor(this);
  290. a->SetPosition(Vector3(start + i * size, start - size, 0.0f));
  291. a->SetRotation(q);
  292. a = new PlaneActor(this);
  293. a->SetPosition(Vector3(start + i * size, -start + size, 0.0f));
  294. a->SetRotation(q);
  295. }
  296. q = Quaternion::Concatenate(q, Quaternion(Vector3::UnitZ, Math::PiOver2));
  297. // Forward/back walls
  298. for (int i = 0; i < 10; i++)
  299. {
  300. a = new PlaneActor(this);
  301. a->SetPosition(Vector3(start - size, start + i * size, 0.0f));
  302. a->SetRotation(q);
  303. a = new PlaneActor(this);
  304. a->SetPosition(Vector3(-start + size, start + i * size, 0.0f));
  305. a->SetRotation(q);
  306. }
  307. // Setup lights
  308. mRenderer->SetAmbientLight(Vector3(0.2f, 0.2f, 0.2f));
  309. DirectionalLight& dir = mRenderer->GetDirectionalLight();
  310. dir.mDirection = Vector3(0.0f, -0.707f, -0.707f);
  311. dir.mDiffuseColor = Vector3(0.78f, 0.88f, 1.0f);
  312. dir.mSpecColor = Vector3(0.8f, 0.8f, 0.8f);
  313. // UI elements
  314. mHUD = new HUD(this);
  315. // Start music
  316. mMusicEvent = mAudioSystem->PlayEvent("event:/Music");
  317. // Enable relative mouse mode for camera look
  318. SDL_SetRelativeMouseMode(SDL_TRUE);
  319. // Make an initial call to get relative to clear out
  320. SDL_GetRelativeMouseState(nullptr, nullptr);
  321. // Different camera actors
  322. mFPSActor = new FPSActor(this);
  323. // Create target actors
  324. a = new TargetActor(this);
  325. a->SetPosition(Vector3(1450.0f, 0.0f, 100.0f));
  326. a = new TargetActor(this);
  327. a->SetPosition(Vector3(1450.0f, 0.0f, 400.0f));
  328. a = new TargetActor(this);
  329. a->SetPosition(Vector3(1450.0f, -500.0f, 200.0f));
  330. a = new TargetActor(this);
  331. a->SetPosition(Vector3(1450.0f, 500.0f, 200.0f));
  332. a = new TargetActor(this);
  333. a->SetPosition(Vector3(0.0f, -1450.0f, 200.0f));
  334. a->SetRotation(Quaternion(Vector3::UnitZ, Math::PiOver2));
  335. a = new TargetActor(this);
  336. a->SetPosition(Vector3(0.0f, 1450.0f, 200.0f));
  337. a->SetRotation(Quaternion(Vector3::UnitZ, -Math::PiOver2));
  338. }
  339. void Game::UnloadData()
  340. {
  341. // Delete actors
  342. // Because ~Actor calls RemoveActor, have to use a different style loop
  343. while (!mActors.empty())
  344. {
  345. delete mActors.back();
  346. }
  347. // Clear the UI stack
  348. while (!mUIStack.empty())
  349. {
  350. delete mUIStack.back();
  351. mUIStack.pop_back();
  352. }
  353. if (mRenderer)
  354. {
  355. mRenderer->UnloadData();
  356. }
  357. }
  358. void Game::Shutdown()
  359. {
  360. UnloadData();
  361. TTF_Quit();
  362. delete mPhysWorld;
  363. if (mRenderer)
  364. {
  365. mRenderer->Shutdown();
  366. }
  367. if (mAudioSystem)
  368. {
  369. mAudioSystem->Shutdown();
  370. }
  371. SDL_Quit();
  372. }
  373. void Game::AddActor(Actor* actor)
  374. {
  375. // If we're updating actors, need to add to pending
  376. if (mUpdatingActors)
  377. {
  378. mPendingActors.emplace_back(actor);
  379. }
  380. else
  381. {
  382. mActors.emplace_back(actor);
  383. }
  384. }
  385. void Game::RemoveActor(Actor* actor)
  386. {
  387. // Is it in pending actors?
  388. auto iter = std::find(mPendingActors.begin(), mPendingActors.end(), actor);
  389. if (iter != mPendingActors.end())
  390. {
  391. // Swap to end of vector and pop off (avoid erase copies)
  392. std::iter_swap(iter, mPendingActors.end() - 1);
  393. mPendingActors.pop_back();
  394. }
  395. // Is it in actors?
  396. iter = std::find(mActors.begin(), mActors.end(), actor);
  397. if (iter != mActors.end())
  398. {
  399. // Swap to end of vector and pop off (avoid erase copies)
  400. std::iter_swap(iter, mActors.end() - 1);
  401. mActors.pop_back();
  402. }
  403. }
  404. void Game::PushUI(UIScreen* screen)
  405. {
  406. mUIStack.emplace_back(screen);
  407. }
  408. Font* Game::GetFont(const std::string& fileName)
  409. {
  410. auto iter = mFonts.find(fileName);
  411. if (iter != mFonts.end())
  412. {
  413. return iter->second;
  414. }
  415. else
  416. {
  417. Font* font = new Font(this);
  418. if (font->Load(fileName))
  419. {
  420. mFonts.emplace(fileName, font);
  421. }
  422. else
  423. {
  424. font->Unload();
  425. delete font;
  426. font = nullptr;
  427. }
  428. return font;
  429. }
  430. }
  431. void Game::LoadText(const std::string& fileName)
  432. {
  433. // Clear the existing map, if already loaded
  434. mText.clear();
  435. // Try to open the file
  436. std::ifstream file(fileName);
  437. if (!file.is_open())
  438. {
  439. SDL_Log("Text file %s not found", fileName.c_str());
  440. return;
  441. }
  442. // Read the entire file to a string stream
  443. std::stringstream fileStream;
  444. fileStream << file.rdbuf();
  445. std::string contents = fileStream.str();
  446. // Open this file in rapidJSON
  447. rapidjson::StringStream jsonStr(contents.c_str());
  448. rapidjson::Document doc;
  449. doc.ParseStream(jsonStr);
  450. if (!doc.IsObject())
  451. {
  452. SDL_Log("Text file %s is not valid JSON", fileName.c_str());
  453. return;
  454. }
  455. // Parse the text map
  456. const rapidjson::Value& actions = doc["TextMap"];
  457. for (rapidjson::Value::ConstMemberIterator itr = actions.MemberBegin();
  458. itr != actions.MemberEnd(); ++itr)
  459. {
  460. if (itr->name.IsString() && itr->value.IsString())
  461. {
  462. mText.emplace(itr->name.GetString(),
  463. itr->value.GetString());
  464. }
  465. }
  466. }
  467. const std::string& Game::GetText(const std::string& key)
  468. {
  469. static std::string errorMsg("**KEY NOT FOUND**");
  470. // Find this text in the map, if it exists
  471. auto iter = mText.find(key);
  472. if (iter != mText.end())
  473. {
  474. return iter->second;
  475. }
  476. else
  477. {
  478. return errorMsg;
  479. }
  480. }