CCreatureWindow.cpp 32 KB

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