CCreatureWindow.cpp 32 KB

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