AdventureMapInterface.cpp 30 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946
  1. /*
  2. * AdventureMapInterface.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 "AdventureMapInterface.h"
  12. #include "AdventureOptions.h"
  13. #include "AdventureState.h"
  14. #include "CInGameConsole.h"
  15. #include "CMinimap.h"
  16. #include "CList.h"
  17. #include "CInfoBar.h"
  18. #include "MapAudioPlayer.h"
  19. #include "TurnTimerWidget.h"
  20. #include "AdventureMapWidget.h"
  21. #include "AdventureMapShortcuts.h"
  22. #include "../mapView/mapHandler.h"
  23. #include "../mapView/MapView.h"
  24. #include "../windows/InfoWindows.h"
  25. #include "../widgets/RadialMenu.h"
  26. #include "../gui/CursorHandler.h"
  27. #include "../GameEngine.h"
  28. #include "../GameInstance.h"
  29. #include "../gui/Shortcut.h"
  30. #include "../gui/WindowHandler.h"
  31. #include "../render/Canvas.h"
  32. #include "../render/IImage.h"
  33. #include "../render/IRenderHandler.h"
  34. #include "../render/IScreenHandler.h"
  35. #include "../PlayerLocalState.h"
  36. #include "../CPlayerInterface.h"
  37. #include "../../lib/mapping/CMap.h"
  38. #include "../../lib/GameLibrary.h"
  39. #include "../../lib/IGameSettings.h"
  40. #include "../../lib/StartInfo.h"
  41. #include "../../lib/callback/CCallback.h"
  42. #include "../../lib/texts/CGeneralTextHandler.h"
  43. #include "../../lib/spells/CSpellHandler.h"
  44. #include "../../lib/mapObjects/CGHeroInstance.h"
  45. #include "../../lib/mapObjects/CGTownInstance.h"
  46. #include "../../lib/pathfinder/CGPathNode.h"
  47. #include "../../lib/pathfinder/TurnInfo.h"
  48. #include "../../lib/spells/adventure/AdventureSpellEffect.h"
  49. #include "../../lib/spells/ISpellMechanics.h"
  50. #include "../../lib/spells/Problem.h"
  51. std::shared_ptr<AdventureMapInterface> adventureInt;
  52. AdventureMapInterface::AdventureMapInterface():
  53. mapAudio(new MapAudioPlayer()),
  54. spellBeingCasted(nullptr),
  55. scrollingWasActive(false),
  56. scrollingWasBlocked(false),
  57. backgroundDimLevel(settings["adventure"]["backgroundDimLevel"].Integer())
  58. {
  59. OBJECT_CONSTRUCTION;
  60. pos.x = pos.y = 0;
  61. pos.w = ENGINE->screenDimensions().x;
  62. pos.h = ENGINE->screenDimensions().y;
  63. shortcuts = std::make_shared<AdventureMapShortcuts>(*this);
  64. widget = std::make_shared<AdventureMapWidget>(shortcuts);
  65. shortcuts->setState(EAdventureState::MAKING_TURN);
  66. widget->getMapView()->onViewMapActivated();
  67. if(GAME->interface()->cb->getStartInfo()->turnTimerInfo.turnTimer != 0)
  68. watches = std::make_shared<TurnTimerWidget>(Point(24, 24));
  69. addUsedEvents(KEYBOARD | TIME);
  70. }
  71. void AdventureMapInterface::onMapViewMoved(const Rect & visibleArea, int mapLevel)
  72. {
  73. shortcuts->onMapViewMoved(visibleArea, mapLevel);
  74. widget->getMinimap()->onMapViewMoved(visibleArea, mapLevel);
  75. widget->onMapViewMoved(visibleArea, mapLevel);
  76. }
  77. void AdventureMapInterface::onAudioResumed()
  78. {
  79. mapAudio->onAudioResumed();
  80. }
  81. void AdventureMapInterface::onAudioPaused()
  82. {
  83. mapAudio->onAudioPaused();
  84. }
  85. void AdventureMapInterface::onHeroMovementStarted(const CGHeroInstance * hero)
  86. {
  87. if (shortcuts->optionMapViewActive())
  88. {
  89. widget->getInfoBar()->popAll();
  90. widget->getInfoBar()->showSelection();
  91. }
  92. }
  93. void AdventureMapInterface::onHeroChanged(const CGHeroInstance *h)
  94. {
  95. widget->getHeroList()->updateElement(h);
  96. if (h && h == GAME->interface()->localState->getCurrentHero() && !widget->getInfoBar()->showingComponents())
  97. widget->getInfoBar()->showSelection();
  98. widget->updateActiveState();
  99. }
  100. void AdventureMapInterface::onTownChanged(const CGTownInstance * town)
  101. {
  102. widget->getTownList()->updateElement(town);
  103. if (town && town == GAME->interface()->localState->getCurrentTown() && !widget->getInfoBar()->showingComponents())
  104. widget->getInfoBar()->showSelection();
  105. }
  106. void AdventureMapInterface::showInfoBoxMessage(const std::vector<Component> & components, std::string message, int timer)
  107. {
  108. widget->getInfoBar()->pushComponents(components, message, timer);
  109. }
  110. void AdventureMapInterface::activate()
  111. {
  112. CIntObject::activate();
  113. adjustActiveness();
  114. if(GAME->interface())
  115. {
  116. GAME->interface()->cingconsole->activate();
  117. GAME->interface()->cingconsole->pos = this->pos;
  118. }
  119. ENGINE->fakeMouseMove(); //to restore the cursor
  120. // workaround for an edge case:
  121. // if player unequips Angel Wings / Boots of Levitation of currently active hero
  122. // game will correctly invalidate paths but current route will not be updated since verifyPath() is not called for current hero
  123. if (GAME->interface()->makingTurn && GAME->interface()->localState->getCurrentHero())
  124. GAME->interface()->localState->verifyPath(GAME->interface()->localState->getCurrentHero());
  125. }
  126. void AdventureMapInterface::deactivate()
  127. {
  128. CIntObject::deactivate();
  129. ENGINE->cursor().set(Cursor::Map::POINTER);
  130. if(GAME->interface())
  131. GAME->interface()->cingconsole->deactivate();
  132. }
  133. void AdventureMapInterface::showAll(Canvas & to)
  134. {
  135. CIntObject::showAll(to);
  136. dim(to);
  137. GAME->interface()->cingconsole->show(to);
  138. }
  139. void AdventureMapInterface::show(Canvas & to)
  140. {
  141. CIntObject::show(to);
  142. dim(to);
  143. GAME->interface()->cingconsole->show(to);
  144. }
  145. void AdventureMapInterface::dim(Canvas & to)
  146. {
  147. auto const isBigWindow = [&](std::shared_ptr<CIntObject> window) { return window->pos.w >= 800 && window->pos.h >= 600; }; // OH3 fullscreen
  148. if(settings["adventure"]["hideBackground"].Bool())
  149. for (auto window : ENGINE->windows().findWindows<CIntObject>())
  150. {
  151. if(!std::dynamic_pointer_cast<AdventureMapInterface>(window) && std::dynamic_pointer_cast<CIntObject>(window) && isBigWindow(window))
  152. {
  153. to.fillTexture(ENGINE->renderHandler().loadImage(ImagePath::builtin("DiBoxBck"), EImageBlitMode::OPAQUE));
  154. return;
  155. }
  156. }
  157. for (auto window : ENGINE->windows().findWindows<CIntObject>())
  158. {
  159. if (!std::dynamic_pointer_cast<AdventureMapInterface>(window) && !std::dynamic_pointer_cast<RadialMenu>(window) && !window->isPopupWindow() && (settings["adventure"]["backgroundDimSmallWindows"].Bool() || isBigWindow(window) || shortcuts->getState() == EAdventureState::HOTSEAT_WAIT))
  160. {
  161. Rect targetRect(0, 0, ENGINE->screenDimensions().x, ENGINE->screenDimensions().y);
  162. ColorRGBA colorToFill(0, 0, 0, std::clamp<int>(backgroundDimLevel, 0, 255));
  163. if(backgroundDimLevel > 0)
  164. to.drawColorBlended(targetRect, colorToFill);
  165. return;
  166. }
  167. }
  168. }
  169. void AdventureMapInterface::tick(uint32_t msPassed)
  170. {
  171. handleMapScrollingUpdate(msPassed);
  172. // we want animations to be active during enemy turn but map itself to be non-interactive
  173. // so call timer update directly on inactive element
  174. widget->getMapView()->tick(msPassed);
  175. }
  176. void AdventureMapInterface::handleMapScrollingUpdate(uint32_t timePassed)
  177. {
  178. /// Width of window border, in pixels, that triggers map scrolling
  179. static constexpr int32_t borderScrollWidth = 15;
  180. int32_t scrollSpeedPixels = settings["adventure"]["scrollSpeedPixels"].Float();
  181. int32_t scrollDistance = scrollSpeedPixels * timePassed / 1000;
  182. Point cursorPosition = ENGINE->getCursorPosition();
  183. Point scrollDirection;
  184. if (cursorPosition.x < borderScrollWidth)
  185. scrollDirection.x = -1;
  186. if (cursorPosition.x > ENGINE->screenDimensions().x - borderScrollWidth)
  187. scrollDirection.x = +1;
  188. if (cursorPosition.y < borderScrollWidth)
  189. scrollDirection.y = -1;
  190. if (cursorPosition.y > ENGINE->screenDimensions().y - borderScrollWidth)
  191. scrollDirection.y = +1;
  192. Point scrollDelta = scrollDirection * scrollDistance;
  193. bool cursorInScrollArea = scrollDelta != Point(0,0);
  194. bool scrollingActive = cursorInScrollArea && shortcuts->optionMapScrollingActive() && !scrollingWasBlocked;
  195. bool scrollingBlocked = ENGINE->isKeyboardCtrlDown() || !settings["adventure"]["borderScroll"].Bool() || !ENGINE->screenHandler().hasFocus();
  196. if (!scrollingWasActive && scrollingBlocked)
  197. {
  198. scrollingWasBlocked = true;
  199. return;
  200. }
  201. if (!cursorInScrollArea && scrollingWasBlocked)
  202. {
  203. scrollingWasBlocked = false;
  204. return;
  205. }
  206. if (scrollingActive)
  207. widget->getMapView()->onMapScrolled(scrollDelta);
  208. if (!scrollingActive && !scrollingWasActive)
  209. return;
  210. if(scrollDelta.x > 0)
  211. {
  212. if(scrollDelta.y < 0)
  213. ENGINE->cursor().set(Cursor::Map::SCROLL_NORTHEAST);
  214. if(scrollDelta.y > 0)
  215. ENGINE->cursor().set(Cursor::Map::SCROLL_SOUTHEAST);
  216. if(scrollDelta.y == 0)
  217. ENGINE->cursor().set(Cursor::Map::SCROLL_EAST);
  218. }
  219. if(scrollDelta.x < 0)
  220. {
  221. if(scrollDelta.y < 0)
  222. ENGINE->cursor().set(Cursor::Map::SCROLL_NORTHWEST);
  223. if(scrollDelta.y > 0)
  224. ENGINE->cursor().set(Cursor::Map::SCROLL_SOUTHWEST);
  225. if(scrollDelta.y == 0)
  226. ENGINE->cursor().set(Cursor::Map::SCROLL_WEST);
  227. }
  228. if (scrollDelta.x == 0)
  229. {
  230. if(scrollDelta.y < 0)
  231. ENGINE->cursor().set(Cursor::Map::SCROLL_NORTH);
  232. if(scrollDelta.y > 0)
  233. ENGINE->cursor().set(Cursor::Map::SCROLL_SOUTH);
  234. if(scrollDelta.y == 0)
  235. ENGINE->cursor().set(Cursor::Map::POINTER);
  236. }
  237. scrollingWasActive = scrollingActive;
  238. }
  239. void AdventureMapInterface::centerOnTile(int3 on)
  240. {
  241. widget->getMapView()->onCenteredTile(on);
  242. }
  243. void AdventureMapInterface::centerOnObject(const CGObjectInstance * obj)
  244. {
  245. widget->getMapView()->onCenteredObject(obj);
  246. }
  247. void AdventureMapInterface::keyPressed(EShortcut key)
  248. {
  249. if (key == EShortcut::GLOBAL_CANCEL && spellBeingCasted)
  250. hotkeyAbortCastingMode();
  251. //fake mouse use to trigger onTileHovered()
  252. ENGINE->fakeMouseMove();
  253. }
  254. void AdventureMapInterface::onSelectionChanged(const CArmedInstance *sel)
  255. {
  256. assert(sel);
  257. widget->getInfoBar()->popAll();
  258. mapAudio->onSelectionChanged(sel);
  259. bool centerView = !settings["session"]["autoSkip"].Bool();
  260. if (centerView)
  261. centerOnObject(sel);
  262. if(sel->ID==Obj::TOWN)
  263. {
  264. auto town = dynamic_cast<const CGTownInstance*>(sel);
  265. widget->getInfoBar()->showTownSelection(town);
  266. widget->getTownList()->updateWidget();
  267. widget->getTownList()->select(town);
  268. widget->getHeroList()->select(nullptr);
  269. onHeroChanged(nullptr);
  270. }
  271. else //hero selected
  272. {
  273. auto hero = dynamic_cast<const CGHeroInstance*>(sel);
  274. widget->getInfoBar()->showHeroSelection(hero);
  275. widget->getHeroList()->select(hero);
  276. widget->getTownList()->select(nullptr);
  277. GAME->interface()->localState->verifyPath(hero);
  278. onHeroChanged(hero);
  279. }
  280. widget->updateActiveState();
  281. widget->getHeroList()->redraw();
  282. widget->getTownList()->redraw();
  283. }
  284. void AdventureMapInterface::onTownOrderChanged()
  285. {
  286. widget->getTownList()->updateWidget();
  287. }
  288. void AdventureMapInterface::onHeroOrderChanged()
  289. {
  290. widget->getHeroList()->updateWidget();
  291. }
  292. void AdventureMapInterface::onMapTilesChanged(boost::optional<FowTilesType> positions)
  293. {
  294. if (positions)
  295. widget->getMinimap()->updateTiles(*positions);
  296. else
  297. widget->getMinimap()->update();
  298. }
  299. void AdventureMapInterface::onHotseatWaitStarted(PlayerColor playerID)
  300. {
  301. backgroundDimLevel = 255;
  302. widget->getMinimap()->setAIRadar(true);
  303. onCurrentPlayerChanged(playerID);
  304. setState(EAdventureState::HOTSEAT_WAIT);
  305. }
  306. void AdventureMapInterface::onEnemyTurnStarted(PlayerColor playerID, bool isHuman)
  307. {
  308. if(settings["session"]["spectate"].Bool())
  309. return;
  310. mapAudio->onEnemyTurnStarted();
  311. widget->getMinimap()->setAIRadar(!isHuman);
  312. widget->getInfoBar()->startEnemyTurn(playerID);
  313. setState(isHuman ? EAdventureState::MAKING_TURN : EAdventureState::AI_PLAYER_TURN);
  314. }
  315. void AdventureMapInterface::setState(EAdventureState state)
  316. {
  317. shortcuts->setState(state);
  318. adjustActiveness();
  319. widget->updateActiveState();
  320. }
  321. void AdventureMapInterface::adjustActiveness()
  322. {
  323. bool widgetMustBeActive = isActive() && shortcuts->optionSidePanelActive();
  324. bool mapViewMustBeActive = isActive() && (shortcuts->optionMapViewActive());
  325. widget->setInputEnabled(widgetMustBeActive);
  326. widget->getMapView()->setInputEnabled(mapViewMustBeActive);
  327. }
  328. void AdventureMapInterface::onCurrentPlayerChanged(PlayerColor playerID)
  329. {
  330. if (playerID == currentPlayerID)
  331. return;
  332. currentPlayerID = playerID;
  333. widget->setPlayerColor(playerID);
  334. }
  335. void AdventureMapInterface::onPlayerTurnStarted(PlayerColor playerID)
  336. {
  337. backgroundDimLevel = settings["adventure"]["backgroundDimLevel"].Integer();
  338. onCurrentPlayerChanged(playerID);
  339. setState(EAdventureState::MAKING_TURN);
  340. if(playerID == GAME->interface()->playerID || settings["session"]["spectate"].Bool())
  341. {
  342. widget->getMinimap()->setAIRadar(false);
  343. widget->getInfoBar()->showSelection();
  344. }
  345. widget->getHeroList()->updateWidget();
  346. widget->getTownList()->updateWidget();
  347. const CGHeroInstance * heroToSelect = nullptr;
  348. // find first non-sleeping hero
  349. for (auto hero : GAME->interface()->localState->getWanderingHeroes())
  350. {
  351. if (!GAME->interface()->localState->isHeroSleeping(hero))
  352. {
  353. heroToSelect = hero;
  354. break;
  355. }
  356. }
  357. //select first hero if available.
  358. if (heroToSelect != nullptr)
  359. {
  360. GAME->interface()->localState->setSelection(heroToSelect);
  361. }
  362. else if (GAME->interface()->localState->getOwnedTowns().size())
  363. {
  364. GAME->interface()->localState->setSelection(GAME->interface()->localState->getOwnedTown(0));
  365. }
  366. else
  367. {
  368. GAME->interface()->localState->setSelection(GAME->interface()->localState->getWanderingHero(0));
  369. }
  370. onSelectionChanged(GAME->interface()->localState->getCurrentArmy());
  371. //show new day animation and sound on infobar, except for 1st day of the game
  372. if (GAME->interface()->cb->getDate(Date::DAY) != 1)
  373. widget->getInfoBar()->showDate();
  374. onHeroChanged(nullptr);
  375. ENGINE->windows().totalRedraw();
  376. mapAudio->onPlayerTurnStarted();
  377. if(settings["session"]["autoSkip"].Bool() && !ENGINE->isKeyboardShiftDown())
  378. {
  379. if(auto iw = ENGINE->windows().topWindow<CInfoWindow>())
  380. iw->close();
  381. ENGINE->dispatchMainThread([this]()
  382. {
  383. hotkeyEndingTurn();
  384. });
  385. }
  386. }
  387. void AdventureMapInterface::hotkeyEndingTurn()
  388. {
  389. if(settings["session"]["spectate"].Bool())
  390. return;
  391. if(!settings["general"]["startTurnAutosave"].Bool())
  392. {
  393. GAME->interface()->performAutosave();
  394. }
  395. GAME->interface()->makingTurn = false;
  396. GAME->interface()->cb->endTurn();
  397. mapAudio->onPlayerTurnEnded();
  398. // Normally, game will receive PlayerStartsTurn call almost instantly with new player ID that will switch UI to waiting mode
  399. // However, when simturns are active it is possible for such call not to come because another player is still acting
  400. // So find first player other than ours that is acting at the moment and update UI as if he had started turn
  401. for (auto player = PlayerColor(0); player < PlayerColor::PLAYER_LIMIT; ++player)
  402. {
  403. if (player != GAME->interface()->playerID && GAME->interface()->cb->isPlayerMakingTurn(player))
  404. {
  405. onEnemyTurnStarted(player, GAME->interface()->cb->getStartInfo()->playerInfos.at(player).isControlledByHuman());
  406. break;
  407. }
  408. }
  409. }
  410. const CGObjectInstance* AdventureMapInterface::getActiveObject(const int3 &mapPos)
  411. {
  412. std::vector < const CGObjectInstance * > bobjs = GAME->interface()->cb->getBlockingObjs(mapPos); //blocking objects at tile
  413. if (bobjs.empty())
  414. return nullptr;
  415. return *boost::range::max_element(bobjs, &CMap::compareObjectBlitOrder);
  416. }
  417. void AdventureMapInterface::onTileLeftClicked(const int3 &targetPosition)
  418. {
  419. if(!shortcuts->optionMapViewActive())
  420. return;
  421. const CGObjectInstance *topBlocking = GAME->interface()->cb->isVisible(targetPosition) ? getActiveObject(targetPosition) : nullptr;
  422. if(spellBeingCasted)
  423. {
  424. assert(shortcuts->optionSpellcasting());
  425. if(isValidAdventureSpellTarget(targetPosition))
  426. performSpellcasting(targetPosition);
  427. return;
  428. }
  429. if(!GAME->interface()->cb->isVisible(targetPosition))
  430. return;
  431. //check if we can select this object
  432. bool canSelect = topBlocking && topBlocking->ID == Obj::HERO && topBlocking->tempOwner == GAME->interface()->playerID;
  433. canSelect |= topBlocking && topBlocking->ID == Obj::TOWN && GAME->interface()->cb->getPlayerRelations(GAME->interface()->playerID, topBlocking->tempOwner) != PlayerRelations::ENEMIES;
  434. if(GAME->interface()->localState->getCurrentArmy()->ID != Obj::HERO) //hero is not selected (presumably town)
  435. {
  436. if(GAME->interface()->localState->getCurrentArmy() == topBlocking) //selected town clicked
  437. GAME->interface()->openTownWindow(static_cast<const CGTownInstance*>(topBlocking));
  438. else if(canSelect)
  439. GAME->interface()->localState->setSelection(static_cast<const CArmedInstance*>(topBlocking));
  440. }
  441. else if(const CGHeroInstance * currentHero = GAME->interface()->localState->getCurrentHero()) //hero is selected
  442. {
  443. const CGPathNode *pn = GAME->interface()->getPathsInfo(currentHero)->getPathInfo(targetPosition);
  444. const auto shipyard = dynamic_cast<const IShipyard *>(topBlocking);
  445. if(currentHero == topBlocking) //clicked selected hero
  446. {
  447. GAME->interface()->openHeroWindow(currentHero);
  448. return;
  449. }
  450. else if(canSelect && pn->turns == 255 ) //selectable object at inaccessible tile
  451. {
  452. GAME->interface()->localState->setSelection(static_cast<const CArmedInstance*>(topBlocking));
  453. return;
  454. }
  455. else if(shipyard != nullptr && pn->turns == 255 && GAME->interface()->cb->getPlayerRelations(GAME->interface()->playerID, topBlocking->tempOwner) != PlayerRelations::ENEMIES)
  456. {
  457. GAME->interface()->showShipyardDialogOrProblemPopup(shipyard);
  458. }
  459. else //still here? we need to move hero if we clicked end of already selected path or calculate a new path otherwise
  460. {
  461. int3 destinationTile = targetPosition;
  462. if(topBlocking && topBlocking->isVisitable() && !topBlocking->visitableAt(destinationTile) && settings["gameTweaks"]["simpleObjectSelection"].Bool())
  463. destinationTile = topBlocking->visitablePos();
  464. if(!settings["adventure"]["showMovePath"].Bool())
  465. {
  466. GAME->interface()->localState->setPath(currentHero, destinationTile);
  467. onHeroChanged(currentHero);
  468. }
  469. if(GAME->interface()->localState->hasPath(currentHero) &&
  470. GAME->interface()->localState->getPath(currentHero).endPos() == destinationTile &&
  471. !ENGINE->isKeyboardShiftDown())//we'll be moving
  472. {
  473. assert(!GAME->map().hasOngoingAnimations());
  474. if(!GAME->map().hasOngoingAnimations() && GAME->interface()->localState->getPath(currentHero).nextNode().turns == 0)
  475. GAME->interface()->moveHero(currentHero, GAME->interface()->localState->getPath(currentHero));
  476. return;
  477. }
  478. else
  479. {
  480. if(ENGINE->isKeyboardShiftDown()) //normal click behaviour (as no hero selected)
  481. {
  482. if(canSelect)
  483. GAME->interface()->localState->setSelection(static_cast<const CArmedInstance*>(topBlocking));
  484. }
  485. else //remove old path and find a new one if we clicked on accessible tile
  486. {
  487. GAME->interface()->localState->setPath(currentHero, destinationTile);
  488. onHeroChanged(currentHero);
  489. }
  490. }
  491. }
  492. } //end of hero is selected "case"
  493. else
  494. {
  495. throw std::runtime_error("Nothing is selected...");
  496. }
  497. }
  498. void AdventureMapInterface::onTileHovered(const int3 &targetPosition)
  499. {
  500. if(!shortcuts->optionMapViewActive())
  501. return;
  502. //if the player is not ingame (loser, winner, wrong) we are in a shutdown process
  503. if (!GAME->interface()->cb || GAME->interface()->cb->getPlayerStatus(GAME->interface()->playerID) != EPlayerStatus::INGAME)
  504. return;
  505. //may occur just at the start of game (fake move before full initialization)
  506. if(!GAME->interface()->localState->getCurrentArmy())
  507. return;
  508. bool isTargetPositionVisible = GAME->interface()->cb->isVisible(targetPosition);
  509. const CGObjectInstance *objAtTile = isTargetPositionVisible ? getActiveObject(targetPosition) : nullptr;
  510. if(spellBeingCasted)
  511. {
  512. const auto * hero = GAME->interface()->localState->getCurrentHero();
  513. const auto * spellEffect = spellBeingCasted->getAdventureMechanics().getEffectAs<AdventureSpellRangedEffect>(hero);
  514. spells::detail::ProblemImpl problem;
  515. if(spellEffect && spellEffect->canBeCastAtImpl(problem, GAME->interface()->cb.get(), hero, targetPosition))
  516. ENGINE->cursor().set(spellEffect->getCursorForTarget(GAME->interface()->cb.get(), hero, targetPosition));
  517. else
  518. ENGINE->cursor().set(Cursor::Map::POINTER);
  519. return;
  520. }
  521. if(!isTargetPositionVisible)
  522. {
  523. ENGINE->cursor().set(Cursor::Map::POINTER);
  524. return;
  525. }
  526. auto objRelations = PlayerRelations::ALLIES;
  527. if(objAtTile)
  528. {
  529. objRelations = GAME->interface()->cb->getPlayerRelations(GAME->interface()->playerID, objAtTile->tempOwner);
  530. std::string text = GAME->interface()->localState->getCurrentHero() ? objAtTile->getHoverText(GAME->interface()->localState->getCurrentHero()) : objAtTile->getHoverText(GAME->interface()->playerID);
  531. boost::replace_all(text,"\n"," ");
  532. if (ENGINE->isKeyboardCmdDown())
  533. text.append(" (" + std::to_string(targetPosition.x) + ", " + std::to_string(targetPosition.y) + ", " + std::to_string(targetPosition.z) + ")");
  534. ENGINE->statusbar()->write(text);
  535. }
  536. else if(isTargetPositionVisible)
  537. {
  538. std::string tileTooltipText = GAME->map().getTerrainDescr(targetPosition, false);
  539. if (ENGINE->isKeyboardCmdDown())
  540. tileTooltipText.append(" (" + std::to_string(targetPosition.x) + ", " + std::to_string(targetPosition.y) + ", " + std::to_string(targetPosition.z) + ")");
  541. ENGINE->statusbar()->write(tileTooltipText);
  542. }
  543. if(GAME->interface()->localState->getCurrentArmy()->ID == Obj::TOWN || ENGINE->isKeyboardShiftDown())
  544. {
  545. if(objAtTile)
  546. {
  547. if(objAtTile->ID == Obj::TOWN && objRelations != PlayerRelations::ENEMIES)
  548. ENGINE->cursor().set(Cursor::Map::TOWN);
  549. else if(objAtTile->ID == Obj::HERO && objRelations == PlayerRelations::SAME_PLAYER)
  550. ENGINE->cursor().set(Cursor::Map::HERO);
  551. else
  552. ENGINE->cursor().set(Cursor::Map::POINTER);
  553. }
  554. else
  555. ENGINE->cursor().set(Cursor::Map::POINTER);
  556. }
  557. else if(const CGHeroInstance * hero = GAME->interface()->localState->getCurrentHero())
  558. {
  559. std::array<Cursor::Map, 4> cursorMove = { Cursor::Map::T1_MOVE, Cursor::Map::T2_MOVE, Cursor::Map::T3_MOVE, Cursor::Map::T4_MOVE, };
  560. std::array<Cursor::Map, 4> cursorAttack = { Cursor::Map::T1_ATTACK, Cursor::Map::T2_ATTACK, Cursor::Map::T3_ATTACK, Cursor::Map::T4_ATTACK, };
  561. std::array<Cursor::Map, 4> cursorSail = { Cursor::Map::T1_SAIL, Cursor::Map::T2_SAIL, Cursor::Map::T3_SAIL, Cursor::Map::T4_SAIL, };
  562. std::array<Cursor::Map, 4> cursorDisembark = { Cursor::Map::T1_DISEMBARK, Cursor::Map::T2_DISEMBARK, Cursor::Map::T3_DISEMBARK, Cursor::Map::T4_DISEMBARK, };
  563. std::array<Cursor::Map, 4> cursorExchange = { Cursor::Map::T1_EXCHANGE, Cursor::Map::T2_EXCHANGE, Cursor::Map::T3_EXCHANGE, Cursor::Map::T4_EXCHANGE, };
  564. std::array<Cursor::Map, 4> cursorVisit = { Cursor::Map::T1_VISIT, Cursor::Map::T2_VISIT, Cursor::Map::T3_VISIT, Cursor::Map::T4_VISIT, };
  565. std::array<Cursor::Map, 4> cursorSailVisit = { Cursor::Map::T1_SAIL_VISIT, Cursor::Map::T2_SAIL_VISIT, Cursor::Map::T3_SAIL_VISIT, Cursor::Map::T4_SAIL_VISIT, };
  566. const CGPathNode * pathNode = GAME->interface()->getPathsInfo(hero)->getPathInfo(targetPosition);
  567. assert(pathNode);
  568. if((ENGINE->isKeyboardAltDown() || settings["gameTweaks"]["forceMovementInfo"].Bool()) && pathNode->reachable()) //overwrite status bar text with movement info
  569. {
  570. showMoveDetailsInStatusbar(*hero, *pathNode);
  571. }
  572. if (objAtTile && pathNode->action == EPathNodeAction::UNKNOWN)
  573. {
  574. if(objAtTile->ID == Obj::TOWN && objRelations != PlayerRelations::ENEMIES)
  575. {
  576. ENGINE-> cursor().set(Cursor::Map::TOWN);
  577. return;
  578. }
  579. else if(objAtTile->ID == Obj::HERO && objRelations == PlayerRelations::SAME_PLAYER)
  580. {
  581. ENGINE-> cursor().set(Cursor::Map::HERO);
  582. return;
  583. }
  584. else if (objAtTile->ID == Obj::SHIPYARD && objRelations != PlayerRelations::ENEMIES)
  585. {
  586. ENGINE-> cursor().set(Cursor::Map::T1_SAIL);
  587. return;
  588. }
  589. if(objAtTile->isVisitable() && !objAtTile->visitableAt(targetPosition) && settings["gameTweaks"]["simpleObjectSelection"].Bool())
  590. pathNode = GAME->interface()->getPathsInfo(hero)->getPathInfo(objAtTile->visitablePos());
  591. }
  592. int turns = pathNode->turns;
  593. vstd::amin(turns, 3);
  594. switch(pathNode->action)
  595. {
  596. case EPathNodeAction::NORMAL:
  597. case EPathNodeAction::TELEPORT_NORMAL:
  598. if(pathNode->layer == EPathfindingLayer::LAND)
  599. ENGINE->cursor().set(cursorMove[turns]);
  600. else
  601. ENGINE->cursor().set(cursorSail[turns]);
  602. break;
  603. case EPathNodeAction::VISIT:
  604. case EPathNodeAction::BLOCKING_VISIT:
  605. case EPathNodeAction::TELEPORT_BLOCKING_VISIT:
  606. if(objAtTile && objAtTile->ID == Obj::HERO)
  607. {
  608. if(GAME->interface()->localState->getCurrentArmy() == objAtTile)
  609. ENGINE->cursor().set(Cursor::Map::HERO);
  610. else
  611. ENGINE->cursor().set(cursorExchange[turns]);
  612. }
  613. else if(pathNode->layer == EPathfindingLayer::LAND)
  614. ENGINE->cursor().set(cursorVisit[turns]);
  615. else if (pathNode->layer == EPathfindingLayer::SAIL &&
  616. objAtTile &&
  617. objAtTile->isCoastVisitable() &&
  618. pathNode->theNodeBefore &&
  619. pathNode->theNodeBefore->layer == EPathfindingLayer::LAND )
  620. {
  621. // exception - when visiting shipwreck located on coast from land - show 'horse' cursor, not 'ship' cursor
  622. ENGINE->cursor().set(cursorVisit[turns]);
  623. }
  624. else
  625. ENGINE->cursor().set(cursorSailVisit[turns]);
  626. break;
  627. case EPathNodeAction::BATTLE:
  628. case EPathNodeAction::TELEPORT_BATTLE:
  629. ENGINE->cursor().set(cursorAttack[turns]);
  630. break;
  631. case EPathNodeAction::EMBARK:
  632. ENGINE->cursor().set(cursorSail[turns]);
  633. break;
  634. case EPathNodeAction::DISEMBARK:
  635. ENGINE->cursor().set(cursorDisembark[turns]);
  636. break;
  637. default:
  638. ENGINE->cursor().set(Cursor::Map::POINTER);
  639. break;
  640. }
  641. }
  642. }
  643. void AdventureMapInterface::showMoveDetailsInStatusbar(const CGHeroInstance & hero, const CGPathNode & pathNode)
  644. {
  645. const int maxMovementPointsAtStartOfLastTurn = pathNode.turns > 0 ? hero.movementPointsLimit(pathNode.layer == EPathfindingLayer::LAND) : hero.movementPointsRemaining();
  646. const int movementPointsLastTurnCost = maxMovementPointsAtStartOfLastTurn - pathNode.moveRemains;
  647. const int remainingPointsAfterMove = pathNode.moveRemains;
  648. int totalMovementCost = hero.movementPointsRemaining();
  649. for (int i = 1; i <= pathNode.turns; ++i)
  650. {
  651. auto turnInfo = hero.getTurnInfo(i);
  652. if (pathNode.layer == EPathfindingLayer::SAIL)
  653. totalMovementCost += turnInfo->getMovePointsLimitWater();
  654. else
  655. totalMovementCost += turnInfo->getMovePointsLimitLand();
  656. }
  657. totalMovementCost -= pathNode.moveRemains;
  658. std::string result = LIBRARY->generaltexth->translate("vcmi.adventureMap", pathNode.turns > 0 ? "moveCostDetails" : "moveCostDetailsNoTurns");
  659. boost::replace_first(result, "%TURNS", std::to_string(pathNode.turns));
  660. boost::replace_first(result, "%POINTS", std::to_string(movementPointsLastTurnCost));
  661. boost::replace_first(result, "%REMAINING", std::to_string(remainingPointsAfterMove));
  662. boost::replace_first(result, "%TOTAL", std::to_string(totalMovementCost));
  663. ENGINE->statusbar()->write(result);
  664. }
  665. void AdventureMapInterface::onTileRightClicked(const int3 &mapPos)
  666. {
  667. if(!shortcuts->optionMapViewActive())
  668. return;
  669. if(spellBeingCasted)
  670. {
  671. hotkeyAbortCastingMode();
  672. return;
  673. }
  674. if(!GAME->interface()->cb->isVisible(mapPos))
  675. {
  676. CRClickPopup::createAndPush(LIBRARY->generaltexth->allTexts[61]); //Uncharted Territory
  677. return;
  678. }
  679. const CGObjectInstance * obj = getActiveObject(mapPos);
  680. if(!obj)
  681. {
  682. // Bare or undiscovered terrain
  683. const TerrainTile * tile = GAME->interface()->cb->getTile(mapPos);
  684. if(tile)
  685. {
  686. std::string hlp = GAME->map().getTerrainDescr(mapPos, true);
  687. CRClickPopup::createAndPush(hlp);
  688. }
  689. return;
  690. }
  691. CRClickPopup::createAndPush(obj, ENGINE->getCursorPosition(), ETextAlignment::CENTER);
  692. }
  693. void AdventureMapInterface::enterCastingMode(const CSpell * sp)
  694. {
  695. spellBeingCasted = sp;
  696. GAME->interface()->localState->setCurrentSpell(sp->id);
  697. setState(EAdventureState::CASTING_SPELL);
  698. }
  699. void AdventureMapInterface::exitCastingMode()
  700. {
  701. assert(spellBeingCasted);
  702. spellBeingCasted = nullptr;
  703. setState(EAdventureState::MAKING_TURN);
  704. GAME->interface()->localState->setCurrentSpell(SpellID::NONE);
  705. }
  706. void AdventureMapInterface::hotkeyAbortCastingMode()
  707. {
  708. exitCastingMode();
  709. GAME->interface()->showInfoDialog(LIBRARY->generaltexth->allTexts[731]); //Spell cancelled
  710. }
  711. void AdventureMapInterface::performSpellcasting(const int3 & dest)
  712. {
  713. SpellID id = spellBeingCasted->id;
  714. exitCastingMode();
  715. GAME->interface()->cb->castSpell(GAME->interface()->localState->getCurrentHero(), id, dest);
  716. }
  717. Rect AdventureMapInterface::terrainAreaPixels() const
  718. {
  719. return widget->getMapView()->pos;
  720. }
  721. void AdventureMapInterface::hotkeyExitWorldView()
  722. {
  723. setState(EAdventureState::MAKING_TURN);
  724. widget->getMapView()->onViewMapActivated();
  725. }
  726. void AdventureMapInterface::openWorldView(int tileSize)
  727. {
  728. setState(EAdventureState::WORLD_VIEW);
  729. widget->getMapView()->onViewWorldActivated(tileSize);
  730. }
  731. void AdventureMapInterface::openWorldView()
  732. {
  733. openWorldView(11);
  734. }
  735. void AdventureMapInterface::openWorldView(const std::vector<ObjectPosInfo>& objectPositions, bool showTerrain)
  736. {
  737. openWorldView(11);
  738. widget->getMapView()->onViewSpellActivated(11, objectPositions, showTerrain);
  739. }
  740. void AdventureMapInterface::hotkeyNextTown()
  741. {
  742. int selectedIndex = widget->getTownList()->getSelectedIndex();
  743. widget->getTownList()->selectNext();
  744. if(selectedIndex == widget->getTownList()->getSelectedIndex())
  745. widget->getTownList()->refreshSelected();
  746. }
  747. void AdventureMapInterface::hotkeySwitchMapLevel()
  748. {
  749. widget->getMapView()->onMapLevelSwitched();
  750. }
  751. void AdventureMapInterface::hotkeyZoom(int delta, bool useDeadZone)
  752. {
  753. widget->getMapView()->onMapZoomLevelChanged(delta, useDeadZone);
  754. }
  755. void AdventureMapInterface::onScreenResize()
  756. {
  757. OBJECT_CONSTRUCTION;
  758. // remember our activation state and reactive after reconstruction
  759. // since othervice activate() calls for created elements will bypass virtual dispatch
  760. // and will call directly CIntObject::activate() instead of dispatching virtual function call
  761. bool widgetActive = isActive();
  762. if (widgetActive)
  763. deactivate();
  764. widget.reset();
  765. pos.x = pos.y = 0;
  766. pos.w = ENGINE->screenDimensions().x;
  767. pos.h = ENGINE->screenDimensions().y;
  768. widget = std::make_shared<AdventureMapWidget>(shortcuts);
  769. widget->getMapView()->onViewMapActivated();
  770. widget->setPlayerColor(currentPlayerID);
  771. widget->updateActiveState();
  772. widget->getMinimap()->update();
  773. widget->getInfoBar()->showSelection();
  774. if (GAME->interface() && GAME->interface()->localState->getCurrentArmy())
  775. widget->getMapView()->onCenteredObject(GAME->interface()->localState->getCurrentArmy());
  776. adjustActiveness();
  777. if (widgetActive)
  778. activate();
  779. }
  780. bool AdventureMapInterface::isValidAdventureSpellTarget(int3 targetPosition) const
  781. {
  782. spells::detail::ProblemImpl problem;
  783. return spellBeingCasted->getAdventureMechanics().canBeCastAt(problem, GAME->interface()->cb.get(), GAME->interface()->localState->getCurrentHero(), targetPosition);
  784. }
  785. void AdventureMapInterface::updateActiveState()
  786. {
  787. widget->updateActiveState();
  788. }