CComponent.cpp 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566
  1. /*
  2. * CComponent.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 "CComponent.h"
  12. #include "CArtifactHolder.h"
  13. #include "Images.h"
  14. #include <vcmi/spells/Service.h>
  15. #include <vcmi/spells/Spell.h>
  16. #include "../gui/CGuiHandler.h"
  17. #include "../gui/CursorHandler.h"
  18. #include "../gui/TextAlignment.h"
  19. #include "../gui/Shortcut.h"
  20. #include "../render/Canvas.h"
  21. #include "../render/IFont.h"
  22. #include "../render/Graphics.h"
  23. #include "../windows/CMessage.h"
  24. #include "../windows/InfoWindows.h"
  25. #include "../widgets/TextControls.h"
  26. #include "../CGameInfo.h"
  27. #include "../../lib/ArtifactUtils.h"
  28. #include "../../lib/CTownHandler.h"
  29. #include "../../lib/CHeroHandler.h"
  30. #include "../../lib/networkPacks/Component.h"
  31. #include "../../lib/spells/CSpellHandler.h"
  32. #include "../../lib/CCreatureHandler.h"
  33. #include "../../lib/CSkillHandler.h"
  34. #include "../../lib/CGeneralTextHandler.h"
  35. #include "../../lib/CArtHandler.h"
  36. #include "../../lib/CArtifactInstance.h"
  37. CComponent::CComponent(ComponentType Type, ComponentSubType Subtype, std::optional<int32_t> Val, ESize imageSize, EFonts font)
  38. {
  39. init(Type, Subtype, Val, imageSize, font, "");
  40. }
  41. CComponent::CComponent(ComponentType Type, ComponentSubType Subtype, const std::string & Val, ESize imageSize, EFonts font)
  42. {
  43. init(Type, Subtype, std::nullopt, imageSize, font, Val);
  44. }
  45. CComponent::CComponent(const Component & c, ESize imageSize, EFonts font)
  46. {
  47. init(c.type, c.subType, c.value, imageSize, font, "");
  48. }
  49. void CComponent::init(ComponentType Type, ComponentSubType Subtype, std::optional<int32_t> Val, ESize imageSize, EFonts fnt, const std::string & ValText)
  50. {
  51. OBJECT_CONSTRUCTION_CAPTURING(255-DISPOSE);
  52. addUsedEvents(SHOW_POPUP);
  53. data.type = Type;
  54. data.subType = Subtype;
  55. data.value = Val;
  56. customSubtitle = ValText;
  57. size = imageSize;
  58. font = fnt;
  59. assert(size < sizeInvalid);
  60. setSurface(getFileName()[size], (int)getIndex());
  61. pos.w = image->pos.w;
  62. pos.h = image->pos.h;
  63. if (imageSize < small)
  64. font = FONT_TINY; //for tiny images - tiny font
  65. pos.h += 4; //distance between text and image
  66. // WARNING: too low values will lead to bad line-breaks in CPlayerOptionTooltipBox - check right-click on starting town in pregame
  67. int max = 80;
  68. if (size < large)
  69. max = 72;
  70. if (size < medium)
  71. max = 60;
  72. if (size < small)
  73. max = 55;
  74. if(Type == ComponentType::RESOURCE && !ValText.empty())
  75. max = 80;
  76. std::vector<std::string> textLines = CMessage::breakText(getSubtitle(), std::max<int>(max, pos.w), font);
  77. for(auto & line : textLines)
  78. {
  79. int height = static_cast<int>(graphics->fonts[font]->getLineHeight());
  80. auto label = std::make_shared<CLabel>(pos.w/2, pos.h + height/2, font, ETextAlignment::CENTER, Colors::WHITE, line);
  81. pos.h += height;
  82. if(label->pos.w > pos.w)
  83. {
  84. pos.x -= (label->pos.w - pos.w)/2;
  85. pos.w = label->pos.w;
  86. }
  87. lines.push_back(label);
  88. }
  89. }
  90. std::vector<AnimationPath> CComponent::getFileName() const
  91. {
  92. static const std::array<std::string, 4> primSkillsArr = {"PSKIL32", "PSKIL32", "PSKIL42", "PSKILL"};
  93. static const std::array<std::string, 4> secSkillsArr = {"SECSK32", "SECSK32", "SECSKILL", "SECSK82"};
  94. static const std::array<std::string, 4> resourceArr = {"SMALRES", "RESOURCE", "RESOURCE", "RESOUR82"};
  95. static const std::array<std::string, 4> creatureArr = {"CPRSMALL", "CPRSMALL", "CPRSMALL", "TWCRPORT"};
  96. static const std::array<std::string, 4> artifactArr = {"Artifact", "Artifact", "Artifact", "Artifact"};
  97. static const std::array<std::string, 4> spellsArr = {"SpellInt", "SpellInt", "SpellInt", "SPELLSCR"};
  98. static const std::array<std::string, 4> moraleArr = {"IMRL22", "IMRL30", "IMRL42", "imrl82"};
  99. static const std::array<std::string, 4> luckArr = {"ILCK22", "ILCK30", "ILCK42", "ilck82"};
  100. static const std::array<std::string, 4> heroArr = {"PortraitsSmall", "PortraitsSmall", "PortraitsSmall", "PortraitsLarge"};
  101. static const std::array<std::string, 4> flagArr = {"CREST58", "CREST58", "CREST58", "CREST58"};
  102. auto gen = [](const std::array<std::string, 4> & arr) -> std::vector<AnimationPath>
  103. {
  104. return { AnimationPath::builtin(arr[0]), AnimationPath::builtin(arr[1]), AnimationPath::builtin(arr[2]), AnimationPath::builtin(arr[3]) };
  105. };
  106. switch(data.type)
  107. {
  108. case ComponentType::PRIM_SKILL:
  109. case ComponentType::EXPERIENCE:
  110. case ComponentType::MANA:
  111. case ComponentType::LEVEL:
  112. return gen(primSkillsArr);
  113. case ComponentType::SEC_SKILL:
  114. return gen(secSkillsArr);
  115. case ComponentType::RESOURCE:
  116. case ComponentType::RESOURCE_PER_DAY:
  117. return gen(resourceArr);
  118. case ComponentType::CREATURE:
  119. return gen(creatureArr);
  120. case ComponentType::ARTIFACT:
  121. return gen(artifactArr);
  122. case ComponentType::SPELL_SCROLL:
  123. case ComponentType::SPELL:
  124. return gen(spellsArr);
  125. case ComponentType::MORALE:
  126. return gen(moraleArr);
  127. case ComponentType::LUCK:
  128. return gen(luckArr);
  129. case ComponentType::BUILDING:
  130. return std::vector<AnimationPath>(4, (*CGI->townh)[data.subType.as<BuildingTypeUniqueID>().getFaction()]->town->clientInfo.buildingsIcons);
  131. case ComponentType::HERO_PORTRAIT:
  132. return gen(heroArr);
  133. case ComponentType::FLAG:
  134. return gen(flagArr);
  135. default:
  136. assert(0);
  137. return {};
  138. }
  139. }
  140. size_t CComponent::getIndex() const
  141. {
  142. switch(data.type)
  143. {
  144. case ComponentType::PRIM_SKILL:
  145. return data.subType.getNum();
  146. case ComponentType::EXPERIENCE:
  147. case ComponentType::LEVEL:
  148. return 4; // for whatever reason, in H3 experience icon is located in primary skills icons
  149. case ComponentType::MANA:
  150. return 5; // for whatever reason, in H3 mana points icon is located in primary skills icons
  151. case ComponentType::SEC_SKILL:
  152. return data.subType.getNum() * 3 + 3 + data.value.value_or(0) - 1;
  153. case ComponentType::RESOURCE:
  154. case ComponentType::RESOURCE_PER_DAY:
  155. return data.subType.getNum();
  156. case ComponentType::CREATURE:
  157. return CGI->creatures()->getById(data.subType.as<CreatureID>())->getIconIndex();
  158. case ComponentType::ARTIFACT:
  159. return CGI->artifacts()->getById(data.subType.as<ArtifactID>())->getIconIndex();
  160. case ComponentType::SPELL_SCROLL:
  161. case ComponentType::SPELL:
  162. return (size < large) ? data.subType.getNum() + 1 : data.subType.getNum();
  163. case ComponentType::MORALE:
  164. return data.value.value_or(0) + 3;
  165. case ComponentType::LUCK:
  166. return data.value.value_or(0) + 3;
  167. case ComponentType::BUILDING:
  168. return data.subType.as<BuildingTypeUniqueID>().getBuilding();
  169. case ComponentType::HERO_PORTRAIT:
  170. return CGI->heroTypes()->getById(data.subType.as<HeroTypeID>())->getIconIndex();
  171. case ComponentType::FLAG:
  172. return data.subType.getNum();
  173. default:
  174. assert(0);
  175. return 0;
  176. }
  177. }
  178. std::string CComponent::getDescription() const
  179. {
  180. switch(data.type)
  181. {
  182. case ComponentType::PRIM_SKILL:
  183. return CGI->generaltexth->arraytxt[2+data.subType.getNum()];
  184. case ComponentType::EXPERIENCE:
  185. case ComponentType::LEVEL:
  186. return CGI->generaltexth->allTexts[241];
  187. case ComponentType::MANA:
  188. return CGI->generaltexth->allTexts[149];
  189. case ComponentType::SEC_SKILL:
  190. return CGI->skillh->getByIndex(data.subType.getNum())->getDescriptionTranslated(data.value.value_or(0));
  191. case ComponentType::RESOURCE:
  192. case ComponentType::RESOURCE_PER_DAY:
  193. return CGI->generaltexth->allTexts[242];
  194. case ComponentType::CREATURE:
  195. return "";
  196. case ComponentType::ARTIFACT:
  197. return VLC->artifacts()->getById(data.subType.as<ArtifactID>())->getDescriptionTranslated();
  198. case ComponentType::SPELL_SCROLL:
  199. {
  200. auto description = VLC->arth->objects[ArtifactID::SPELL_SCROLL]->getDescriptionTranslated();
  201. ArtifactUtils::insertScrrollSpellName(description, data.subType.as<SpellID>());
  202. return description;
  203. }
  204. case ComponentType::SPELL:
  205. return VLC->spells()->getById(data.subType.as<SpellID>())->getDescriptionTranslated(data.value.value_or(0));
  206. case ComponentType::MORALE:
  207. return CGI->generaltexth->heroscrn[ 4 - (data.value.value_or(0)>0) + (data.value.value_or(0)<0)];
  208. case ComponentType::LUCK:
  209. return CGI->generaltexth->heroscrn[ 7 - (data.value.value_or(0)>0) + (data.value.value_or(0)<0)];
  210. case ComponentType::BUILDING:
  211. {
  212. auto index = data.subType.as<BuildingTypeUniqueID>();
  213. return (*CGI->townh)[index.getFaction()]->town->buildings[index.getBuilding()]->getDescriptionTranslated();
  214. }
  215. case ComponentType::HERO_PORTRAIT:
  216. return "";
  217. case ComponentType::FLAG:
  218. return "";
  219. default:
  220. assert(0);
  221. return "";
  222. }
  223. }
  224. std::string CComponent::getSubtitle() const
  225. {
  226. if (!customSubtitle.empty())
  227. return customSubtitle;
  228. switch(data.type)
  229. {
  230. case ComponentType::PRIM_SKILL:
  231. if (data.value)
  232. return boost::str(boost::format("%+d %s") % data.value.value_or(0) % CGI->generaltexth->primarySkillNames[data.subType.getNum()]);
  233. else
  234. return CGI->generaltexth->primarySkillNames[data.subType.getNum()];
  235. case ComponentType::EXPERIENCE:
  236. return std::to_string(data.value.value_or(0));
  237. case ComponentType::LEVEL:
  238. {
  239. std::string level = CGI->generaltexth->allTexts[442];
  240. boost::replace_first(level, "1", std::to_string(data.value.value_or(0)));
  241. return level;
  242. }
  243. case ComponentType::MANA:
  244. return boost::str(boost::format("%+d %s") % data.value.value_or(0) % CGI->generaltexth->allTexts[387]);
  245. case ComponentType::SEC_SKILL:
  246. return CGI->generaltexth->levels[data.value.value_or(0)-1] + "\n" + CGI->skillh->getById(data.subType.as<SecondarySkill>())->getNameTranslated();
  247. case ComponentType::RESOURCE:
  248. return std::to_string(data.value.value_or(0));
  249. case ComponentType::RESOURCE_PER_DAY:
  250. return boost::str(boost::format(CGI->generaltexth->allTexts[3]) % data.value.value_or(0));
  251. case ComponentType::CREATURE:
  252. {
  253. auto creature = CGI->creh->getById(data.subType.as<CreatureID>());
  254. if(data.value)
  255. return std::to_string(*data.value) + " " + (*data.value > 1 ? creature->getNamePluralTranslated() : creature->getNameSingularTranslated());
  256. else
  257. return creature->getNamePluralTranslated();
  258. }
  259. case ComponentType::ARTIFACT:
  260. return CGI->artifacts()->getById(data.subType.as<ArtifactID>())->getNameTranslated();
  261. case ComponentType::SPELL_SCROLL:
  262. case ComponentType::SPELL:
  263. return CGI->spells()->getById(data.subType.as<SpellID>())->getNameTranslated();
  264. case ComponentType::MORALE:
  265. return "";
  266. case ComponentType::LUCK:
  267. return "";
  268. case ComponentType::BUILDING:
  269. {
  270. auto index = data.subType.as<BuildingTypeUniqueID>();
  271. auto building = (*CGI->townh)[index.getFaction()]->town->buildings[index.getBuilding()];
  272. if(!building)
  273. {
  274. logGlobal->error("Town of faction %s has no building #%d", (*CGI->townh)[index.getFaction()]->town->faction->getNameTranslated(), index.getBuilding().getNum());
  275. return (boost::format("Missing building #%d") % index.getBuilding().getNum()).str();
  276. }
  277. return building->getNameTranslated();
  278. }
  279. case ComponentType::HERO_PORTRAIT:
  280. return "";
  281. case ComponentType::FLAG:
  282. return CGI->generaltexth->capColors[data.subType.as<PlayerColor>().getNum()];
  283. default:
  284. assert(0);
  285. return "";
  286. }
  287. }
  288. void CComponent::setSurface(const AnimationPath & defName, int imgPos)
  289. {
  290. OBJECT_CONSTRUCTION_CUSTOM_CAPTURING(255-DISPOSE);
  291. image = std::make_shared<CAnimImage>(defName, imgPos);
  292. }
  293. void CComponent::showPopupWindow(const Point & cursorPosition)
  294. {
  295. if(!getDescription().empty())
  296. CRClickPopup::createAndPush(getDescription());
  297. }
  298. void CSelectableComponent::clickPressed(const Point & cursorPosition)
  299. {
  300. if(onSelect)
  301. onSelect();
  302. }
  303. void CSelectableComponent::clickDouble(const Point & cursorPosition)
  304. {
  305. if(onChoose)
  306. onChoose();
  307. }
  308. void CSelectableComponent::init()
  309. {
  310. selected = false;
  311. }
  312. CSelectableComponent::CSelectableComponent(const Component &c, std::function<void()> OnSelect):
  313. CComponent(c),onSelect(OnSelect)
  314. {
  315. setRedrawParent(true);
  316. addUsedEvents(LCLICK | DOUBLECLICK | KEYBOARD);
  317. init();
  318. }
  319. CSelectableComponent::CSelectableComponent(ComponentType Type, ComponentSubType Sub, int Val, ESize imageSize, std::function<void()> OnSelect):
  320. CComponent(Type,Sub,Val, imageSize),onSelect(OnSelect)
  321. {
  322. setRedrawParent(true);
  323. addUsedEvents(LCLICK | DOUBLECLICK | KEYBOARD);
  324. init();
  325. }
  326. void CSelectableComponent::select(bool on)
  327. {
  328. if(on != selected)
  329. {
  330. selected = on;
  331. redraw();
  332. }
  333. }
  334. void CSelectableComponent::showAll(Canvas & to)
  335. {
  336. CComponent::showAll(to);
  337. if(selected)
  338. {
  339. to.drawBorder(Rect::createAround(image->pos, 1), Colors::BRIGHT_YELLOW);
  340. }
  341. }
  342. void CComponentBox::selectionChanged(std::shared_ptr<CSelectableComponent> newSelection)
  343. {
  344. if (newSelection == selected)
  345. return;
  346. if (selected)
  347. selected->select(false);
  348. selected = newSelection;
  349. if (onSelect)
  350. onSelect(selectedIndex());
  351. if (selected)
  352. selected->select(true);
  353. }
  354. int CComponentBox::selectedIndex()
  355. {
  356. if (selected)
  357. return static_cast<int>(std::find(components.begin(), components.end(), selected) - components.begin());
  358. return -1;
  359. }
  360. Point CComponentBox::getOrTextPos(CComponent *left, CComponent *right)
  361. {
  362. int leftSubtitle = ( left->pos.w - left->image->pos.w) / 2;
  363. int rightSubtitle = (right->pos.w - right->image->pos.w) / 2;
  364. int fullDistance = getDistance(left, right) + leftSubtitle + rightSubtitle;
  365. return Point(fullDistance/2 - leftSubtitle, (left->image->pos.h + right->image->pos.h) / 4);
  366. }
  367. int CComponentBox::getDistance(CComponent *left, CComponent *right)
  368. {
  369. int leftSubtitle = ( left->pos.w - left->image->pos.w) / 2;
  370. int rightSubtitle = (right->pos.w - right->image->pos.w) / 2;
  371. int subtitlesOffset = leftSubtitle + rightSubtitle;
  372. return std::max(betweenSubtitlesMin, betweenImagesMin - subtitlesOffset);
  373. }
  374. void CComponentBox::placeComponents(bool selectable)
  375. {
  376. OBJECT_CONSTRUCTION_CAPTURING(255-DISPOSE);
  377. if (components.empty())
  378. return;
  379. //prepare components
  380. for(auto & comp : components)
  381. {
  382. addChild(comp.get());
  383. comp->recActions = defActions; //FIXME: for some reason, received component might have recActions set to 0
  384. comp->moveTo(Point(pos.x, pos.y));
  385. }
  386. struct RowData
  387. {
  388. size_t comps;
  389. int width;
  390. int height;
  391. RowData (size_t Comps, int Width, int Height):
  392. comps(Comps), width (Width), height (Height){};
  393. };
  394. std::vector<RowData> rows;
  395. rows.push_back (RowData (0,0,0));
  396. //split components in rows
  397. std::shared_ptr<CComponent> prevComp;
  398. for(std::shared_ptr<CComponent> comp : components)
  399. {
  400. //make sure that components are smaller than our width
  401. //assert(pos.w == 0 || pos.w < comp->pos.w);
  402. const int distance = prevComp ? getDistance(prevComp.get(), comp.get()) : 0;
  403. //start next row
  404. if ((pos.w != 0 && rows.back().width + comp->pos.w + distance > pos.w) // row is full
  405. || rows.back().comps >= componentsInRow)
  406. {
  407. prevComp = nullptr;
  408. rows.push_back (RowData (0,0,0));
  409. }
  410. if (prevComp)
  411. rows.back().width += distance;
  412. rows.back().comps++;
  413. rows.back().width += comp->pos.w;
  414. vstd::amax(rows.back().height, comp->pos.h);
  415. prevComp = comp;
  416. }
  417. if (pos.w == 0)
  418. {
  419. for(auto & row : rows)
  420. vstd::amax(pos.w, row.width);
  421. }
  422. int height = ((int)rows.size() - 1) * betweenRows;
  423. for(auto & row : rows)
  424. height += row.height;
  425. //assert(pos.h == 0 || pos.h < height);
  426. if (pos.h == 0)
  427. pos.h = height;
  428. auto iter = components.begin();
  429. int currentY = (pos.h - height) / 2;
  430. //move components to their positions
  431. for (auto & rows_row : rows)
  432. {
  433. // amount of free space we may add on each side of every component
  434. int freeSpace = (pos.w - rows_row.width) / ((int)rows_row.comps * 2);
  435. prevComp = nullptr;
  436. int currentX = 0;
  437. for (size_t col = 0; col < rows_row.comps; col++)
  438. {
  439. currentX += freeSpace;
  440. if (prevComp)
  441. {
  442. if (selectable)
  443. {
  444. Point orPos = Point(currentX - freeSpace, currentY) + getOrTextPos(prevComp.get(), iter->get());
  445. orLabels.push_back(std::make_shared<CLabel>(orPos.x, orPos.y, FONT_MEDIUM, ETextAlignment::CENTER, Colors::WHITE, CGI->generaltexth->allTexts[4]));
  446. }
  447. currentX += getDistance(prevComp.get(), iter->get());
  448. }
  449. (*iter)->moveBy(Point(currentX, currentY));
  450. currentX += (*iter)->pos.w;
  451. currentX += freeSpace;
  452. prevComp = *(iter++);
  453. }
  454. currentY += rows_row.height + betweenRows;
  455. }
  456. }
  457. CComponentBox::CComponentBox(std::vector<std::shared_ptr<CComponent>> _components, Rect position):
  458. CComponentBox(_components, position, defaultBetweenImagesMin, defaultBetweenSubtitlesMin, defaultBetweenRows, defaultComponentsInRow)
  459. {
  460. }
  461. CComponentBox::CComponentBox(std::vector<std::shared_ptr<CComponent>> _components, Rect position, int betweenImagesMin, int betweenSubtitlesMin, int betweenRows, int componentsInRow):
  462. components(_components),
  463. betweenImagesMin(betweenImagesMin),
  464. betweenSubtitlesMin(betweenSubtitlesMin),
  465. betweenRows(betweenRows),
  466. componentsInRow(componentsInRow)
  467. {
  468. setRedrawParent(true);
  469. pos = position + pos.topLeft();
  470. placeComponents(false);
  471. }
  472. CComponentBox::CComponentBox(std::vector<std::shared_ptr<CSelectableComponent>> _components, Rect position, std::function<void(int newID)> _onSelect):
  473. CComponentBox(_components, position, _onSelect, defaultBetweenImagesMin, defaultBetweenSubtitlesMin, defaultBetweenRows, defaultComponentsInRow)
  474. {
  475. }
  476. CComponentBox::CComponentBox(std::vector<std::shared_ptr<CSelectableComponent>> _components, Rect position, std::function<void(int newID)> _onSelect, int betweenImagesMin, int betweenSubtitlesMin, int betweenRows, int componentsInRow):
  477. components(_components.begin(), _components.end()),
  478. onSelect(_onSelect),
  479. betweenImagesMin(betweenImagesMin),
  480. betweenSubtitlesMin(betweenSubtitlesMin),
  481. betweenRows(betweenRows),
  482. componentsInRow(componentsInRow)
  483. {
  484. setRedrawParent(true);
  485. pos = position + pos.topLeft();
  486. placeComponents(true);
  487. assert(!components.empty());
  488. auto key = EShortcut::SELECT_INDEX_1;
  489. for(auto & comp : _components)
  490. {
  491. comp->onSelect = std::bind(&CComponentBox::selectionChanged, this, comp);
  492. comp->assignedKey = key;
  493. key = vstd::next(key, 1);
  494. }
  495. selectionChanged(_components.front());
  496. }