Game.cpp 12 KB

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