BaseGameLogic.cpp 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449
  1. //========================================================================
  2. // BaseGameLogic.cpp : defines game logic class
  3. //
  4. // Part of the GameCode4 Application
  5. //
  6. // GameCode4 is the sample application that encapsulates much of the source code
  7. // discussed in "Game Coding Complete - 4th Edition" by Mike McShaffry and David
  8. // "Rez" Graham, published by Charles River Media.
  9. // ISBN-10: 1133776574 | ISBN-13: 978-1133776574
  10. //
  11. // If this source code has found it's way to you, and you think it has helped you
  12. // in any way, do the authors a favor and buy a new copy of the book - there are
  13. // detailed explanations in it that compliment this code well. Buy a copy at Amazon.com
  14. // by clicking here:
  15. // http://www.amazon.com/gp/product/1133776574/ref=olp_product_details?ie=UTF8&me=&seller=
  16. //
  17. // There's a companion web site at http://www.mcshaffry.com/GameCode/
  18. //
  19. // The source code is managed and maintained through Google Code:
  20. // http://code.google.com/p/gamecode4/
  21. //
  22. // (c) Copyright 2012 Michael L. McShaffry and David Graham
  23. //
  24. // This program is free software; you can redistribute it and/or
  25. // modify it under the terms of the GNU Lesser GPL v3
  26. // as published by the Free Software Foundation.
  27. //
  28. // This program is distributed in the hope that it will be useful,
  29. // but WITHOUT ANY WARRANTY; without even the implied warranty of
  30. // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See
  31. // http://www.gnu.org/licenses/lgpl-3.0.txt for more details.
  32. //
  33. // You should have received a copy of the GNU Lesser GPL v3
  34. // along with this program; if not, write to the Free Software
  35. // Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
  36. //
  37. //========================================================================
  38. #include "../Unix/GameCodeStd.h"
  39. #include "../EventManager/Events.h" // only for EvtData_Game_State
  40. #include "../ResourceCache/XmlResource.h"
  41. #include "../UserInterface/HumanView.h" // [rez] not ideal, but the loading sequence needs to know if this is a human view
  42. #include "BaseGameLogic.h"
  43. //========================================================================
  44. //
  45. // LevelManager implementation
  46. //
  47. //========================================================================
  48. bool LevelManager::Initialize(std::vector<std::string> &levels)
  49. {
  50. std::vector<std::string>::iterator i = levels.begin();
  51. while (i != levels.end())
  52. {
  53. m_Levels.push_back(*i);
  54. ++i;
  55. }
  56. return true;
  57. }
  58. //========================================================================
  59. //
  60. // BaseGameLogic implementation
  61. //
  62. //========================================================================
  63. BaseGameLogic::BaseGameLogic()
  64. {
  65. m_Lifetime = 0;
  66. m_State = BGS_Initializing;
  67. m_bProxy = false;
  68. m_ExpectedPlayers = 0;
  69. m_ExpectedRemotePlayers = 0;
  70. m_ExpectedAI = 0;
  71. m_HumanPlayersAttached = 0;
  72. m_AIPlayersAttached = 0;
  73. m_HumanGamesLoaded = 0;
  74. m_pLevelManager = GCC_NEW LevelManager;
  75. // GCC_ASSERT(m_pProcessManager && m_pLevelManager);
  76. // TODO(munnellg) - book passes levels directly, but my compiler doesn't like that. Find out why
  77. std::vector<std::string> levels = g_pApp->m_ResCache->Match("world/*.xml");
  78. m_pLevelManager->Initialize(levels);
  79. }
  80. BaseGameLogic::~BaseGameLogic()
  81. {
  82. // MrMike: 12-Apr-2009
  83. // Added this to explicitly remove views from the game logic list.
  84. while (!m_gameViews.empty())
  85. m_gameViews.pop_front();
  86. SAFE_DELETE(m_pLevelManager);
  87. // SAFE_DELETE(m_pProcessManager);
  88. SAFE_DELETE(m_pActorFactory);
  89. // destroy all actors
  90. for (auto it = m_actors.begin(); it != m_actors.end(); ++it)
  91. it->second->Destroy();
  92. m_actors.clear();
  93. // IEventManager::Get()->VRemoveListener(MakeDelegate(this, &BaseGameLogic::RequestDestroyActorDelegate), EvtData_Request_Destroy_Actor::sk_EventType);
  94. }
  95. bool BaseGameLogic::Init(void)
  96. {
  97. m_pActorFactory = VCreateActorFactory();
  98. // m_pPathingGraph.reset(CreatePathingGraph());
  99. // IEventManager::Get()->VAddListener(MakeDelegate(this, &BaseGameLogic::RequestDestroyActorDelegate), EvtData_Request_Destroy_Actor::sk_EventType);
  100. return true;
  101. }
  102. bool BaseGameLogic::VLoadGame(const char* levelResource)
  103. {
  104. // Grab the root XML node
  105. TiXmlElement* pRoot = XmlResourceLoader::LoadAndReturnRootXmlElement(levelResource);
  106. if (!pRoot)
  107. {
  108. GCC_ERROR("Failed to find level resource file: " + std::string(levelResource));
  109. return false;
  110. }
  111. // pre and post load scripts
  112. const char* preLoadScript = NULL;
  113. const char* postLoadScript = NULL;
  114. // parse the pre & post script attributes
  115. TiXmlElement* pScriptElement = pRoot->FirstChildElement("Script");
  116. if (pScriptElement)
  117. {
  118. preLoadScript = pScriptElement->Attribute("preLoad");
  119. postLoadScript = pScriptElement->Attribute("postLoad");
  120. }
  121. // load the pre-load script if there is one
  122. if (preLoadScript)
  123. {
  124. Resource resource(preLoadScript);
  125. std::shared_ptr<ResHandle> pResourceHandle = g_pApp->m_ResCache->GetHandle(&resource);
  126. }
  127. // load all initial actors
  128. TiXmlElement* pActorsNode = pRoot->FirstChildElement("StaticActors");
  129. if (pActorsNode)
  130. {
  131. for (TiXmlElement* pNode = pActorsNode->FirstChildElement(); pNode; pNode = pNode->NextSiblingElement())
  132. {
  133. const char* actorResource = pNode->Attribute("resource");
  134. StrongActorPtr pActor = VCreateActor(actorResource, pNode);
  135. if (pActor)
  136. {
  137. // fire an event letting everyone else know that we created a new actor
  138. std::shared_ptr<EvtData_New_Actor> pNewActorEvent(GCC_NEW EvtData_New_Actor(pActor->GetId()));
  139. IEventManager::Get()->VQueueEvent(pNewActorEvent);
  140. }
  141. }
  142. }
  143. // initialize all human views
  144. for (auto it = m_gameViews.begin(); it != m_gameViews.end(); ++it)
  145. {
  146. std::shared_ptr<IGameView> pView = *it;
  147. if (pView->VGetType() == GameView_Human)
  148. {
  149. std::shared_ptr<HumanView> pHumanView = static_pointer_cast<HumanView, IGameView>(pView);
  150. pHumanView->LoadGame(pRoot);
  151. }
  152. }
  153. // register script events from the engine
  154. // [mrmike] this was moved to the constructor post-press, since this function can be called when new levels are loaded by the game or editor
  155. // RegisterEngineScriptEvents();
  156. // call the delegate load function
  157. if (!VLoadGameDelegate(pRoot))
  158. return false; // no error message here because it's assumed VLoadGameDelegate() kicked out the error
  159. // load the post-load script if there is one
  160. if (postLoadScript)
  161. {
  162. Resource resource(postLoadScript);
  163. std::shared_ptr<ResHandle> pResourceHandle = g_pApp->m_ResCache->GetHandle(&resource); // this actually loads the XML file from the zip file
  164. }
  165. // trigger the Environment Loaded Game event - only then can player actors and AI be spawned!
  166. if (m_bProxy)
  167. {
  168. std::shared_ptr<EvtData_Remote_Environment_Loaded> pNewGameEvent(GCC_NEW EvtData_Remote_Environment_Loaded);
  169. IEventManager::Get()->VTriggerEvent(pNewGameEvent);
  170. }
  171. else
  172. {
  173. std::shared_ptr<EvtData_Environment_Loaded> pNewGameEvent(GCC_NEW EvtData_Environment_Loaded);
  174. IEventManager::Get()->VTriggerEvent(pNewGameEvent);
  175. }
  176. return true;
  177. }
  178. void BaseGameLogic::VSetProxy()
  179. {
  180. m_bProxy = true;
  181. // IEventManager::Get()->VAddListener(MakeDelegate(this, &BaseGameLogic::RequestNewActorDelegate), EvtData_Request_New_Actor::sk_EventType);
  182. // m_pPhysics.reset(CreateNullPhysics());
  183. }
  184. StrongActorPtr BaseGameLogic::VCreateActor(
  185. const std::string &actorResource,
  186. TiXmlElement* overrides,
  187. std::optional<const glm::mat4> initialTransform,
  188. const ActorId serversActorId
  189. ) {
  190. GCC_ASSERT(m_pActorFactory);
  191. if (!m_bProxy && serversActorId != INVALID_ACTOR_ID)
  192. return StrongActorPtr();
  193. if (m_bProxy && serversActorId == INVALID_ACTOR_ID)
  194. return StrongActorPtr();
  195. StrongActorPtr pActor = m_pActorFactory->CreateActor(actorResource.c_str(), overrides, initialTransform, serversActorId);
  196. if (pActor)
  197. {
  198. m_actors.insert(std::make_pair(pActor->GetId(), pActor));
  199. if (!m_bProxy && (m_State==BGS_SpawningPlayersActors || m_State==BGS_Running))
  200. {
  201. std::shared_ptr<EvtData_Request_New_Actor> pNewActor(GCC_NEW EvtData_Request_New_Actor(actorResource, initialTransform, pActor->GetId()));
  202. IEventManager::Get()->VTriggerEvent(pNewActor);
  203. }
  204. return pActor;
  205. }
  206. else
  207. {
  208. return StrongActorPtr();
  209. }
  210. }
  211. void BaseGameLogic::VDestroyActor(const ActorId actorId)
  212. {
  213. std::shared_ptr<EvtData_Destroy_Actor> pEvent(GCC_NEW EvtData_Destroy_Actor(actorId));
  214. IEventManager::Get()->VTriggerEvent(pEvent);
  215. auto findIt = m_actors.find(actorId);
  216. if (findIt != m_actors.end())
  217. {
  218. findIt->second->Destroy();
  219. m_actors.erase(findIt);
  220. }
  221. }
  222. WeakActorPtr BaseGameLogic::VGetActor(const ActorId actorId)
  223. {
  224. ActorMap::iterator findIt = m_actors.find(actorId);
  225. if (findIt != m_actors.end())
  226. return findIt->second;
  227. return WeakActorPtr();
  228. }
  229. void BaseGameLogic::VModifyActor(const ActorId actorId, TiXmlElement *override)
  230. {
  231. GCC_ASSERT(m_pActorFactory);
  232. if (!m_pActorFactory)
  233. return;
  234. auto findIt = m_actors.find(actorId);
  235. if (findIt != m_actors.end())
  236. {
  237. m_pActorFactory->ModifyActor(findIt->second, override);
  238. }
  239. }
  240. void BaseGameLogic::VOnUpdate(float time, float elapsedTime)
  241. {
  242. int deltaMilliseconds = int(elapsedTime * 1000.0f);
  243. m_Lifetime += elapsedTime;
  244. switch(m_State)
  245. {
  246. case BGS_Initializing:
  247. {
  248. // If we get to here we're ready to attach players
  249. VChangeState(BGS_MainMenu);
  250. break;
  251. }
  252. case BGS_MainMenu:
  253. {
  254. break;
  255. }
  256. case BGS_LoadingGameEnvironment:
  257. {
  258. /***
  259. // [mrmike] This was modified a little from what you see in the book - VLoadGame() is now called from
  260. // BaseGameLogic::VChangeState()
  261. //
  262. if (!g_pApp->VLoadGame())
  263. {
  264. GCC_ERROR("The game failed to load.");
  265. g_pApp->AbortGame();
  266. }
  267. ***/
  268. break;
  269. }
  270. case BGS_WaitingForPlayersToLoadEnvironment:
  271. {
  272. if (m_ExpectedPlayers + m_ExpectedRemotePlayers <= m_HumanGamesLoaded)
  273. {
  274. VChangeState(BGS_SpawningPlayersActors);
  275. }
  276. break;
  277. }
  278. case BGS_SpawningPlayersActors:
  279. {
  280. VChangeState(BGS_Running);
  281. break;
  282. }
  283. case BGS_WaitingForPlayers:
  284. {
  285. if (m_ExpectedPlayers + m_ExpectedRemotePlayers == m_HumanPlayersAttached)
  286. {
  287. // The server sends us the level name as a part of the login message.
  288. // We have to wait until it arrives before loading the level
  289. if (!g_pApp->m_Options.m_Level.empty())
  290. {
  291. VChangeState(BGS_LoadingGameEnvironment);
  292. }
  293. }
  294. break;
  295. }
  296. case BGS_Running:
  297. {
  298. // m_pProcessManager->UpdateProcesses(deltaMilliseconds);
  299. // if (m_pPhysics && !m_bProxy)
  300. // {
  301. // m_pPhysics->VOnUpdate(elapsedTime);
  302. // m_pPhysics->VSyncVisibleScene();
  303. // }
  304. break;
  305. }
  306. default:
  307. GCC_ERROR("Unrecognized state.");
  308. }
  309. // update all game views
  310. for (GameViewList::iterator it = m_gameViews.begin(); it != m_gameViews.end(); ++it)
  311. {
  312. (*it)->VOnUpdate(deltaMilliseconds);
  313. }
  314. // update game actors
  315. // for (ActorMap::const_iterator it = m_actors.begin(); it != m_actors.end(); ++it)
  316. // {
  317. // it->second->Update(deltaMilliseconds);
  318. // }
  319. }
  320. //
  321. // BaseGameLogic::VChangeState - Chapter 19, page 710
  322. //
  323. void BaseGameLogic::VChangeState(BaseGameState newState)
  324. {
  325. // TODO(munnellg) - implement
  326. if (newState==BGS_WaitingForPlayers)
  327. {
  328. // Get rid of the Main Menu
  329. m_gameViews.pop_front();
  330. // Note: Split screen support would require this to change!
  331. m_ExpectedPlayers = 1;
  332. m_ExpectedRemotePlayers = g_pApp->m_Options.m_expectedPlayers - 1;
  333. m_ExpectedAI = g_pApp->m_Options.m_numAIs;
  334. if (!g_pApp->m_Options.m_gameHost.empty())
  335. {
  336. VSetProxy();
  337. m_ExpectedAI = 0; // the server will create these
  338. m_ExpectedRemotePlayers = 0; // the server will create these
  339. // TODO(munnellg) - implement
  340. // if (!g_pApp->AttachAsClient())
  341. // {
  342. // // Throw up a main menu
  343. // VChangeState(BGS_MainMenu);
  344. // return
  345. // }
  346. }
  347. // else if (m_ExpectedRemotePlayers > 0)
  348. // {
  349. // TODO(munnellg) - implement for network games
  350. // }
  351. }
  352. else if (newState == BGS_LoadingGameEnvironment)
  353. {
  354. m_State = newState;
  355. if (!g_pApp->VLoadGame())
  356. {
  357. GCC_ERROR("The game failed to load.");
  358. g_pApp->AbortGame();
  359. }
  360. else
  361. {
  362. VChangeState(BGS_WaitingForPlayersToLoadEnvironment); // we must wait for all human player to report their environments are loaded.
  363. return;
  364. }
  365. }
  366. m_State = newState;
  367. }
  368. // Chapter 19/20 refactor work
  369. // - move physics pointer into BaseGameLogic
  370. // - but make the inherited logic choose the implementation
  371. void BaseGameLogic::VRenderDiagnostics()
  372. {
  373. if (m_RenderDiagnostics)
  374. {
  375. // TODO(munnellg) - uncomment this when we have physics
  376. // m_pPhysics->VRenderDiagnostics();
  377. }
  378. }
  379. void BaseGameLogic::VAddView(std::shared_ptr<IGameView> pView, ActorId actorId)
  380. {
  381. // This makes sure that all views have a non-zero view id.
  382. int viewId = static_cast<int>(m_gameViews.size());
  383. m_gameViews.push_back(pView);
  384. pView->VOnAttach(viewId, actorId);
  385. pView->VOnRestore();
  386. }
  387. void BaseGameLogic::VRemoveView(std::shared_ptr<IGameView> pView)
  388. {
  389. m_gameViews.remove(pView);
  390. }
  391. ActorFactory* BaseGameLogic::VCreateActorFactory(void)
  392. {
  393. return GCC_NEW ActorFactory;
  394. }