CCreatureWindow.cpp 40 KB

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