CComponent.cpp 18 KB

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