CSpellWindow.cpp 27 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865
  1. /*
  2. * CSpellWindow.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 "CSpellWindow.h"
  12. #include "../../lib/ScopeGuard.h"
  13. #include "GUIClasses.h"
  14. #include "InfoWindows.h"
  15. #include "CCastleInterface.h"
  16. #include "../CPlayerInterface.h"
  17. #include "../PlayerLocalState.h"
  18. #include "../battle/BattleInterface.h"
  19. #include "../GameEngine.h"
  20. #include "../GameInstance.h"
  21. #include "../gui/Shortcut.h"
  22. #include "../gui/WindowHandler.h"
  23. #include "../media/IVideoPlayer.h"
  24. #include "../render/CAnimation.h"
  25. #include "../render/IRenderHandler.h"
  26. #include "../widgets/GraphicalPrimitiveCanvas.h"
  27. #include "../widgets/CComponent.h"
  28. #include "../widgets/CTextInput.h"
  29. #include "../widgets/TextControls.h"
  30. #include "../widgets/Buttons.h"
  31. #include "../widgets/VideoWidget.h"
  32. #include "../adventureMap/AdventureMapInterface.h"
  33. #include "../../lib/CConfigHandler.h"
  34. #include "../../lib/GameConstants.h"
  35. #include "../../lib/GameLibrary.h"
  36. #include "../../lib/battle/CPlayerBattleCallback.h"
  37. #include "../../lib/callback/CCallback.h"
  38. #include "../../lib/spells/CSpellHandler.h"
  39. #include "../../lib/spells/ISpellMechanics.h"
  40. #include "../../lib/spells/Problem.h"
  41. #include "../../lib/spells/SpellSchoolHandler.h"
  42. #include "../../lib/texts/CGeneralTextHandler.h"
  43. #include "../../lib/texts/TextOperations.h"
  44. #include "../../lib/mapObjects/CGHeroInstance.h"
  45. // Ordering of spell school tabs in SpelTab.def
  46. static const std::array schoolTabOrder =
  47. {
  48. SpellSchool::AIR,
  49. SpellSchool::FIRE,
  50. SpellSchool::WATER,
  51. SpellSchool::EARTH,
  52. SpellSchool::ANY
  53. };
  54. int getAnimFrameFromSchool(SpellSchool school)
  55. {
  56. auto it = std::find(schoolTabOrder.begin(), schoolTabOrder.end(), school);
  57. if (it != schoolTabOrder.end())
  58. return std::distance(schoolTabOrder.begin(), it);
  59. else
  60. return -1;
  61. }
  62. bool isLegacySpellSchool(SpellSchool school)
  63. {
  64. return getAnimFrameFromSchool(school) != -1;
  65. }
  66. CSpellWindow::InteractiveArea::InteractiveArea(const Rect & myRect, std::function<void()> funcL, int helpTextId, CSpellWindow * _owner)
  67. {
  68. addUsedEvents(LCLICK | SHOW_POPUP | HOVER);
  69. pos = myRect;
  70. onLeft = funcL;
  71. hoverText = LIBRARY->generaltexth->zelp[helpTextId].first;
  72. helpText = LIBRARY->generaltexth->zelp[helpTextId].second;
  73. owner = _owner;
  74. }
  75. CSpellWindow::InteractiveArea::InteractiveArea(const Rect & myRect, std::function<void()> funcL, std::string textId, CSpellWindow * _owner)
  76. {
  77. addUsedEvents(LCLICK | SHOW_POPUP | HOVER);
  78. pos = myRect;
  79. onLeft = funcL;
  80. auto hoverTextTmp = MetaString::createFromTextID("vcmi.spellBook.tab.hover");
  81. hoverTextTmp.replaceTextID(textId);
  82. hoverText = hoverTextTmp.toString();
  83. auto helpTextTmp = MetaString::createFromTextID("vcmi.spellBook.tab.help");
  84. helpTextTmp.replaceTextID(textId);
  85. helpText = helpTextTmp.toString();
  86. owner = _owner;
  87. }
  88. void CSpellWindow::InteractiveArea::clickPressed(const Point & cursorPosition)
  89. {
  90. onLeft();
  91. }
  92. void CSpellWindow::InteractiveArea::showPopupWindow(const Point & cursorPosition)
  93. {
  94. CRClickPopup::createAndPush(helpText);
  95. }
  96. void CSpellWindow::InteractiveArea::hover(bool on)
  97. {
  98. if(on)
  99. owner->statusBar->write(hoverText);
  100. else
  101. owner->statusBar->clear();
  102. }
  103. class SpellbookSpellSorter
  104. {
  105. public:
  106. bool operator()(const CSpell * A, const CSpell * B)
  107. {
  108. if(A->getLevel() < B->getLevel())
  109. return true;
  110. if(A->getLevel() > B->getLevel())
  111. return false;
  112. for (const auto schoolId : LIBRARY->spellSchoolHandler->getAllObjects())
  113. {
  114. if(A->schools.count(schoolId) && !B->schools.count(schoolId))
  115. return true;
  116. if(!A->schools.count(schoolId) && B->schools.count(schoolId))
  117. return false;
  118. }
  119. return TextOperations::compareLocalizedStrings(A->getNameTranslated(), B->getNameTranslated());
  120. }
  121. };
  122. CSpellWindow::CSpellWindow(const CGHeroInstance * _myHero, CPlayerInterface * _myInt, bool openOnBattleSpells, const std::function<void(SpellID)> & onSpellSelect):
  123. CWindowObject(PLAYER_COLORED | (settings["gameTweaks"]["enableLargeSpellbook"].Bool() ? BORDERED : 0)),
  124. battleSpellsOnly(openOnBattleSpells),
  125. selectedTab(SpellSchool::ANY),
  126. currentPage(0),
  127. myHero(_myHero),
  128. myInt(_myInt),
  129. openOnBattleSpells(openOnBattleSpells),
  130. onSpellSelect(onSpellSelect),
  131. isBigSpellbook(settings["gameTweaks"]["enableLargeSpellbook"].Bool()),
  132. spellsPerPage(24),
  133. offL(-11),
  134. offR(195),
  135. offRM(110),
  136. offT(-37),
  137. offB(56)
  138. {
  139. OBJECT_CONSTRUCTION;
  140. for(const auto schoolId : LIBRARY->spellSchoolHandler->getAllObjects())
  141. if(
  142. !isLegacySpellSchool(schoolId) &&
  143. customSpellSchools.size() < (isBigSpellbook ? MAX_CUSTOM_SPELL_SCHOOLS_BIG : MAX_CUSTOM_SPELL_SCHOOLS) &&
  144. !LIBRARY->spellSchoolHandler->getById(schoolId)->getSchoolBookmarkPath().empty() &&
  145. !LIBRARY->spellSchoolHandler->getById(schoolId)->getSchoolHeaderPath().empty()
  146. )
  147. customSpellSchools.push_back(schoolId);
  148. if(isBigSpellbook)
  149. {
  150. background = std::make_shared<CPicture>(ImagePath::builtin("SpellBookLarge"), 0, 0);
  151. updateShadow();
  152. }
  153. else
  154. {
  155. background = std::make_shared<CPicture>(ImagePath::builtin("SpelBack"), 0, 0);
  156. offL = offR = offT = offB = offRM = 0;
  157. spellsPerPage = 12;
  158. }
  159. pos = background->center(Point(pos.w/2 + pos.x, pos.h/2 + pos.y));
  160. Rect r(90, isBigSpellbook ? 480 : 420, isBigSpellbook ? 160 : 110, 16);
  161. if(settings["general"]["enableUiEnhancements"].Bool())
  162. {
  163. const ColorRGBA rectangleColor = ColorRGBA(0, 0, 0, 75);
  164. const ColorRGBA borderColor = ColorRGBA(128, 100, 75);
  165. const ColorRGBA grayedColor = ColorRGBA(158, 130, 105);
  166. searchBoxRectangle = std::make_shared<TransparentFilledRectangle>(r.resize(1), rectangleColor, borderColor);
  167. searchBoxDescription = std::make_shared<CLabel>(r.center().x, r.center().y, FONT_SMALL, ETextAlignment::CENTER, grayedColor, LIBRARY->generaltexth->translate("vcmi.spellBook.search"));
  168. searchBox = std::make_shared<CTextInput>(r, FONT_SMALL, ETextAlignment::CENTER, false);
  169. searchBox->setCallback(std::bind(&CSpellWindow::searchInput, this));
  170. }
  171. if(onSpellSelect)
  172. {
  173. Point boxPos = r.bottomLeft() + Point(-2, 5);
  174. showAllSpells = std::make_shared<CToggleButton>(boxPos, AnimationPath::builtin("sysopchk.def"), CButton::tooltip(LIBRARY->generaltexth->translate("core.help.458.hover"), LIBRARY->generaltexth->translate("core.help.458.hover")), [this](bool state){ searchInput(); });
  175. showAllSpellsDescription = std::make_shared<CLabel>(boxPos.x + 40, boxPos.y + 12, FONT_SMALL, ETextAlignment::CENTERLEFT, Colors::WHITE, LIBRARY->generaltexth->translate("core.help.458.hover"));
  176. }
  177. processSpells();
  178. //numbers of spell pages computed
  179. leftCorner = std::make_shared<CPicture>(ImagePath::builtin("SpelTrnL.bmp"), 97 + offL, 77 + offT);
  180. rightCorner = std::make_shared<CPicture>(ImagePath::builtin("SpelTrnR.bmp"), 487 + offR, 72 + offT);
  181. schoolTab = std::make_shared<CAnimImage>(AnimationPath::builtin("SpelTab"), getAnimFrameFromSchool(selectedTab), 0, 524 + offR, 88);
  182. for(int i = 0; i < customSpellSchools.size(); i++)
  183. schoolTabCustom.push_back(std::make_shared<CAnimImage>(LIBRARY->spellSchoolHandler->getById(customSpellSchools[i])->getSchoolBookmarkPath(), i == 0 ? 0 : 1, 0, isBigSpellbook ? 0 : 15, 93 + 62 * i));
  184. schoolPicture = std::make_shared<CAnimImage>(AnimationPath::builtin("Schools"), 0, 0, 117 + offL, 74 + offT);
  185. mana = std::make_shared<CLabel>(435 + (isBigSpellbook ? 159 : 0), 426 + offB, FONT_SMALL, ETextAlignment::CENTER, Colors::YELLOW, std::to_string(myHero->mana));
  186. if(isBigSpellbook)
  187. statusBar = CGStatusBar::create(400, 587);
  188. else
  189. statusBar = CGStatusBar::create(7, 569, ImagePath::builtin("Spelroll.bmp"));
  190. Rect schoolRect( 549 + pos.x + offR, 94 + pos.y, 45, 35);
  191. interactiveAreas.push_back(std::make_shared<InteractiveArea>( Rect( 479 + pos.x + (isBigSpellbook ? 175 : 0), 405 + pos.y + offB, isBigSpellbook ? 60 : 36, 56), std::bind(&CSpellWindow::fexitb, this), 460, this));
  192. interactiveAreas.push_back(std::make_shared<InteractiveArea>( Rect( 221 + pos.x + (isBigSpellbook ? 43 : 0), 405 + pos.y + offB, isBigSpellbook ? 60 : 36, 56), std::bind(&CSpellWindow::fbattleSpellsb, this), 453, this));
  193. interactiveAreas.push_back(std::make_shared<InteractiveArea>( Rect( 355 + pos.x + (isBigSpellbook ? 110 : 0), 405 + pos.y + offB, isBigSpellbook ? 60 : 36, 56), std::bind(&CSpellWindow::fadvSpellsb, this), 452, this));
  194. interactiveAreas.push_back(std::make_shared<InteractiveArea>( Rect( 418 + pos.x + (isBigSpellbook ? 142 : 0), 405 + pos.y + offB, isBigSpellbook ? 60 : 36, 56), std::bind(&CSpellWindow::fmanaPtsb, this), 459, this));
  195. interactiveAreas.push_back(std::make_shared<InteractiveArea>( schoolRect + Point(0, 0), std::bind(&CSpellWindow::selectSchool, this, SpellSchool::AIR), 454, this));
  196. interactiveAreas.push_back(std::make_shared<InteractiveArea>( schoolRect + Point(0, 57), std::bind(&CSpellWindow::selectSchool, this, SpellSchool::EARTH), 457, this));
  197. interactiveAreas.push_back(std::make_shared<InteractiveArea>( schoolRect + Point(0, 116), std::bind(&CSpellWindow::selectSchool, this, SpellSchool::FIRE), 455, this));
  198. interactiveAreas.push_back(std::make_shared<InteractiveArea>( schoolRect + Point(0, 176), std::bind(&CSpellWindow::selectSchool, this, SpellSchool::WATER), 456, this));
  199. interactiveAreas.push_back(std::make_shared<InteractiveArea>( schoolRect + Point(0, 236), std::bind(&CSpellWindow::selectSchool, this, SpellSchool::ANY), 458, this));
  200. for(int i = 0; i < customSpellSchools.size(); i++)
  201. interactiveAreas.push_back(std::make_shared<InteractiveArea>(Rect(schoolTabCustom[i]->pos.topLeft(), Point(80, 60)), std::bind(&CSpellWindow::selectSchool, this, customSpellSchools[i]), LIBRARY->spellSchoolHandler->getById(customSpellSchools[i])->getNameTextID(), this));
  202. interactiveAreas.push_back(std::make_shared<InteractiveArea>( Rect( 97 + offL + pos.x, 77 + offT + pos.y, leftCorner->pos.h, leftCorner->pos.w ), std::bind(&CSpellWindow::fLcornerb, this), 450, this));
  203. interactiveAreas.push_back(std::make_shared<InteractiveArea>( Rect( 487 + offR + pos.x, 72 + offT + pos.y, rightCorner->pos.h, rightCorner->pos.w ), std::bind(&CSpellWindow::fRcornerb, this), 451, this));
  204. //areas for spells
  205. int xpos = 117 + offL + pos.x;
  206. int ypos = 90 + offT + pos.y;
  207. for(int v=0; v<spellsPerPage; ++v)
  208. {
  209. spellAreas[v] = std::make_shared<SpellArea>( Rect(xpos, ypos, 65, 78), this);
  210. if(v == (spellsPerPage / 2) - 1) //to right page
  211. {
  212. xpos = offRM + 336 + pos.x; ypos = 90 + offT + pos.y;
  213. }
  214. else
  215. {
  216. if(v%(isBigSpellbook ? 3 : 2) == 0 || (v%3 == 1 && isBigSpellbook))
  217. {
  218. xpos+=85;
  219. }
  220. else
  221. {
  222. xpos -= (isBigSpellbook ? 2 : 1)*85; ypos+=97;
  223. }
  224. }
  225. }
  226. SpellSchool school = battleSpellsOnly ? myInt->localState->getSpellbookSettings().spellbookLastTabBattle : myInt->localState->getSpellbookSettings().spellbookLastTabAdvmap;
  227. bool schoolFound = false;
  228. for(const auto schoolId : LIBRARY->spellSchoolHandler->getAllObjects()) // check if spellschool exists -> if not, then keep any
  229. if(schoolId == school)
  230. schoolFound = true;
  231. if(schoolFound)
  232. selectedTab = school;
  233. setSchoolImages(selectedTab);
  234. int cp = battleSpellsOnly ? myInt->localState->getSpellbookSettings().spellbookLastPageBattle : myInt->localState->getSpellbookSettings().spellbookLastPageAdvmap;
  235. // spellbook last page battle index is not reset after battle, so this needs to stay here
  236. vstd::abetween(cp, 0, std::max(0, pagesWithinCurrentTab() - 1));
  237. if(!schoolFound)
  238. cp = 0;
  239. setCurrentPage(cp);
  240. computeSpellsPerArea();
  241. addUsedEvents(KEYBOARD);
  242. }
  243. CSpellWindow::~CSpellWindow()
  244. {
  245. }
  246. void CSpellWindow::searchInput()
  247. {
  248. if(searchBox)
  249. searchBoxDescription->setEnabled(searchBox->getText().empty());
  250. processSpells();
  251. int cp = 0;
  252. // spellbook last page battle index is not reset after battle, so this needs to stay here
  253. vstd::abetween(cp, 0, std::max(0, pagesWithinCurrentTab() - 1));
  254. setCurrentPage(cp);
  255. computeSpellsPerArea();
  256. }
  257. void CSpellWindow::processSpells()
  258. {
  259. mySpells.clear();
  260. //initializing castable spells
  261. mySpells.reserve(LIBRARY->spellh->objects.size());
  262. for(auto const & spell : LIBRARY->spellh->objects)
  263. {
  264. bool searchTextFound = !searchBox || TextOperations::textSearchSimilarityScore(searchBox->getText(), spell->getNameTranslated());
  265. if(onSpellSelect)
  266. {
  267. if(spell->isCombat() == openOnBattleSpells
  268. && !spell->isSpecial()
  269. && !spell->isCreatureAbility()
  270. && searchTextFound
  271. && (showAllSpells->isSelected() || myHero->canCastThisSpell(spell.get())))
  272. {
  273. mySpells.push_back(spell.get());
  274. }
  275. continue;
  276. }
  277. if(!spell->isCreatureAbility() && myHero->canCastThisSpell(spell.get()) && searchTextFound)
  278. mySpells.push_back(spell.get());
  279. }
  280. SpellbookSpellSorter spellsorter;
  281. std::sort(mySpells.begin(), mySpells.end(), spellsorter);
  282. for(const auto spell : mySpells)
  283. {
  284. auto& sitesPerOurTab = spell->isCombat() ? sitesPerTabBattle : sitesPerTabAdv;
  285. ++sitesPerOurTab[SpellSchool::ANY];
  286. spell->forEachSchool([&sitesPerOurTab](const SpellSchool & school, bool & stop)
  287. {
  288. ++sitesPerOurTab[school];
  289. });
  290. }
  291. if(sitesPerTabAdv[SpellSchool::ANY] % spellsPerPage == 0)
  292. sitesPerTabAdv[SpellSchool::ANY]/=spellsPerPage;
  293. else
  294. sitesPerTabAdv[SpellSchool::ANY] = sitesPerTabAdv[SpellSchool::ANY]/spellsPerPage + 1;
  295. for(const auto v : LIBRARY->spellSchoolHandler->getAllObjects())
  296. {
  297. if(v == SpellSchool::ANY)
  298. continue;
  299. if(sitesPerTabAdv[v] <= spellsPerPage - 2)
  300. sitesPerTabAdv[v] = 1;
  301. else
  302. {
  303. if((sitesPerTabAdv[v] - (spellsPerPage - 2)) % spellsPerPage == 0)
  304. sitesPerTabAdv[v] = (sitesPerTabAdv[v] - (spellsPerPage - 2)) / spellsPerPage + 1;
  305. else
  306. sitesPerTabAdv[v] = (sitesPerTabAdv[v] - (spellsPerPage - 2)) / spellsPerPage + 2;
  307. }
  308. }
  309. if(sitesPerTabBattle[SpellSchool::ANY] % spellsPerPage == 0)
  310. sitesPerTabBattle[SpellSchool::ANY]/=spellsPerPage;
  311. else
  312. sitesPerTabBattle[SpellSchool::ANY] = sitesPerTabBattle[SpellSchool::ANY]/spellsPerPage + 1;
  313. for(const auto v : LIBRARY->spellSchoolHandler->getAllObjects())
  314. {
  315. if(v == SpellSchool::ANY)
  316. continue;
  317. if(sitesPerTabBattle[v] <= spellsPerPage - 2)
  318. sitesPerTabBattle[v] = 1;
  319. else
  320. {
  321. if((sitesPerTabBattle[v] - (spellsPerPage - 2)) % spellsPerPage == 0)
  322. sitesPerTabBattle[v] = (sitesPerTabBattle[v] - (spellsPerPage - 2)) / spellsPerPage + 1;
  323. else
  324. sitesPerTabBattle[v] = (sitesPerTabBattle[v] - (spellsPerPage - 2)) / spellsPerPage + 2;
  325. }
  326. }
  327. }
  328. void CSpellWindow::fexitb()
  329. {
  330. auto spellBookState = myInt->localState->getSpellbookSettings();
  331. if(myInt->battleInt)
  332. {
  333. spellBookState.spellbookLastTabBattle = selectedTab;
  334. spellBookState.spellbookLastPageBattle = currentPage;
  335. }
  336. else
  337. {
  338. spellBookState.spellbookLastTabAdvmap = selectedTab;
  339. spellBookState.spellbookLastPageAdvmap = currentPage;
  340. }
  341. myInt->localState->setSpellbookSettings(spellBookState);
  342. if(onSpellSelect)
  343. onSpellSelect(SpellID::NONE);
  344. close();
  345. }
  346. void CSpellWindow::fadvSpellsb()
  347. {
  348. if(battleSpellsOnly == true)
  349. {
  350. turnPageRight();
  351. battleSpellsOnly = false;
  352. setCurrentPage(0);
  353. }
  354. computeSpellsPerArea();
  355. }
  356. void CSpellWindow::fbattleSpellsb()
  357. {
  358. if(battleSpellsOnly == false)
  359. {
  360. turnPageLeft();
  361. battleSpellsOnly = true;
  362. setCurrentPage(0);
  363. }
  364. computeSpellsPerArea();
  365. }
  366. void CSpellWindow::toggleSearchBoxFocus()
  367. {
  368. if(searchBox != nullptr)
  369. {
  370. searchBox->hasFocus() ? searchBox->removeFocus() : searchBox->giveFocus();
  371. }
  372. }
  373. void CSpellWindow::fmanaPtsb()
  374. {
  375. }
  376. void CSpellWindow::selectSchool(SpellSchool school)
  377. {
  378. if(selectedTab != school)
  379. {
  380. if(selectedTab < school)
  381. turnPageLeft();
  382. else
  383. turnPageRight();
  384. selectedTab = school;
  385. setSchoolImages(selectedTab);
  386. setCurrentPage(0);
  387. }
  388. computeSpellsPerArea();
  389. }
  390. void CSpellWindow::fLcornerb()
  391. {
  392. if(currentPage>0)
  393. {
  394. turnPageLeft();
  395. setCurrentPage(currentPage - 1);
  396. }
  397. computeSpellsPerArea();
  398. }
  399. void CSpellWindow::fRcornerb()
  400. {
  401. if((currentPage + 1) < (pagesWithinCurrentTab()))
  402. {
  403. turnPageRight();
  404. setCurrentPage(currentPage + 1);
  405. }
  406. computeSpellsPerArea();
  407. }
  408. void CSpellWindow::show(Canvas & to)
  409. {
  410. if(video)
  411. video->show(to);
  412. statusBar->show(to);
  413. }
  414. void CSpellWindow::computeSpellsPerArea()
  415. {
  416. std::vector<const CSpell *> spellsCurSite;
  417. spellsCurSite.reserve(mySpells.size());
  418. for(const CSpell * spell : mySpells)
  419. {
  420. if(spell->isCombat() ^ !battleSpellsOnly
  421. && ((selectedTab == SpellSchool::ANY) || spell->schools.count(selectedTab))
  422. )
  423. {
  424. spellsCurSite.push_back(spell);
  425. }
  426. }
  427. if(selectedTab == SpellSchool::ANY)
  428. {
  429. if(spellsCurSite.size() > spellsPerPage)
  430. {
  431. spellsCurSite = std::vector<const CSpell *>(spellsCurSite.begin() + currentPage*spellsPerPage, spellsCurSite.end());
  432. if(spellsCurSite.size() > spellsPerPage)
  433. {
  434. spellsCurSite.erase(spellsCurSite.begin()+spellsPerPage, spellsCurSite.end());
  435. }
  436. }
  437. }
  438. else
  439. {
  440. if(spellsCurSite.size() > spellsPerPage - 2)
  441. {
  442. if(currentPage == 0)
  443. {
  444. spellsCurSite.erase(spellsCurSite.begin()+spellsPerPage-2, spellsCurSite.end());
  445. }
  446. else
  447. {
  448. spellsCurSite = std::vector<const CSpell *>(spellsCurSite.begin() + (currentPage-1)*spellsPerPage + spellsPerPage-2, spellsCurSite.end());
  449. if(spellsCurSite.size() > spellsPerPage)
  450. {
  451. spellsCurSite.erase(spellsCurSite.begin()+spellsPerPage, spellsCurSite.end());
  452. }
  453. }
  454. }
  455. }
  456. //applying
  457. if(selectedTab == SpellSchool::ANY || currentPage != 0)
  458. {
  459. for(size_t c=0; c<spellsPerPage; ++c)
  460. {
  461. if(c < spellsCurSite.size())
  462. {
  463. spellAreas[c]->setSpell(spellsCurSite[c]);
  464. }
  465. else
  466. {
  467. spellAreas[c]->setSpell(nullptr);
  468. }
  469. }
  470. }
  471. else
  472. {
  473. spellAreas[0]->setSpell(nullptr);
  474. spellAreas[1]->setSpell(nullptr);
  475. for(size_t c=0; c<spellsPerPage-2; ++c)
  476. {
  477. if(c < spellsCurSite.size())
  478. spellAreas[c+2]->setSpell(spellsCurSite[c]);
  479. else
  480. spellAreas[c+2]->setSpell(nullptr);
  481. }
  482. }
  483. redraw();
  484. }
  485. void CSpellWindow::setSchoolImages(SpellSchool school)
  486. {
  487. OBJECT_CONSTRUCTION;
  488. schoolTabAnyDisabled.reset();
  489. if(isLegacySpellSchool(school))
  490. {
  491. schoolTab->setFrame(getAnimFrameFromSchool(school), 0);
  492. schoolTab->visible = true;
  493. }
  494. else
  495. {
  496. schoolTabAnyDisabled = std::make_shared<CPicture>(ImagePath::builtin("SpelTabNone.png"), 524 + offR, 88);
  497. schoolTab->visible = false;
  498. }
  499. auto it = std::find(customSpellSchools.begin(), customSpellSchools.end(), school);
  500. int pos = (it == customSpellSchools.end()) ? -1 : std::distance(customSpellSchools.begin(), it);
  501. for(int i = 0; i < schoolTabCustom.size(); i++)
  502. schoolTabCustom[i]->setFrame(i == pos ? 0 : 1, 0);
  503. schoolPicture->visible = school != SpellSchool::ANY && currentPage == 0 && isLegacySpellSchool(school);
  504. if(school != SpellSchool::ANY && isLegacySpellSchool(school))
  505. schoolPicture->setFrame(getAnimFrameFromSchool(school), 0);
  506. schoolPictureCustom.reset();
  507. if(!isLegacySpellSchool(school))
  508. schoolPictureCustom = std::make_shared<CPicture>(LIBRARY->spellSchoolHandler->getById(school)->getSchoolHeaderPath(), 117 + offL, 74 + offT);
  509. }
  510. void CSpellWindow::setCurrentPage(int value)
  511. {
  512. currentPage = value;
  513. setSchoolImages(selectedTab);
  514. if (currentPage != 0)
  515. leftCorner->enable();
  516. else
  517. leftCorner->disable();
  518. if (currentPage + 1 < pagesWithinCurrentTab())
  519. rightCorner->enable();
  520. else
  521. rightCorner->disable();
  522. mana->setText(std::to_string(myHero->mana));//just in case, it will be possible to cast spell without closing book
  523. }
  524. void CSpellWindow::turnPageLeft()
  525. {
  526. OBJECT_CONSTRUCTION;
  527. if(settings["video"]["spellbookAnimation"].Bool() && !isBigSpellbook)
  528. video = std::make_shared<VideoWidgetOnce>(Point(13, 14), VideoPath::builtin("PGTRNLFT.SMK"), false, this);
  529. }
  530. void CSpellWindow::turnPageRight()
  531. {
  532. OBJECT_CONSTRUCTION;
  533. if(settings["video"]["spellbookAnimation"].Bool() && !isBigSpellbook)
  534. video = std::make_shared<VideoWidgetOnce>(Point(13, 14), VideoPath::builtin("PGTRNRGH.SMK"), false, this);
  535. }
  536. void CSpellWindow::onVideoPlaybackFinished()
  537. {
  538. video.reset();
  539. redraw();
  540. }
  541. void CSpellWindow::keyPressed(EShortcut key)
  542. {
  543. switch(key)
  544. {
  545. case EShortcut::GLOBAL_RETURN:
  546. fexitb();
  547. break;
  548. case EShortcut::MOVE_LEFT:
  549. fLcornerb();
  550. break;
  551. case EShortcut::MOVE_RIGHT:
  552. fRcornerb();
  553. break;
  554. case EShortcut::MOVE_UP:
  555. case EShortcut::MOVE_DOWN:
  556. {
  557. bool down = key == EShortcut::MOVE_DOWN;
  558. static const SpellSchool schoolsOrder[] = { SpellSchool::AIR, SpellSchool::EARTH, SpellSchool::FIRE, SpellSchool::WATER, SpellSchool::ANY };
  559. int index = -1;
  560. while(schoolsOrder[++index] != selectedTab);
  561. index += (down ? 1 : -1);
  562. vstd::abetween<int>(index, 0, std::size(schoolsOrder) - 1);
  563. if(selectedTab != schoolsOrder[index])
  564. selectSchool(schoolsOrder[index]);
  565. break;
  566. }
  567. case EShortcut::SPELLBOOK_TAB_COMBAT:
  568. fbattleSpellsb();
  569. break;
  570. case EShortcut::SPELLBOOK_TAB_ADVENTURE:
  571. fadvSpellsb();
  572. break;
  573. case EShortcut::SPELLBOOK_SEARCH_FOCUS:
  574. toggleSearchBoxFocus();
  575. break;
  576. }
  577. }
  578. int CSpellWindow::pagesWithinCurrentTab()
  579. {
  580. return battleSpellsOnly ? sitesPerTabBattle[selectedTab] : sitesPerTabAdv[selectedTab];
  581. }
  582. CSpellWindow::SpellArea::SpellArea(Rect pos, CSpellWindow * owner)
  583. {
  584. this->pos = pos;
  585. this->owner = owner;
  586. addUsedEvents(LCLICK | SHOW_POPUP | HOVER);
  587. schoolLevel = -1;
  588. mySpell = nullptr;
  589. OBJECT_CONSTRUCTION;
  590. image = std::make_shared<CAnimImage>(AnimationPath::builtin("Spells"), 0, 0);
  591. image->visible = false;
  592. name = std::make_shared<CLabel>(39, 70, FONT_TINY, ETextAlignment::CENTER);
  593. level = std::make_shared<CLabel>(39, 82, FONT_TINY, ETextAlignment::CENTER);
  594. cost = std::make_shared<CLabel>(39, 94, FONT_TINY, ETextAlignment::CENTER);
  595. for(auto l : {name, level, cost})
  596. l->setAutoRedraw(false);
  597. }
  598. CSpellWindow::SpellArea::~SpellArea() = default;
  599. void CSpellWindow::SpellArea::clickPressed(const Point & cursorPosition)
  600. {
  601. if(mySpell)
  602. {
  603. if(owner->onSpellSelect)
  604. {
  605. owner->onSpellSelect(mySpell->id);
  606. owner->close();
  607. return;
  608. }
  609. auto spellCost = owner->myInt->cb->getSpellCost(mySpell, owner->myHero);
  610. if(spellCost > owner->myHero->mana) //insufficient mana
  611. {
  612. GAME->interface()->showInfoDialog(boost::str(boost::format(LIBRARY->generaltexth->allTexts[206]) % spellCost % owner->myHero->mana));
  613. return;
  614. }
  615. //anything that is not combat spell is adventure spell
  616. //this not an error in general to cast even creature ability with hero
  617. const bool combatSpell = mySpell->isCombat();
  618. if(combatSpell == mySpell->isAdventure())
  619. {
  620. logGlobal->error("Spell have invalid flags");
  621. return;
  622. }
  623. const bool inCombat = owner->myInt->battleInt != nullptr;
  624. const bool inCastle = owner->myInt->castleInt != nullptr;
  625. //battle spell on adv map or adventure map spell during combat => display infowindow, not cast
  626. if((combatSpell != inCombat) || inCastle || (!combatSpell && !GAME->interface()->makingTurn))
  627. {
  628. std::vector<std::shared_ptr<CComponent>> hlp(1, std::make_shared<CComponent>(ComponentType::SPELL, mySpell->id));
  629. GAME->interface()->showInfoDialog(mySpell->getDescriptionTranslated(schoolLevel), hlp);
  630. }
  631. else if(combatSpell)
  632. {
  633. spells::detail::ProblemImpl problem;
  634. if(mySpell->canBeCast(problem, owner->myInt->battleInt->getBattle().get(), spells::Mode::HERO, owner->myHero))
  635. {
  636. owner->myInt->battleInt->castThisSpell(mySpell->id);
  637. owner->fexitb();
  638. }
  639. else
  640. {
  641. std::vector<std::string> texts;
  642. problem.getAll(texts);
  643. if(!texts.empty())
  644. GAME->interface()->showInfoDialog(texts.front());
  645. else
  646. GAME->interface()->showInfoDialog(LIBRARY->generaltexth->translate("vcmi.adventureMap.spellUnknownProblem"));
  647. }
  648. }
  649. else //adventure spell
  650. {
  651. const CGHeroInstance * h = owner->myHero;
  652. ENGINE->windows().popWindows(1);
  653. auto guard = vstd::makeScopeGuard([this]()
  654. {
  655. auto spellBookState = owner->myInt->localState->getSpellbookSettings();
  656. spellBookState.spellbookLastTabAdvmap = owner->selectedTab;
  657. spellBookState.spellbookLastPageAdvmap = owner->currentPage;
  658. owner->myInt->localState->setSpellbookSettings(spellBookState);
  659. });
  660. spells::detail::ProblemImpl problem;
  661. if (mySpell->getAdventureMechanics().canBeCast(problem, GAME->interface()->cb.get(), owner->myHero))
  662. {
  663. if(mySpell->getTargetType() == spells::AimType::LOCATION)
  664. adventureInt->enterCastingMode(mySpell);
  665. else if(mySpell->getTargetType() == spells::AimType::NO_TARGET)
  666. owner->myInt->cb->castSpell(h, mySpell->id);
  667. else
  668. logGlobal->error("Invalid spell target type");
  669. }
  670. else
  671. {
  672. std::vector<std::string> texts;
  673. problem.getAll(texts);
  674. if(!texts.empty())
  675. GAME->interface()->showInfoDialog(texts.front());
  676. else
  677. GAME->interface()->showInfoDialog(LIBRARY->generaltexth->translate("vcmi.adventureMap.spellUnknownProblem"));
  678. }
  679. }
  680. }
  681. }
  682. void CSpellWindow::SpellArea::showPopupWindow(const Point & cursorPosition)
  683. {
  684. if(mySpell)
  685. {
  686. std::string dmgInfo;
  687. auto causedDmg = owner->myInt->cb->estimateSpellDamage(mySpell, owner->myHero);
  688. if(causedDmg == 0 || mySpell->id == SpellID::TITANS_LIGHTNING_BOLT) //Titan's Lightning Bolt already has damage info included
  689. dmgInfo.clear();
  690. else
  691. {
  692. dmgInfo = LIBRARY->generaltexth->allTexts[343];
  693. boost::algorithm::replace_first(dmgInfo, "%d", std::to_string(causedDmg));
  694. }
  695. CRClickPopup::createAndPush(mySpell->getDescriptionTranslated(schoolLevel) + dmgInfo, std::make_shared<CComponent>(ComponentType::SPELL, mySpell->id));
  696. }
  697. }
  698. void CSpellWindow::SpellArea::hover(bool on)
  699. {
  700. if(mySpell)
  701. {
  702. if(on)
  703. owner->statusBar->write(boost::str(boost::format("%s (%s)") % mySpell->getNameTranslated() % LIBRARY->generaltexth->allTexts[171+mySpell->getLevel()]));
  704. else
  705. owner->statusBar->clear();
  706. }
  707. }
  708. void CSpellWindow::SpellArea::setSpell(const CSpell * spell)
  709. {
  710. schoolBorder.reset();
  711. image->visible = false;
  712. name->setText("");
  713. level->setText("");
  714. cost->setText("");
  715. mySpell = spell;
  716. if(mySpell)
  717. {
  718. SpellSchool whichSchool;
  719. schoolLevel = owner->myHero->getSpellSchoolLevel(mySpell, &whichSchool);
  720. auto spellCost = owner->myInt->cb->getSpellCost(mySpell, owner->myHero);
  721. image->setFrame(mySpell->id.getNum());
  722. image->visible = true;
  723. {
  724. OBJECT_CONSTRUCTION;
  725. schoolBorder.reset();
  726. if (!isLegacySpellSchool(owner->selectedTab) || owner->selectedTab == SpellSchool::ANY)
  727. {
  728. if (whichSchool.hasValue())
  729. schoolBorder = std::make_shared<CAnimImage>(LIBRARY->spellSchoolHandler->getById(whichSchool)->getSpellBordersPath(), schoolLevel);
  730. }
  731. else
  732. schoolBorder = std::make_shared<CAnimImage>(LIBRARY->spellSchoolHandler->getById(owner->selectedTab)->getSpellBordersPath(), schoolLevel);
  733. }
  734. ColorRGBA firstLineColor, secondLineColor;
  735. if(spellCost > owner->myHero->mana && !owner->onSpellSelect) //hero cannot cast this spell
  736. {
  737. firstLineColor = Colors::WHITE;
  738. secondLineColor = Colors::ORANGE;
  739. }
  740. else
  741. {
  742. firstLineColor = Colors::YELLOW;
  743. secondLineColor = Colors::WHITE;
  744. }
  745. name->color = firstLineColor;
  746. name->setText(mySpell->getNameTranslated());
  747. level->color = secondLineColor;
  748. if(schoolLevel > 0)
  749. {
  750. boost::format fmt("%s/%s");
  751. fmt % LIBRARY->generaltexth->allTexts[171 + mySpell->getLevel()];
  752. fmt % LIBRARY->generaltexth->levels[3+(schoolLevel-1)];//lines 4-6
  753. level->setText(fmt.str());
  754. }
  755. else
  756. level->setText(LIBRARY->generaltexth->allTexts[171 + mySpell->getLevel()]);
  757. cost->color = secondLineColor;
  758. boost::format costfmt("%s: %d");
  759. costfmt % LIBRARY->generaltexth->allTexts[387] % spellCost;
  760. cost->setText(costfmt.str());
  761. }
  762. }