Game.cpp 7.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375
  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 <GL/glew.h>
  10. #include "Texture.h"
  11. #include "VertexArray.h"
  12. #include "Shader.h"
  13. #include <algorithm>
  14. #include "Actor.h"
  15. #include "SpriteComponent.h"
  16. #include "Actor.h"
  17. #include "Ship.h"
  18. #include "Asteroid.h"
  19. #include "Random.h"
  20. Game::Game()
  21. :mWindow(nullptr)
  22. ,mSpriteShader(nullptr)
  23. ,mIsRunning(true)
  24. ,mUpdatingActors(false)
  25. {
  26. }
  27. bool Game::Initialize()
  28. {
  29. if (SDL_Init(SDL_INIT_VIDEO|SDL_INIT_AUDIO) != 0)
  30. {
  31. SDL_Log("Unable to initialize SDL: %s", SDL_GetError());
  32. return false;
  33. }
  34. // Set OpenGL attributes
  35. // Use the core OpenGL profile
  36. SDL_GL_SetAttribute(SDL_GL_CONTEXT_PROFILE_MASK, SDL_GL_CONTEXT_PROFILE_CORE);
  37. // Specify version 3.3
  38. SDL_GL_SetAttribute(SDL_GL_CONTEXT_MAJOR_VERSION, 3);
  39. SDL_GL_SetAttribute(SDL_GL_CONTEXT_MINOR_VERSION, 3);
  40. // Request a color buffer with 8-bits per RGBA channel
  41. SDL_GL_SetAttribute(SDL_GL_RED_SIZE, 8);
  42. SDL_GL_SetAttribute(SDL_GL_GREEN_SIZE, 8);
  43. SDL_GL_SetAttribute(SDL_GL_BLUE_SIZE, 8);
  44. SDL_GL_SetAttribute(SDL_GL_ALPHA_SIZE, 8);
  45. // Enable double buffering
  46. SDL_GL_SetAttribute(SDL_GL_DOUBLEBUFFER, 1);
  47. // Force OpenGL to use hardware acceleration
  48. SDL_GL_SetAttribute(SDL_GL_ACCELERATED_VISUAL, 1);
  49. mWindow = SDL_CreateWindow("Game Programming in C++ (Chapter 5)", 100, 100,
  50. 1024, 768, SDL_WINDOW_OPENGL);
  51. if (!mWindow)
  52. {
  53. SDL_Log("Failed to create window: %s", SDL_GetError());
  54. return false;
  55. }
  56. // Create an OpenGL context
  57. mContext = SDL_GL_CreateContext(mWindow);
  58. // Initialize GLEW
  59. glewExperimental = GL_TRUE;
  60. if (glewInit() != GLEW_OK)
  61. {
  62. SDL_Log("Failed to initialize GLEW.");
  63. return false;
  64. }
  65. // On some platforms, GLEW will emit a benign error code,
  66. // so clear it
  67. glGetError();
  68. // Make sure we can create/compile shaders
  69. if (!LoadShaders())
  70. {
  71. SDL_Log("Failed to load shaders.");
  72. return false;
  73. }
  74. // Create quad for drawing sprites
  75. CreateSpriteVerts();
  76. LoadData();
  77. mTicksCount = SDL_GetTicks();
  78. return true;
  79. }
  80. void Game::RunLoop()
  81. {
  82. while (mIsRunning)
  83. {
  84. ProcessInput();
  85. UpdateGame();
  86. GenerateOutput();
  87. }
  88. }
  89. void Game::ProcessInput()
  90. {
  91. SDL_Event event;
  92. while (SDL_PollEvent(&event))
  93. {
  94. switch (event.type)
  95. {
  96. case SDL_QUIT:
  97. mIsRunning = false;
  98. break;
  99. }
  100. }
  101. const Uint8* keyState = SDL_GetKeyboardState(NULL);
  102. if (keyState[SDL_SCANCODE_ESCAPE])
  103. {
  104. mIsRunning = false;
  105. }
  106. mUpdatingActors = true;
  107. for (auto actor : mActors)
  108. {
  109. actor->ProcessInput(keyState);
  110. }
  111. mUpdatingActors = false;
  112. }
  113. void Game::UpdateGame()
  114. {
  115. // Compute delta time
  116. // Wait until 16ms has elapsed since last frame
  117. while (!SDL_TICKS_PASSED(SDL_GetTicks(), mTicksCount + 16))
  118. ;
  119. float deltaTime = (SDL_GetTicks() - mTicksCount) / 1000.0f;
  120. if (deltaTime > 0.05f)
  121. {
  122. deltaTime = 0.05f;
  123. }
  124. mTicksCount = SDL_GetTicks();
  125. // Update all actors
  126. mUpdatingActors = true;
  127. for (auto actor : mActors)
  128. {
  129. actor->Update(deltaTime);
  130. }
  131. mUpdatingActors = false;
  132. // Move any pending actors to mActors
  133. for (auto pending : mPendingActors)
  134. {
  135. pending->ComputeWorldTransform();
  136. mActors.emplace_back(pending);
  137. }
  138. mPendingActors.clear();
  139. // Add any dead actors to a temp vector
  140. std::vector<Actor*> deadActors;
  141. for (auto actor : mActors)
  142. {
  143. if (actor->GetState() == Actor::EDead)
  144. {
  145. deadActors.emplace_back(actor);
  146. }
  147. }
  148. // Delete dead actors (which removes them from mActors)
  149. for (auto actor : deadActors)
  150. {
  151. delete actor;
  152. }
  153. }
  154. void Game::GenerateOutput()
  155. {
  156. // Set the clear color to grey
  157. glClearColor(0.86f, 0.86f, 0.86f, 1.0f);
  158. // Clear the color buffer
  159. glClear(GL_COLOR_BUFFER_BIT);
  160. // Draw all sprite components
  161. // Enable alpha blending on the color buffer
  162. glEnable(GL_BLEND);
  163. glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
  164. // Set shader/vao as active
  165. mSpriteShader->SetActive();
  166. mSpriteVerts->SetActive();
  167. for (auto sprite : mSprites)
  168. {
  169. sprite->Draw(mSpriteShader);
  170. }
  171. // Swap the buffers
  172. SDL_GL_SwapWindow(mWindow);
  173. }
  174. bool Game::LoadShaders()
  175. {
  176. mSpriteShader = new Shader();
  177. if (!mSpriteShader->Load("Shaders/Sprite.vert", "Shaders/Sprite.frag"))
  178. {
  179. return false;
  180. }
  181. mSpriteShader->SetActive();
  182. // Set the view-projection matrix
  183. Matrix4 viewProj = Matrix4::CreateSimpleViewProj(1024.f, 768.f);
  184. mSpriteShader->SetMatrixUniform("uViewProj", viewProj);
  185. return true;
  186. }
  187. void Game::CreateSpriteVerts()
  188. {
  189. float vertices[] = {
  190. -0.5f, 0.5f, 0.f, 0.f, 0.f, // top left
  191. 0.5f, 0.5f, 0.f, 1.f, 0.f, // top right
  192. 0.5f, -0.5f, 0.f, 1.f, 1.f, // bottom right
  193. -0.5f, -0.5f, 0.f, 0.f, 1.f // bottom left
  194. };
  195. unsigned int indices[] = {
  196. 0, 1, 2,
  197. 2, 3, 0
  198. };
  199. mSpriteVerts = new VertexArray(vertices, 4, indices, 6);
  200. }
  201. void Game::LoadData()
  202. {
  203. // Create player's ship
  204. mShip = new Ship(this);
  205. mShip->SetRotation(Math::PiOver2);
  206. // Create asteroids
  207. const int numAsteroids = 20;
  208. for (int i = 0; i < numAsteroids; i++)
  209. {
  210. new Asteroid(this);
  211. }
  212. }
  213. void Game::UnloadData()
  214. {
  215. // Delete actors
  216. // Because ~Actor calls RemoveActor, have to use a different style loop
  217. while (!mActors.empty())
  218. {
  219. delete mActors.back();
  220. }
  221. // Destroy textures
  222. for (auto i : mTextures)
  223. {
  224. i.second->Unload();
  225. delete i.second;
  226. }
  227. mTextures.clear();
  228. }
  229. Texture* Game::GetTexture(const std::string& fileName)
  230. {
  231. Texture* tex = nullptr;
  232. auto iter = mTextures.find(fileName);
  233. if (iter != mTextures.end())
  234. {
  235. tex = iter->second;
  236. }
  237. else
  238. {
  239. tex = new Texture();
  240. if (tex->Load(fileName))
  241. {
  242. mTextures.emplace(fileName, tex);
  243. }
  244. else
  245. {
  246. delete tex;
  247. tex = nullptr;
  248. }
  249. }
  250. return tex;
  251. }
  252. void Game::AddAsteroid(Asteroid* ast)
  253. {
  254. mAsteroids.emplace_back(ast);
  255. }
  256. void Game::RemoveAsteroid(Asteroid* ast)
  257. {
  258. auto iter = std::find(mAsteroids.begin(),
  259. mAsteroids.end(), ast);
  260. if (iter != mAsteroids.end())
  261. {
  262. mAsteroids.erase(iter);
  263. }
  264. }
  265. void Game::Shutdown()
  266. {
  267. UnloadData();
  268. delete mSpriteVerts;
  269. mSpriteShader->Unload();
  270. delete mSpriteShader;
  271. SDL_GL_DeleteContext(mContext);
  272. SDL_DestroyWindow(mWindow);
  273. SDL_Quit();
  274. }
  275. void Game::AddActor(Actor* actor)
  276. {
  277. // If we're updating actors, need to add to pending
  278. if (mUpdatingActors)
  279. {
  280. mPendingActors.emplace_back(actor);
  281. }
  282. else
  283. {
  284. mActors.emplace_back(actor);
  285. }
  286. }
  287. void Game::RemoveActor(Actor* actor)
  288. {
  289. // Is it in pending actors?
  290. auto iter = std::find(mPendingActors.begin(), mPendingActors.end(), actor);
  291. if (iter != mPendingActors.end())
  292. {
  293. // Swap to end of vector and pop off (avoid erase copies)
  294. std::iter_swap(iter, mPendingActors.end() - 1);
  295. mPendingActors.pop_back();
  296. }
  297. // Is it in actors?
  298. iter = std::find(mActors.begin(), mActors.end(), actor);
  299. if (iter != mActors.end())
  300. {
  301. // Swap to end of vector and pop off (avoid erase copies)
  302. std::iter_swap(iter, mActors.end() - 1);
  303. mActors.pop_back();
  304. }
  305. }
  306. void Game::AddSprite(SpriteComponent* sprite)
  307. {
  308. // Find the insertion point in the sorted vector
  309. // (The first element with a higher draw order than me)
  310. int myDrawOrder = sprite->GetDrawOrder();
  311. auto iter = mSprites.begin();
  312. for (;
  313. iter != mSprites.end();
  314. ++iter)
  315. {
  316. if (myDrawOrder < (*iter)->GetDrawOrder())
  317. {
  318. break;
  319. }
  320. }
  321. // Inserts element before position of iterator
  322. mSprites.insert(iter, sprite);
  323. }
  324. void Game::RemoveSprite(SpriteComponent* sprite)
  325. {
  326. auto iter = std::find(mSprites.begin(), mSprites.end(), sprite);
  327. mSprites.erase(iter);
  328. }