CCreatureWindow.cpp 32 KB

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