HeroMovementController.cpp 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421
  1. /*
  2. * HeroMovementController.cpp, part of VCMI engine
  3. *
  4. * Authors: listed in file AUTHORS in main folder
  5. *
  6. * License: GNU General Public License v2.0 or later
  7. * Full text of license available in license.txt file, in main folder
  8. *
  9. */
  10. #include "StdInc.h"
  11. #include "HeroMovementController.h"
  12. #include "CPlayerInterface.h"
  13. #include "PlayerLocalState.h"
  14. #include "adventureMap/AdventureMapInterface.h"
  15. #include "eventsSDL/InputHandler.h"
  16. #include "GameEngine.h"
  17. #include "GameInstance.h"
  18. #include "gui/CursorHandler.h"
  19. #include "mapView/mapHandler.h"
  20. #include "media/ISoundPlayer.h"
  21. #include "../lib/ConditionalWait.h"
  22. #include "../lib/CConfigHandler.h"
  23. #include "../lib/CRandomGenerator.h"
  24. #include "../lib/callback/CCallback.h"
  25. #include "../lib/pathfinder/CGPathNode.h"
  26. #include "../lib/mapObjects/CGHeroInstance.h"
  27. #include "../lib/mapping/TerrainTile.h"
  28. #include "../lib/networkPacks/PacksForClient.h"
  29. #include "../lib/RoadHandler.h"
  30. #include "../lib/TerrainHandler.h"
  31. bool HeroMovementController::isHeroMovingThroughGarrison(const CGHeroInstance * hero, const CArmedInstance * garrison) const
  32. {
  33. if(!duringMovement)
  34. return false;
  35. if(!GAME->interface()->localState->hasPath(hero))
  36. return false;
  37. if(garrison->visitableAt(GAME->interface()->localState->getPath(hero).lastNode().coord))
  38. return false; // hero want to enter garrison, not pass through it
  39. return true;
  40. }
  41. bool HeroMovementController::isHeroMoving() const
  42. {
  43. return duringMovement;
  44. }
  45. void HeroMovementController::onPlayerTurnStarted()
  46. {
  47. assert(duringMovement == false);
  48. assert(stoppingMovement == false);
  49. duringMovement = false;
  50. currentlyMovingHero = nullptr;
  51. }
  52. void HeroMovementController::onBattleStarted()
  53. {
  54. // when battle starts, game will send battleStart pack *before* movement confirmation
  55. // and since network thread wait for battle intro to play, movement confirmation will only happen after intro
  56. // leading to several bugs, such as blocked input during intro
  57. requestMovementAbort();
  58. }
  59. void HeroMovementController::showTeleportDialog(const CGHeroInstance * hero, TeleportChannelID channel, TTeleportExitsList exits, bool impassable, QueryID askID)
  60. {
  61. if (impassable || exits.empty()) //FIXME: why we even have this dialog in such case?
  62. {
  63. GAME->interface()->cb->selectionMade(-1, askID);
  64. return;
  65. }
  66. // Player entered teleporter
  67. // Check whether hero that has entered teleporter has paths that goes through teleporter and select appropriate exit
  68. // othervice, ask server to select one randomly by sending invalid (-1) value as answer
  69. assert(waitingForQueryApplyReply == false);
  70. waitingForQueryApplyReply = true;
  71. if(!GAME->interface()->localState->hasPath(hero))
  72. {
  73. // Hero enters teleporter without specifying exit - select it randomly
  74. GAME->interface()->cb->selectionMade(-1, askID);
  75. return;
  76. }
  77. const auto & heroPath = GAME->interface()->localState->getPath(hero);
  78. const auto & nextNode = heroPath.nextNode();
  79. for(size_t i = 0; i < exits.size(); ++i)
  80. {
  81. if(exits[i].second == nextNode.coord)
  82. {
  83. // Remove this node from path - it will be covered by teleportation
  84. //GAME->interface()->localState->removeLastNode(hero);
  85. GAME->interface()->cb->selectionMade(i, askID);
  86. return;
  87. }
  88. }
  89. // may happen when hero has path but does not moves alongside it
  90. // for example, while standing on teleporter set path that does not leads throught teleporter and press space
  91. GAME->interface()->cb->selectionMade(-1, askID);
  92. return;
  93. }
  94. void HeroMovementController::updatePath(const CGHeroInstance * hero, const TryMoveHero & details)
  95. {
  96. // Once hero moved (or attempted to move) we need to update path
  97. // to make sure that it is still valid or remove it completely if destination has been reached
  98. if(hero->tempOwner != GAME->interface()->playerID)
  99. return;
  100. if(!GAME->interface()->localState->hasPath(hero))
  101. return; // may happen when hero teleports
  102. assert(GAME->interface()->makingTurn);
  103. bool directlyAttackingCreature = details.attackedFrom.isValid() && GAME->interface()->localState->getPath(hero).lastNode().coord == details.attackedFrom;
  104. int3 desiredTarget = GAME->interface()->localState->getPath(hero).nextNode().coord;
  105. int3 actualTarget = hero->convertToVisitablePos(details.end);
  106. //don't erase path when revisiting with spacebar
  107. bool heroChangedTile = details.start != details.end;
  108. if(heroChangedTile)
  109. {
  110. if(desiredTarget != actualTarget)
  111. {
  112. //invalidate path - movement was not along current path
  113. //possible reasons: teleport, visit of object with "blocking visit" property
  114. GAME->interface()->localState->erasePath(hero);
  115. }
  116. else
  117. {
  118. //movement along desired path - remove one node and keep rest of path
  119. GAME->interface()->localState->removeLastNode(hero);
  120. }
  121. if(directlyAttackingCreature)
  122. GAME->interface()->localState->erasePath(hero);
  123. }
  124. }
  125. void HeroMovementController::onTryMoveHero(const CGHeroInstance * hero, const TryMoveHero & details)
  126. {
  127. // Server initiated movement -> start movement animation
  128. // Note that this movement is not necessarily of owned heroes - other players movement will also pass through this method
  129. if(details.result == TryMoveHero::EMBARK || details.result == TryMoveHero::DISEMBARK)
  130. {
  131. if (hero->tempOwner == GAME->interface()->playerID)
  132. {
  133. auto removalSound = hero->getRemovalSound(CRandomGenerator::getDefault());
  134. if (removalSound)
  135. ENGINE->sound().playSound(removalSound.value());
  136. }
  137. }
  138. bool directlyAttackingCreature =
  139. details.attackedFrom.isValid() &&
  140. GAME->interface()->localState->hasPath(hero) &&
  141. GAME->interface()->localState->getPath(hero).lastNode().coord == details.attackedFrom;
  142. FowTilesType changedTiles {
  143. hero->convertToVisitablePos(details.start),
  144. hero->convertToVisitablePos(details.end)
  145. };
  146. adventureInt->onMapTilesChanged(changedTiles);
  147. adventureInt->onHeroMovementStarted(hero);
  148. updatePath(hero, details);
  149. if(details.stopMovement())
  150. {
  151. if(duringMovement)
  152. endMove(hero);
  153. return;
  154. }
  155. // We are in network thread
  156. // Block netpack processing until movement animation is over
  157. GAME->map().waitForOngoingAnimations();
  158. //move finished
  159. adventureInt->onHeroChanged(hero);
  160. // Hero attacked creature, set direction to face it.
  161. if(directlyAttackingCreature)
  162. {
  163. // Get direction to attacker.
  164. int3 posOffset = details.attackedFrom - details.end + int3(2, 1, 0);
  165. static const ui8 dirLookup[3][3] =
  166. {
  167. { 1, 2, 3 },
  168. { 8, 0, 4 },
  169. { 7, 6, 5 }
  170. };
  171. //FIXME: better handling of this case without const_cast
  172. const_cast<CGHeroInstance *>(hero)->moveDir = dirLookup[posOffset.y][posOffset.x];
  173. }
  174. }
  175. void HeroMovementController::onQueryReplyApplied()
  176. {
  177. if (!waitingForQueryApplyReply)
  178. return;
  179. waitingForQueryApplyReply = false;
  180. // Server accepted our TeleportDialog query reply and moved hero
  181. // Continue moving alongside our path, if any
  182. if(duringMovement)
  183. onMoveHeroApplied();
  184. }
  185. void HeroMovementController::onMoveHeroApplied()
  186. {
  187. // at this point, server have finished processing of hero movement request
  188. // as well as all side effectes from movement, such as object visit or combat start
  189. // this was request to move alongside path from player, but either another player or teleport action
  190. if(!duringMovement)
  191. return;
  192. // hero has moved onto teleporter and activated it
  193. // in this case next movement should be done only after query reply has been acknowledged
  194. // and hero has been moved to teleport destination
  195. if(waitingForQueryApplyReply)
  196. return;
  197. if(ENGINE->input().ignoreEventsUntilInput())
  198. stoppingMovement = true;
  199. assert(currentlyMovingHero);
  200. const auto * hero = currentlyMovingHero;
  201. bool canMove = GAME->interface()->localState->hasPath(hero) && GAME->interface()->localState->getPath(hero).nextNode().turns == 0 && !GAME->interface()->showingDialog->isBusy();
  202. bool wantStop = stoppingMovement;
  203. bool canStop = !canMove || canHeroStopAtNode(GAME->interface()->localState->getPath(hero).currNode());
  204. if(!canMove || (wantStop && canStop))
  205. {
  206. endMove(hero);
  207. }
  208. else
  209. {
  210. sendMovementRequest(hero, GAME->interface()->localState->getPath(hero));
  211. }
  212. }
  213. void HeroMovementController::requestMovementAbort()
  214. {
  215. if(duringMovement)
  216. endMove(currentlyMovingHero);
  217. }
  218. void HeroMovementController::endMove(const CGHeroInstance * hero)
  219. {
  220. assert(duringMovement == true);
  221. assert(currentlyMovingHero != nullptr);
  222. duringMovement = false;
  223. stoppingMovement = false;
  224. currentlyMovingHero = nullptr;
  225. stopMovementSound();
  226. adventureInt->onHeroChanged(hero);
  227. ENGINE->cursor().show();
  228. }
  229. AudioPath HeroMovementController::getMovementSoundFor(const CGHeroInstance * hero, int3 posPrev, int3 posNext, EPathNodeAction moveType)
  230. {
  231. if(moveType == EPathNodeAction::TELEPORT_BATTLE || moveType == EPathNodeAction::TELEPORT_BLOCKING_VISIT || moveType == EPathNodeAction::TELEPORT_NORMAL)
  232. return {};
  233. if(moveType == EPathNodeAction::EMBARK || moveType == EPathNodeAction::DISEMBARK)
  234. return {};
  235. if(moveType == EPathNodeAction::BLOCKING_VISIT)
  236. return {};
  237. // flying movement sound
  238. if(hero->hasBonusOfType(BonusType::FLYING_MOVEMENT))
  239. return AudioPath::builtin("HORSE10.wav");
  240. auto prevTile = GAME->interface()->cb->getTile(posPrev);
  241. auto nextTile = GAME->interface()->cb->getTile(posNext);
  242. bool movingOnRoad = prevTile->hasRoad() && nextTile->hasRoad();
  243. if(movingOnRoad)
  244. return nextTile->getTerrain()->horseSound;
  245. else
  246. return nextTile->getTerrain()->horseSoundPenalty;
  247. };
  248. void HeroMovementController::updateMovementSound(const CGHeroInstance * h, int3 posPrev, int3 nextCoord, EPathNodeAction moveType)
  249. {
  250. // Start a new sound for the hero movement or let the existing one carry on.
  251. AudioPath newSoundName = getMovementSoundFor(h, posPrev, nextCoord, moveType);
  252. if(newSoundName != currentMovementSoundName)
  253. {
  254. currentMovementSoundName = newSoundName;
  255. if(currentMovementSoundChannel != -1)
  256. ENGINE->sound().stopSound(currentMovementSoundChannel);
  257. if(!currentMovementSoundName.empty())
  258. currentMovementSoundChannel = ENGINE->sound().playSoundLooped(currentMovementSoundName);
  259. else
  260. currentMovementSoundChannel = -1;
  261. }
  262. }
  263. void HeroMovementController::stopMovementSound()
  264. {
  265. if(currentMovementSoundChannel != -1)
  266. ENGINE->sound().stopSound(currentMovementSoundChannel);
  267. currentMovementSoundChannel = -1;
  268. currentMovementSoundName = AudioPath();
  269. }
  270. bool HeroMovementController::canHeroStopAtNode(const CGPathNode & node) const
  271. {
  272. if(node.layer != EPathfindingLayer::LAND && node.layer != EPathfindingLayer::SAIL)
  273. return false;
  274. if(node.accessible != EPathAccessibility::ACCESSIBLE)
  275. return false;
  276. return true;
  277. }
  278. void HeroMovementController::requestMovementStart(const CGHeroInstance * h, const CGPath & path)
  279. {
  280. assert(duringMovement == false);
  281. duringMovement = true;
  282. currentlyMovingHero = h;
  283. ENGINE->cursor().hide();
  284. sendMovementRequest(h, path);
  285. }
  286. void HeroMovementController::sendMovementRequest(const CGHeroInstance * h, const CGPath & path)
  287. {
  288. assert(duringMovement == true);
  289. int heroMovementSpeed = settings["adventure"]["heroMoveTime"].Integer();
  290. bool useMovementBatching = heroMovementSpeed == 0;
  291. const auto & currNode = path.currNode();
  292. const auto & nextNode = path.nextNode();
  293. assert(nextNode.turns == 0);
  294. assert(currNode.coord == h->visitablePos());
  295. if(nextNode.isTeleportAction())
  296. {
  297. stopMovementSound();
  298. logGlobal->trace("Requesting hero teleportation to %s", nextNode.coord.toString());
  299. GAME->interface()->cb->moveHero(h, h->pos, false);
  300. return;
  301. }
  302. if (!useMovementBatching)
  303. {
  304. updateMovementSound(h, currNode.coord, nextNode.coord, nextNode.action);
  305. assert(h->anchorPos().z == nextNode.coord.z); // Z should change only if it's movement via teleporter and in this case this code shouldn't be executed at all
  306. logGlobal->trace("Requesting hero movement to %s", nextNode.coord.toString());
  307. bool useTransit = nextNode.layer == EPathfindingLayer::AIR || nextNode.layer == EPathfindingLayer::WATER;
  308. int3 nextCoord = h->convertFromVisitablePos(nextNode.coord);
  309. GAME->interface()->cb->moveHero(h, nextCoord, useTransit);
  310. return;
  311. }
  312. bool useTransitAtStart = path.nextNode().layer == EPathfindingLayer::AIR || path.nextNode().layer == EPathfindingLayer::WATER;
  313. std::vector<int3> pathToMove;
  314. for (auto const & node : boost::adaptors::reverse(path.nodes))
  315. {
  316. if (node.coord == h->visitablePos())
  317. continue; // first node, ignore - this is hero current position
  318. if(node.isTeleportAction())
  319. break; // pause after monolith / subterra gates
  320. if (node.turns != 0)
  321. break; // ran out of move points
  322. bool useTransitHere = node.layer == EPathfindingLayer::AIR || node.layer == EPathfindingLayer::WATER;
  323. if (useTransitHere != useTransitAtStart)
  324. break;
  325. int3 coord = h->convertFromVisitablePos(node.coord);
  326. pathToMove.push_back(coord);
  327. if (GAME->interface()->cb->guardingCreaturePosition(node.coord) != int3(-1, -1, -1))
  328. break; // we reached zone-of-control of wandering monster
  329. if (!GAME->interface()->cb->getVisitableObjs(node.coord).empty())
  330. break; // we reached event, garrison or some other visitable object - end this movement batch
  331. }
  332. assert(!pathToMove.empty());
  333. if (!pathToMove.empty())
  334. {
  335. updateMovementSound(h, currNode.coord, nextNode.coord, nextNode.action);
  336. GAME->interface()->cb->moveHero(h, pathToMove, useTransitAtStart);
  337. }
  338. }