CCreatureWindow.cpp 32 KB

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