CComponent.cpp 18 KB

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