BattleFieldController.cpp 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556
  1. /*
  2. * BattleFieldController.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 "BattleFieldController.h"
  12. #include "BattleInterface.h"
  13. #include "BattleActionsController.h"
  14. #include "BattleInterfaceClasses.h"
  15. #include "BattleEffectsController.h"
  16. #include "BattleSiegeController.h"
  17. #include "BattleStacksController.h"
  18. #include "BattleObstacleController.h"
  19. #include "BattleProjectileController.h"
  20. #include "BattleRenderer.h"
  21. #include "../CGameInfo.h"
  22. #include "../CPlayerInterface.h"
  23. #include "../widgets/AdventureMapClasses.h"
  24. #include "../gui/CAnimation.h"
  25. #include "../gui/Canvas.h"
  26. #include "../gui/CGuiHandler.h"
  27. #include "../gui/CursorHandler.h"
  28. #include "../../CCallback.h"
  29. #include "../../lib/BattleFieldHandler.h"
  30. #include "../../lib/CConfigHandler.h"
  31. #include "../../lib/CStack.h"
  32. #include "../../lib/spells/ISpellMechanics.h"
  33. BattleFieldController::BattleFieldController(BattleInterface & owner):
  34. owner(owner)
  35. {
  36. OBJ_CONSTRUCTION_CAPTURING_ALL_NO_DISPOSE;
  37. strongInterest = true;
  38. //preparing cells and hexes
  39. cellBorder = IImage::createFromFile("CCELLGRD.BMP");
  40. cellShade = IImage::createFromFile("CCELLSHD.BMP");
  41. if(!owner.siegeController)
  42. {
  43. auto bfieldType = owner.curInt->cb->battleGetBattlefieldType();
  44. if(bfieldType == BattleField::NONE)
  45. logGlobal->error("Invalid battlefield returned for current battle");
  46. else
  47. background = IImage::createFromFile(bfieldType.getInfo()->graphics);
  48. }
  49. else
  50. {
  51. std::string backgroundName = owner.siegeController->getBattleBackgroundName();
  52. background = IImage::createFromFile(backgroundName);
  53. }
  54. pos.w = background->width();
  55. pos.h = background->height();
  56. //preparing graphic with cell borders
  57. cellBorders = std::make_unique<Canvas>(Point(background->width(), background->height()));
  58. for (int i=0; i<GameConstants::BFIELD_SIZE; ++i)
  59. {
  60. if ( i % GameConstants::BFIELD_WIDTH == 0)
  61. continue;
  62. if ( i % GameConstants::BFIELD_WIDTH == GameConstants::BFIELD_WIDTH - 1)
  63. continue;
  64. cellBorders->draw(cellBorder, hexPositionLocal(i).topLeft());
  65. }
  66. backgroundWithHexes = std::make_unique<Canvas>(Point(background->width(), background->height()));
  67. for (int h = 0; h < GameConstants::BFIELD_SIZE; ++h)
  68. {
  69. auto hex = std::make_shared<ClickableHex>();
  70. hex->myNumber = h;
  71. hex->pos = hexPositionAbsolute(h);
  72. hex->myInterface = &owner;
  73. bfield.push_back(hex);
  74. }
  75. auto accessibility = owner.curInt->cb->getAccesibility();
  76. for(int i = 0; i < accessibility.size(); i++)
  77. stackCountOutsideHexes[i] = (accessibility[i] == EAccessibility::ACCESSIBLE);
  78. addUsedEvents(MOVE);
  79. LOCPLINT->cingconsole->pos = this->pos;
  80. }
  81. void BattleFieldController::createHeroes()
  82. {
  83. OBJ_CONSTRUCTION_CAPTURING_ALL_NO_DISPOSE;
  84. // create heroes as part of our constructor for correct positioning inside battlefield
  85. if(owner.attackingHeroInstance)
  86. owner.attackingHero = std::make_shared<BattleHero>(owner, owner.attackingHeroInstance, false);
  87. if(owner.defendingHeroInstance)
  88. owner.defendingHero = std::make_shared<BattleHero>(owner, owner.defendingHeroInstance, true);
  89. }
  90. void BattleFieldController::mouseMoved(const SDL_MouseMotionEvent &event)
  91. {
  92. BattleHex selectedHex = getHoveredHex();
  93. owner.actionsController->handleHex(selectedHex, MOVE);
  94. }
  95. void BattleFieldController::renderBattlefield(Canvas & canvas)
  96. {
  97. Canvas clippedCanvas(canvas, pos);
  98. showBackground(clippedCanvas);
  99. BattleRenderer renderer(owner);
  100. renderer.execute(clippedCanvas);
  101. owner.projectilesController->showProjectiles(clippedCanvas);
  102. }
  103. void BattleFieldController::showBackground(Canvas & canvas)
  104. {
  105. if (owner.stacksController->getActiveStack() != nullptr ) //&& creAnims[stacksController->getActiveStack()->ID]->isIdle() //show everything with range
  106. showBackgroundImageWithHexes(canvas);
  107. else
  108. showBackgroundImage(canvas);
  109. showHighlightedHexes(canvas);
  110. }
  111. void BattleFieldController::showBackgroundImage(Canvas & canvas)
  112. {
  113. canvas.draw(background, Point(0, 0));
  114. owner.obstacleController->showAbsoluteObstacles(canvas);
  115. if ( owner.siegeController )
  116. owner.siegeController->showAbsoluteObstacles(canvas);
  117. if (settings["battle"]["cellBorders"].Bool())
  118. canvas.draw(*cellBorders, Point(0, 0));
  119. }
  120. void BattleFieldController::showBackgroundImageWithHexes(Canvas & canvas)
  121. {
  122. canvas.draw(*backgroundWithHexes.get(), Point(0, 0));
  123. }
  124. void BattleFieldController::redrawBackgroundWithHexes()
  125. {
  126. const CStack *activeStack = owner.stacksController->getActiveStack();
  127. std::vector<BattleHex> attackableHexes;
  128. if (activeStack)
  129. occupyableHexes = owner.curInt->cb->battleGetAvailableHexes(activeStack, true, &attackableHexes);
  130. auto accessibility = owner.curInt->cb->getAccesibility();
  131. for(int i = 0; i < accessibility.size(); i++)
  132. stackCountOutsideHexes[i] = (accessibility[i] == EAccessibility::ACCESSIBLE);
  133. //prepare background graphic with hexes and shaded hexes
  134. backgroundWithHexes->draw(background, Point(0,0));
  135. owner.obstacleController->showAbsoluteObstacles(*backgroundWithHexes);
  136. if ( owner.siegeController )
  137. owner.siegeController->showAbsoluteObstacles(*backgroundWithHexes);
  138. if (settings["battle"]["stackRange"].Bool())
  139. {
  140. std::vector<BattleHex> hexesToShade = occupyableHexes;
  141. hexesToShade.insert(hexesToShade.end(), attackableHexes.begin(), attackableHexes.end());
  142. for (BattleHex hex : hexesToShade)
  143. {
  144. backgroundWithHexes->draw(cellShade, hexPositionLocal(hex).topLeft());
  145. }
  146. }
  147. if(settings["battle"]["cellBorders"].Bool())
  148. backgroundWithHexes->draw(*cellBorders, Point(0, 0));
  149. }
  150. void BattleFieldController::showHighlightedHex(Canvas & canvas, BattleHex hex, bool darkBorder)
  151. {
  152. Point hexPos = hexPositionLocal(hex).topLeft();
  153. canvas.draw(cellShade, hexPos);
  154. if(!darkBorder && settings["battle"]["cellBorders"].Bool())
  155. canvas.draw(cellBorder, hexPos);
  156. }
  157. std::set<BattleHex> BattleFieldController::getHighlightedHexesStackRange()
  158. {
  159. std::set<BattleHex> result;
  160. if ( !owner.stacksController->getActiveStack())
  161. return result;
  162. if ( !settings["battle"]["stackRange"].Bool())
  163. return result;
  164. auto hoveredHex = getHoveredHex();
  165. std::set<BattleHex> set = owner.curInt->cb->battleGetAttackedHexes(owner.stacksController->getActiveStack(), hoveredHex, attackingHex);
  166. for(BattleHex hex : set)
  167. result.insert(hex);
  168. // display the movement shadow of the stack at b (i.e. stack under mouse)
  169. const CStack * const shere = owner.curInt->cb->battleGetStackByPos(hoveredHex, false);
  170. if(shere && shere != owner.stacksController->getActiveStack() && shere->alive())
  171. {
  172. std::vector<BattleHex> v = owner.curInt->cb->battleGetAvailableHexes(shere, true, nullptr);
  173. for(BattleHex hex : v)
  174. result.insert(hex);
  175. }
  176. return result;
  177. }
  178. std::set<BattleHex> BattleFieldController::getHighlightedHexesSpellRange()
  179. {
  180. std::set<BattleHex> result;
  181. auto hoveredHex = getHoveredHex();
  182. if(!settings["battle"]["mouseShadow"].Bool())
  183. return result;
  184. const spells::Caster *caster = nullptr;
  185. const CSpell *spell = nullptr;
  186. spells::Mode mode = spells::Mode::HERO;
  187. if(owner.actionsController->spellcastingModeActive())//hero casts spell
  188. {
  189. spell = owner.actionsController->selectedSpell().toSpell();
  190. caster = owner.getActiveHero();
  191. }
  192. else if(owner.stacksController->activeStackSpellToCast() != SpellID::NONE)//stack casts spell
  193. {
  194. spell = SpellID(owner.stacksController->activeStackSpellToCast()).toSpell();
  195. caster = owner.stacksController->getActiveStack();
  196. mode = spells::Mode::CREATURE_ACTIVE;
  197. }
  198. if(caster && spell) //when casting spell
  199. {
  200. // printing shaded hex(es)
  201. spells::BattleCast event(owner.curInt->cb.get(), caster, mode, spell);
  202. auto shaded = spell->battleMechanics(&event)->rangeInHexes(hoveredHex);
  203. for(BattleHex shadedHex : shaded)
  204. {
  205. if((shadedHex.getX() != 0) && (shadedHex.getX() != GameConstants::BFIELD_WIDTH - 1))
  206. result.insert(shadedHex);
  207. }
  208. }
  209. return result;
  210. }
  211. std::set<BattleHex> BattleFieldController::getHighlightedHexesMovementTarget()
  212. {
  213. const CStack * stack = owner.stacksController->getActiveStack();
  214. auto hoveredHex = getHoveredHex();
  215. if (stack)
  216. {
  217. std::vector<BattleHex> v = owner.curInt->cb->battleGetAvailableHexes(stack, false, nullptr);
  218. auto hoveredStack = owner.curInt->cb->battleGetStackByPos(hoveredHex, true);
  219. if(owner.curInt->cb->battleCanAttack(stack, hoveredStack, hoveredHex))
  220. {
  221. if (isTileAttackable(hoveredHex))
  222. {
  223. BattleHex attackFromHex = fromWhichHexAttack(hoveredHex);
  224. if (stack->doubleWide())
  225. return {attackFromHex, stack->occupiedHex(attackFromHex)};
  226. else
  227. return {attackFromHex};
  228. }
  229. }
  230. if (vstd::contains(v,hoveredHex))
  231. {
  232. if (stack->doubleWide())
  233. return {hoveredHex, stack->occupiedHex(hoveredHex)};
  234. else
  235. return {hoveredHex};
  236. }
  237. if (stack->doubleWide())
  238. {
  239. for (auto const & hex : v)
  240. {
  241. if (stack->occupiedHex(hex) == hoveredHex)
  242. return { hoveredHex, hex };
  243. }
  244. }
  245. }
  246. return {};
  247. }
  248. void BattleFieldController::showHighlightedHexes(Canvas & canvas)
  249. {
  250. std::set<BattleHex> hoveredStack = getHighlightedHexesStackRange();
  251. std::set<BattleHex> hoveredSpell = getHighlightedHexesSpellRange();
  252. std::set<BattleHex> hoveredMove = getHighlightedHexesMovementTarget();
  253. auto const & hoveredMouse = owner.actionsController->spellcastingModeActive() ? hoveredSpell : hoveredMove;
  254. for(int b=0; b<GameConstants::BFIELD_SIZE; ++b)
  255. {
  256. bool stack = hoveredStack.count(b);
  257. bool mouse = hoveredMouse.count(b);
  258. if ( stack && mouse )
  259. {
  260. // area where enemy stack can move AND affected by mouse cursor - create darker highlight by blitting twice
  261. showHighlightedHex(canvas, b, true);
  262. showHighlightedHex(canvas, b, true);
  263. }
  264. if ( !stack && mouse )
  265. {
  266. showHighlightedHex(canvas, b, true);
  267. }
  268. if ( stack && !mouse )
  269. {
  270. showHighlightedHex(canvas, b, false);
  271. }
  272. }
  273. }
  274. Rect BattleFieldController::hexPositionLocal(BattleHex hex) const
  275. {
  276. int x = 14 + ((hex.getY())%2==0 ? 22 : 0) + 44*hex.getX();
  277. int y = 86 + 42 *hex.getY();
  278. int w = cellShade->width();
  279. int h = cellShade->height();
  280. return Rect(x, y, w, h);
  281. }
  282. Rect BattleFieldController::hexPositionAbsolute(BattleHex hex) const
  283. {
  284. return hexPositionLocal(hex) + pos.topLeft();
  285. }
  286. bool BattleFieldController::isPixelInHex(Point const & position)
  287. {
  288. return !cellShade->isTransparent(position);
  289. }
  290. BattleHex BattleFieldController::getHoveredHex()
  291. {
  292. for ( auto const & hex : bfield)
  293. if (hex->hovered && hex->strictHovered)
  294. return hex->myNumber;
  295. return BattleHex::INVALID;
  296. }
  297. void BattleFieldController::setBattleCursor(BattleHex myNumber)
  298. {
  299. Point cursorPos = CCS->curh->position();
  300. std::vector<Cursor::Combat> sectorCursor = {
  301. Cursor::Combat::HIT_SOUTHEAST,
  302. Cursor::Combat::HIT_SOUTHWEST,
  303. Cursor::Combat::HIT_WEST,
  304. Cursor::Combat::HIT_NORTHWEST,
  305. Cursor::Combat::HIT_NORTHEAST,
  306. Cursor::Combat::HIT_EAST,
  307. Cursor::Combat::HIT_SOUTH,
  308. Cursor::Combat::HIT_NORTH,
  309. };
  310. auto direction = static_cast<size_t>(selectAttackDirection(myNumber, cursorPos));
  311. assert(direction != -1);
  312. if (direction != -1)
  313. CCS->curh->set(sectorCursor[direction]);
  314. }
  315. BattleHex::EDir BattleFieldController::selectAttackDirection(BattleHex myNumber, const Point & cursorPos)
  316. {
  317. const bool doubleWide = owner.stacksController->getActiveStack()->doubleWide();
  318. auto neighbours = myNumber.allNeighbouringTiles();
  319. // 0 1
  320. // 5 x 2
  321. // 4 3
  322. // if true - our current stack can move into this hex (and attack)
  323. std::array<bool, 8> attackAvailability;
  324. if (doubleWide)
  325. {
  326. // For double-hexes we need to ensure that both hexes needed for this direction are occupyable:
  327. // | -0- | -1- | -2- | -3- | -4- | -5- | -6- | -7-
  328. // | o o - | - o o | - - | - - | - - | - - | o o | - -
  329. // | - x - | - x - | - x o o| - x - | - x - |o o x - | - x - | - x -
  330. // | - - | - - | - - | - o o | o o - | - - | - - | o o
  331. for (size_t i : { 1, 2, 3})
  332. attackAvailability[i] = vstd::contains(occupyableHexes, neighbours[i]) && vstd::contains(occupyableHexes, neighbours[i].cloneInDirection(BattleHex::RIGHT, false));
  333. for (size_t i : { 4, 5, 0})
  334. attackAvailability[i] = vstd::contains(occupyableHexes, neighbours[i]) && vstd::contains(occupyableHexes, neighbours[i].cloneInDirection(BattleHex::LEFT, false));
  335. attackAvailability[6] = vstd::contains(occupyableHexes, neighbours[0]) && vstd::contains(occupyableHexes, neighbours[1]);
  336. attackAvailability[7] = vstd::contains(occupyableHexes, neighbours[3]) && vstd::contains(occupyableHexes, neighbours[4]);
  337. }
  338. else
  339. {
  340. for (size_t i = 0; i < 6; ++i)
  341. attackAvailability[i] = vstd::contains(occupyableHexes, neighbours[i]);
  342. attackAvailability[6] = false;
  343. attackAvailability[7] = false;
  344. }
  345. // Zero available tiles to attack from
  346. if ( vstd::find(attackAvailability, true) == attackAvailability.end())
  347. {
  348. logGlobal->error("Error: cannot find a hex to attack hex %d from!", myNumber);
  349. return BattleHex::NONE;
  350. }
  351. // For each valid direction, select position to test against
  352. std::array<Point, 8> testPoint;
  353. for (size_t i = 0; i < 6; ++i)
  354. if (attackAvailability[i])
  355. testPoint[i] = hexPositionAbsolute(neighbours[i]).center();
  356. // For bottom/top directions select central point, but move it a bit away from true center to reduce zones allocated to them
  357. if (attackAvailability[6])
  358. testPoint[6] = (hexPositionAbsolute(neighbours[0]).center() + hexPositionAbsolute(neighbours[1]).center()) / 2 + Point(0, -5);
  359. if (attackAvailability[7])
  360. testPoint[7] = (hexPositionAbsolute(neighbours[3]).center() + hexPositionAbsolute(neighbours[4]).center()) / 2 + Point(0, 5);
  361. // Compute distance between tested position & cursor position and pick nearest
  362. std::array<int, 8> distance2;
  363. for (size_t i = 0; i < 8; ++i)
  364. if (attackAvailability[i])
  365. distance2[i] = (testPoint[i].y - cursorPos.y)*(testPoint[i].y - cursorPos.y) + (testPoint[i].x - cursorPos.x)*(testPoint[i].x - cursorPos.x);
  366. size_t nearest = -1;
  367. for (size_t i = 0; i < 8; ++i)
  368. if (attackAvailability[i] && (nearest == -1 || distance2[i] < distance2[nearest]) )
  369. nearest = i;
  370. assert(nearest != -1);
  371. return BattleHex::EDir(nearest);
  372. }
  373. BattleHex BattleFieldController::fromWhichHexAttack(BattleHex attackTarget)
  374. {
  375. BattleHex::EDir direction = selectAttackDirection(attackTarget, CCS->curh->position());
  376. const CStack * attacker = owner.stacksController->getActiveStack();
  377. assert(direction != BattleHex::NONE);
  378. assert(attacker);
  379. if (!attacker->doubleWide())
  380. {
  381. assert(direction != BattleHex::BOTTOM);
  382. assert(direction != BattleHex::TOP);
  383. return attackTarget.cloneInDirection(direction);
  384. }
  385. else
  386. {
  387. // We need to find position of right hex of double-hex creature (or left for defending side)
  388. // | TOP_LEFT |TOP_RIGHT | RIGHT |BOTTOM_RIGHT|BOTTOM_LEFT| LEFT | TOP |BOTTOM
  389. // | o o - | - o o | - - | - - | - - | - - | o o | - -
  390. // | - x - | - x - | - x o o| - x - | - x - |o o x - | - x - | - x -
  391. // | - - | - - | - - | - o o | o o - | - - | - - | o o
  392. switch (direction)
  393. {
  394. case BattleHex::TOP_LEFT:
  395. case BattleHex::LEFT:
  396. case BattleHex::BOTTOM_LEFT:
  397. {
  398. if ( attacker->side == BattleSide::ATTACKER )
  399. return attackTarget.cloneInDirection(direction);
  400. else
  401. return attackTarget.cloneInDirection(direction).cloneInDirection(BattleHex::LEFT);
  402. }
  403. case BattleHex::TOP_RIGHT:
  404. case BattleHex::RIGHT:
  405. case BattleHex::BOTTOM_RIGHT:
  406. {
  407. if ( attacker->side == BattleSide::ATTACKER )
  408. return attackTarget.cloneInDirection(direction).cloneInDirection(BattleHex::RIGHT);
  409. else
  410. return attackTarget.cloneInDirection(direction);
  411. }
  412. case BattleHex::TOP:
  413. {
  414. if ( attacker->side == BattleSide::ATTACKER )
  415. return attackTarget.cloneInDirection(BattleHex::TOP_RIGHT);
  416. else
  417. return attackTarget.cloneInDirection(BattleHex::TOP_LEFT);
  418. }
  419. case BattleHex::BOTTOM:
  420. {
  421. if ( attacker->side == BattleSide::ATTACKER )
  422. return attackTarget.cloneInDirection(BattleHex::BOTTOM_RIGHT);
  423. else
  424. return attackTarget.cloneInDirection(BattleHex::BOTTOM_LEFT);
  425. }
  426. default:
  427. assert(0);
  428. return attackTarget.cloneInDirection(BattleHex::LEFT);
  429. }
  430. }
  431. }
  432. bool BattleFieldController::isTileAttackable(const BattleHex & number) const
  433. {
  434. for (auto & elem : occupyableHexes)
  435. {
  436. if (BattleHex::mutualPosition(elem, number) != -1 || elem == number)
  437. return true;
  438. }
  439. return false;
  440. }
  441. bool BattleFieldController::stackCountOutsideHex(const BattleHex & number) const
  442. {
  443. return stackCountOutsideHexes[number];
  444. }
  445. void BattleFieldController::showAll(SDL_Surface * to)
  446. {
  447. show(to);
  448. }
  449. void BattleFieldController::show(SDL_Surface * to)
  450. {
  451. owner.stacksController->update();
  452. owner.obstacleController->update();
  453. Canvas canvas(to);
  454. renderBattlefield(canvas);
  455. }