CCreatureWindow.cpp 32 KB

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