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