HeroMovementController.cpp 13 KB

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