CCreatureWindow.cpp 41 KB

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