CCreatureWindow.cpp 33 KB

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