CCreatureWindow.cpp 33 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021
  1. /*
  2. * CCreatureWindow.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 "CCreatureWindow.h"
  12. #include <vcmi/spells/Spell.h>
  13. #include <vcmi/spells/Service.h>
  14. #include "../CGameInfo.h"
  15. #include "../CPlayerInterface.h"
  16. #include "../render/Canvas.h"
  17. #include "../widgets/Buttons.h"
  18. #include "../widgets/CComponent.h"
  19. #include "../widgets/CComponentHolder.h"
  20. #include "../widgets/Images.h"
  21. #include "../widgets/TextControls.h"
  22. #include "../widgets/ObjectLists.h"
  23. #include "../windows/InfoWindows.h"
  24. #include "../gui/CGuiHandler.h"
  25. #include "../gui/Shortcut.h"
  26. #include "../battle/BattleInterface.h"
  27. #include "../../CCallback.h"
  28. #include "../../lib/ArtifactUtils.h"
  29. #include "../../lib/CStack.h"
  30. #include "../../lib/CBonusTypeHandler.h"
  31. #include "../../lib/IGameSettings.h"
  32. #include "../../lib/entities/hero/CHeroHandler.h"
  33. #include "../../lib/gameState/CGameState.h"
  34. #include "../../lib/networkPacks/ArtifactLocation.h"
  35. #include "../../lib/texts/CGeneralTextHandler.h"
  36. #include "../../lib/texts/TextOperations.h"
  37. class CCreatureArtifactInstance;
  38. class CSelectableSkill;
  39. class UnitView
  40. {
  41. public:
  42. // helper structs
  43. struct CommanderLevelInfo
  44. {
  45. std::vector<ui32> skills;
  46. std::function<void(ui32)> callback;
  47. };
  48. struct StackDismissInfo
  49. {
  50. std::function<void()> callback;
  51. };
  52. struct StackUpgradeInfo
  53. {
  54. UpgradeInfo info;
  55. std::function<void(CreatureID)> callback;
  56. };
  57. // pointers to permanent objects in game state
  58. const CCreature * creature;
  59. const CCommanderInstance * commander;
  60. const CStackInstance * stackNode;
  61. const CStack * stack;
  62. const CGHeroInstance * owner;
  63. // temporary objects which should be kept as copy if needed
  64. std::optional<CommanderLevelInfo> levelupInfo;
  65. std::optional<StackDismissInfo> dismissInfo;
  66. std::optional<StackUpgradeInfo> upgradeInfo;
  67. // misc fields
  68. unsigned int creatureCount;
  69. bool popupWindow;
  70. UnitView()
  71. : creature(nullptr),
  72. commander(nullptr),
  73. stackNode(nullptr),
  74. stack(nullptr),
  75. owner(nullptr),
  76. creatureCount(0),
  77. popupWindow(false)
  78. {
  79. }
  80. std::string getName() const
  81. {
  82. if(commander)
  83. return commander->type->getNameSingularTranslated();
  84. else
  85. return creature->getNamePluralTranslated();
  86. }
  87. private:
  88. };
  89. CCommanderSkillIcon::CCommanderSkillIcon(std::shared_ptr<CIntObject> object_, bool isMasterAbility_, std::function<void()> callback)
  90. : object(),
  91. isMasterAbility(isMasterAbility_),
  92. isSelected(false),
  93. callback(callback)
  94. {
  95. pos = object_->pos;
  96. this->isMasterAbility = isMasterAbility_;
  97. setObject(object_);
  98. }
  99. void CCommanderSkillIcon::setObject(std::shared_ptr<CIntObject> newObject)
  100. {
  101. if(object)
  102. removeChild(object.get());
  103. object = newObject;
  104. addChild(object.get());
  105. object->moveTo(pos.topLeft());
  106. redraw();
  107. }
  108. void CCommanderSkillIcon::clickPressed(const Point & cursorPosition)
  109. {
  110. callback();
  111. isSelected = true;
  112. }
  113. void CCommanderSkillIcon::deselect()
  114. {
  115. isSelected = false;
  116. }
  117. bool CCommanderSkillIcon::getIsMasterAbility()
  118. {
  119. return isMasterAbility;
  120. }
  121. void CCommanderSkillIcon::show(Canvas &to)
  122. {
  123. CIntObject::show(to);
  124. if(isMasterAbility && isSelected)
  125. to.drawBorder(pos, Colors::YELLOW, 2);
  126. }
  127. static ImagePath skillToFile(int skill, int level, bool selected)
  128. {
  129. // FIXME: is this a correct handling?
  130. // level 0 = skill not present, use image with "no" suffix
  131. // level 1-5 = skill available, mapped to images indexed as 0-4
  132. // selecting skill means that it will appear one level higher (as if already upgraded)
  133. std::string file = "zvs/Lib1.res/_";
  134. switch (skill)
  135. {
  136. case ECommander::ATTACK:
  137. file += "AT";
  138. break;
  139. case ECommander::DEFENSE:
  140. file += "DF";
  141. break;
  142. case ECommander::HEALTH:
  143. file += "HP";
  144. break;
  145. case ECommander::DAMAGE:
  146. file += "DM";
  147. break;
  148. case ECommander::SPEED:
  149. file += "SP";
  150. break;
  151. case ECommander::SPELL_POWER:
  152. file += "MP";
  153. break;
  154. }
  155. std::string suffix;
  156. if (selected)
  157. level++; // UI will display resulting level
  158. if (level == 0)
  159. suffix = "no"; //not available - no number
  160. else
  161. suffix = std::to_string(level-1);
  162. if (selected)
  163. suffix += "="; //level-up highlight
  164. return ImagePath::builtin(file + suffix + ".bmp");
  165. }
  166. CStackWindow::CWindowSection::CWindowSection(CStackWindow * parent, const ImagePath & backgroundPath, int yOffset)
  167. : parent(parent)
  168. {
  169. pos.y += yOffset;
  170. OBJECT_CONSTRUCTION;
  171. if(!backgroundPath.empty())
  172. {
  173. background = std::make_shared<CPicture>(backgroundPath);
  174. pos.w = background->pos.w;
  175. pos.h = background->pos.h;
  176. }
  177. }
  178. CStackWindow::ActiveSpellsSection::ActiveSpellsSection(CStackWindow * owner, int yOffset)
  179. : CWindowSection(owner, ImagePath::builtin("stackWindow/spell-effects"), yOffset)
  180. {
  181. static const Point firstPos(6, 2); // position of 1st spell box
  182. static const Point offset(54, 0); // offset of each spell box from previous
  183. OBJECT_CONSTRUCTION;
  184. const CStack * battleStack = parent->info->stack;
  185. assert(battleStack); // Section should be created only for battles
  186. //spell effects
  187. int printed=0; //how many effect pics have been printed
  188. std::vector<SpellID> spells = battleStack->activeSpells();
  189. for(SpellID effect : spells)
  190. {
  191. const spells::Spell * spell = CGI->spells()->getById(effect);
  192. std::string spellText;
  193. //not all effects have graphics (for eg. Acid Breath)
  194. //for modded spells iconEffect is added to SpellInt.def
  195. const bool hasGraphics = (effect < SpellID::THUNDERBOLT) || (effect >= SpellID::AFTER_LAST);
  196. if (hasGraphics)
  197. {
  198. spellText = CGI->generaltexth->allTexts[610]; //"%s, duration: %d rounds."
  199. boost::replace_first(spellText, "%s", spell->getNameTranslated());
  200. //FIXME: support permanent duration
  201. int duration = battleStack->getFirstBonus(Selector::source(BonusSource::SPELL_EFFECT, BonusSourceID(effect)))->turnsRemain;
  202. boost::replace_first(spellText, "%d", std::to_string(duration));
  203. spellIcons.push_back(std::make_shared<CAnimImage>(AnimationPath::builtin("SpellInt"), effect + 1, 0, firstPos.x + offset.x * printed, firstPos.y + offset.y * printed));
  204. labels.push_back(std::make_shared<CLabel>(firstPos.x + offset.x * printed + 46, firstPos.y + offset.y * printed + 36, EFonts::FONT_TINY, ETextAlignment::BOTTOMRIGHT, Colors::WHITE, std::to_string(duration)));
  205. clickableAreas.push_back(std::make_shared<LRClickableAreaWText>(Rect(firstPos + offset * printed, Point(50, 38)), spellText, spellText));
  206. if(++printed >= 8) // interface limit reached
  207. break;
  208. }
  209. }
  210. }
  211. CStackWindow::BonusLineSection::BonusLineSection(CStackWindow * owner, size_t lineIndex)
  212. : CWindowSection(owner, ImagePath::builtin("stackWindow/bonus-effects"), 0)
  213. {
  214. OBJECT_CONSTRUCTION;
  215. static const std::array<Point, 2> offset =
  216. {
  217. Point(6, 4),
  218. Point(214, 4)
  219. };
  220. for(size_t leftRight : {0, 1})
  221. {
  222. auto position = offset[leftRight];
  223. size_t bonusIndex = lineIndex * 2 + leftRight;
  224. if(parent->activeBonuses.size() > bonusIndex)
  225. {
  226. BonusInfo & bi = parent->activeBonuses[bonusIndex];
  227. icon[leftRight] = std::make_shared<CPicture>(bi.imagePath, position.x, position.y);
  228. name[leftRight] = std::make_shared<CLabel>(position.x + 60, position.y + 2, FONT_SMALL, ETextAlignment::TOPLEFT, Colors::WHITE, bi.name);
  229. description[leftRight] = std::make_shared<CMultiLineLabel>(Rect(position.x + 60, position.y + 17, 137, 30), FONT_SMALL, ETextAlignment::TOPLEFT, Colors::WHITE, bi.description);
  230. }
  231. }
  232. }
  233. CStackWindow::BonusesSection::BonusesSection(CStackWindow * owner, int yOffset, std::optional<size_t> preferredSize):
  234. CWindowSection(owner, {}, yOffset)
  235. {
  236. OBJECT_CONSTRUCTION;
  237. // size of single image for an item
  238. static const int itemHeight = 59;
  239. size_t totalSize = (owner->activeBonuses.size() + 1) / 2;
  240. size_t visibleSize = preferredSize.value_or(std::min<size_t>(3, totalSize));
  241. pos.w = owner->pos.w;
  242. pos.h = itemHeight * (int)visibleSize;
  243. auto onCreate = [=](size_t index) -> std::shared_ptr<CIntObject>
  244. {
  245. return std::make_shared<BonusLineSection>(owner, index);
  246. };
  247. lines = std::make_shared<CListBox>(onCreate, Point(0, 0), Point(0, itemHeight), visibleSize, totalSize, 0, 1, Rect(pos.w - 15, 0, pos.h, pos.h));
  248. }
  249. CStackWindow::ButtonsSection::ButtonsSection(CStackWindow * owner, int yOffset)
  250. : CWindowSection(owner, ImagePath::builtin("stackWindow/button-panel"), yOffset)
  251. {
  252. OBJECT_CONSTRUCTION;
  253. if(parent->info->dismissInfo && parent->info->dismissInfo->callback)
  254. {
  255. auto onDismiss = [=]()
  256. {
  257. parent->info->dismissInfo->callback();
  258. parent->close();
  259. };
  260. auto onClick = [=] ()
  261. {
  262. LOCPLINT->showYesNoDialog(CGI->generaltexth->allTexts[12], onDismiss, nullptr);
  263. };
  264. dismiss = std::make_shared<CButton>(Point(5, 5),AnimationPath::builtin("IVIEWCR2.DEF"), CGI->generaltexth->zelp[445], onClick, EShortcut::HERO_DISMISS);
  265. }
  266. if(parent->info->upgradeInfo && !parent->info->commander)
  267. {
  268. // used space overlaps with commander switch button
  269. // besides - should commander really be upgradeable?
  270. auto & upgradeInfo = parent->info->upgradeInfo.value();
  271. const size_t buttonsToCreate = std::min<size_t>(upgradeInfo.info.newID.size(), upgrade.size());
  272. for(size_t buttonIndex = 0; buttonIndex < buttonsToCreate; buttonIndex++)
  273. {
  274. TResources totalCost = upgradeInfo.info.cost[buttonIndex] * parent->info->creatureCount;
  275. auto onUpgrade = [=]()
  276. {
  277. upgradeInfo.callback(upgradeInfo.info.newID[buttonIndex]);
  278. parent->close();
  279. };
  280. auto onClick = [=]()
  281. {
  282. std::vector<std::shared_ptr<CComponent>> resComps;
  283. for(TResources::nziterator i(totalCost); i.valid(); i++)
  284. {
  285. resComps.push_back(std::make_shared<CComponent>(ComponentType::RESOURCE, i->resType, i->resVal));
  286. }
  287. if(LOCPLINT->cb->getResourceAmount().canAfford(totalCost))
  288. {
  289. LOCPLINT->showYesNoDialog(CGI->generaltexth->allTexts[207], onUpgrade, nullptr, resComps);
  290. }
  291. else
  292. {
  293. LOCPLINT->showInfoDialog(CGI->generaltexth->allTexts[314], resComps);
  294. }
  295. };
  296. auto upgradeBtn = std::make_shared<CButton>(Point(221 + (int)buttonIndex * 40, 5), AnimationPath::builtin("stackWindow/upgradeButton"), CGI->generaltexth->zelp[446], onClick);
  297. upgradeBtn->setOverlay(std::make_shared<CAnimImage>(AnimationPath::builtin("CPRSMALL"), VLC->creh->objects[upgradeInfo.info.newID[buttonIndex]]->getIconIndex()));
  298. if(buttonsToCreate == 1) // single upgrade available
  299. upgradeBtn->assignedKey = EShortcut::RECRUITMENT_UPGRADE;
  300. upgrade[buttonIndex] = upgradeBtn;
  301. }
  302. }
  303. if(parent->info->commander)
  304. {
  305. for(size_t buttonIndex = 0; buttonIndex < 2; buttonIndex++)
  306. {
  307. std::string btnIDs[2] = { "showSkills", "showBonuses" };
  308. auto onSwitch = [buttonIndex, this]()
  309. {
  310. logAnim->debug("Switch %d->%d", parent->activeTab, buttonIndex);
  311. parent->switchButtons[parent->activeTab]->enable();
  312. parent->commanderTab->setActive(buttonIndex);
  313. parent->switchButtons[buttonIndex]->disable();
  314. parent->redraw(); // FIXME: enable/disable don't redraw screen themselves
  315. };
  316. std::string tooltipText = "vcmi.creatureWindow." + btnIDs[buttonIndex];
  317. parent->switchButtons[buttonIndex] = std::make_shared<CButton>(Point(302 + (int)buttonIndex*40, 5), AnimationPath::builtin("stackWindow/upgradeButton"), CButton::tooltipLocalized(tooltipText), onSwitch);
  318. parent->switchButtons[buttonIndex]->setOverlay(std::make_shared<CAnimImage>(AnimationPath::builtin("stackWindow/switchModeIcons"), buttonIndex));
  319. }
  320. parent->switchButtons[parent->activeTab]->disable();
  321. }
  322. exit = std::make_shared<CButton>(Point(382, 5), AnimationPath::builtin("hsbtns.def"), CGI->generaltexth->zelp[447], [=](){ parent->close(); }, EShortcut::GLOBAL_RETURN);
  323. }
  324. CStackWindow::CommanderMainSection::CommanderMainSection(CStackWindow * owner, int yOffset)
  325. : CWindowSection(owner, ImagePath::builtin("stackWindow/commander-bg"), yOffset)
  326. {
  327. OBJECT_CONSTRUCTION;
  328. auto getSkillPos = [](int index)
  329. {
  330. return Point(10 + 80 * (index%3), 20 + 80 * (index/3));
  331. };
  332. auto getSkillImage = [this](int skillIndex)
  333. {
  334. bool selected = ((parent->selectedSkill == skillIndex) && parent->info->levelupInfo );
  335. return skillToFile(skillIndex, parent->info->commander->secondarySkills[skillIndex], selected);
  336. };
  337. auto getSkillDescription = [this](int skillIndex) -> std::string
  338. {
  339. return parent->getCommanderSkillDescription(skillIndex, parent->info->commander->secondarySkills[skillIndex]);
  340. };
  341. for(int index = ECommander::ATTACK; index <= ECommander::SPELL_POWER; ++index)
  342. {
  343. Point skillPos = getSkillPos(index);
  344. auto icon = std::make_shared<CCommanderSkillIcon>(std::make_shared<CPicture>(getSkillImage(index), skillPos.x, skillPos.y), false, [=]()
  345. {
  346. LOCPLINT->showInfoDialog(getSkillDescription(index));
  347. });
  348. icon->text = getSkillDescription(index); //used to handle right click description via LRClickableAreaWText::ClickRight()
  349. if(parent->selectedSkill == index)
  350. parent->selectedIcon = icon;
  351. if(parent->info->levelupInfo && vstd::contains(parent->info->levelupInfo->skills, index)) // can be upgraded - enable selection switch
  352. {
  353. if(parent->selectedSkill == index)
  354. parent->setSelection(index, icon);
  355. icon->callback = [=]()
  356. {
  357. parent->setSelection(index, icon);
  358. };
  359. }
  360. skillIcons.push_back(icon);
  361. }
  362. auto getArtifactPos = [](int index)
  363. {
  364. return Point(269 + 47 * (index % 3), 22 + 47 * (index / 3));
  365. };
  366. for(auto equippedArtifact : parent->info->commander->artifactsWorn)
  367. {
  368. Point artPos = getArtifactPos(equippedArtifact.first);
  369. const auto commanderArt = equippedArtifact.second.artifact;
  370. assert(commanderArt);
  371. auto artPlace = std::make_shared<CCommanderArtPlace>(artPos, parent->info->owner, equippedArtifact.first, commanderArt->getTypeId());
  372. artifacts.push_back(artPlace);
  373. }
  374. if(parent->info->levelupInfo)
  375. {
  376. abilitiesBackground = std::make_shared<CPicture>(ImagePath::builtin("stackWindow/commander-abilities.png"));
  377. abilitiesBackground->moveBy(Point(0, pos.h));
  378. size_t abilitiesCount = boost::range::count_if(parent->info->levelupInfo->skills, [](ui32 skillID)
  379. {
  380. return skillID >= 100;
  381. });
  382. auto onCreate = [=](size_t index)->std::shared_ptr<CIntObject>
  383. {
  384. for(auto skillID : parent->info->levelupInfo->skills)
  385. {
  386. if(index == 0 && skillID >= 100)
  387. {
  388. const auto bonus = CGI->creh->skillRequirements[skillID-100].first;
  389. const CStackInstance * stack = parent->info->commander;
  390. auto icon = std::make_shared<CCommanderSkillIcon>(std::make_shared<CPicture>(stack->bonusToGraphics(bonus)), true, [](){});
  391. icon->callback = [=]()
  392. {
  393. parent->setSelection(skillID, icon);
  394. };
  395. icon->text = stack->bonusToString(bonus, true);
  396. icon->hoverText = stack->bonusToString(bonus, false);
  397. return icon;
  398. }
  399. if(skillID >= 100)
  400. index--;
  401. }
  402. return nullptr;
  403. };
  404. abilities = std::make_shared<CListBox>(onCreate, Point(38, 3+pos.h), Point(63, 0), 6, abilitiesCount);
  405. abilities->setRedrawParent(true);
  406. leftBtn = std::make_shared<CButton>(Point(10, pos.h + 6), AnimationPath::builtin("hsbtns3.def"), CButton::tooltip(), [=](){ abilities->moveToPrev(); }, EShortcut::MOVE_LEFT);
  407. rightBtn = std::make_shared<CButton>(Point(411, pos.h + 6), AnimationPath::builtin("hsbtns5.def"), CButton::tooltip(), [=](){ abilities->moveToNext(); }, EShortcut::MOVE_RIGHT);
  408. if(abilitiesCount <= 6)
  409. {
  410. leftBtn->block(true);
  411. rightBtn->block(true);
  412. }
  413. pos.h += abilitiesBackground->pos.h;
  414. }
  415. }
  416. CStackWindow::MainSection::MainSection(CStackWindow * owner, int yOffset, bool showExp, bool showArt)
  417. : CWindowSection(owner, getBackgroundName(showExp, showArt), yOffset)
  418. {
  419. OBJECT_CONSTRUCTION;
  420. statNames =
  421. {
  422. CGI->generaltexth->primarySkillNames[0], //ATTACK
  423. CGI->generaltexth->primarySkillNames[1],//DEFENCE
  424. CGI->generaltexth->allTexts[198],//SHOTS
  425. CGI->generaltexth->allTexts[199],//DAMAGE
  426. CGI->generaltexth->allTexts[388],//HEALTH
  427. CGI->generaltexth->allTexts[200],//HEALTH_LEFT
  428. CGI->generaltexth->zelp[441].first,//SPEED
  429. CGI->generaltexth->allTexts[399]//MANA
  430. };
  431. statFormats =
  432. {
  433. "%d (%d)",
  434. "%d (%d)",
  435. "%d (%d)",
  436. "%d - %d",
  437. "%d (%d)",
  438. "%d (%d)",
  439. "%d (%d)",
  440. "%d (%d)"
  441. };
  442. animation = std::make_shared<CCreaturePic>(5, 41, parent->info->creature);
  443. animationArea = std::make_shared<LRClickableArea>(Rect(5, 41, 100, 130), nullptr, [&]{
  444. if(!parent->info->creature->getDescriptionTranslated().empty())
  445. CRClickPopup::createAndPush(parent->info->creature->getDescriptionTranslated());
  446. });
  447. if(parent->info->stackNode != nullptr && parent->info->commander == nullptr)
  448. {
  449. //normal stack, not a commander and not non-existing stack (e.g. recruitment dialog)
  450. animation->setAmount(parent->info->creatureCount);
  451. }
  452. name = std::make_shared<CLabel>(215, 12, FONT_SMALL, ETextAlignment::CENTER, Colors::YELLOW, parent->info->getName());
  453. const BattleInterface* battleInterface = LOCPLINT->battleInt.get();
  454. const CStack* battleStack = parent->info->stack;
  455. int dmgMultiply = 1;
  456. if (battleInterface && battleInterface->getBattle() != nullptr && battleStack->hasBonusOfType(BonusType::SIEGE_WEAPON))
  457. {
  458. // Determine the relevant hero based on the unit side
  459. const auto hero = (battleStack->unitSide() == BattleSide::ATTACKER)
  460. ? battleInterface->attackingHeroInstance
  461. : battleInterface->defendingHeroInstance;
  462. dmgMultiply += hero->getPrimSkillLevel(PrimarySkill::ATTACK);
  463. }
  464. icons = std::make_shared<CPicture>(ImagePath::builtin("stackWindow/icons"), 117, 32);
  465. morale = std::make_shared<MoraleLuckBox>(true, Rect(Point(321, 110), Point(42, 42) ));
  466. luck = std::make_shared<MoraleLuckBox>(false, Rect(Point(375, 110), Point(42, 42) ));
  467. if(battleStack != nullptr) // in battle
  468. {
  469. addStatLabel(EStat::ATTACK, parent->info->creature->getAttack(battleStack->isShooter()), battleStack->getAttack(battleStack->isShooter()));
  470. addStatLabel(EStat::DEFENCE, parent->info->creature->getDefense(battleStack->isShooter()), battleStack->getDefense(battleStack->isShooter()));
  471. addStatLabel(EStat::DAMAGE, parent->info->stackNode->getMinDamage(battleStack->isShooter()) * dmgMultiply, battleStack->getMaxDamage(battleStack->isShooter()) * dmgMultiply);
  472. addStatLabel(EStat::HEALTH, parent->info->creature->getMaxHealth(), battleStack->getMaxHealth());
  473. addStatLabel(EStat::SPEED, parent->info->creature->getMovementRange(), battleStack->getMovementRange());
  474. if(battleStack->isShooter())
  475. addStatLabel(EStat::SHOTS, battleStack->shots.total(), battleStack->shots.available());
  476. if(battleStack->isCaster())
  477. addStatLabel(EStat::MANA, battleStack->casts.total(), battleStack->casts.available());
  478. addStatLabel(EStat::HEALTH_LEFT, battleStack->getFirstHPleft());
  479. morale->set(battleStack);
  480. luck->set(battleStack);
  481. }
  482. else
  483. {
  484. const bool shooter = parent->info->stackNode->hasBonusOfType(BonusType::SHOOTER) && parent->info->stackNode->valOfBonuses(BonusType::SHOTS);
  485. const bool caster = parent->info->stackNode->valOfBonuses(BonusType::CASTS);
  486. addStatLabel(EStat::ATTACK, parent->info->creature->getAttack(shooter), parent->info->stackNode->getAttack(shooter));
  487. addStatLabel(EStat::DEFENCE, parent->info->creature->getDefense(shooter), parent->info->stackNode->getDefense(shooter));
  488. addStatLabel(EStat::DAMAGE, parent->info->stackNode->getMinDamage(shooter), parent->info->stackNode->getMaxDamage(shooter));
  489. addStatLabel(EStat::HEALTH, parent->info->creature->getMaxHealth(), parent->info->stackNode->getMaxHealth());
  490. addStatLabel(EStat::SPEED, parent->info->creature->getMovementRange(), parent->info->stackNode->getMovementRange());
  491. if(shooter)
  492. addStatLabel(EStat::SHOTS, parent->info->stackNode->valOfBonuses(BonusType::SHOTS));
  493. if(caster)
  494. addStatLabel(EStat::MANA, parent->info->stackNode->valOfBonuses(BonusType::CASTS));
  495. morale->set(parent->info->stackNode);
  496. luck->set(parent->info->stackNode);
  497. }
  498. if(showExp)
  499. {
  500. const CStackInstance * stack = parent->info->stackNode;
  501. Point pos = showArt ? Point(321, 32) : Point(347, 32);
  502. if(parent->info->commander)
  503. {
  504. const CCommanderInstance * commander = parent->info->commander;
  505. expRankIcon = std::make_shared<CAnimImage>(AnimationPath::builtin("PSKIL42"), 4, 0, pos.x, pos.y);
  506. auto area = std::make_shared<LRClickableAreaWTextComp>(Rect(pos.x, pos.y, 44, 44), ComponentType::EXPERIENCE);
  507. expArea = area;
  508. area->text = CGI->generaltexth->allTexts[2];
  509. area->component.value = commander->getExpRank();
  510. boost::replace_first(area->text, "%d", std::to_string(commander->getExpRank()));
  511. boost::replace_first(area->text, "%d", std::to_string(CGI->heroh->reqExp(commander->getExpRank() + 1)));
  512. boost::replace_first(area->text, "%d", std::to_string(commander->experience));
  513. }
  514. else
  515. {
  516. expRankIcon = std::make_shared<CAnimImage>(AnimationPath::builtin("stackWindow/levels"), stack->getExpRank(), 0, pos.x, pos.y);
  517. expArea = std::make_shared<LRClickableAreaWText>(Rect(pos.x, pos.y, 44, 44));
  518. expArea->text = parent->generateStackExpDescription();
  519. }
  520. expLabel = std::make_shared<CLabel>(
  521. pos.x + 21, pos.y + 52, FONT_SMALL, ETextAlignment::CENTER, Colors::WHITE,
  522. TextOperations::formatMetric(stack->experience, 6));
  523. }
  524. if(showArt)
  525. {
  526. Point pos = showExp ? Point(375, 32) : Point(347, 32);
  527. // ALARMA: do not refactor this into a separate function
  528. // otherwise, artifact icon is drawn near the hero's portrait
  529. // this is really strange
  530. auto art = parent->info->stackNode->getArt(ArtifactPosition::CREATURE_SLOT);
  531. if(art)
  532. {
  533. parent->stackArtifact = std::make_shared<CArtPlace>(pos, art->getTypeId());
  534. parent->stackArtifact->setShowPopupCallback([](CComponentHolder & artPlace, const Point & cursorPosition)
  535. {
  536. artPlace.LRClickableAreaWTextComp::showPopupWindow(cursorPosition);
  537. });
  538. if(parent->info->owner)
  539. {
  540. parent->stackArtifactButton = std::make_shared<CButton>(
  541. Point(pos.x - 2 , pos.y + 46), AnimationPath::builtin("stackWindow/cancelButton"),
  542. CButton::tooltipLocalized("vcmi.creatureWindow.returnArtifact"), [=]()
  543. {
  544. parent->removeStackArtifact(ArtifactPosition::CREATURE_SLOT);
  545. });
  546. }
  547. }
  548. }
  549. }
  550. ImagePath CStackWindow::MainSection::getBackgroundName(bool showExp, bool showArt)
  551. {
  552. if(showExp && showArt)
  553. return ImagePath::builtin("stackWindow/info-panel-2");
  554. else if(showExp || showArt)
  555. return ImagePath::builtin("stackWindow/info-panel-1");
  556. else
  557. return ImagePath::builtin("stackWindow/info-panel-0");
  558. }
  559. void CStackWindow::MainSection::addStatLabel(EStat index, int64_t value1, int64_t value2)
  560. {
  561. const auto title = statNames.at(static_cast<size_t>(index));
  562. stats.push_back(std::make_shared<CLabel>(145, 32 + (int)index*19, FONT_SMALL, ETextAlignment::TOPLEFT, Colors::WHITE, title));
  563. const bool useRange = value1 != value2;
  564. std::string formatStr = useRange ? statFormats.at(static_cast<size_t>(index)) : "%d";
  565. boost::format fmt(formatStr);
  566. fmt % value1;
  567. if(useRange)
  568. fmt % value2;
  569. stats.push_back(std::make_shared<CLabel>(307, 48 + (int)index*19, FONT_SMALL, ETextAlignment::BOTTOMRIGHT, Colors::WHITE, fmt.str()));
  570. }
  571. void CStackWindow::MainSection::addStatLabel(EStat index, int64_t value)
  572. {
  573. addStatLabel(index, value, value);
  574. }
  575. CStackWindow::CStackWindow(const CStack * stack, bool popup)
  576. : CWindowObject(BORDERED | (popup ? RCLICK_POPUP : 0)),
  577. info(new UnitView())
  578. {
  579. info->stack = stack;
  580. info->stackNode = stack->base;
  581. info->commander = dynamic_cast<const CCommanderInstance*>(stack->base);
  582. info->creature = stack->unitType();
  583. info->creatureCount = stack->getCount();
  584. info->popupWindow = popup;
  585. init();
  586. }
  587. CStackWindow::CStackWindow(const CCreature * creature, bool popup)
  588. : CWindowObject(BORDERED | (popup ? RCLICK_POPUP : 0)),
  589. info(new UnitView())
  590. {
  591. info->creature = creature;
  592. info->popupWindow = popup;
  593. init();
  594. }
  595. CStackWindow::CStackWindow(const CStackInstance * stack, bool popup)
  596. : CWindowObject(BORDERED | (popup ? RCLICK_POPUP : 0)),
  597. info(new UnitView())
  598. {
  599. info->stackNode = stack;
  600. info->creature = stack->type;
  601. info->creatureCount = stack->count;
  602. info->popupWindow = popup;
  603. info->owner = dynamic_cast<const CGHeroInstance *> (stack->armyObj);
  604. init();
  605. }
  606. CStackWindow::CStackWindow(const CStackInstance * stack, std::function<void()> dismiss, const UpgradeInfo & upgradeInfo, std::function<void(CreatureID)> callback)
  607. : CWindowObject(BORDERED),
  608. info(new UnitView())
  609. {
  610. info->stackNode = stack;
  611. info->creature = stack->type;
  612. info->creatureCount = stack->count;
  613. info->upgradeInfo = std::make_optional(UnitView::StackUpgradeInfo());
  614. info->dismissInfo = std::make_optional(UnitView::StackDismissInfo());
  615. info->upgradeInfo->info = upgradeInfo;
  616. info->upgradeInfo->callback = callback;
  617. info->dismissInfo->callback = dismiss;
  618. info->owner = dynamic_cast<const CGHeroInstance *> (stack->armyObj);
  619. init();
  620. }
  621. CStackWindow::CStackWindow(const CCommanderInstance * commander, bool popup)
  622. : CWindowObject(BORDERED | (popup ? RCLICK_POPUP : 0)),
  623. info(new UnitView())
  624. {
  625. info->stackNode = commander;
  626. info->creature = commander->type;
  627. info->commander = commander;
  628. info->creatureCount = 1;
  629. info->popupWindow = popup;
  630. info->owner = dynamic_cast<const CGHeroInstance *> (commander->armyObj);
  631. init();
  632. }
  633. CStackWindow::CStackWindow(const CCommanderInstance * commander, std::vector<ui32> &skills, std::function<void(ui32)> callback)
  634. : CWindowObject(BORDERED),
  635. info(new UnitView())
  636. {
  637. info->stackNode = commander;
  638. info->creature = commander->type;
  639. info->commander = commander;
  640. info->creatureCount = 1;
  641. info->levelupInfo = std::make_optional(UnitView::CommanderLevelInfo());
  642. info->levelupInfo->skills = skills;
  643. info->levelupInfo->callback = callback;
  644. info->owner = dynamic_cast<const CGHeroInstance *> (commander->armyObj);
  645. init();
  646. }
  647. CStackWindow::~CStackWindow()
  648. {
  649. if(info->levelupInfo && !info->levelupInfo->skills.empty())
  650. info->levelupInfo->callback(vstd::find_pos(info->levelupInfo->skills, selectedSkill));
  651. }
  652. void CStackWindow::init()
  653. {
  654. OBJECT_CONSTRUCTION;
  655. if(!info->stackNode)
  656. info->stackNode = new CStackInstance(info->creature, 1, true);// FIXME: free data
  657. selectedIcon = nullptr;
  658. selectedSkill = -1;
  659. if(info->levelupInfo && !info->levelupInfo->skills.empty())
  660. selectedSkill = info->levelupInfo->skills.front();
  661. activeTab = 0;
  662. initBonusesList();
  663. initSections();
  664. }
  665. void CStackWindow::initBonusesList()
  666. {
  667. BonusList output;
  668. BonusList input;
  669. input = *(info->stackNode->getBonuses(CSelector(Bonus::Permanent), Selector::all));
  670. while(!input.empty())
  671. {
  672. auto b = input.front();
  673. output.push_back(std::make_shared<Bonus>(*b));
  674. output.back()->val = input.valOfBonuses(Selector::typeSubtype(b->type, b->subtype)); //merge multiple bonuses into one
  675. input.remove_if (Selector::typeSubtype(b->type, b->subtype)); //remove used bonuses
  676. }
  677. BonusInfo bonusInfo;
  678. for(auto b : output)
  679. {
  680. bonusInfo.name = info->stackNode->bonusToString(b, false);
  681. bonusInfo.description = info->stackNode->bonusToString(b, true);
  682. bonusInfo.imagePath = info->stackNode->bonusToGraphics(b);
  683. //if it's possible to give any description or image for this kind of bonus
  684. //TODO: figure out why half of bonuses don't have proper description
  685. if(!bonusInfo.name.empty() || !bonusInfo.imagePath.empty())
  686. activeBonuses.push_back(bonusInfo);
  687. }
  688. }
  689. void CStackWindow::initSections()
  690. {
  691. OBJECT_CONSTRUCTION;
  692. bool showArt = LOCPLINT->cb->getSettings().getBoolean(EGameSettings::MODULE_STACK_ARTIFACT) && info->commander == nullptr && info->stackNode;
  693. bool showExp = (LOCPLINT->cb->getSettings().getBoolean(EGameSettings::MODULE_STACK_EXPERIENCE) || info->commander != nullptr) && info->stackNode;
  694. mainSection = std::make_shared<MainSection>(this, pos.h, showExp, showArt);
  695. pos.w = mainSection->pos.w;
  696. pos.h += mainSection->pos.h;
  697. if(info->stack) // in battle
  698. {
  699. activeSpellsSection = std::make_shared<ActiveSpellsSection>(this, pos.h);
  700. pos.h += activeSpellsSection->pos.h;
  701. }
  702. if(info->commander)
  703. {
  704. auto onCreate = [=](size_t index) -> std::shared_ptr<CIntObject>
  705. {
  706. auto obj = switchTab(index);
  707. if(obj)
  708. {
  709. obj->activate();
  710. obj->recActions |= (UPDATE | SHOWALL);
  711. }
  712. return obj;
  713. };
  714. auto deactivateObj = [=](std::shared_ptr<CIntObject> obj)
  715. {
  716. obj->deactivate();
  717. obj->recActions &= ~(UPDATE | SHOWALL);
  718. };
  719. commanderMainSection = std::make_shared<CommanderMainSection>(this, 0);
  720. auto size = std::make_optional<size_t>((info->levelupInfo) ? 4 : 3);
  721. commanderBonusesSection = std::make_shared<BonusesSection>(this, 0, size);
  722. deactivateObj(commanderBonusesSection);
  723. commanderTab = std::make_shared<CTabbedInt>(onCreate, Point(0, pos.h), 0);
  724. pos.h += commanderMainSection->pos.h;
  725. }
  726. if(!info->commander && !activeBonuses.empty())
  727. {
  728. bonusesSection = std::make_shared<BonusesSection>(this, pos.h);
  729. pos.h += bonusesSection->pos.h;
  730. }
  731. if(!info->popupWindow)
  732. {
  733. buttonsSection = std::make_shared<ButtonsSection>(this, pos.h);
  734. pos.h += buttonsSection->pos.h;
  735. //FIXME: add status bar to image?
  736. }
  737. updateShadow();
  738. pos = center(pos);
  739. }
  740. std::string CStackWindow::generateStackExpDescription()
  741. {
  742. const CStackInstance * stack = info->stackNode;
  743. const CCreature * creature = info->creature;
  744. int tier = stack->type->getLevel();
  745. int rank = stack->getExpRank();
  746. if (!vstd::iswithin(tier, 1, 7))
  747. tier = 0;
  748. int number;
  749. std::string expText = CGI->generaltexth->translate("vcmi.stackExperience.description");
  750. boost::replace_first(expText, "%s", creature->getNamePluralTranslated());
  751. boost::replace_first(expText, "%s", CGI->generaltexth->translate("vcmi.stackExperience.rank", rank));
  752. boost::replace_first(expText, "%i", std::to_string(rank));
  753. boost::replace_first(expText, "%i", std::to_string(stack->experience));
  754. number = static_cast<int>(CGI->creh->expRanks[tier][rank] - stack->experience);
  755. boost::replace_first(expText, "%i", std::to_string(number));
  756. number = CGI->creh->maxExpPerBattle[tier]; //percent
  757. boost::replace_first(expText, "%i%", std::to_string(number));
  758. number *= CGI->creh->expRanks[tier].back() / 100; //actual amount
  759. boost::replace_first(expText, "%i", std::to_string(number));
  760. boost::replace_first(expText, "%i", std::to_string(stack->count)); //Number of Creatures in stack
  761. int expmin = std::max(CGI->creh->expRanks[tier][std::max(rank-1, 0)], (ui32)1);
  762. number = static_cast<int>((stack->count * (stack->experience - expmin)) / expmin); //Maximum New Recruits without losing current Rank
  763. boost::replace_first(expText, "%i", std::to_string(number)); //TODO
  764. boost::replace_first(expText, "%.2f", std::to_string(1)); //TODO Experience Multiplier
  765. number = CGI->creh->expAfterUpgrade;
  766. boost::replace_first(expText, "%.2f", std::to_string(number) + "%"); //Upgrade Multiplier
  767. expmin = CGI->creh->expRanks[tier][9];
  768. int expmax = CGI->creh->expRanks[tier][10];
  769. number = expmax - expmin;
  770. boost::replace_first(expText, "%i", std::to_string(number)); //Experience after Rank 10
  771. number = (stack->count * (expmax - expmin)) / expmin;
  772. boost::replace_first(expText, "%i", std::to_string(number)); //Maximum New Recruits to remain at Rank 10 if at Maximum Experience
  773. return expText;
  774. }
  775. std::string CStackWindow::getCommanderSkillDescription(int skillIndex, int skillLevel)
  776. {
  777. constexpr std::array skillNames = {
  778. "attack",
  779. "defence",
  780. "health",
  781. "damage",
  782. "speed",
  783. "magic"
  784. };
  785. std::string textID = TextIdentifier("vcmi", "commander", "skill", skillNames.at(skillIndex), skillLevel).get();
  786. return CGI->generaltexth->translate(textID);
  787. }
  788. void CStackWindow::setSelection(si32 newSkill, std::shared_ptr<CCommanderSkillIcon> newIcon)
  789. {
  790. auto getSkillDescription = [this](int skillIndex, bool selected) -> std::string
  791. {
  792. if(selected)
  793. return getCommanderSkillDescription(skillIndex, info->commander->secondarySkills[skillIndex] + 1); //upgrade description
  794. else
  795. return getCommanderSkillDescription(skillIndex, info->commander->secondarySkills[skillIndex]);
  796. };
  797. auto getSkillImage = [this](int skillIndex)
  798. {
  799. bool selected = ((selectedSkill == skillIndex) && info->levelupInfo );
  800. return skillToFile(skillIndex, info->commander->secondarySkills[skillIndex], selected);
  801. };
  802. OBJECT_CONSTRUCTION;
  803. int oldSelection = selectedSkill; // update selection
  804. selectedSkill = newSkill;
  805. if(selectedIcon && oldSelection < 100) // recreate image on old selection, only for skills
  806. selectedIcon->setObject(std::make_shared<CPicture>(getSkillImage(oldSelection)));
  807. if(selectedIcon)
  808. {
  809. if(!selectedIcon->getIsMasterAbility()) //unlike WoG, in VCMI master skill descriptions are taken from bonus descriptions
  810. {
  811. selectedIcon->text = getSkillDescription(oldSelection, false); //update previously selected icon's message to existing skill level
  812. }
  813. selectedIcon->deselect();
  814. }
  815. selectedIcon = newIcon; // update new selection
  816. if(newSkill < 100)
  817. {
  818. newIcon->setObject(std::make_shared<CPicture>(getSkillImage(newSkill)));
  819. if(!newIcon->getIsMasterAbility())
  820. {
  821. newIcon->text = getSkillDescription(newSkill, true); //update currently selected icon's message to show upgrade description
  822. }
  823. }
  824. }
  825. std::shared_ptr<CIntObject> CStackWindow::switchTab(size_t index)
  826. {
  827. std::shared_ptr<CIntObject> ret;
  828. switch(index)
  829. {
  830. case 0:
  831. {
  832. activeTab = 0;
  833. ret = commanderMainSection;
  834. }
  835. break;
  836. case 1:
  837. {
  838. activeTab = 1;
  839. ret = commanderBonusesSection;
  840. }
  841. break;
  842. default:
  843. break;
  844. }
  845. return ret;
  846. }
  847. void CStackWindow::removeStackArtifact(ArtifactPosition pos)
  848. {
  849. auto art = info->stackNode->getArt(ArtifactPosition::CREATURE_SLOT);
  850. if(!art)
  851. {
  852. logGlobal->error("Attempt to remove missing artifact");
  853. return;
  854. }
  855. const auto slot = ArtifactUtils::getArtBackpackPosition(info->owner, art->getTypeId());
  856. if(slot != ArtifactPosition::PRE_FIRST)
  857. {
  858. auto artLoc = ArtifactLocation(info->owner->id, pos);
  859. artLoc.creature = info->stackNode->armyObj->findStack(info->stackNode);
  860. LOCPLINT->cb->swapArtifacts(artLoc, ArtifactLocation(info->owner->id, slot));
  861. stackArtifactButton.reset();
  862. stackArtifact.reset();
  863. redraw();
  864. }
  865. }