CPreGame.cpp 124 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359
  1. /*
  2. * CPreGame.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 "CPreGame.h"
  12. #include "../lib/filesystem/Filesystem.h"
  13. #include "../lib/filesystem/CCompressedStream.h"
  14. #include "../lib/CStopWatch.h"
  15. #include "gui/SDL_Extensions.h"
  16. #include "CGameInfo.h"
  17. #include "gui/CCursorHandler.h"
  18. #include "../lib/CGeneralTextHandler.h"
  19. #include "../lib/CTownHandler.h"
  20. #include "../lib/CHeroHandler.h"
  21. #include "../lib/mapping/CCampaignHandler.h"
  22. #include "../lib/CCreatureHandler.h"
  23. #include "../lib/JsonNode.h"
  24. #include "CMusicHandler.h"
  25. #include "CVideoHandler.h"
  26. #include "Graphics.h"
  27. #include "../lib/serializer/Connection.h"
  28. #include "../lib/serializer/CTypeList.h"
  29. #include "../lib/VCMIDirs.h"
  30. #include "../lib/mapping/CMap.h"
  31. #include "windows/GUIClasses.h"
  32. #include "CPlayerInterface.h"
  33. #include "../CCallback.h"
  34. #include "CMessage.h"
  35. #include "../lib/spells/CSpellHandler.h" /*for campaign bonuses*/
  36. #include "../lib/CArtHandler.h" /*for campaign bonuses*/
  37. #include "../lib/CBuildingHandler.h" /*for campaign bonuses*/
  38. #include "CBitmapHandler.h"
  39. #include "Client.h"
  40. #include "../lib/NetPacks.h"
  41. #include "../lib/registerTypes//RegisterTypes.h"
  42. #include "../lib/CThreadHelper.h"
  43. #include "../lib/CConfigHandler.h"
  44. #include "../lib/GameConstants.h"
  45. #include "gui/CGuiHandler.h"
  46. #include "gui/CAnimation.h"
  47. #include "widgets/CComponent.h"
  48. #include "widgets/Buttons.h"
  49. #include "widgets/MiscWidgets.h"
  50. #include "widgets/ObjectLists.h"
  51. #include "widgets/TextControls.h"
  52. #include "windows/InfoWindows.h"
  53. #include "../lib/mapping/CMapService.h"
  54. #include "../lib/CRandomGenerator.h"
  55. #include "../lib/CondSh.h"
  56. namespace fs = boost::filesystem;
  57. void startGame(StartInfo * options, CConnection *serv = nullptr);
  58. void endGame();
  59. CGPreGame * CGP = nullptr;
  60. ISelectionScreenInfo *SEL;
  61. static PlayerColor playerColor; //if more than one player - applies to the first
  62. /**
  63. * Stores the current name of the savegame.
  64. *
  65. * TODO better solution for auto-selection when saving already saved games.
  66. * -> CSelectionScreen should be divided into CLoadGameScreen, CSaveGameScreen,...
  67. * The name of the savegame can then be stored non-statically in CGameState and
  68. * passed separately to CSaveGameScreen.
  69. */
  70. static std::string saveGameName;
  71. struct EvilHlpStruct
  72. {
  73. CConnection *serv;
  74. StartInfo *sInfo;
  75. void reset()
  76. {
  77. // vstd::clear_pointer(serv);
  78. vstd::clear_pointer(sInfo);
  79. }
  80. } startingInfo;
  81. static void do_quit()
  82. {
  83. SDL_Event event;
  84. event.quit.type = SDL_QUIT;
  85. SDL_PushEvent(&event);
  86. }
  87. static CMapInfo *mapInfoFromGame()
  88. {
  89. auto ret = new CMapInfo();
  90. ret->mapHeader = std::unique_ptr<CMapHeader>(new CMapHeader(*LOCPLINT->cb->getMapHeader()));
  91. return ret;
  92. }
  93. static void setPlayersFromGame()
  94. {
  95. playerColor = LOCPLINT->playerID;
  96. }
  97. static void swapPlayers(PlayerSettings &a, PlayerSettings &b)
  98. {
  99. std::swap(a.playerID, b.playerID);
  100. std::swap(a.name, b.name);
  101. if(a.playerID == 1)
  102. playerColor = a.color;
  103. else if(b.playerID == 1)
  104. playerColor = b.color;
  105. }
  106. void setPlayer(PlayerSettings &pset, ui8 player, const std::map<ui8, std::string> &playerNames)
  107. {
  108. if(vstd::contains(playerNames, player))
  109. pset.name = playerNames.find(player)->second;
  110. else
  111. pset.name = CGI->generaltexth->allTexts[468];//Computer
  112. pset.playerID = player;
  113. if(player == playerNames.begin()->first)
  114. playerColor = pset.color;
  115. }
  116. void updateStartInfo(std::string filename, StartInfo & sInfo, const std::unique_ptr<CMapHeader> & mapHeader, const std::map<ui8, std::string> &playerNames)
  117. {
  118. sInfo.playerInfos.clear();
  119. if(!mapHeader.get())
  120. {
  121. return;
  122. }
  123. sInfo.mapname = filename;
  124. playerColor = PlayerColor::NEUTRAL;
  125. auto namesIt = playerNames.cbegin();
  126. for (int i = 0; i < mapHeader->players.size(); i++)
  127. {
  128. const PlayerInfo &pinfo = mapHeader->players[i];
  129. //neither computer nor human can play - no player
  130. if (!(pinfo.canHumanPlay || pinfo.canComputerPlay))
  131. continue;
  132. PlayerSettings &pset = sInfo.playerInfos[PlayerColor(i)];
  133. pset.color = PlayerColor(i);
  134. if(pinfo.canHumanPlay && namesIt != playerNames.cend())
  135. {
  136. setPlayer(pset, namesIt++->first, playerNames);
  137. }
  138. else
  139. {
  140. setPlayer(pset, 0, playerNames);
  141. if(!pinfo.canHumanPlay)
  142. {
  143. pset.compOnly = true;
  144. }
  145. }
  146. pset.castle = pinfo.defaultCastle();
  147. pset.hero = pinfo.defaultHero();
  148. if(pset.hero != PlayerSettings::RANDOM && pinfo.hasCustomMainHero())
  149. {
  150. pset.hero = pinfo.mainCustomHeroId;
  151. pset.heroName = pinfo.mainCustomHeroName;
  152. pset.heroPortrait = pinfo.mainCustomHeroPortrait;
  153. }
  154. pset.handicap = PlayerSettings::NO_HANDICAP;
  155. }
  156. }
  157. template <typename T> class CApplyOnPG;
  158. class CBaseForPGApply
  159. {
  160. public:
  161. virtual void applyOnPG(CSelectionScreen *selScr, void *pack) const =0;
  162. virtual ~CBaseForPGApply(){};
  163. template<typename U> static CBaseForPGApply *getApplier(const U * t=nullptr)
  164. {
  165. return new CApplyOnPG<U>();
  166. }
  167. };
  168. template <typename T> class CApplyOnPG : public CBaseForPGApply
  169. {
  170. public:
  171. void applyOnPG(CSelectionScreen *selScr, void *pack) const override
  172. {
  173. T *ptr = static_cast<T*>(pack);
  174. ptr->apply(selScr);
  175. }
  176. };
  177. template <> class CApplyOnPG<CPack> : public CBaseForPGApply
  178. {
  179. public:
  180. void applyOnPG(CSelectionScreen *selScr, void *pack) const override
  181. {
  182. logGlobal->errorStream() << "Cannot apply on PG plain CPack!";
  183. assert(0);
  184. }
  185. };
  186. static CApplier<CBaseForPGApply> *applier = nullptr;
  187. static CPicture* createPicture(const JsonNode& config)
  188. {
  189. return new CPicture(config["name"].String(), config["x"].Float(), config["y"].Float());
  190. }
  191. CMenuScreen::CMenuScreen(const JsonNode& configNode):
  192. config(configNode)
  193. {
  194. OBJ_CONSTRUCTION_CAPTURING_ALL;
  195. background = new CPicture(config["background"].String());
  196. if (config["scalable"].Bool())
  197. {
  198. if (background->bg->format->palette)
  199. background->convertToScreenBPP();
  200. background->scaleTo(Point(screen->w, screen->h));
  201. }
  202. pos = background->center();
  203. for(const JsonNode& node : config["items"].Vector())
  204. menuNameToEntry.push_back(node["name"].String());
  205. for(const JsonNode& node : config["images"].Vector())
  206. images.push_back(createPicture(node));
  207. //Hardcoded entry
  208. menuNameToEntry.push_back("credits");
  209. tabs = new CTabbedInt(std::bind(&CMenuScreen::createTab, this, _1), CTabbedInt::DestroyFunc());
  210. tabs->type |= REDRAW_PARENT;
  211. }
  212. CIntObject * CMenuScreen::createTab(size_t index)
  213. {
  214. if (config["items"].Vector().size() == index)
  215. return new CreditsScreen();
  216. return new CMenuEntry(this, config["items"].Vector()[index]);
  217. }
  218. void CMenuScreen::showAll(SDL_Surface * to)
  219. {
  220. CIntObject::showAll(to);
  221. if (pos.h != to->h || pos.w != to->w)
  222. CMessage::drawBorder(PlayerColor(1), to, pos.w+28, pos.h+30, pos.x-14, pos.y-15);
  223. }
  224. void CMenuScreen::show(SDL_Surface * to)
  225. {
  226. if (!config["video"].isNull())
  227. CCS->videoh->update(config["video"]["x"].Float() + pos.x, config["video"]["y"].Float() + pos.y, to, true, false);
  228. CIntObject::show(to);
  229. }
  230. void CMenuScreen::activate()
  231. {
  232. CCS->musich->playMusic("Music/MainMenu", true);
  233. if (!config["video"].isNull())
  234. CCS->videoh->open(config["video"]["name"].String());
  235. CIntObject::activate();
  236. }
  237. void CMenuScreen::deactivate()
  238. {
  239. if (!config["video"].isNull())
  240. CCS->videoh->close();
  241. CIntObject::deactivate();
  242. }
  243. void CMenuScreen::switchToTab(size_t index)
  244. {
  245. tabs->setActive(index);
  246. }
  247. //funciton for std::string -> std::function conversion for main menu
  248. static std::function<void()> genCommand(CMenuScreen* menu, std::vector<std::string> menuType, const std::string &string)
  249. {
  250. static const std::vector<std::string> commandType =
  251. {"to", "campaigns", "start", "load", "exit", "highscores"};
  252. static const std::vector<std::string> gameType =
  253. {"single", "multi", "campaign", "tutorial"};
  254. std::list<std::string> commands;
  255. boost::split(commands, string, boost::is_any_of("\t "));
  256. if (!commands.empty())
  257. {
  258. size_t index = std::find(commandType.begin(), commandType.end(), commands.front()) - commandType.begin();
  259. commands.pop_front();
  260. if (index > 3 || !commands.empty())
  261. {
  262. switch (index)
  263. {
  264. break; case 0://to - switch to another tab, if such tab exists
  265. {
  266. size_t index2 = std::find(menuType.begin(), menuType.end(), commands.front()) - menuType.begin();
  267. if ( index2 != menuType.size())
  268. return std::bind(&CMenuScreen::switchToTab, menu, index2);
  269. }
  270. break; case 1://open campaign selection window
  271. {
  272. return std::bind(&CGPreGame::openCampaignScreen, CGP, commands.front());
  273. }
  274. break; case 2://start
  275. {
  276. switch (std::find(gameType.begin(), gameType.end(), commands.front()) - gameType.begin())
  277. {
  278. case 0: return std::bind(&CGPreGame::openSel, CGP, CMenuScreen::newGame, CMenuScreen::SINGLE_PLAYER);
  279. case 1: return &pushIntT<CMultiMode>;
  280. case 2: return std::bind(&CGPreGame::openSel, CGP, CMenuScreen::campaignList, CMenuScreen::SINGLE_PLAYER);
  281. //TODO: start tutorial
  282. case 3: return std::bind(CInfoWindow::showInfoDialog, "Sorry, tutorial is not implemented yet\n", (const std::vector<CComponent*>*)nullptr, false, PlayerColor(1));
  283. }
  284. }
  285. break; case 3://load
  286. {
  287. switch (std::find(gameType.begin(), gameType.end(), commands.front()) - gameType.begin())
  288. {
  289. case 0: return std::bind(&CGPreGame::openSel, CGP, CMenuScreen::loadGame, CMenuScreen::SINGLE_PLAYER);
  290. case 1: return std::bind(&CGPreGame::openSel, CGP, CMenuScreen::loadGame, CMenuScreen::MULTI_HOT_SEAT);
  291. case 2: return std::bind(&CGPreGame::openSel, CGP, CMenuScreen::loadGame, CMenuScreen::SINGLE_CAMPAIGN);
  292. //TODO: load tutorial
  293. case 3: return std::bind(CInfoWindow::showInfoDialog, "Sorry, tutorial is not implemented yet\n", (const std::vector<CComponent*>*)nullptr, false, PlayerColor(1));
  294. }
  295. }
  296. break; case 4://exit
  297. {
  298. return std::bind(CInfoWindow::showYesNoDialog, std::ref(CGI->generaltexth->allTexts[69]), (const std::vector<CComponent*>*)nullptr, do_quit, 0, false, PlayerColor(1));
  299. }
  300. break; case 5://highscores
  301. {
  302. //TODO: high scores
  303. return std::bind(CInfoWindow::showInfoDialog, "Sorry, high scores menu is not implemented yet\n", (const std::vector<CComponent*>*)nullptr, false, PlayerColor(1));
  304. }
  305. }
  306. }
  307. }
  308. logGlobal->errorStream()<<"Failed to parse command: "<<string;
  309. return std::function<void()>();
  310. }
  311. CButton* CMenuEntry::createButton(CMenuScreen* parent, const JsonNode& button)
  312. {
  313. std::function<void()> command = genCommand(parent, parent->menuNameToEntry, button["command"].String());
  314. std::pair<std::string, std::string> help;
  315. if (!button["help"].isNull() && button["help"].Float() > 0)
  316. help = CGI->generaltexth->zelp[button["help"].Float()];
  317. int posx = button["x"].Float();
  318. if (posx < 0)
  319. posx = pos.w + posx;
  320. int posy = button["y"].Float();
  321. if (posy < 0)
  322. posy = pos.h + posy;
  323. return new CButton(Point(posx, posy), button["name"].String(), help, command, button["hotkey"].Float());
  324. }
  325. CMenuEntry::CMenuEntry(CMenuScreen* parent, const JsonNode &config)
  326. {
  327. OBJ_CONSTRUCTION_CAPTURING_ALL;
  328. type |= REDRAW_PARENT;
  329. pos = parent->pos;
  330. for(const JsonNode& node : config["images"].Vector())
  331. images.push_back(createPicture(node));
  332. for(const JsonNode& node : config["buttons"].Vector())
  333. {
  334. buttons.push_back(createButton(parent, node));
  335. buttons.back()->hoverable = true;
  336. buttons.back()->type |= REDRAW_PARENT;
  337. }
  338. }
  339. CreditsScreen::CreditsScreen():
  340. positionCounter(0)
  341. {
  342. addUsedEvents(LCLICK | RCLICK);
  343. type |= REDRAW_PARENT;
  344. OBJ_CONSTRUCTION_CAPTURING_ALL;
  345. pos.w = CGP->menu->pos.w;
  346. pos.h = CGP->menu->pos.h;
  347. auto textFile = CResourceHandler::get()->load(ResourceID("DATA/CREDITS.TXT"))->readAll();
  348. std::string text((char*)textFile.first.get(), textFile.second);
  349. size_t firstQuote = text.find('\"')+1;
  350. text = text.substr(firstQuote, text.find('\"', firstQuote) - firstQuote );
  351. credits = new CMultiLineLabel(Rect(pos.w - 350, 0, 350, 600), FONT_CREDITS, CENTER, Colors::WHITE, text);
  352. credits->scrollTextTo(-600); // move all text below the screen
  353. }
  354. void CreditsScreen::show(SDL_Surface * to)
  355. {
  356. CIntObject::show(to);
  357. positionCounter++;
  358. if (positionCounter % 2 == 0)
  359. credits->scrollTextBy(1);
  360. //end of credits, close this screen
  361. if (credits->textSize.y + 600 < positionCounter / 2)
  362. clickRight(false, false);
  363. }
  364. void CreditsScreen::clickLeft(tribool down, bool previousState)
  365. {
  366. clickRight(down, previousState);
  367. }
  368. void CreditsScreen::clickRight(tribool down, bool previousState)
  369. {
  370. CTabbedInt* menu = dynamic_cast<CTabbedInt*>(parent);
  371. assert(menu);
  372. menu->setActive(0);
  373. }
  374. CGPreGameConfig & CGPreGameConfig::get()
  375. {
  376. static CGPreGameConfig config;
  377. return config;
  378. }
  379. const JsonNode & CGPreGameConfig::getConfig() const
  380. {
  381. return config;
  382. }
  383. const JsonNode & CGPreGameConfig::getCampaigns() const
  384. {
  385. return campaignSets;
  386. }
  387. CGPreGameConfig::CGPreGameConfig() :
  388. campaignSets(JsonNode(ResourceID("config/campaignSets.json"))),
  389. config(JsonNode(ResourceID("config/mainmenu.json")))
  390. {
  391. }
  392. CGPreGame::CGPreGame()
  393. {
  394. pos.w = screen->w;
  395. pos.h = screen->h;
  396. GH.defActionsDef = 63;
  397. CGP = this;
  398. menu = new CMenuScreen(CGPreGameConfig::get().getConfig()["window"]);
  399. loadGraphics();
  400. }
  401. CGPreGame::~CGPreGame()
  402. {
  403. boost::unique_lock<boost::recursive_mutex> lock(*CPlayerInterface::pim);
  404. disposeGraphics();
  405. if(CGP == this)
  406. CGP = nullptr;
  407. if(GH.curInt == this)
  408. GH.curInt = nullptr;
  409. }
  410. void CGPreGame::openSel(CMenuScreen::EState screenType, CMenuScreen::EGameMode gameMode)
  411. {
  412. GH.pushInt(new CSelectionScreen(screenType, gameMode));
  413. }
  414. void CGPreGame::loadGraphics()
  415. {
  416. OBJ_CONSTRUCTION_CAPTURING_ALL;
  417. new CFilledTexture("DIBOXBCK", pos);
  418. victoryIcons = std::make_shared<CAnimation>("SCNRVICT.DEF");
  419. victoryIcons->load();
  420. lossIcons = std::make_shared<CAnimation>("SCNRLOSS.DEF");
  421. lossIcons->load();
  422. }
  423. void CGPreGame::disposeGraphics()
  424. {
  425. victoryIcons->unload();
  426. lossIcons->unload();
  427. }
  428. void CGPreGame::update()
  429. {
  430. if(CGP != this) //don't update if you are not a main interface
  431. return;
  432. if (GH.listInt.empty())
  433. {
  434. GH.pushInt(this);
  435. GH.pushInt(menu);
  436. menu->switchToTab(0);
  437. }
  438. if(SEL)
  439. SEL->update();
  440. // Handles mouse and key input
  441. GH.updateTime();
  442. GH.handleEvents();
  443. // check for null othervice crash on finishing a campaign
  444. // /FIXME: find out why GH.listInt is empty to begin with
  445. if (GH.topInt() != nullptr)
  446. GH.topInt()->show(screen);
  447. }
  448. void CGPreGame::openCampaignScreen(std::string name)
  449. {
  450. if (vstd::contains(CGPreGameConfig::get().getCampaigns().Struct(), name))
  451. {
  452. GH.pushInt(new CCampaignScreen(CGPreGameConfig::get().getCampaigns()[name]));
  453. return;
  454. }
  455. logGlobal->errorStream()<<"Unknown campaign set: "<<name;
  456. }
  457. CGPreGame *CGPreGame::create()
  458. {
  459. if(!CGP)
  460. CGP = new CGPreGame();
  461. GH.terminate_cond.set(false);
  462. return CGP;
  463. }
  464. void CGPreGame::removeFromGui()
  465. {
  466. //remove everything but main menu and background
  467. GH.popInts(GH.listInt.size() - 2);
  468. GH.popInt(GH.topInt()); //remove main menu
  469. GH.popInt(GH.topInt()); //remove background
  470. }
  471. CSelectionScreen::CSelectionScreen(CMenuScreen::EState Type, CMenuScreen::EGameMode GameMode, const std::map<ui8, std::string> * Names, const std::string & Address, const ui16 Port)
  472. : ISelectionScreenInfo(Names), serverHandlingThread(nullptr), mx(new boost::recursive_mutex),
  473. serv(nullptr), ongoingClosing(false), myNameID(255)
  474. {
  475. CGPreGame::create(); //we depend on its graphics
  476. screenType = Type;
  477. gameMode = GameMode;
  478. OBJ_CONSTRUCTION_CAPTURING_ALL;
  479. bool network = (isGuest() || isHost());
  480. CServerHandler *sh = nullptr;
  481. if(isHost())
  482. {
  483. sh = new CServerHandler();
  484. sh->startServer();
  485. }
  486. IShowActivatable::type = BLOCK_ADV_HOTKEYS;
  487. pos.w = 762;
  488. pos.h = 584;
  489. if(Type == CMenuScreen::saveGame)
  490. {
  491. bordered = false;
  492. center(pos);
  493. }
  494. else if(Type == CMenuScreen::campaignList)
  495. {
  496. bordered = false;
  497. bg = new CPicture("CamCust.bmp", 0, 0);
  498. pos = bg->center();
  499. }
  500. else
  501. {
  502. bordered = true;
  503. //load random background
  504. const JsonVector & bgNames = CGPreGameConfig::get().getConfig()["game-select"].Vector();
  505. bg = new CPicture(RandomGeneratorUtil::nextItem(bgNames, CRandomGenerator::getDefault())->String(), 0, 0);
  506. pos = bg->center();
  507. }
  508. sInfo.difficulty = 1;
  509. current = nullptr;
  510. sInfo.mode = (Type == CMenuScreen::newGame ? StartInfo::NEW_GAME : StartInfo::LOAD_GAME);
  511. sInfo.turnTime = 0;
  512. curTab = nullptr;
  513. card = new InfoCard(network); //right info card
  514. if (screenType == CMenuScreen::campaignList)
  515. {
  516. opt = nullptr;
  517. randMapTab = nullptr;
  518. }
  519. else
  520. {
  521. opt = new OptionsTab(); //scenario options tab
  522. opt->recActions = DISPOSE;
  523. randMapTab = new CRandomMapTab();
  524. randMapTab->getMapInfoChanged() += std::bind(&CSelectionScreen::changeSelection, this, _1);
  525. randMapTab->recActions = DISPOSE;
  526. }
  527. sel = new SelectionTab(screenType, std::bind(&CSelectionScreen::changeSelection, this, _1), gameMode); //scenario selection tab
  528. sel->recActions = DISPOSE;
  529. switch(screenType)
  530. {
  531. case CMenuScreen::newGame:
  532. {
  533. SDL_Color orange = {232, 184, 32, 0};
  534. SDL_Color overlayColor = isGuest() ? orange : Colors::WHITE;
  535. card->difficulty->addCallback(std::bind(&CSelectionScreen::difficultyChange, this, _1));
  536. card->difficulty->setSelected(1);
  537. CButton * select = new CButton(Point(411, 80), "GSPBUTT.DEF", CGI->generaltexth->zelp[45], 0, SDLK_s);
  538. select->addCallback([&]()
  539. {
  540. toggleTab(sel);
  541. changeSelection(sel->getSelectedMapInfo());
  542. });
  543. select->addTextOverlay(CGI->generaltexth->allTexts[500], FONT_SMALL, overlayColor);
  544. CButton *opts = new CButton(Point(411, 510), "GSPBUTT.DEF", CGI->generaltexth->zelp[46], std::bind(&CSelectionScreen::toggleTab, this, opt), SDLK_a);
  545. opts->addTextOverlay(CGI->generaltexth->allTexts[501], FONT_SMALL, overlayColor);
  546. CButton * randomBtn = new CButton(Point(411, 105), "GSPBUTT.DEF", CGI->generaltexth->zelp[47], 0, SDLK_r);
  547. randomBtn->addTextOverlay(CGI->generaltexth->allTexts[740], FONT_SMALL, overlayColor);
  548. randomBtn->addCallback([&]()
  549. {
  550. toggleTab(randMapTab);
  551. changeSelection(randMapTab->getMapInfo());
  552. });
  553. start = new CButton(Point(411, 535), "SCNRBEG.DEF", CGI->generaltexth->zelp[103], std::bind(&CSelectionScreen::startScenario, this), SDLK_b);
  554. if(network)
  555. {
  556. CButton *hideChat = new CButton(Point(619, 83), "GSPBUT2.DEF", CGI->generaltexth->zelp[48], std::bind(&InfoCard::toggleChat, card), SDLK_h);
  557. hideChat->addTextOverlay(CGI->generaltexth->allTexts[531], FONT_SMALL);
  558. if(isGuest())
  559. {
  560. select->block(true);
  561. opts->block(true);
  562. randomBtn->block(true);
  563. start->block(true);
  564. }
  565. }
  566. }
  567. break;
  568. case CMenuScreen::loadGame:
  569. sel->recActions = 255;
  570. start = new CButton(Point(411, 535), "SCNRLOD.DEF", CGI->generaltexth->zelp[103], std::bind(&CSelectionScreen::startScenario, this), SDLK_l);
  571. break;
  572. case CMenuScreen::saveGame:
  573. sel->recActions = 255;
  574. start = new CButton(Point(411, 535), "SCNRSAV.DEF", CGI->generaltexth->zelp[103], std::bind(&CSelectionScreen::startScenario, this), SDLK_s);
  575. break;
  576. case CMenuScreen::campaignList:
  577. sel->recActions = 255;
  578. start = new CButton(Point(411, 535), "SCNRLOD.DEF", CButton::tooltip(), std::bind(&CSelectionScreen::startCampaign, this), SDLK_b);
  579. break;
  580. }
  581. start->assignedKeys.insert(SDLK_RETURN);
  582. back = new CButton(Point(581, 535), "SCNRBACK.DEF", CGI->generaltexth->zelp[105], std::bind(&CGuiHandler::popIntTotally, &GH, this), SDLK_ESCAPE);
  583. if(network)
  584. {
  585. if(isHost())
  586. {
  587. assert(playerNames.size() == 1 && vstd::contains(playerNames, 1)); //TODO hot-seat/network combo
  588. if(settings["session"]["donotstartserver"].Bool())
  589. serv = CServerHandler::justConnectToServer(Address, Port);
  590. else
  591. serv = sh->connectToServer();
  592. *serv << (ui8) 4;
  593. myNameID = 1;
  594. }
  595. else
  596. serv = CServerHandler::justConnectToServer(Address, Port);
  597. serv->enterPregameConnectionMode();
  598. *serv << playerNames.begin()->second;
  599. if(isGuest())
  600. {
  601. const CMapInfo *map;
  602. *serv >> myNameID >> map;
  603. serv->connectionID = myNameID;
  604. changeSelection(map);
  605. }
  606. else if(current)
  607. {
  608. SelectMap sm(*current);
  609. *serv << &sm;
  610. UpdateStartOptions uso(sInfo);
  611. *serv << &uso;
  612. }
  613. applier = new CApplier<CBaseForPGApply>();
  614. registerTypesPregamePacks(*applier);
  615. serverHandlingThread = new boost::thread(&CSelectionScreen::handleConnection, this);
  616. }
  617. delete sh;
  618. }
  619. CSelectionScreen::~CSelectionScreen()
  620. {
  621. ongoingClosing = true;
  622. if(serv)
  623. {
  624. assert(serverHandlingThread);
  625. QuitMenuWithoutStarting qmws;
  626. *serv << &qmws;
  627. // while(!serverHandlingThread->timed_join(boost::posix_time::milliseconds(50)))
  628. // processPacks();
  629. serverHandlingThread->join();
  630. delete serverHandlingThread;
  631. }
  632. playerColor = PlayerColor::CANNOT_DETERMINE;
  633. playerNames.clear();
  634. assert(!serv);
  635. vstd::clear_pointer(applier);
  636. delete mx;
  637. }
  638. void CSelectionScreen::toggleTab(CIntObject *tab)
  639. {
  640. if(isHost() && serv)
  641. {
  642. PregameGuiAction pga;
  643. if(tab == curTab)
  644. pga.action = PregameGuiAction::NO_TAB;
  645. else if(tab == opt)
  646. pga.action = PregameGuiAction::OPEN_OPTIONS;
  647. else if(tab == sel)
  648. pga.action = PregameGuiAction::OPEN_SCENARIO_LIST;
  649. else if(tab == randMapTab)
  650. pga.action = PregameGuiAction::OPEN_RANDOM_MAP_OPTIONS;
  651. *serv << &pga;
  652. }
  653. if(curTab && curTab->active)
  654. {
  655. curTab->deactivate();
  656. curTab->recActions = DISPOSE;
  657. }
  658. if(curTab != tab)
  659. {
  660. tab->recActions = 255;
  661. tab->activate();
  662. curTab = tab;
  663. }
  664. else
  665. {
  666. curTab = nullptr;
  667. }
  668. GH.totalRedraw();
  669. }
  670. void CSelectionScreen::changeSelection(const CMapInfo * to)
  671. {
  672. if(current == to) return;
  673. if(isGuest())
  674. vstd::clear_pointer(current);
  675. current = to;
  676. if(to && (screenType == CMenuScreen::loadGame ||
  677. screenType == CMenuScreen::saveGame))
  678. SEL->sInfo.difficulty = to->scenarioOpts->difficulty;
  679. if(screenType != CMenuScreen::campaignList)
  680. {
  681. std::unique_ptr<CMapHeader> emptyHeader;
  682. if(to)
  683. updateStartInfo(to->fileURI, sInfo, to->mapHeader);
  684. else
  685. updateStartInfo("", sInfo, emptyHeader);
  686. if(screenType == CMenuScreen::newGame)
  687. {
  688. if(to && to->isRandomMap)
  689. {
  690. sInfo.mapGenOptions = std::shared_ptr<CMapGenOptions>(new CMapGenOptions(randMapTab->getMapGenOptions()));
  691. }
  692. else
  693. {
  694. sInfo.mapGenOptions.reset();
  695. }
  696. }
  697. }
  698. card->changeSelection(to);
  699. if(screenType != CMenuScreen::campaignList)
  700. {
  701. opt->recreate();
  702. }
  703. if(isHost() && serv)
  704. {
  705. SelectMap sm(*to);
  706. *serv << &sm;
  707. UpdateStartOptions uso(sInfo);
  708. *serv << &uso;
  709. }
  710. }
  711. void CSelectionScreen::startCampaign()
  712. {
  713. if (SEL->current)
  714. GH.pushInt(new CBonusSelection(SEL->current->fileURI));
  715. }
  716. void CSelectionScreen::startScenario()
  717. {
  718. if(screenType == CMenuScreen::newGame)
  719. {
  720. //there must be at least one human player before game can be started
  721. std::map<PlayerColor, PlayerSettings>::const_iterator i;
  722. for(i = SEL->sInfo.playerInfos.cbegin(); i != SEL->sInfo.playerInfos.cend(); i++)
  723. if(i->second.playerID != PlayerSettings::PLAYER_AI)
  724. break;
  725. if(i == SEL->sInfo.playerInfos.cend())
  726. {
  727. GH.pushInt(CInfoWindow::create(CGI->generaltexth->allTexts[530])); //You must position yourself prior to starting the game.
  728. return;
  729. }
  730. }
  731. if(isHost())
  732. {
  733. start->block(true);
  734. StartWithCurrentSettings swcs;
  735. *serv << &swcs;
  736. ongoingClosing = true;
  737. return;
  738. }
  739. if(screenType != CMenuScreen::saveGame)
  740. {
  741. if(!current)
  742. return;
  743. if(sInfo.mapGenOptions)
  744. {
  745. //copy settings from interface to actual options. TODO: refactor, it used to have no effect at all -.-
  746. sInfo.mapGenOptions = std::shared_ptr<CMapGenOptions>(new CMapGenOptions(randMapTab->getMapGenOptions()));
  747. // Update player settings for RMG
  748. for(const auto & psetPair : sInfo.playerInfos)
  749. {
  750. const auto & pset = psetPair.second;
  751. sInfo.mapGenOptions->setStartingTownForPlayer(pset.color, pset.castle);
  752. if(pset.playerID != PlayerSettings::PLAYER_AI)
  753. {
  754. sInfo.mapGenOptions->setPlayerTypeForStandardPlayer(pset.color, EPlayerType::HUMAN);
  755. }
  756. }
  757. if(!sInfo.mapGenOptions->checkOptions())
  758. {
  759. GH.pushInt(CInfoWindow::create(CGI->generaltexth->allTexts[751]));
  760. return;
  761. }
  762. }
  763. saveGameName.clear();
  764. if(screenType == CMenuScreen::loadGame)
  765. {
  766. saveGameName = sInfo.mapname;
  767. }
  768. auto si = new StartInfo(sInfo);
  769. CGP->removeFromGui();
  770. CGP->showLoadingScreen(std::bind(&startGame, si, (CConnection *)nullptr));
  771. }
  772. else
  773. {
  774. if(!(sel && sel->txt && sel->txt->text.size()))
  775. return;
  776. saveGameName = "Saves/" + sel->txt->text;
  777. CFunctionList<void()> overWrite;
  778. overWrite += std::bind(&CCallback::save, LOCPLINT->cb.get(), saveGameName);
  779. overWrite += std::bind(&CGuiHandler::popIntTotally, &GH, this);
  780. if(CResourceHandler::get("local")->existsResource(ResourceID(saveGameName, EResType::CLIENT_SAVEGAME)))
  781. {
  782. std::string hlp = CGI->generaltexth->allTexts[493]; //%s exists. Overwrite?
  783. boost::algorithm::replace_first(hlp, "%s", sel->txt->text);
  784. LOCPLINT->showYesNoDialog(hlp, overWrite, 0, false);
  785. }
  786. else
  787. overWrite();
  788. }
  789. }
  790. void CSelectionScreen::difficultyChange( int to )
  791. {
  792. assert(screenType == CMenuScreen::newGame);
  793. sInfo.difficulty = to;
  794. propagateOptions();
  795. redraw();
  796. }
  797. void CSelectionScreen::handleConnection()
  798. {
  799. setThreadName("CSelectionScreen::handleConnection");
  800. try
  801. {
  802. assert(serv);
  803. while(serv)
  804. {
  805. CPackForSelectionScreen *pack = nullptr;
  806. *serv >> pack;
  807. logNetwork->traceStream() << "Received a pack of type " << typeid(*pack).name();
  808. assert(pack);
  809. if(QuitMenuWithoutStarting *endingPack = dynamic_cast<QuitMenuWithoutStarting *>(pack))
  810. {
  811. endingPack->apply(this);
  812. }
  813. else if(StartWithCurrentSettings *endingPack = dynamic_cast<StartWithCurrentSettings *>(pack))
  814. {
  815. endingPack->apply(this);
  816. }
  817. else
  818. {
  819. boost::unique_lock<boost::recursive_mutex> lll(*mx);
  820. upcomingPacks.push_back(pack);
  821. }
  822. }
  823. }
  824. catch(int i)
  825. {
  826. if(i != 666)
  827. throw;
  828. }
  829. catch(...)
  830. {
  831. handleException();
  832. throw;
  833. }
  834. }
  835. void CSelectionScreen::setSInfo(const StartInfo &si)
  836. {
  837. std::map<PlayerColor, PlayerSettings>::const_iterator i;
  838. for(i = si.playerInfos.cbegin(); i != si.playerInfos.cend(); i++)
  839. {
  840. if(i->second.playerID == myNameID)
  841. {
  842. playerColor = i->first;
  843. break;
  844. }
  845. }
  846. if(i == si.playerInfos.cend()) //not found
  847. playerColor = PlayerColor::CANNOT_DETERMINE;
  848. sInfo = si;
  849. if(current)
  850. opt->recreate(); //will force to recreate using current sInfo
  851. card->difficulty->setSelected(si.difficulty);
  852. if(curTab == randMapTab)
  853. randMapTab->setMapGenOptions(si.mapGenOptions);
  854. GH.totalRedraw();
  855. }
  856. void CSelectionScreen::processPacks()
  857. {
  858. boost::unique_lock<boost::recursive_mutex> lll(*mx);
  859. while(!upcomingPacks.empty())
  860. {
  861. CPackForSelectionScreen *pack = upcomingPacks.front();
  862. upcomingPacks.pop_front();
  863. CBaseForPGApply *apply = applier->getApplier(typeList.getTypeID(pack)); //find the applier
  864. apply->applyOnPG(this, pack);
  865. delete pack;
  866. }
  867. }
  868. void CSelectionScreen::update()
  869. {
  870. if(serverHandlingThread)
  871. processPacks();
  872. }
  873. void CSelectionScreen::propagateOptions()
  874. {
  875. if(isHost() && serv)
  876. {
  877. UpdateStartOptions ups(sInfo);
  878. *serv << &ups;
  879. }
  880. }
  881. void CSelectionScreen::postRequest(ui8 what, ui8 dir)
  882. {
  883. if(!isGuest() || !serv)
  884. return;
  885. RequestOptionsChange roc(what, dir, myNameID);
  886. *serv << &roc;
  887. }
  888. void CSelectionScreen::postChatMessage(const std::string &txt)
  889. {
  890. assert(serv);
  891. ChatMessage cm;
  892. cm.message = txt;
  893. cm.playerName = sInfo.getPlayersSettings(myNameID)->name;
  894. *serv << &cm;
  895. }
  896. void CSelectionScreen::propagateNames()
  897. {
  898. PlayersNames pn;
  899. pn.playerNames = playerNames;
  900. *serv << &pn;
  901. }
  902. void CSelectionScreen::showAll(SDL_Surface *to)
  903. {
  904. CIntObject::showAll(to);
  905. if (bordered && (pos.h != to->h || pos.w != to->w))
  906. CMessage::drawBorder(PlayerColor(1), to, pos.w+28, pos.h+30, pos.x-14, pos.y-15);
  907. }
  908. // A new size filter (Small, Medium, ...) has been selected. Populate
  909. // selMaps with the relevant data.
  910. void SelectionTab::filter( int size, bool selectFirst )
  911. {
  912. curItems.clear();
  913. if(tabType == CMenuScreen::campaignList)
  914. {
  915. for (auto & elem : allItems)
  916. curItems.push_back(&elem);
  917. }
  918. else
  919. {
  920. for (auto & elem : allItems)
  921. if( elem.mapHeader && elem.mapHeader->version && (!size || elem.mapHeader->width == size))
  922. curItems.push_back(&elem);
  923. }
  924. if(curItems.size())
  925. {
  926. slider->block(false);
  927. slider->setAmount(curItems.size());
  928. sort();
  929. if(selectFirst)
  930. {
  931. slider->moveTo(0);
  932. onSelect(curItems[0]);
  933. selectAbs(0);
  934. }
  935. }
  936. else
  937. {
  938. slider->block(true);
  939. onSelect(nullptr);
  940. }
  941. }
  942. std::unordered_set<ResourceID> SelectionTab::getFiles(std::string dirURI, int resType)
  943. {
  944. boost::to_upper(dirURI);
  945. CResourceHandler::get()->updateFilteredFiles([&](const std::string & mount)
  946. {
  947. return boost::algorithm::starts_with(mount, dirURI);
  948. });
  949. std::unordered_set<ResourceID> ret = CResourceHandler::get()->getFilteredFiles([&](const ResourceID & ident)
  950. {
  951. return ident.getType() == resType
  952. && boost::algorithm::starts_with(ident.getName(), dirURI);
  953. });
  954. return ret;
  955. }
  956. void SelectionTab::parseMaps(const std::unordered_set<ResourceID> &files)
  957. {
  958. logGlobal->debug("Parsing %d maps", files.size());
  959. allItems.clear();
  960. for(auto & file : files)
  961. {
  962. try
  963. {
  964. CMapInfo mapInfo;
  965. mapInfo.mapInit(file.getName());
  966. // ignore unsupported map versions (e.g. WoG maps without WoG)
  967. // but accept VCMI maps
  968. if((mapInfo.mapHeader->version >= EMapFormat::VCMI) || (mapInfo.mapHeader->version <= CGI->modh->settings.data["textData"]["mapVersion"].Float()))
  969. allItems.push_back(std::move(mapInfo));
  970. }
  971. catch(std::exception & e)
  972. {
  973. logGlobal->errorStream() << "Map " << file.getName() << " is invalid. Message: " << e.what();
  974. }
  975. }
  976. }
  977. void SelectionTab::parseGames(const std::unordered_set<ResourceID> &files, CMenuScreen::EGameMode gameMode)
  978. {
  979. for(auto & file : files)
  980. {
  981. try
  982. {
  983. CLoadFile lf(*CResourceHandler::get()->getResourceName(file), MINIMAL_SERIALIZATION_VERSION);
  984. lf.checkMagicBytes(SAVEGAME_MAGIC);
  985. // ui8 sign[8];
  986. // lf >> sign;
  987. // if(std::memcmp(sign,"VCMISVG",7))
  988. // {
  989. // throw std::runtime_error("not a correct savefile!");
  990. // }
  991. // Create the map info object
  992. CMapInfo mapInfo;
  993. mapInfo.mapHeader = make_unique<CMapHeader>();
  994. mapInfo.scenarioOpts = nullptr;//to be created by serialiser
  995. lf >> *(mapInfo.mapHeader.get()) >> mapInfo.scenarioOpts;
  996. mapInfo.fileURI = file.getName();
  997. mapInfo.countPlayers();
  998. std::time_t time = boost::filesystem::last_write_time(*CResourceHandler::get()->getResourceName(file));
  999. mapInfo.date = std::asctime(std::localtime(&time));
  1000. // Filter out other game modes
  1001. bool isCampaign = mapInfo.scenarioOpts->mode == StartInfo::CAMPAIGN;
  1002. bool isMultiplayer = mapInfo.actualHumanPlayers > 1;
  1003. switch(gameMode)
  1004. {
  1005. case CMenuScreen::SINGLE_PLAYER:
  1006. if(isMultiplayer || isCampaign)
  1007. mapInfo.mapHeader.reset();
  1008. break;
  1009. case CMenuScreen::SINGLE_CAMPAIGN:
  1010. if(!isCampaign)
  1011. mapInfo.mapHeader.reset();
  1012. break;
  1013. default:
  1014. if(!isMultiplayer)
  1015. mapInfo.mapHeader.reset();
  1016. break;
  1017. }
  1018. allItems.push_back(std::move(mapInfo));
  1019. }
  1020. catch(const std::exception & e)
  1021. {
  1022. logGlobal->errorStream() << "Error: Failed to process " << file.getName() <<": " << e.what();
  1023. }
  1024. }
  1025. }
  1026. void SelectionTab::parseCampaigns(const std::unordered_set<ResourceID> &files )
  1027. {
  1028. allItems.reserve(files.size());
  1029. for (auto & file : files)
  1030. {
  1031. CMapInfo info;
  1032. //allItems[i].date = std::asctime(std::localtime(&files[i].date));
  1033. info.fileURI = file.getName();
  1034. info.campaignInit();
  1035. allItems.push_back(std::move(info));
  1036. }
  1037. }
  1038. SelectionTab::SelectionTab(CMenuScreen::EState Type, const std::function<void(CMapInfo *)> &OnSelect, CMenuScreen::EGameMode GameMode)
  1039. :bg(nullptr), onSelect(OnSelect)
  1040. {
  1041. OBJ_CONSTRUCTION;
  1042. selectionPos = 0;
  1043. addUsedEvents(LCLICK | WHEEL | KEYBOARD | DOUBLECLICK);
  1044. slider = nullptr;
  1045. txt = nullptr;
  1046. tabType = Type;
  1047. if (Type != CMenuScreen::campaignList)
  1048. {
  1049. bg = new CPicture("SCSELBCK.bmp", 0, 6);
  1050. pos = bg->pos;
  1051. }
  1052. else
  1053. {
  1054. bg = nullptr; //use background from parent
  1055. type |= REDRAW_PARENT; // we use parent background so we need to make sure it's will be redrawn too
  1056. pos.w = parent->pos.w;
  1057. pos.h = parent->pos.h;
  1058. pos.x += 3; pos.y += 6;
  1059. }
  1060. if(GameMode == CMenuScreen::MULTI_NETWORK_GUEST)
  1061. {
  1062. positions = 18;
  1063. }
  1064. else
  1065. {
  1066. switch(tabType)
  1067. {
  1068. case CMenuScreen::newGame:
  1069. parseMaps(getFiles("Maps/", EResType::MAP));
  1070. positions = 18;
  1071. break;
  1072. case CMenuScreen::loadGame:
  1073. case CMenuScreen::saveGame:
  1074. parseGames(getFiles("Saves/", EResType::CLIENT_SAVEGAME), GameMode);
  1075. if(tabType == CMenuScreen::loadGame)
  1076. {
  1077. positions = 18;
  1078. }
  1079. else
  1080. {
  1081. positions = 16;
  1082. }
  1083. if(tabType == CMenuScreen::saveGame)
  1084. {
  1085. txt = new CTextInput(Rect(32, 539, 350, 20), Point(-32, -25), "GSSTRIP.bmp", 0);
  1086. txt->filters += CTextInput::filenameFilter;
  1087. }
  1088. break;
  1089. case CMenuScreen::campaignList:
  1090. parseCampaigns(getFiles("Maps/", EResType::CAMPAIGN));
  1091. positions = 18;
  1092. break;
  1093. default:
  1094. assert(0);
  1095. break;
  1096. }
  1097. }
  1098. generalSortingBy = (tabType == CMenuScreen::loadGame || tabType == CMenuScreen::saveGame) ? _fileName : _name;
  1099. if (tabType != CMenuScreen::campaignList)
  1100. {
  1101. //size filter buttons
  1102. {
  1103. int sizes[] = {36, 72, 108, 144, 0};
  1104. const char * names[] = {"SCSMBUT.DEF", "SCMDBUT.DEF", "SCLGBUT.DEF", "SCXLBUT.DEF", "SCALBUT.DEF"};
  1105. for(int i = 0; i < 5; i++)
  1106. new CButton(Point(158 + 47*i, 46), names[i], CGI->generaltexth->zelp[54+i], std::bind(&SelectionTab::filter, this, sizes[i], true));
  1107. }
  1108. //sort buttons buttons
  1109. {
  1110. int xpos[] = {23, 55, 88, 121, 306, 339};
  1111. const char * names[] = {"SCBUTT1.DEF", "SCBUTT2.DEF", "SCBUTCP.DEF", "SCBUTT3.DEF", "SCBUTT4.DEF", "SCBUTT5.DEF"};
  1112. for(int i = 0; i < 6; i++)
  1113. {
  1114. ESortBy criteria = (ESortBy)i;
  1115. if(criteria == _name)
  1116. criteria = generalSortingBy;
  1117. new CButton(Point(xpos[i], 86), names[i], CGI->generaltexth->zelp[107+i], std::bind(&SelectionTab::sortBy, this, criteria));
  1118. }
  1119. }
  1120. }
  1121. else
  1122. {
  1123. //sort by buttons
  1124. new CButton(Point(23, 86), "CamCusM.DEF", CButton::tooltip(), std::bind(&SelectionTab::sortBy, this, _numOfMaps)); //by num of maps
  1125. new CButton(Point(55, 86), "CamCusL.DEF", CButton::tooltip(), std::bind(&SelectionTab::sortBy, this, _name)); //by name
  1126. }
  1127. slider = new CSlider(Point(372, 86), tabType != CMenuScreen::saveGame ? 480 : 430, std::bind(&SelectionTab::sliderMove, this, _1), positions, curItems.size(), 0, false, CSlider::BLUE);
  1128. slider->addUsedEvents(WHEEL);
  1129. formatIcons = std::make_shared<CAnimation>("SCSELC.DEF");
  1130. formatIcons->load();
  1131. sortingBy = _format;
  1132. ascending = true;
  1133. filter(0);
  1134. //select(0);
  1135. switch(tabType)
  1136. {
  1137. case CMenuScreen::newGame:
  1138. logGlobal->error(settings["session"]["lastMap"].String());
  1139. if(settings["session"]["lastMap"].isNull())
  1140. selectFName("Maps/Arrogance");
  1141. else
  1142. selectFName(settings["session"]["lastMap"].String());
  1143. break;
  1144. case CMenuScreen::campaignList:
  1145. select(0);
  1146. break;
  1147. case CMenuScreen::loadGame:
  1148. case CMenuScreen::saveGame:;
  1149. if(saveGameName.empty())
  1150. {
  1151. if(tabType == CMenuScreen::saveGame)
  1152. txt->setText("NEWGAME");
  1153. else
  1154. select(0);
  1155. }
  1156. else
  1157. {
  1158. selectFName(saveGameName);
  1159. }
  1160. }
  1161. }
  1162. SelectionTab::~SelectionTab()
  1163. {
  1164. formatIcons->unload();
  1165. }
  1166. void SelectionTab::sortBy( int criteria )
  1167. {
  1168. if(criteria == sortingBy)
  1169. {
  1170. ascending = !ascending;
  1171. }
  1172. else
  1173. {
  1174. sortingBy = (ESortBy)criteria;
  1175. ascending = true;
  1176. }
  1177. sort();
  1178. selectAbs(0);
  1179. }
  1180. void SelectionTab::sort()
  1181. {
  1182. if(sortingBy != generalSortingBy)
  1183. std::stable_sort(curItems.begin(), curItems.end(), mapSorter(generalSortingBy));
  1184. std::stable_sort(curItems.begin(), curItems.end(), mapSorter(sortingBy));
  1185. if(!ascending)
  1186. std::reverse(curItems.begin(), curItems.end());
  1187. redraw();
  1188. }
  1189. void SelectionTab::select( int position )
  1190. {
  1191. if(!curItems.size()) return;
  1192. // New selection. py is the index in curItems.
  1193. int py = position + slider->getValue();
  1194. vstd::amax(py, 0);
  1195. vstd::amin(py, curItems.size()-1);
  1196. selectionPos = py;
  1197. if(position < 0)
  1198. slider->moveBy(position);
  1199. else if(position >= positions)
  1200. slider->moveBy(position - positions + 1);
  1201. if(tabType == CMenuScreen::newGame)
  1202. {
  1203. Settings lastMap = settings.write["session"]["lastMap"];
  1204. lastMap->String() = getSelectedMapInfo()->fileURI;
  1205. }
  1206. if(txt)
  1207. {
  1208. auto filename = *CResourceHandler::get("local")->getResourceName(
  1209. ResourceID(curItems[py]->fileURI, EResType::CLIENT_SAVEGAME));
  1210. txt->setText(filename.stem().string());
  1211. }
  1212. onSelect(curItems[py]);
  1213. }
  1214. void SelectionTab::selectAbs( int position )
  1215. {
  1216. select(position - slider->getValue());
  1217. }
  1218. int SelectionTab::getPosition( int x, int y )
  1219. {
  1220. return -1;
  1221. }
  1222. void SelectionTab::sliderMove( int slidPos )
  1223. {
  1224. if(!slider) return; //ignore spurious call when slider is being created
  1225. redraw();
  1226. }
  1227. // Display the tab with the scenario names
  1228. //
  1229. // elemIdx is the index of the maps or saved game to display on line 0
  1230. // slider->capacity contains the number of available screen lines
  1231. // slider->positionsAmnt is the number of elements after filtering
  1232. void SelectionTab::printMaps(SDL_Surface *to)
  1233. {
  1234. int elemIdx = slider->getValue();
  1235. // Display all elements if there's enough space
  1236. //if(slider->amount < slider->capacity)
  1237. // elemIdx = 0;
  1238. SDL_Color itemColor;
  1239. for (int line = 0; line < positions && elemIdx < curItems.size(); elemIdx++, line++)
  1240. {
  1241. CMapInfo *currentItem = curItems[elemIdx];
  1242. if(elemIdx == selectionPos)
  1243. itemColor=Colors::YELLOW;
  1244. else
  1245. itemColor=Colors::WHITE;
  1246. if(tabType != CMenuScreen::campaignList)
  1247. {
  1248. //amount of players
  1249. std::ostringstream ostr(std::ostringstream::out);
  1250. ostr << currentItem->playerAmnt << "/" << currentItem->humanPlayers;
  1251. printAtLoc(ostr.str(), 29, 120 + line * 25, FONT_SMALL, itemColor, to);
  1252. //map size
  1253. std::string temp2 = "C";
  1254. switch (currentItem->mapHeader->width)
  1255. {
  1256. case 36:
  1257. temp2="S";
  1258. break;
  1259. case 72:
  1260. temp2="M";
  1261. break;
  1262. case 108:
  1263. temp2="L";
  1264. break;
  1265. case 144:
  1266. temp2="XL";
  1267. break;
  1268. }
  1269. printAtMiddleLoc(temp2, 70, 128 + line * 25, FONT_SMALL, itemColor, to);
  1270. int frame = -1, group = 0;
  1271. switch (currentItem->mapHeader->version)
  1272. {
  1273. case EMapFormat::ROE:
  1274. frame = 0;
  1275. break;
  1276. case EMapFormat::AB:
  1277. frame = 1;
  1278. break;
  1279. case EMapFormat::SOD:
  1280. frame = 2;
  1281. break;
  1282. case EMapFormat::WOG:
  1283. frame = 3;
  1284. break;
  1285. case EMapFormat::VCMI:
  1286. frame = 0;
  1287. group = 1;
  1288. break;
  1289. default:
  1290. // Unknown version. Be safe and ignore that map
  1291. logGlobal->warnStream() << "Warning: " << currentItem->fileURI << " has wrong version!";
  1292. continue;
  1293. }
  1294. IImage * icon = formatIcons->getImage(frame,group);
  1295. if(icon)
  1296. {
  1297. icon->draw(to, pos.x + 88, pos.y + 117 + line * 25);
  1298. icon->decreaseRef();
  1299. }
  1300. //victory conditions
  1301. icon = CGP->victoryIcons->getImage(currentItem->mapHeader->victoryIconIndex,0);
  1302. if(icon)
  1303. {
  1304. icon->draw(to, pos.x + 306, pos.y + 117 + line * 25);
  1305. icon->decreaseRef();
  1306. }
  1307. //loss conditions
  1308. icon = CGP->lossIcons->getImage(currentItem->mapHeader->defeatIconIndex,0);
  1309. if(icon)
  1310. {
  1311. icon->draw(to, pos.x + 339, pos.y + 117 + line * 25);
  1312. icon->decreaseRef();
  1313. }
  1314. }
  1315. else //if campaign
  1316. {
  1317. //number of maps in campaign
  1318. std::ostringstream ostr(std::ostringstream::out);
  1319. ostr << CGI->generaltexth->campaignRegionNames[ currentItem->campaignHeader->mapVersion ].size();
  1320. printAtLoc(ostr.str(), 29, 120 + line * 25, FONT_SMALL, itemColor, to);
  1321. }
  1322. std::string name;
  1323. if(tabType == CMenuScreen::newGame)
  1324. {
  1325. if (!currentItem->mapHeader->name.length())
  1326. currentItem->mapHeader->name = "Unnamed";
  1327. name = currentItem->mapHeader->name;
  1328. }
  1329. else if(tabType == CMenuScreen::campaignList)
  1330. {
  1331. name = currentItem->campaignHeader->name;
  1332. }
  1333. else
  1334. {
  1335. name = CResourceHandler::get("local")->getResourceName(
  1336. ResourceID(currentItem->fileURI, EResType::CLIENT_SAVEGAME))->stem().string();
  1337. }
  1338. //print name
  1339. printAtMiddleLoc(name, 213, 128 + line * 25, FONT_SMALL, itemColor, to);
  1340. }
  1341. }
  1342. void SelectionTab::showAll(SDL_Surface * to)
  1343. {
  1344. CIntObject::showAll(to);
  1345. printMaps(to);
  1346. std::string title;
  1347. switch(tabType) {
  1348. case CMenuScreen::newGame:
  1349. title = CGI->generaltexth->arraytxt[229];
  1350. break;
  1351. case CMenuScreen::loadGame:
  1352. title = CGI->generaltexth->arraytxt[230];
  1353. break;
  1354. case CMenuScreen::saveGame:
  1355. title = CGI->generaltexth->arraytxt[231];
  1356. break;
  1357. case CMenuScreen::campaignList:
  1358. title = CGI->generaltexth->allTexts[726];
  1359. break;
  1360. }
  1361. printAtMiddleLoc(title, 205, 28, FONT_MEDIUM, Colors::YELLOW, to); //Select a Scenario to Play
  1362. if(tabType != CMenuScreen::campaignList)
  1363. {
  1364. printAtMiddleLoc(CGI->generaltexth->allTexts[510], 87, 62, FONT_SMALL, Colors::YELLOW, to); //Map sizes
  1365. }
  1366. }
  1367. void SelectionTab::clickLeft( tribool down, bool previousState )
  1368. {
  1369. if(down)
  1370. {
  1371. int line = getLine();
  1372. if(line != -1)
  1373. select(line);
  1374. }
  1375. }
  1376. void SelectionTab::keyPressed( const SDL_KeyboardEvent & key )
  1377. {
  1378. if(key.state != SDL_PRESSED) return;
  1379. int moveBy = 0;
  1380. switch(key.keysym.sym)
  1381. {
  1382. case SDLK_UP:
  1383. moveBy = -1;
  1384. break;
  1385. case SDLK_DOWN:
  1386. moveBy = +1;
  1387. break;
  1388. case SDLK_PAGEUP:
  1389. moveBy = -positions+1;
  1390. break;
  1391. case SDLK_PAGEDOWN:
  1392. moveBy = +positions-1;
  1393. break;
  1394. case SDLK_HOME:
  1395. select(-slider->getValue());
  1396. return;
  1397. case SDLK_END:
  1398. select(curItems.size() - slider->getValue());
  1399. return;
  1400. default:
  1401. return;
  1402. }
  1403. select(selectionPos - slider->getValue() + moveBy);
  1404. }
  1405. void SelectionTab::onDoubleClick()
  1406. {
  1407. if(getLine() != -1) //double clicked scenarios list
  1408. {
  1409. //act as if start button was pressed
  1410. (static_cast<CSelectionScreen*>(parent))->start->clickLeft(false, true);
  1411. }
  1412. }
  1413. int SelectionTab::getLine()
  1414. {
  1415. int line = -1;
  1416. Point clickPos(GH.current->button.x, GH.current->button.y);
  1417. clickPos = clickPos - pos.topLeft();
  1418. // Ignore clicks on save name area
  1419. int maxPosY;
  1420. if(tabType == CMenuScreen::saveGame)
  1421. maxPosY = 516;
  1422. else
  1423. maxPosY = 564;
  1424. if(clickPos.y > 115 && clickPos.y < maxPosY && clickPos.x > 22 && clickPos.x < 371)
  1425. {
  1426. line = (clickPos.y-115) / 25; //which line
  1427. }
  1428. return line;
  1429. }
  1430. void SelectionTab::selectFName( std::string fname )
  1431. {
  1432. boost::to_upper(fname);
  1433. for(int i = curItems.size() - 1; i >= 0; i--)
  1434. {
  1435. if(curItems[i]->fileURI == fname)
  1436. {
  1437. slider->moveTo(i);
  1438. selectAbs(i);
  1439. return;
  1440. }
  1441. }
  1442. selectAbs(0);
  1443. }
  1444. const CMapInfo * SelectionTab::getSelectedMapInfo() const
  1445. {
  1446. return curItems.empty() ? nullptr : curItems[selectionPos];
  1447. }
  1448. CRandomMapTab::CRandomMapTab()
  1449. {
  1450. OBJ_CONSTRUCTION;
  1451. bg = new CPicture("RANMAPBK", 0, 6);
  1452. // Map Size
  1453. mapSizeBtnGroup = new CToggleGroup(0);
  1454. mapSizeBtnGroup->pos.y += 81;
  1455. mapSizeBtnGroup->pos.x += 158;
  1456. const std::vector<std::string> mapSizeBtns = {"RANSIZS", "RANSIZM","RANSIZL","RANSIZX"};
  1457. addButtonsToGroup(mapSizeBtnGroup, mapSizeBtns, 0, 3, 47, 198);
  1458. mapSizeBtnGroup->setSelected(1);
  1459. mapSizeBtnGroup->addCallback([&](int btnId)
  1460. {
  1461. auto mapSizeVal = getPossibleMapSizes();
  1462. mapGenOptions.setWidth(mapSizeVal[btnId]);
  1463. mapGenOptions.setHeight(mapSizeVal[btnId]);
  1464. if(!SEL->isGuest())
  1465. updateMapInfo();
  1466. });
  1467. // Two levels
  1468. twoLevelsBtn = new CToggleButton(Point(346, 81), "RANUNDR", CGI->generaltexth->zelp[202]);
  1469. //twoLevelsBtn->select(true); for now, deactivated
  1470. twoLevelsBtn->addCallback([&](bool on)
  1471. {
  1472. mapGenOptions.setHasTwoLevels(on);
  1473. if(!SEL->isGuest())
  1474. updateMapInfo();
  1475. });
  1476. // Create number defs list
  1477. std::vector<std::string> numberDefs;
  1478. for(int i = 0; i <= 8; ++i)
  1479. {
  1480. numberDefs.push_back("RANNUM" + boost::lexical_cast<std::string>(i));
  1481. }
  1482. const int NUMBERS_WIDTH = 32;
  1483. const int BTNS_GROUP_LEFT_MARGIN = 67;
  1484. // Amount of players
  1485. playersCntGroup = new CToggleGroup(0);
  1486. playersCntGroup->pos.y += 153;
  1487. playersCntGroup->pos.x += BTNS_GROUP_LEFT_MARGIN;
  1488. addButtonsWithRandToGroup(playersCntGroup, numberDefs, 1, 8, NUMBERS_WIDTH, 204, 212);
  1489. playersCntGroup->addCallback([&](int btnId)
  1490. {
  1491. mapGenOptions.setPlayerCount(btnId);
  1492. deactivateButtonsFrom(teamsCntGroup, btnId);
  1493. deactivateButtonsFrom(compOnlyPlayersCntGroup, btnId);
  1494. validatePlayersCnt(btnId);
  1495. if(!SEL->isGuest())
  1496. updateMapInfo();
  1497. });
  1498. // Amount of teams
  1499. teamsCntGroup = new CToggleGroup(0);
  1500. teamsCntGroup->pos.y += 219;
  1501. teamsCntGroup->pos.x += BTNS_GROUP_LEFT_MARGIN;
  1502. addButtonsWithRandToGroup(teamsCntGroup, numberDefs, 0, 7, NUMBERS_WIDTH, 214, 222);
  1503. teamsCntGroup->addCallback([&](int btnId)
  1504. {
  1505. mapGenOptions.setTeamCount(btnId);
  1506. if(!SEL->isGuest())
  1507. updateMapInfo();
  1508. });
  1509. // Computer only players
  1510. compOnlyPlayersCntGroup = new CToggleGroup(0);
  1511. compOnlyPlayersCntGroup->pos.y += 285;
  1512. compOnlyPlayersCntGroup->pos.x += BTNS_GROUP_LEFT_MARGIN;
  1513. addButtonsWithRandToGroup(compOnlyPlayersCntGroup, numberDefs, 0, 7, NUMBERS_WIDTH, 224, 232);
  1514. compOnlyPlayersCntGroup->addCallback([&](int btnId)
  1515. {
  1516. mapGenOptions.setCompOnlyPlayerCount(btnId);
  1517. deactivateButtonsFrom(compOnlyTeamsCntGroup, (btnId == 0 ? 1 : btnId));
  1518. validateCompOnlyPlayersCnt(btnId);
  1519. if(!SEL->isGuest())
  1520. updateMapInfo();
  1521. });
  1522. // Computer only teams
  1523. compOnlyTeamsCntGroup = new CToggleGroup(0);
  1524. compOnlyTeamsCntGroup->pos.y += 351;
  1525. compOnlyTeamsCntGroup->pos.x += BTNS_GROUP_LEFT_MARGIN;
  1526. addButtonsWithRandToGroup(compOnlyTeamsCntGroup, numberDefs, 0, 6, NUMBERS_WIDTH, 234, 241);
  1527. deactivateButtonsFrom(compOnlyTeamsCntGroup, 1);
  1528. compOnlyTeamsCntGroup->addCallback([&](int btnId)
  1529. {
  1530. mapGenOptions.setCompOnlyTeamCount(btnId);
  1531. if(!SEL->isGuest())
  1532. updateMapInfo();
  1533. });
  1534. const int WIDE_BTN_WIDTH = 85;
  1535. // Water content
  1536. waterContentGroup = new CToggleGroup(0);
  1537. waterContentGroup->pos.y += 419;
  1538. waterContentGroup->pos.x += BTNS_GROUP_LEFT_MARGIN;
  1539. const std::vector<std::string> waterContentBtns = {"RANNONE","RANNORM","RANISLD"};
  1540. addButtonsWithRandToGroup(waterContentGroup, waterContentBtns, 0, 2, WIDE_BTN_WIDTH, 243, 246);
  1541. waterContentGroup->addCallback([&](int btnId)
  1542. {
  1543. mapGenOptions.setWaterContent(static_cast<EWaterContent::EWaterContent>(btnId));
  1544. });
  1545. // Monster strength
  1546. monsterStrengthGroup = new CToggleGroup(0);
  1547. monsterStrengthGroup->pos.y += 485;
  1548. monsterStrengthGroup->pos.x += BTNS_GROUP_LEFT_MARGIN;
  1549. const std::vector<std::string> monsterStrengthBtns = {"RANWEAK","RANNORM","RANSTRG"};
  1550. addButtonsWithRandToGroup(monsterStrengthGroup, monsterStrengthBtns, 0, 2, WIDE_BTN_WIDTH, 248, 251);
  1551. monsterStrengthGroup->addCallback([&](int btnId)
  1552. {
  1553. if (btnId < 0)
  1554. mapGenOptions.setMonsterStrength(EMonsterStrength::RANDOM);
  1555. else
  1556. mapGenOptions.setMonsterStrength(static_cast<EMonsterStrength::EMonsterStrength>(btnId + EMonsterStrength::GLOBAL_WEAK)); //value 2 to 4
  1557. });
  1558. // Show random maps btn
  1559. showRandMaps = new CButton(Point(54, 535), "RANSHOW", CGI->generaltexth->zelp[252]);
  1560. // Initialize map info object
  1561. if(!SEL->isGuest())
  1562. updateMapInfo();
  1563. }
  1564. void CRandomMapTab::addButtonsWithRandToGroup(CToggleGroup * group, const std::vector<std::string> & defs, int nStart, int nEnd, int btnWidth, int helpStartIndex, int helpRandIndex) const
  1565. {
  1566. addButtonsToGroup(group, defs, nStart, nEnd, btnWidth, helpStartIndex);
  1567. // Buttons are relative to button group, TODO better solution?
  1568. SObjectConstruction obj__i(group);
  1569. const std::string RANDOM_DEF = "RANRAND";
  1570. group->addToggle(CMapGenOptions::RANDOM_SIZE, new CToggleButton(Point(256, 0), RANDOM_DEF, CGI->generaltexth->zelp[helpRandIndex]));
  1571. group->setSelected(CMapGenOptions::RANDOM_SIZE);
  1572. }
  1573. void CRandomMapTab::addButtonsToGroup(CToggleGroup * group, const std::vector<std::string> & defs, int nStart, int nEnd, int btnWidth, int helpStartIndex) const
  1574. {
  1575. // Buttons are relative to button group, TODO better solution?
  1576. SObjectConstruction obj__i(group);
  1577. int cnt = nEnd - nStart + 1;
  1578. for(int i = 0; i < cnt; ++i)
  1579. {
  1580. auto button = new CToggleButton(Point(i * btnWidth, 0), defs[i + nStart], CGI->generaltexth->zelp[helpStartIndex + i]);
  1581. // For blocked state we should use pressed image actually
  1582. button->setImageOrder(0, 1, 1, 3);
  1583. group->addToggle(i + nStart, button);
  1584. }
  1585. }
  1586. void CRandomMapTab::deactivateButtonsFrom(CToggleGroup * group, int startId)
  1587. {
  1588. logGlobal->infoStream() << "Blocking buttons from " << startId;
  1589. for(auto toggle : group->buttons)
  1590. {
  1591. if (auto button = dynamic_cast<CToggleButton*>(toggle.second))
  1592. {
  1593. if(startId == CMapGenOptions::RANDOM_SIZE || toggle.first < startId)
  1594. {
  1595. button->block(false);
  1596. }
  1597. else
  1598. {
  1599. button->block(true);
  1600. }
  1601. }
  1602. }
  1603. }
  1604. void CRandomMapTab::validatePlayersCnt(int playersCnt)
  1605. {
  1606. if(playersCnt == CMapGenOptions::RANDOM_SIZE)
  1607. {
  1608. return;
  1609. }
  1610. if(mapGenOptions.getTeamCount() >= playersCnt)
  1611. {
  1612. mapGenOptions.setTeamCount(playersCnt - 1);
  1613. teamsCntGroup->setSelected(mapGenOptions.getTeamCount());
  1614. }
  1615. if(mapGenOptions.getCompOnlyPlayerCount() >= playersCnt)
  1616. {
  1617. mapGenOptions.setCompOnlyPlayerCount(playersCnt - 1);
  1618. compOnlyPlayersCntGroup->setSelected(mapGenOptions.getCompOnlyPlayerCount());
  1619. }
  1620. validateCompOnlyPlayersCnt(mapGenOptions.getCompOnlyPlayerCount());
  1621. }
  1622. void CRandomMapTab::validateCompOnlyPlayersCnt(int compOnlyPlayersCnt)
  1623. {
  1624. if(compOnlyPlayersCnt == CMapGenOptions::RANDOM_SIZE)
  1625. {
  1626. return;
  1627. }
  1628. if(mapGenOptions.getCompOnlyTeamCount() >= compOnlyPlayersCnt)
  1629. {
  1630. int compOnlyTeamCount = compOnlyPlayersCnt == 0 ? 0 : compOnlyPlayersCnt - 1;
  1631. mapGenOptions.setCompOnlyTeamCount(compOnlyTeamCount);
  1632. compOnlyTeamsCntGroup->setSelected(compOnlyTeamCount);
  1633. }
  1634. }
  1635. std::vector<int> CRandomMapTab::getPossibleMapSizes()
  1636. {
  1637. return {CMapHeader::MAP_SIZE_SMALL,CMapHeader::MAP_SIZE_MIDDLE,CMapHeader::MAP_SIZE_LARGE,CMapHeader::MAP_SIZE_XLARGE};
  1638. }
  1639. void CRandomMapTab::showAll(SDL_Surface * to)
  1640. {
  1641. CIntObject::showAll(to);
  1642. // Headline
  1643. printAtMiddleLoc(CGI->generaltexth->allTexts[738], 222, 36, FONT_BIG, Colors::YELLOW, to);
  1644. printAtMiddleLoc(CGI->generaltexth->allTexts[739], 222, 56, FONT_SMALL, Colors::WHITE, to);
  1645. // Map size
  1646. printAtMiddleLoc(CGI->generaltexth->allTexts[752], 104, 97, FONT_SMALL, Colors::WHITE, to);
  1647. // Players cnt
  1648. printAtLoc(CGI->generaltexth->allTexts[753], 68, 133, FONT_SMALL, Colors::WHITE, to);
  1649. // Teams cnt
  1650. printAtLoc(CGI->generaltexth->allTexts[754], 68, 199, FONT_SMALL, Colors::WHITE, to);
  1651. // Computer only players cnt
  1652. printAtLoc(CGI->generaltexth->allTexts[755], 68, 265, FONT_SMALL, Colors::WHITE, to);
  1653. // Computer only teams cnt
  1654. printAtLoc(CGI->generaltexth->allTexts[756], 68, 331, FONT_SMALL, Colors::WHITE, to);
  1655. // Water content
  1656. printAtLoc(CGI->generaltexth->allTexts[757], 68, 398, FONT_SMALL, Colors::WHITE, to);
  1657. // Monster strength
  1658. printAtLoc(CGI->generaltexth->allTexts[758], 68, 465, FONT_SMALL, Colors::WHITE, to);
  1659. }
  1660. void CRandomMapTab::updateMapInfo()
  1661. {
  1662. // Generate header info
  1663. mapInfo = make_unique<CMapInfo>();
  1664. mapInfo->isRandomMap = true;
  1665. mapInfo->mapHeader = make_unique<CMapHeader>();
  1666. mapInfo->mapHeader->version = EMapFormat::SOD;
  1667. mapInfo->mapHeader->name = CGI->generaltexth->allTexts[740];
  1668. mapInfo->mapHeader->description = CGI->generaltexth->allTexts[741];
  1669. mapInfo->mapHeader->difficulty = 1; // Normal
  1670. mapInfo->mapHeader->height = mapGenOptions.getHeight();
  1671. mapInfo->mapHeader->width = mapGenOptions.getWidth();
  1672. mapInfo->mapHeader->twoLevel = mapGenOptions.getHasTwoLevels();
  1673. // Generate player information
  1674. mapInfo->mapHeader->players.clear();
  1675. int playersToGen = PlayerColor::PLAYER_LIMIT_I;
  1676. if(mapGenOptions.getPlayerCount() != CMapGenOptions::RANDOM_SIZE)
  1677. playersToGen = mapGenOptions.getPlayerCount();
  1678. mapInfo->mapHeader->howManyTeams = playersToGen;
  1679. for(int i = 0; i < playersToGen; ++i)
  1680. {
  1681. PlayerInfo player;
  1682. player.isFactionRandom = true;
  1683. player.canComputerPlay = true;
  1684. if(mapGenOptions.getCompOnlyPlayerCount() != CMapGenOptions::RANDOM_SIZE &&
  1685. i >= mapGenOptions.getHumanOnlyPlayerCount())
  1686. {
  1687. player.canHumanPlay = false;
  1688. }
  1689. else
  1690. {
  1691. player.canHumanPlay = true;
  1692. }
  1693. player.team = TeamID(i);
  1694. player.hasMainTown = true;
  1695. player.generateHeroAtMainTown = true;
  1696. mapInfo->mapHeader->players.push_back(player);
  1697. }
  1698. mapInfoChanged(mapInfo.get());
  1699. }
  1700. CFunctionList<void(const CMapInfo *)> & CRandomMapTab::getMapInfoChanged()
  1701. {
  1702. return mapInfoChanged;
  1703. }
  1704. const CMapInfo * CRandomMapTab::getMapInfo() const
  1705. {
  1706. return mapInfo.get();
  1707. }
  1708. const CMapGenOptions & CRandomMapTab::getMapGenOptions() const
  1709. {
  1710. return mapGenOptions;
  1711. }
  1712. void CRandomMapTab::setMapGenOptions(std::shared_ptr<CMapGenOptions> opts)
  1713. {
  1714. mapSizeBtnGroup->setSelected(vstd::find_pos(getPossibleMapSizes(), opts->getWidth()));
  1715. twoLevelsBtn->setSelected(opts->getHasTwoLevels());
  1716. playersCntGroup->setSelected(opts->getPlayerCount());
  1717. teamsCntGroup->setSelected(opts->getTeamCount());
  1718. compOnlyPlayersCntGroup->setSelected(opts->getCompOnlyPlayerCount());
  1719. compOnlyTeamsCntGroup->setSelected(opts->getCompOnlyTeamCount());
  1720. waterContentGroup->setSelected(opts->getWaterContent());
  1721. monsterStrengthGroup->setSelected(opts->getMonsterStrength());
  1722. }
  1723. CChatBox::CChatBox(const Rect &rect)
  1724. {
  1725. OBJ_CONSTRUCTION;
  1726. pos += rect;
  1727. addUsedEvents(KEYBOARD | TEXTINPUT);
  1728. captureAllKeys = true;
  1729. type |= REDRAW_PARENT;
  1730. const int height = graphics->fonts[FONT_SMALL]->getLineHeight();
  1731. inputBox = new CTextInput(Rect(0, rect.h - height, rect.w, height));
  1732. inputBox->removeUsedEvents(KEYBOARD);
  1733. chatHistory = new CTextBox("", Rect(0, 0, rect.w, rect.h - height), 1);
  1734. chatHistory->label->color = Colors::GREEN;
  1735. }
  1736. void CChatBox::keyPressed(const SDL_KeyboardEvent & key)
  1737. {
  1738. if(key.keysym.sym == SDLK_RETURN && key.state == SDL_PRESSED && inputBox->text.size())
  1739. {
  1740. SEL->postChatMessage(inputBox->text);
  1741. inputBox->setText("");
  1742. }
  1743. else
  1744. inputBox->keyPressed(key);
  1745. }
  1746. void CChatBox::addNewMessage(const std::string &text)
  1747. {
  1748. CCS->soundh->playSound("CHAT");
  1749. chatHistory->setText(chatHistory->label->text + text + "\n");
  1750. if(chatHistory->slider)
  1751. chatHistory->slider->moveToMax();
  1752. }
  1753. InfoCard::InfoCard( bool Network )
  1754. : sizes(nullptr), bg(nullptr), network(Network), chatOn(false), chat(nullptr), playerListBg(nullptr),
  1755. difficulty(nullptr)
  1756. {
  1757. OBJ_CONSTRUCTION_CAPTURING_ALL;
  1758. CIntObject::type |= REDRAW_PARENT;
  1759. pos.x += 393;
  1760. pos.y += 6;
  1761. addUsedEvents(RCLICK);
  1762. mapDescription = nullptr;
  1763. Rect descriptionRect(26, 149, 320, 115);
  1764. mapDescription = new CTextBox("", descriptionRect, 1);
  1765. if(SEL->screenType == CMenuScreen::campaignList)
  1766. {
  1767. CSelectionScreen *ss = static_cast<CSelectionScreen*>(parent);
  1768. mapDescription->addChild(new CPicture(*ss->bg, descriptionRect + Point(-393, 0)), true); //move subpicture bg to our description control (by default it's our (Infocard) child)
  1769. }
  1770. else
  1771. {
  1772. bg = new CPicture("GSELPOP1.bmp", 0, 0);
  1773. parent->addChild(bg);
  1774. auto it = vstd::find(parent->children, this); //our position among parent children
  1775. parent->children.insert(it, bg); //put BG before us
  1776. parent->children.pop_back();
  1777. pos.w = bg->pos.w;
  1778. pos.h = bg->pos.h;
  1779. sizes = new CAnimImage("SCNRMPSZ", 4, 0, 318, 22);//let it be custom size (frame 4) by default
  1780. sizes->recActions &= ~(SHOWALL | UPDATE);//explicit draw
  1781. sFlags = std::make_shared<CAnimation>("ITGFLAGS.DEF");
  1782. sFlags->load();
  1783. difficulty = new CToggleGroup(0);
  1784. {
  1785. static const char *difButns[] = {"GSPBUT3.DEF", "GSPBUT4.DEF", "GSPBUT5.DEF", "GSPBUT6.DEF", "GSPBUT7.DEF"};
  1786. for(int i = 0; i < 5; i++)
  1787. {
  1788. auto button = new CToggleButton(Point(110 + i*32, 450), difButns[i], CGI->generaltexth->zelp[24+i]);
  1789. difficulty->addToggle(i, button);
  1790. if(SEL->screenType != CMenuScreen::newGame)
  1791. button->block(true);
  1792. }
  1793. }
  1794. if(network)
  1795. {
  1796. playerListBg = new CPicture("CHATPLUG.bmp", 16, 276);
  1797. chat = new CChatBox(Rect(26, 132, 340, 132));
  1798. chatOn = true;
  1799. mapDescription->disable();
  1800. }
  1801. }
  1802. victory = new CAnimImage("SCNRVICT",0, 0, 24, 302);
  1803. victory->recActions &= ~(SHOWALL | UPDATE);//explicit draw
  1804. loss = new CAnimImage("SCNRLOSS", 0, 0, 24, 359);
  1805. loss->recActions &= ~(SHOWALL | UPDATE);//explicit draw
  1806. }
  1807. InfoCard::~InfoCard()
  1808. {
  1809. if(sFlags)
  1810. sFlags->unload();
  1811. }
  1812. void InfoCard::showAll(SDL_Surface * to)
  1813. {
  1814. CIntObject::showAll(to);
  1815. //blit texts
  1816. if(SEL->screenType != CMenuScreen::campaignList)
  1817. {
  1818. printAtLoc(CGI->generaltexth->allTexts[390] + ":", 24, 400, FONT_SMALL, Colors::WHITE, to); //Allies
  1819. printAtLoc(CGI->generaltexth->allTexts[391] + ":", 190, 400, FONT_SMALL, Colors::WHITE, to); //Enemies
  1820. printAtLoc(CGI->generaltexth->allTexts[494], 33, 430, FONT_SMALL, Colors::YELLOW, to);//"Map Diff:"
  1821. printAtLoc(CGI->generaltexth->allTexts[492] + ":", 133,430, FONT_SMALL, Colors::YELLOW, to); //player difficulty
  1822. printAtLoc(CGI->generaltexth->allTexts[218] + ":", 290,430, FONT_SMALL, Colors::YELLOW, to); //"Rating:"
  1823. printAtLoc(CGI->generaltexth->allTexts[495], 26, 22, FONT_SMALL, Colors::YELLOW, to); //Scenario Name:
  1824. if(!chatOn)
  1825. {
  1826. printAtLoc(CGI->generaltexth->allTexts[496], 26, 132, FONT_SMALL, Colors::YELLOW, to); //Scenario Description:
  1827. printAtLoc(CGI->generaltexth->allTexts[497], 26, 283, FONT_SMALL, Colors::YELLOW, to); //Victory Condition:
  1828. printAtLoc(CGI->generaltexth->allTexts[498], 26, 339, FONT_SMALL, Colors::YELLOW, to); //Loss Condition:
  1829. }
  1830. else //players list
  1831. {
  1832. std::map<ui8, std::string> playerNames = SEL->playerNames;
  1833. int playerSoFar = 0;
  1834. for (auto i = SEL->sInfo.playerInfos.cbegin(); i != SEL->sInfo.playerInfos.cend(); i++)
  1835. {
  1836. if(i->second.playerID != PlayerSettings::PLAYER_AI)
  1837. {
  1838. printAtLoc(i->second.name, 24, 285 + playerSoFar++ * graphics->fonts[FONT_SMALL]->getLineHeight(), FONT_SMALL, Colors::WHITE, to);
  1839. playerNames.erase(i->second.playerID);
  1840. }
  1841. }
  1842. playerSoFar = 0;
  1843. for (auto i = playerNames.cbegin(); i != playerNames.cend(); i++)
  1844. {
  1845. printAtLoc(i->second, 193, 285 + playerSoFar++ * graphics->fonts[FONT_SMALL]->getLineHeight(), FONT_SMALL, Colors::WHITE, to);
  1846. }
  1847. }
  1848. }
  1849. if(SEL->current)
  1850. {
  1851. if(SEL->screenType != CMenuScreen::campaignList)
  1852. {
  1853. if(!chatOn)
  1854. {
  1855. CMapHeader * header = SEL->current->mapHeader.get();
  1856. //victory conditions
  1857. printAtLoc(header->victoryMessage, 60, 307, FONT_SMALL, Colors::WHITE, to);
  1858. victory->setFrame(header->victoryIconIndex);
  1859. victory->showAll(to);
  1860. //loss conditoins
  1861. printAtLoc(header->defeatMessage, 60, 366, FONT_SMALL, Colors::WHITE, to);
  1862. loss->setFrame(header->defeatIconIndex);
  1863. loss->showAll(to);
  1864. }
  1865. //difficulty
  1866. assert(SEL->current->mapHeader->difficulty <= 4);
  1867. std::string &diff = CGI->generaltexth->arraytxt[142 + SEL->current->mapHeader->difficulty];
  1868. printAtMiddleLoc(diff, 62, 472, FONT_SMALL, Colors::WHITE, to);
  1869. //selecting size icon
  1870. switch (SEL->current->mapHeader->width)
  1871. {
  1872. case 36:
  1873. sizes->setFrame(0);
  1874. break;
  1875. case 72:
  1876. sizes->setFrame(1);
  1877. break;
  1878. case 108:
  1879. sizes->setFrame(2);
  1880. break;
  1881. case 144:
  1882. sizes->setFrame(3);
  1883. break;
  1884. default:
  1885. sizes->setFrame(4);
  1886. break;
  1887. }
  1888. sizes->showAll(to);
  1889. if(SEL->screenType == CMenuScreen::loadGame)
  1890. printToLoc((static_cast<const CMapInfo*>(SEL->current))->date,308,34, FONT_SMALL, Colors::WHITE, to);
  1891. //print flags
  1892. int fx = 34 + graphics->fonts[FONT_SMALL]->getStringWidth(CGI->generaltexth->allTexts[390]);
  1893. int ex = 200 + graphics->fonts[FONT_SMALL]->getStringWidth(CGI->generaltexth->allTexts[391]);
  1894. TeamID myT;
  1895. if(playerColor < PlayerColor::PLAYER_LIMIT)
  1896. myT = SEL->current->mapHeader->players[playerColor.getNum()].team;
  1897. else
  1898. myT = TeamID::NO_TEAM;
  1899. for (auto i = SEL->sInfo.playerInfos.cbegin(); i != SEL->sInfo.playerInfos.cend(); i++)
  1900. {
  1901. int *myx = ((i->first == playerColor || SEL->current->mapHeader->players[i->first.getNum()].team == myT) ? &fx : &ex);
  1902. IImage * flag = sFlags->getImage(i->first.getNum(),0);
  1903. flag->draw(to, pos.x + *myx, pos.y + 399);
  1904. *myx += flag->width();
  1905. flag->decreaseRef();
  1906. }
  1907. std::string tob;
  1908. switch (SEL->sInfo.difficulty)
  1909. {
  1910. case 0:
  1911. tob="80%";
  1912. break;
  1913. case 1:
  1914. tob="100%";
  1915. break;
  1916. case 2:
  1917. tob="130%";
  1918. break;
  1919. case 3:
  1920. tob="160%";
  1921. break;
  1922. case 4:
  1923. tob="200%";
  1924. break;
  1925. }
  1926. printAtMiddleLoc(tob, 311, 472, FONT_SMALL, Colors::WHITE, to);
  1927. }
  1928. //blit description
  1929. std::string name;
  1930. if (SEL->screenType == CMenuScreen::campaignList)
  1931. {
  1932. name = SEL->current->campaignHeader->name;
  1933. }
  1934. else
  1935. {
  1936. name = SEL->current->mapHeader->name;
  1937. }
  1938. //name
  1939. if (name.length())
  1940. printAtLoc(name, 26, 39, FONT_BIG, Colors::YELLOW, to);
  1941. else
  1942. printAtLoc("Unnamed", 26, 39, FONT_BIG, Colors::YELLOW, to);
  1943. }
  1944. }
  1945. void InfoCard::changeSelection( const CMapInfo *to )
  1946. {
  1947. if(to && mapDescription)
  1948. {
  1949. if (SEL->screenType == CMenuScreen::campaignList)
  1950. mapDescription->setText(to->campaignHeader->description);
  1951. else
  1952. mapDescription->setText(to->mapHeader->description);
  1953. mapDescription->label->scrollTextTo(0);
  1954. if (mapDescription->slider)
  1955. mapDescription->slider->moveToMin();
  1956. if(SEL->screenType != CMenuScreen::newGame && SEL->screenType != CMenuScreen::campaignList) {
  1957. //difficulty->block(true);
  1958. difficulty->setSelected(SEL->sInfo.difficulty);
  1959. }
  1960. }
  1961. redraw();
  1962. }
  1963. void InfoCard::clickRight( tribool down, bool previousState )
  1964. {
  1965. static const Rect flagArea(19, 397, 335, 23);
  1966. if(SEL->current && down && SEL->current && isItInLoc(flagArea, GH.current->motion.x, GH.current->motion.y))
  1967. showTeamsPopup();
  1968. }
  1969. void InfoCard::showTeamsPopup()
  1970. {
  1971. SDL_Surface *bmp = CMessage::drawDialogBox(256, 90 + 50 * SEL->current->mapHeader->howManyTeams);
  1972. graphics->fonts[FONT_MEDIUM]->renderTextCenter(bmp, CGI->generaltexth->allTexts[657], Colors::YELLOW, Point(128, 30));
  1973. for(int i = 0; i < SEL->current->mapHeader->howManyTeams; i++)
  1974. {
  1975. std::vector<ui8> flags;
  1976. std::string hlp = CGI->generaltexth->allTexts[656]; //Team %d
  1977. hlp.replace(hlp.find("%d"), 2, boost::lexical_cast<std::string>(i+1));
  1978. graphics->fonts[FONT_SMALL]->renderTextCenter(bmp, hlp, Colors::WHITE, Point(128, 65 + 50 * i));
  1979. for(int j = 0; j < PlayerColor::PLAYER_LIMIT_I; j++)
  1980. if((SEL->current->mapHeader->players[j].canHumanPlay || SEL->current->mapHeader->players[j].canComputerPlay)
  1981. && SEL->current->mapHeader->players[j].team == TeamID(i))
  1982. flags.push_back(j);
  1983. int curx = 128 - 9*flags.size();
  1984. for(auto & flag : flags)
  1985. {
  1986. IImage * icon = sFlags->getImage(flag,0);
  1987. icon->draw(bmp, curx, 75 + 50*i);
  1988. icon->decreaseRef();
  1989. curx += 18;
  1990. }
  1991. }
  1992. GH.pushInt(new CInfoPopup(bmp, true));
  1993. }
  1994. void InfoCard::toggleChat()
  1995. {
  1996. setChat(!chatOn);
  1997. }
  1998. void InfoCard::setChat(bool activateChat)
  1999. {
  2000. if(chatOn == activateChat)
  2001. return;
  2002. assert(active);
  2003. if(activateChat)
  2004. {
  2005. mapDescription->disable();
  2006. chat->enable();
  2007. playerListBg->enable();
  2008. }
  2009. else
  2010. {
  2011. mapDescription->enable();
  2012. chat->disable();
  2013. playerListBg->disable();
  2014. }
  2015. chatOn = activateChat;
  2016. GH.totalRedraw();
  2017. }
  2018. OptionsTab::OptionsTab():
  2019. turnDuration(nullptr)
  2020. {
  2021. OBJ_CONSTRUCTION;
  2022. bg = new CPicture("ADVOPTBK", 0, 6);
  2023. pos = bg->pos;
  2024. if(SEL->screenType == CMenuScreen::newGame)
  2025. turnDuration = new CSlider(Point(55, 551), 194, std::bind(&OptionsTab::setTurnLength, this, _1), 1, 11, 11, true, CSlider::BLUE);
  2026. }
  2027. OptionsTab::~OptionsTab()
  2028. {
  2029. }
  2030. void OptionsTab::showAll(SDL_Surface * to)
  2031. {
  2032. CIntObject::showAll(to);
  2033. printAtMiddleLoc(CGI->generaltexth->allTexts[515], 222, 30, FONT_BIG, Colors::YELLOW, to);
  2034. printAtMiddleWBLoc(CGI->generaltexth->allTexts[516], 222, 68, FONT_SMALL, 300, Colors::WHITE, to); //Select starting options, handicap, and name for each player in the game.
  2035. printAtMiddleWBLoc(CGI->generaltexth->allTexts[517], 107, 110, FONT_SMALL, 100, Colors::YELLOW, to); //Player Name Handicap Type
  2036. printAtMiddleWBLoc(CGI->generaltexth->allTexts[518], 197, 110, FONT_SMALL, 70, Colors::YELLOW, to); //Starting Town
  2037. printAtMiddleWBLoc(CGI->generaltexth->allTexts[519], 273, 110, FONT_SMALL, 70, Colors::YELLOW, to); //Starting Hero
  2038. printAtMiddleWBLoc(CGI->generaltexth->allTexts[520], 349, 110, FONT_SMALL, 70, Colors::YELLOW, to); //Starting Bonus
  2039. printAtMiddleLoc(CGI->generaltexth->allTexts[521], 222, 538, FONT_SMALL, Colors::YELLOW, to); // Player Turn Duration
  2040. if (turnDuration)
  2041. printAtMiddleLoc(CGI->generaltexth->turnDurations[turnDuration->getValue()], 319,559, FONT_SMALL, Colors::WHITE, to);//Turn duration value
  2042. }
  2043. void OptionsTab::nextCastle( PlayerColor player, int dir )
  2044. {
  2045. if(SEL->isGuest())
  2046. {
  2047. SEL->postRequest(RequestOptionsChange::TOWN, dir);
  2048. return;
  2049. }
  2050. PlayerSettings &s = SEL->sInfo.playerInfos[player];
  2051. si16 &cur = s.castle;
  2052. auto & allowed = SEL->current->mapHeader->players[s.color.getNum()].allowedFactions;
  2053. if (cur == PlayerSettings::NONE) //no change
  2054. return;
  2055. if (cur == PlayerSettings::RANDOM) //first/last available
  2056. {
  2057. if (dir > 0)
  2058. cur = *allowed.begin(); //id of first town
  2059. else
  2060. cur = *allowed.rbegin(); //id of last town
  2061. }
  2062. else // next/previous available
  2063. {
  2064. if ( (cur == *allowed.begin() && dir < 0 )
  2065. || (cur == *allowed.rbegin() && dir > 0) )
  2066. cur = -1;
  2067. else
  2068. {
  2069. assert(dir >= -1 && dir <= 1); //othervice std::advance may go out of range
  2070. auto iter = allowed.find(cur);
  2071. std::advance(iter, dir);
  2072. cur = *iter;
  2073. }
  2074. }
  2075. if(s.hero >= 0 && !SEL->current->mapHeader->players[s.color.getNum()].hasCustomMainHero()) // remove hero unless it set to fixed one in map editor
  2076. {
  2077. usedHeroes.erase(s.hero); // restore previously selected hero back to available pool
  2078. s.hero = PlayerSettings::RANDOM;
  2079. }
  2080. if(cur < 0 && s.bonus == PlayerSettings::RESOURCE)
  2081. s.bonus = PlayerSettings::RANDOM;
  2082. entries[player]->selectButtons();
  2083. SEL->propagateOptions();
  2084. entries[player]->update();
  2085. redraw();
  2086. }
  2087. void OptionsTab::nextHero( PlayerColor player, int dir )
  2088. {
  2089. if(SEL->isGuest())
  2090. {
  2091. SEL->postRequest(RequestOptionsChange::HERO, dir);
  2092. return;
  2093. }
  2094. PlayerSettings &s = SEL->sInfo.playerInfos[player];
  2095. int old = s.hero;
  2096. if (s.castle < 0 || s.playerID == PlayerSettings::PLAYER_AI || s.hero == PlayerSettings::NONE)
  2097. return;
  2098. if (s.hero == PlayerSettings::RANDOM) // first/last available
  2099. {
  2100. int max = CGI->heroh->heroes.size(),
  2101. min = 0;
  2102. s.hero = nextAllowedHero(player, min,max,0,dir);
  2103. }
  2104. else
  2105. {
  2106. if(dir > 0)
  2107. s.hero = nextAllowedHero(player, s.hero, CGI->heroh->heroes.size(), 1, dir);
  2108. else
  2109. s.hero = nextAllowedHero(player, -1, s.hero, 1, dir); // min needs to be -1 -- hero at index 0 would be skipped otherwise
  2110. }
  2111. if(old != s.hero)
  2112. {
  2113. usedHeroes.erase(old);
  2114. usedHeroes.insert(s.hero);
  2115. entries[player]->update();
  2116. redraw();
  2117. }
  2118. SEL->propagateOptions();
  2119. }
  2120. int OptionsTab::nextAllowedHero( PlayerColor player, int min, int max, int incl, int dir )
  2121. {
  2122. if(dir>0)
  2123. {
  2124. for(int i=min+incl; i<=max-incl; i++)
  2125. if(canUseThisHero(player, i))
  2126. return i;
  2127. }
  2128. else
  2129. {
  2130. for(int i=max-incl; i>=min+incl; i--)
  2131. if(canUseThisHero(player, i))
  2132. return i;
  2133. }
  2134. return -1;
  2135. }
  2136. bool OptionsTab::canUseThisHero( PlayerColor player, int ID )
  2137. {
  2138. return CGI->heroh->heroes.size() > ID
  2139. && SEL->sInfo.playerInfos[player].castle == CGI->heroh->heroes[ID]->heroClass->faction
  2140. && !vstd::contains(usedHeroes, ID)
  2141. && SEL->current->mapHeader->allowedHeroes[ID];
  2142. }
  2143. void OptionsTab::nextBonus( PlayerColor player, int dir )
  2144. {
  2145. if(SEL->isGuest())
  2146. {
  2147. SEL->postRequest(RequestOptionsChange::BONUS, dir);
  2148. return;
  2149. }
  2150. PlayerSettings &s = SEL->sInfo.playerInfos[player];
  2151. PlayerSettings::Ebonus &ret = s.bonus = static_cast<PlayerSettings::Ebonus>(static_cast<int>(s.bonus) + dir);
  2152. if (s.hero==PlayerSettings::NONE &&
  2153. !SEL->current->mapHeader->players[s.color.getNum()].heroesNames.size() &&
  2154. ret==PlayerSettings::ARTIFACT) //no hero - can't be artifact
  2155. {
  2156. if (dir<0)
  2157. ret=PlayerSettings::RANDOM;
  2158. else ret=PlayerSettings::GOLD;
  2159. }
  2160. if(ret > PlayerSettings::RESOURCE)
  2161. ret = PlayerSettings::RANDOM;
  2162. if(ret < PlayerSettings::RANDOM)
  2163. ret = PlayerSettings::RESOURCE;
  2164. if (s.castle==PlayerSettings::RANDOM && ret==PlayerSettings::RESOURCE) //random castle - can't be resource
  2165. {
  2166. if (dir<0)
  2167. ret=PlayerSettings::GOLD;
  2168. else ret=PlayerSettings::RANDOM;
  2169. }
  2170. SEL->propagateOptions();
  2171. entries[player]->update();
  2172. redraw();
  2173. }
  2174. void OptionsTab::recreate()
  2175. {
  2176. for(auto & elem : entries)
  2177. {
  2178. delete elem.second;
  2179. }
  2180. entries.clear();
  2181. usedHeroes.clear();
  2182. OBJ_CONSTRUCTION_CAPTURING_ALL;
  2183. for(auto it = SEL->sInfo.playerInfos.begin(); it != SEL->sInfo.playerInfos.end(); ++it)
  2184. {
  2185. entries.insert(std::make_pair(it->first, new PlayerOptionsEntry(this, it->second)));
  2186. const std::vector<SHeroName> &heroes = SEL->current->mapHeader->players[it->first.getNum()].heroesNames;
  2187. for(auto & heroe : heroes)
  2188. if(heroe.heroId >= 0)//in VCMI map format heroId = -1 means random hero
  2189. usedHeroes.insert(heroe.heroId);
  2190. }
  2191. }
  2192. void OptionsTab::setTurnLength( int npos )
  2193. {
  2194. static const int times[] = {1, 2, 4, 6, 8, 10, 15, 20, 25, 30, 0};
  2195. vstd::amin(npos, ARRAY_COUNT(times) - 1);
  2196. SEL->sInfo.turnTime = times[npos];
  2197. redraw();
  2198. }
  2199. void OptionsTab::flagPressed( PlayerColor color )
  2200. {
  2201. PlayerSettings &clicked = SEL->sInfo.playerInfos[color];
  2202. PlayerSettings *old = nullptr;
  2203. if(SEL->playerNames.size() == 1) //single player -> just swap
  2204. {
  2205. if(color == playerColor) //that color is already selected, no action needed
  2206. return;
  2207. old = &SEL->sInfo.playerInfos[playerColor];
  2208. swapPlayers(*old, clicked);
  2209. }
  2210. else
  2211. {
  2212. //identify clicked player
  2213. int clickedNameID = clicked.playerID; //human is a number of player, zero means AI
  2214. if(clickedNameID > 0 && playerToRestore.id == clickedNameID) //player to restore is about to being replaced -> put him back to the old place
  2215. {
  2216. PlayerSettings &restPos = SEL->sInfo.playerInfos[playerToRestore.color];
  2217. SEL->setPlayer(restPos, playerToRestore.id);
  2218. playerToRestore.reset();
  2219. }
  2220. int newPlayer; //which player will take clicked position
  2221. //who will be put here?
  2222. if(!clickedNameID) //AI player clicked -> if possible replace computer with unallocated player
  2223. {
  2224. newPlayer = SEL->getIdOfFirstUnallocatedPlayer();
  2225. if(!newPlayer) //no "free" player -> get just first one
  2226. newPlayer = SEL->playerNames.begin()->first;
  2227. }
  2228. else //human clicked -> take next
  2229. {
  2230. auto i = SEL->playerNames.find(clickedNameID); //clicked one
  2231. i++; //player AFTER clicked one
  2232. if(i != SEL->playerNames.end())
  2233. newPlayer = i->first;
  2234. else
  2235. newPlayer = 0; //AI if we scrolled through all players
  2236. }
  2237. SEL->setPlayer(clicked, newPlayer); //put player
  2238. //if that player was somewhere else, we need to replace him with computer
  2239. if(newPlayer) //not AI
  2240. {
  2241. for(auto i = SEL->sInfo.playerInfos.begin(); i != SEL->sInfo.playerInfos.end(); i++)
  2242. {
  2243. int curNameID = i->second.playerID;
  2244. if(i->first != color && curNameID == newPlayer)
  2245. {
  2246. assert(i->second.playerID);
  2247. playerToRestore.color = i->first;
  2248. playerToRestore.id = newPlayer;
  2249. SEL->setPlayer(i->second, 0); //set computer
  2250. old = &i->second;
  2251. break;
  2252. }
  2253. }
  2254. }
  2255. }
  2256. entries[clicked.color]->selectButtons();
  2257. if(old)
  2258. {
  2259. entries[old->color]->selectButtons();
  2260. if(old->hero >= 0)
  2261. usedHeroes.erase(old->hero);
  2262. old->hero = entries[old->color]->pi.defaultHero();
  2263. entries[old->color]->update(); // update previous frame images in case entries were auto-updated
  2264. }
  2265. SEL->propagateOptions();
  2266. GH.totalRedraw();
  2267. }
  2268. OptionsTab::PlayerOptionsEntry::PlayerOptionsEntry( OptionsTab *owner, PlayerSettings &S)
  2269. : pi(SEL->current->mapHeader->players[S.color.getNum()]), s(S)
  2270. {
  2271. OBJ_CONSTRUCTION;
  2272. defActions |= SHARE_POS;
  2273. int serial = 0;
  2274. for(int g=0; g < s.color.getNum(); ++g)
  2275. {
  2276. PlayerInfo &itred = SEL->current->mapHeader->players[g];
  2277. if( itred.canComputerPlay || itred.canHumanPlay)
  2278. serial++;
  2279. }
  2280. pos.x += 54;
  2281. pos.y += 122 + serial*50;
  2282. static const char *flags[] = {"AOFLGBR.DEF", "AOFLGBB.DEF", "AOFLGBY.DEF", "AOFLGBG.DEF",
  2283. "AOFLGBO.DEF", "AOFLGBP.DEF", "AOFLGBT.DEF", "AOFLGBS.DEF"};
  2284. static const char *bgs[] = {"ADOPRPNL.bmp", "ADOPBPNL.bmp", "ADOPYPNL.bmp", "ADOPGPNL.bmp",
  2285. "ADOPOPNL.bmp", "ADOPPPNL.bmp", "ADOPTPNL.bmp", "ADOPSPNL.bmp"};
  2286. bg = new CPicture(BitmapHandler::loadBitmap(bgs[s.color.getNum()]), 0, 0, true);
  2287. if(SEL->screenType == CMenuScreen::newGame)
  2288. {
  2289. btns[0] = new CButton(Point(107, 5), "ADOPLFA.DEF", CGI->generaltexth->zelp[132], std::bind(&OptionsTab::nextCastle, owner, s.color, -1));
  2290. btns[1] = new CButton(Point(168, 5), "ADOPRTA.DEF", CGI->generaltexth->zelp[133], std::bind(&OptionsTab::nextCastle, owner, s.color, +1));
  2291. btns[2] = new CButton(Point(183, 5), "ADOPLFA.DEF", CGI->generaltexth->zelp[148], std::bind(&OptionsTab::nextHero, owner, s.color, -1));
  2292. btns[3] = new CButton(Point(244, 5), "ADOPRTA.DEF", CGI->generaltexth->zelp[149], std::bind(&OptionsTab::nextHero, owner, s.color, +1));
  2293. btns[4] = new CButton(Point(259, 5), "ADOPLFA.DEF", CGI->generaltexth->zelp[164], std::bind(&OptionsTab::nextBonus, owner, s.color, -1));
  2294. btns[5] = new CButton(Point(320, 5), "ADOPRTA.DEF", CGI->generaltexth->zelp[165], std::bind(&OptionsTab::nextBonus, owner, s.color, +1));
  2295. }
  2296. else
  2297. for(auto & elem : btns)
  2298. elem = nullptr;
  2299. selectButtons();
  2300. assert(SEL->current && SEL->current->mapHeader);
  2301. const PlayerInfo &p = SEL->current->mapHeader->players[s.color.getNum()];
  2302. assert(p.canComputerPlay || p.canHumanPlay); //someone must be able to control this player
  2303. if(p.canHumanPlay && p.canComputerPlay)
  2304. whoCanPlay = HUMAN_OR_CPU;
  2305. else if(p.canComputerPlay)
  2306. whoCanPlay = CPU;
  2307. else
  2308. whoCanPlay = HUMAN;
  2309. if(SEL->screenType != CMenuScreen::scenarioInfo
  2310. && SEL->current->mapHeader->players[s.color.getNum()].canHumanPlay)
  2311. {
  2312. flag = new CButton(Point(-43, 2), flags[s.color.getNum()], CGI->generaltexth->zelp[180], std::bind(&OptionsTab::flagPressed, owner, s.color));
  2313. flag->hoverable = true;
  2314. flag->block(SEL->isGuest());
  2315. }
  2316. else
  2317. flag = nullptr;
  2318. town = new SelectedBox(Point(119, 2), s, TOWN);
  2319. hero = new SelectedBox(Point(195, 2), s, HERO);
  2320. bonus = new SelectedBox(Point(271, 2), s, BONUS);
  2321. }
  2322. void OptionsTab::PlayerOptionsEntry::showAll(SDL_Surface * to)
  2323. {
  2324. CIntObject::showAll(to);
  2325. printAtMiddleLoc(s.name, 55, 10, FONT_SMALL, Colors::WHITE, to);
  2326. printAtMiddleWBLoc(CGI->generaltexth->arraytxt[206+whoCanPlay], 28, 39, FONT_TINY, 50, Colors::WHITE, to);
  2327. }
  2328. void OptionsTab::PlayerOptionsEntry::update()
  2329. {
  2330. town->update();
  2331. hero->update();
  2332. bonus->update();
  2333. }
  2334. void OptionsTab::PlayerOptionsEntry::selectButtons()
  2335. {
  2336. if(!btns[0])
  2337. return;
  2338. if( (pi.defaultCastle() != -1) //fixed tow
  2339. || (SEL->isGuest() && s.color != playerColor)) //or not our player
  2340. {
  2341. btns[0]->disable();
  2342. btns[1]->disable();
  2343. }
  2344. else
  2345. {
  2346. btns[0]->enable();
  2347. btns[1]->enable();
  2348. }
  2349. if( (pi.defaultHero() != -1 || !s.playerID || s.castle < 0) //fixed hero
  2350. || (SEL->isGuest() && s.color != playerColor))//or not our player
  2351. {
  2352. btns[2]->disable();
  2353. btns[3]->disable();
  2354. }
  2355. else
  2356. {
  2357. btns[2]->enable();
  2358. btns[3]->enable();
  2359. }
  2360. if(SEL->isGuest() && s.color != playerColor)//or not our player
  2361. {
  2362. btns[4]->disable();
  2363. btns[5]->disable();
  2364. }
  2365. else
  2366. {
  2367. btns[4]->enable();
  2368. btns[5]->enable();
  2369. }
  2370. }
  2371. size_t OptionsTab::CPlayerSettingsHelper::getImageIndex()
  2372. {
  2373. enum EBonusSelection //frames of bonuses file
  2374. {
  2375. WOOD_ORE = 0, CRYSTAL = 1, GEM = 2,
  2376. MERCURY = 3, SULFUR = 5, GOLD = 8,
  2377. ARTIFACT = 9, RANDOM = 10,
  2378. WOOD = 0, ORE = 0, MITHRIL = 10, // resources unavailable in bonuses file
  2379. TOWN_RANDOM = 38, TOWN_NONE = 39, // Special frames in ITPA
  2380. HERO_RANDOM = 163, HERO_NONE = 164 // Special frames in PortraitsSmall
  2381. };
  2382. switch(type)
  2383. {
  2384. case TOWN:
  2385. switch (settings.castle)
  2386. {
  2387. case PlayerSettings::NONE: return TOWN_NONE;
  2388. case PlayerSettings::RANDOM: return TOWN_RANDOM;
  2389. default: return CGI->townh->factions[settings.castle]->town->clientInfo.icons[true][false] + 2;
  2390. }
  2391. case HERO:
  2392. switch (settings.hero)
  2393. {
  2394. case PlayerSettings::NONE: return HERO_NONE;
  2395. case PlayerSettings::RANDOM: return HERO_RANDOM;
  2396. default:
  2397. {
  2398. if(settings.heroPortrait >= 0)
  2399. return settings.heroPortrait;
  2400. return CGI->heroh->heroes[settings.hero]->imageIndex;
  2401. }
  2402. }
  2403. case BONUS:
  2404. {
  2405. switch(settings.bonus)
  2406. {
  2407. case PlayerSettings::RANDOM: return RANDOM;
  2408. case PlayerSettings::ARTIFACT: return ARTIFACT;
  2409. case PlayerSettings::GOLD: return GOLD;
  2410. case PlayerSettings::RESOURCE:
  2411. {
  2412. switch(CGI->townh->factions[settings.castle]->town->primaryRes)
  2413. {
  2414. case Res::WOOD_AND_ORE : return WOOD_ORE;
  2415. case Res::WOOD : return WOOD;
  2416. case Res::MERCURY : return MERCURY;
  2417. case Res::ORE : return ORE;
  2418. case Res::SULFUR : return SULFUR;
  2419. case Res::CRYSTAL : return CRYSTAL;
  2420. case Res::GEMS : return GEM;
  2421. case Res::GOLD : return GOLD;
  2422. case Res::MITHRIL : return MITHRIL;
  2423. }
  2424. }
  2425. }
  2426. }
  2427. }
  2428. return 0;
  2429. }
  2430. std::string OptionsTab::CPlayerSettingsHelper::getImageName()
  2431. {
  2432. switch(type)
  2433. {
  2434. case OptionsTab::TOWN: return "ITPA";
  2435. case OptionsTab::HERO: return "PortraitsSmall";
  2436. case OptionsTab::BONUS: return "SCNRSTAR";
  2437. }
  2438. return "";
  2439. }
  2440. std::string OptionsTab::CPlayerSettingsHelper::getTitle()
  2441. {
  2442. switch(type)
  2443. {
  2444. case OptionsTab::TOWN: return (settings.castle < 0) ? CGI->generaltexth->allTexts[103] : CGI->generaltexth->allTexts[80];
  2445. case OptionsTab::HERO: return (settings.hero < 0) ? CGI->generaltexth->allTexts[101] : CGI->generaltexth->allTexts[77];
  2446. case OptionsTab::BONUS:
  2447. {
  2448. switch(settings.bonus)
  2449. {
  2450. case PlayerSettings::RANDOM: return CGI->generaltexth->allTexts[86]; //{Random Bonus}
  2451. case PlayerSettings::ARTIFACT: return CGI->generaltexth->allTexts[83]; //{Artifact Bonus}
  2452. case PlayerSettings::GOLD: return CGI->generaltexth->allTexts[84]; //{Gold Bonus}
  2453. case PlayerSettings::RESOURCE: return CGI->generaltexth->allTexts[85]; //{Resource Bonus}
  2454. }
  2455. }
  2456. }
  2457. return "";
  2458. }
  2459. std::string OptionsTab::CPlayerSettingsHelper::getName()
  2460. {
  2461. switch(type)
  2462. {
  2463. case TOWN:
  2464. {
  2465. switch (settings.castle)
  2466. {
  2467. case PlayerSettings::NONE : return CGI->generaltexth->allTexts[523];
  2468. case PlayerSettings::RANDOM : return CGI->generaltexth->allTexts[522];
  2469. default : return CGI->townh->factions[settings.castle]->name;
  2470. }
  2471. }
  2472. case HERO:
  2473. {
  2474. switch (settings.hero)
  2475. {
  2476. case PlayerSettings::NONE : return CGI->generaltexth->allTexts[523];
  2477. case PlayerSettings::RANDOM : return CGI->generaltexth->allTexts[522];
  2478. default :
  2479. {
  2480. if (!settings.heroName.empty())
  2481. return settings.heroName;
  2482. return CGI->heroh->heroes[settings.hero]->name;
  2483. }
  2484. }
  2485. }
  2486. case BONUS:
  2487. {
  2488. switch (settings.bonus)
  2489. {
  2490. case PlayerSettings::RANDOM : return CGI->generaltexth->allTexts[522];
  2491. default: return CGI->generaltexth->arraytxt[214 + settings.bonus];
  2492. }
  2493. }
  2494. }
  2495. return "";
  2496. }
  2497. std::string OptionsTab::CPlayerSettingsHelper::getSubtitle()
  2498. {
  2499. switch(type)
  2500. {
  2501. case TOWN: return getName();
  2502. case HERO:
  2503. {
  2504. if (settings.hero >= 0)
  2505. return getName() + " - " + CGI->heroh->heroes[settings.hero]->heroClass->name;
  2506. return getName();
  2507. }
  2508. case BONUS:
  2509. {
  2510. switch(settings.bonus)
  2511. {
  2512. case PlayerSettings::GOLD: return CGI->generaltexth->allTexts[87]; //500-1000
  2513. case PlayerSettings::RESOURCE:
  2514. {
  2515. switch(CGI->townh->factions[settings.castle]->town->primaryRes)
  2516. {
  2517. case Res::MERCURY: return CGI->generaltexth->allTexts[694];
  2518. case Res::SULFUR: return CGI->generaltexth->allTexts[695];
  2519. case Res::CRYSTAL: return CGI->generaltexth->allTexts[692];
  2520. case Res::GEMS: return CGI->generaltexth->allTexts[693];
  2521. case Res::WOOD_AND_ORE: return CGI->generaltexth->allTexts[89]; //At the start of the game, 5-10 wood and 5-10 ore are added to your Kingdom's resource pool
  2522. }
  2523. }
  2524. }
  2525. }
  2526. }
  2527. return "";
  2528. }
  2529. std::string OptionsTab::CPlayerSettingsHelper::getDescription()
  2530. {
  2531. switch(type)
  2532. {
  2533. case TOWN: return CGI->generaltexth->allTexts[104];
  2534. case HERO: return CGI->generaltexth->allTexts[102];
  2535. case BONUS:
  2536. {
  2537. switch(settings.bonus)
  2538. {
  2539. case PlayerSettings::RANDOM: return CGI->generaltexth->allTexts[94]; //Gold, wood and ore, or an artifact is randomly chosen as your starting bonus
  2540. case PlayerSettings::ARTIFACT: return CGI->generaltexth->allTexts[90]; //An artifact is randomly chosen and equipped to your starting hero
  2541. case PlayerSettings::GOLD: return CGI->generaltexth->allTexts[92]; //At the start of the game, 500-1000 gold is added to your Kingdom's resource pool
  2542. case PlayerSettings::RESOURCE:
  2543. {
  2544. switch(CGI->townh->factions[settings.castle]->town->primaryRes)
  2545. {
  2546. case Res::MERCURY: return CGI->generaltexth->allTexts[690];
  2547. case Res::SULFUR: return CGI->generaltexth->allTexts[691];
  2548. case Res::CRYSTAL: return CGI->generaltexth->allTexts[688];
  2549. case Res::GEMS: return CGI->generaltexth->allTexts[689];
  2550. case Res::WOOD_AND_ORE: return CGI->generaltexth->allTexts[93]; //At the start of the game, 5-10 wood and 5-10 ore are added to your Kingdom's resource pool
  2551. }
  2552. }
  2553. }
  2554. }
  2555. }
  2556. return "";
  2557. }
  2558. OptionsTab::CPregameTooltipBox::CPregameTooltipBox(CPlayerSettingsHelper & helper):
  2559. CWindowObject(BORDERED | RCLICK_POPUP),
  2560. CPlayerSettingsHelper(helper)
  2561. {
  2562. OBJ_CONSTRUCTION_CAPTURING_ALL;
  2563. int value = PlayerSettings::NONE;
  2564. switch(CPlayerSettingsHelper::type)
  2565. {
  2566. break; case TOWN:
  2567. value = settings.castle;
  2568. break; case HERO:
  2569. value = settings.hero;
  2570. break; case BONUS:
  2571. value = settings.bonus;
  2572. }
  2573. if (value == PlayerSettings::RANDOM)
  2574. genBonusWindow();
  2575. else if (CPlayerSettingsHelper::type == BONUS)
  2576. genBonusWindow();
  2577. else if (CPlayerSettingsHelper::type == HERO)
  2578. genHeroWindow();
  2579. else if (CPlayerSettingsHelper::type == TOWN)
  2580. genTownWindow();
  2581. center();
  2582. }
  2583. void OptionsTab::CPregameTooltipBox::genHeader()
  2584. {
  2585. new CFilledTexture("DIBOXBCK", pos);
  2586. updateShadow();
  2587. new CLabel(pos.w / 2 + 8, 21, FONT_MEDIUM, CENTER, Colors::YELLOW, getTitle());
  2588. new CLabel(pos.w / 2, 88, FONT_SMALL, CENTER, Colors::WHITE, getSubtitle());
  2589. new CAnimImage(getImageName(), getImageIndex(), 0, pos.w / 2 - 24, 45);
  2590. }
  2591. void OptionsTab::CPregameTooltipBox::genTownWindow()
  2592. {
  2593. pos = Rect(0, 0, 228, 290);
  2594. genHeader();
  2595. new CLabel(pos.w / 2 + 8, 122, FONT_MEDIUM, CENTER, Colors::YELLOW, CGI->generaltexth->allTexts[79]);
  2596. std::vector<CComponent *> components;
  2597. const CTown * town = CGI->townh->factions[settings.castle]->town;
  2598. for (auto & elem : town->creatures)
  2599. {
  2600. if (!elem.empty())
  2601. components.push_back(new CComponent(CComponent::creature, elem.front(), 0, CComponent::tiny));
  2602. }
  2603. new CComponentBox(components, Rect(10, 140, pos.w - 20, 140));
  2604. }
  2605. void OptionsTab::CPregameTooltipBox::genHeroWindow()
  2606. {
  2607. pos = Rect(0, 0, 292, 226);
  2608. genHeader();
  2609. // specialty
  2610. new CAnimImage("UN44", CGI->heroh->heroes[settings.hero]->imageIndex, 0, pos.w / 2 - 22, 134);
  2611. new CLabel(pos.w / 2 + 4, 117, FONT_MEDIUM, CENTER, Colors::YELLOW, CGI->generaltexth->allTexts[78]);
  2612. new CLabel(pos.w / 2, 188, FONT_SMALL, CENTER, Colors::WHITE, CGI->heroh->heroes[settings.hero]->specName);
  2613. }
  2614. void OptionsTab::CPregameTooltipBox::genBonusWindow()
  2615. {
  2616. pos = Rect(0, 0, 228, 162);
  2617. genHeader();
  2618. new CTextBox(getDescription(), Rect(10, 100, pos.w - 20, 70), 0, FONT_SMALL, CENTER, Colors::WHITE );
  2619. }
  2620. OptionsTab::SelectedBox::SelectedBox(Point position, PlayerSettings & settings, SelType type)
  2621. :CIntObject(RCLICK, position),
  2622. CPlayerSettingsHelper(settings, type)
  2623. {
  2624. OBJ_CONSTRUCTION_CAPTURING_ALL;
  2625. image = new CAnimImage(getImageName(), getImageIndex());
  2626. subtitle = new CLabel(23, 39, FONT_TINY, CENTER, Colors::WHITE, getName());
  2627. pos = image->pos;
  2628. }
  2629. void OptionsTab::SelectedBox::update()
  2630. {
  2631. image->setFrame(getImageIndex());
  2632. subtitle->setText(getName());
  2633. }
  2634. void OptionsTab::SelectedBox::clickRight( tribool down, bool previousState )
  2635. {
  2636. if (down)
  2637. {
  2638. // cases when we do not need to display a message
  2639. if (settings.castle == -2 && CPlayerSettingsHelper::type == TOWN )
  2640. return;
  2641. if (settings.hero == -2 && !SEL->current->mapHeader->players[settings.color.getNum()].hasCustomMainHero() && CPlayerSettingsHelper::type == HERO)
  2642. return;
  2643. GH.pushInt(new CPregameTooltipBox(*this));
  2644. }
  2645. }
  2646. CScenarioInfo::CScenarioInfo(const CMapHeader *mapHeader, const StartInfo *startInfo)
  2647. {
  2648. OBJ_CONSTRUCTION_CAPTURING_ALL;
  2649. for(auto it = startInfo->playerInfos.cbegin(); it != startInfo->playerInfos.cend(); ++it)
  2650. {
  2651. if(it->second.playerID)
  2652. {
  2653. playerColor = it->first;
  2654. }
  2655. }
  2656. pos.w = 762;
  2657. pos.h = 584;
  2658. center(pos);
  2659. assert(LOCPLINT);
  2660. sInfo = *LOCPLINT->cb->getStartInfo();
  2661. assert(!SEL->current);
  2662. current = mapInfoFromGame();
  2663. setPlayersFromGame();
  2664. screenType = CMenuScreen::scenarioInfo;
  2665. card = new InfoCard();
  2666. opt = new OptionsTab();
  2667. opt->recreate();
  2668. card->changeSelection(current);
  2669. card->difficulty->setSelected(startInfo->difficulty);
  2670. back = new CButton(Point(584, 535), "SCNRBACK.DEF", CGI->generaltexth->zelp[105], std::bind(&CGuiHandler::popIntTotally, &GH, this), SDLK_ESCAPE);
  2671. }
  2672. CScenarioInfo::~CScenarioInfo()
  2673. {
  2674. delete current;
  2675. }
  2676. bool mapSorter::operator()(const CMapInfo *aaa, const CMapInfo *bbb)
  2677. {
  2678. const CMapHeader * a = aaa->mapHeader.get(),
  2679. * b = bbb->mapHeader.get();
  2680. if(a && b) //if we are sorting scenarios
  2681. {
  2682. switch (sortBy)
  2683. {
  2684. case _format: //by map format (RoE, WoG, etc)
  2685. return (a->version<b->version);
  2686. break;
  2687. case _loscon: //by loss conditions
  2688. return (a->defeatMessage < b->defeatMessage);
  2689. break;
  2690. case _playerAm: //by player amount
  2691. int playerAmntB,humenPlayersB,playerAmntA,humenPlayersA;
  2692. playerAmntB=humenPlayersB=playerAmntA=humenPlayersA=0;
  2693. for (int i=0;i<8;i++)
  2694. {
  2695. if (a->players[i].canHumanPlay) {playerAmntA++;humenPlayersA++;}
  2696. else if (a->players[i].canComputerPlay) {playerAmntA++;}
  2697. if (b->players[i].canHumanPlay) {playerAmntB++;humenPlayersB++;}
  2698. else if (b->players[i].canComputerPlay) {playerAmntB++;}
  2699. }
  2700. if (playerAmntB!=playerAmntA)
  2701. return (playerAmntA<playerAmntB);
  2702. else
  2703. return (humenPlayersA<humenPlayersB);
  2704. break;
  2705. case _size: //by size of map
  2706. return (a->width<b->width);
  2707. break;
  2708. case _viccon: //by victory conditions
  2709. return (a->victoryMessage < b->victoryMessage);
  2710. break;
  2711. case _name: //by name
  2712. return boost::ilexicographical_compare(a->name, b->name);
  2713. case _fileName: //by filename
  2714. return boost::ilexicographical_compare(aaa->fileURI, bbb->fileURI);
  2715. default:
  2716. return boost::ilexicographical_compare(a->name, b->name);
  2717. }
  2718. }
  2719. else //if we are sorting campaigns
  2720. {
  2721. switch(sortBy)
  2722. {
  2723. case _numOfMaps: //by number of maps in campaign
  2724. return CGI->generaltexth->campaignRegionNames[ aaa->campaignHeader->mapVersion ].size() <
  2725. CGI->generaltexth->campaignRegionNames[ bbb->campaignHeader->mapVersion ].size();
  2726. break;
  2727. case _name: //by name
  2728. return boost::ilexicographical_compare(aaa->campaignHeader->name, bbb->campaignHeader->name);
  2729. default:
  2730. return boost::ilexicographical_compare(aaa->campaignHeader->name, bbb->campaignHeader->name);
  2731. }
  2732. }
  2733. }
  2734. CMultiMode::CMultiMode()
  2735. {
  2736. OBJ_CONSTRUCTION_CAPTURING_ALL;
  2737. bg = new CPicture("MUPOPUP.bmp");
  2738. bg->convertToScreenBPP(); //so we could draw without problems
  2739. blitAt(CPicture("MUMAP.bmp"), 16, 77, *bg); //blit img
  2740. pos = bg->center(); //center, window has size of bg graphic
  2741. bar = new CGStatusBar(new CPicture(Rect(7, 465, 440, 18), 0));//226, 472
  2742. txt = new CTextInput(Rect(19, 436, 334, 16), *bg);
  2743. txt->setText(settings["general"]["playerName"].String()); //Player
  2744. btns[0] = new CButton(Point(373, 78), "MUBHOT.DEF", CGI->generaltexth->zelp[266], std::bind(&CMultiMode::openHotseat, this));
  2745. btns[1] = new CButton(Point(373, 78 + 57*1), "MUBHOST.DEF", CButton::tooltip("Host TCP/IP game", ""), std::bind(&CMultiMode::hostTCP, this));
  2746. btns[2] = new CButton(Point(373, 78 + 57*2), "MUBJOIN.DEF", CButton::tooltip("Join TCP/IP game", ""), std::bind(&CMultiMode::joinTCP, this));
  2747. btns[6] = new CButton(Point(373, 424), "MUBCANC.DEF", CGI->generaltexth->zelp[288], [&](){ GH.popIntTotally(this);}, SDLK_ESCAPE);
  2748. }
  2749. void CMultiMode::openHotseat()
  2750. {
  2751. GH.pushInt(new CHotSeatPlayers(txt->text));
  2752. }
  2753. void CMultiMode::hostTCP()
  2754. {
  2755. Settings name = settings.write["general"]["playerName"];
  2756. name->String() = txt->text;
  2757. GH.popIntTotally(this);
  2758. if(settings["session"]["donotstartserver"].Bool())
  2759. GH.pushInt(new CSimpleJoinScreen(CMenuScreen::MULTI_NETWORK_HOST));
  2760. else
  2761. GH.pushInt(new CSelectionScreen(CMenuScreen::newGame, CMenuScreen::MULTI_NETWORK_HOST));
  2762. }
  2763. void CMultiMode::joinTCP()
  2764. {
  2765. Settings name = settings.write["general"]["playerName"];
  2766. name->String() = txt->text;
  2767. GH.pushInt(new CSimpleJoinScreen(CMenuScreen::MULTI_NETWORK_GUEST));
  2768. }
  2769. CHotSeatPlayers::CHotSeatPlayers(const std::string &firstPlayer)
  2770. {
  2771. OBJ_CONSTRUCTION_CAPTURING_ALL;
  2772. bg = new CPicture("MUHOTSEA.bmp");
  2773. pos = bg->center(); //center, window has size of bg graphic
  2774. std::string text = CGI->generaltexth->allTexts[446];
  2775. boost::replace_all(text, "\t","\n");
  2776. Rect boxRect(25, 20, 315, 50);
  2777. title = new CTextBox(text, boxRect, 0, FONT_BIG, CENTER, Colors::WHITE);//HOTSEAT Please enter names
  2778. for(int i = 0; i < ARRAY_COUNT(txt); i++)
  2779. {
  2780. txt[i] = new CTextInput(Rect(60, 85 + i*30, 280, 16), *bg);
  2781. txt[i]->cb += std::bind(&CHotSeatPlayers::onChange, this, _1);
  2782. }
  2783. ok = new CButton(Point(95, 338), "MUBCHCK.DEF", CGI->generaltexth->zelp[560], std::bind(&CHotSeatPlayers::enterSelectionScreen, this), SDLK_RETURN);
  2784. cancel = new CButton(Point(205, 338), "MUBCANC.DEF", CGI->generaltexth->zelp[561], std::bind(&CGuiHandler::popIntTotally, std::ref(GH), this), SDLK_ESCAPE);
  2785. bar = new CGStatusBar(new CPicture(Rect(7, 381, 348, 18), 0));//226, 472
  2786. txt[0]->setText(firstPlayer, true);
  2787. txt[0]->giveFocus();
  2788. }
  2789. void CHotSeatPlayers::onChange(std::string newText)
  2790. {
  2791. size_t namesCount = 0;
  2792. for(auto & elem : txt)
  2793. if(!elem->text.empty())
  2794. namesCount++;
  2795. ok->block(namesCount < 2);
  2796. }
  2797. void CHotSeatPlayers::enterSelectionScreen()
  2798. {
  2799. std::map<ui8, std::string> names;
  2800. for(int i = 0, j = 1; i < ARRAY_COUNT(txt); i++)
  2801. if(txt[i]->text.length())
  2802. names[j++] = txt[i]->text;
  2803. Settings name = settings.write["general"]["playerName"];
  2804. name->String() = names.begin()->second;
  2805. GH.popInts(2); //pop MP mode window and this
  2806. GH.pushInt(new CSelectionScreen(CMenuScreen::newGame, CMenuScreen::MULTI_HOT_SEAT, &names));
  2807. }
  2808. void CBonusSelection::init()
  2809. {
  2810. highlightedRegion = nullptr;
  2811. ourHeader.reset();
  2812. diffLb = nullptr;
  2813. diffRb = nullptr;
  2814. bonuses = nullptr;
  2815. selectedMap = 0;
  2816. // Initialize start info
  2817. startInfo.mapname = ourCampaign->camp->header.filename;
  2818. startInfo.mode = StartInfo::CAMPAIGN;
  2819. startInfo.campState = ourCampaign;
  2820. startInfo.turnTime = 0;
  2821. OBJ_CONSTRUCTION_CAPTURING_ALL;
  2822. static const std::string bgNames [] = {"E1_BG.BMP", "G2_BG.BMP", "E2_BG.BMP", "G1_BG.BMP", "G3_BG.BMP", "N1_BG.BMP",
  2823. "S1_BG.BMP", "BR_BG.BMP", "IS_BG.BMP", "KR_BG.BMP", "NI_BG.BMP", "TA_BG.BMP", "AR_BG.BMP", "HS_BG.BMP",
  2824. "BB_BG.BMP", "NB_BG.BMP", "EL_BG.BMP", "RN_BG.BMP", "UA_BG.BMP", "SP_BG.BMP"};
  2825. loadPositionsOfGraphics();
  2826. background = BitmapHandler::loadBitmap(bgNames[ourCampaign->camp->header.mapVersion]);
  2827. pos.h = background->h;
  2828. pos.w = background->w;
  2829. center();
  2830. SDL_Surface * panel = BitmapHandler::loadBitmap("CAMPBRF.BMP");
  2831. blitAt(panel, 456, 6, background);
  2832. startB = new CButton(Point(475, 536), "CBBEGIB.DEF", CButton::tooltip(), std::bind(&CBonusSelection::startMap, this), SDLK_RETURN);
  2833. restartB = new CButton(Point(475, 536), "CBRESTB.DEF", CButton::tooltip(), std::bind(&CBonusSelection::restartMap, this), SDLK_RETURN);
  2834. backB = new CButton(Point(624, 536), "CBCANCB.DEF", CButton::tooltip(), std::bind(&CBonusSelection::goBack, this), SDLK_ESCAPE);
  2835. //campaign name
  2836. if (ourCampaign->camp->header.name.length())
  2837. graphics->fonts[FONT_BIG]->renderTextLeft(background, ourCampaign->camp->header.name, Colors::YELLOW, Point(481, 28));
  2838. else
  2839. graphics->fonts[FONT_BIG]->renderTextLeft(background, CGI->generaltexth->allTexts[508], Colors::YELLOW, Point(481, 28));
  2840. //map size icon
  2841. sizes = new CAnimImage("SCNRMPSZ",4,0,735, 26);
  2842. sizes->recActions &= ~(SHOWALL | UPDATE);//explicit draw
  2843. //campaign description
  2844. graphics->fonts[FONT_SMALL]->renderTextLeft(background, CGI->generaltexth->allTexts[38], Colors::YELLOW, Point(481, 63));
  2845. campaignDescription = new CTextBox(ourCampaign->camp->header.description, Rect(480, 86, 286, 117), 1);
  2846. //campaignDescription->showAll(background);
  2847. //map description
  2848. mapDescription = new CTextBox("", Rect(480, 280, 286, 117), 1);
  2849. //bonus choosing
  2850. graphics->fonts[FONT_MEDIUM]->renderTextLeft(background, CGI->generaltexth->allTexts[71], Colors::WHITE, Point(511, 432));
  2851. bonuses = new CToggleGroup(std::bind(&CBonusSelection::selectBonus, this, _1));
  2852. //set left part of window
  2853. bool isCurrentMapConquerable = ourCampaign->currentMap && ourCampaign->camp->conquerable(*ourCampaign->currentMap);
  2854. for(int g = 0; g < ourCampaign->camp->scenarios.size(); ++g)
  2855. {
  2856. if(ourCampaign->camp->conquerable(g))
  2857. {
  2858. regions.push_back(new CRegion(this, true, true, g));
  2859. regions[regions.size()-1]->rclickText = ourCampaign->camp->scenarios[g].regionText;
  2860. if(highlightedRegion == nullptr)
  2861. {
  2862. if(!isCurrentMapConquerable || (isCurrentMapConquerable && g == *ourCampaign->currentMap))
  2863. {
  2864. highlightedRegion = regions.back();
  2865. selectMap(g, true);
  2866. }
  2867. }
  2868. }
  2869. else if (ourCampaign->camp->scenarios[g].conquered) //display as striped
  2870. {
  2871. regions.push_back(new CRegion(this, false, false, g));
  2872. regions[regions.size()-1]->rclickText = ourCampaign->camp->scenarios[g].regionText;
  2873. }
  2874. }
  2875. //allies / enemies
  2876. graphics->fonts[FONT_SMALL]->renderTextLeft(background, CGI->generaltexth->allTexts[390] + ":", Colors::WHITE, Point(486, 407));
  2877. graphics->fonts[FONT_SMALL]->renderTextLeft(background, CGI->generaltexth->allTexts[391] + ":", Colors::WHITE, Point(619, 407));
  2878. SDL_FreeSurface(panel);
  2879. //difficulty
  2880. std::vector<std::string> difficulty;
  2881. boost::split(difficulty, CGI->generaltexth->allTexts[492], boost::is_any_of(" "));
  2882. graphics->fonts[FONT_MEDIUM]->renderTextLeft(background, difficulty.back(), Colors::WHITE, Point(689, 432));
  2883. //difficulty pics
  2884. for (size_t b=0; b < diffPics.size(); ++b)
  2885. {
  2886. diffPics[b] = new CAnimImage("GSPBUT" + boost::lexical_cast<std::string>(b+3) + ".DEF", 0, 0, 709, 455);
  2887. diffPics[b]->recActions &= ~(SHOWALL | UPDATE);//explicit draw
  2888. }
  2889. //difficulty selection buttons
  2890. if (ourCampaign->camp->header.difficultyChoosenByPlayer)
  2891. {
  2892. diffLb = new CButton(Point(694, 508), "SCNRBLF.DEF", CButton::tooltip(), std::bind(&CBonusSelection::decreaseDifficulty, this));
  2893. diffRb = new CButton(Point(738, 508), "SCNRBRT.DEF", CButton::tooltip(), std::bind(&CBonusSelection::increaseDifficulty, this));
  2894. }
  2895. //load miniflags
  2896. sFlags = std::make_shared<CAnimation>("ITGFLAGS.DEF");
  2897. sFlags->load();
  2898. }
  2899. CBonusSelection::CBonusSelection(std::shared_ptr<CCampaignState> _ourCampaign) : ourCampaign(_ourCampaign)
  2900. {
  2901. init();
  2902. }
  2903. CBonusSelection::CBonusSelection(const std::string & campaignFName)
  2904. {
  2905. ourCampaign = std::make_shared<CCampaignState>(CCampaignHandler::getCampaign(campaignFName));
  2906. init();
  2907. }
  2908. CBonusSelection::~CBonusSelection()
  2909. {
  2910. SDL_FreeSurface(background);
  2911. sFlags->unload();
  2912. }
  2913. void CBonusSelection::goBack()
  2914. {
  2915. GH.popIntTotally(this);
  2916. }
  2917. void CBonusSelection::showAll(SDL_Surface * to)
  2918. {
  2919. blitAt(background, pos.x, pos.y, to);
  2920. CIntObject::showAll(to);
  2921. show(to);
  2922. if (pos.h != to->h || pos.w != to->w)
  2923. CMessage::drawBorder(PlayerColor(1), to, pos.w+28, pos.h+30, pos.x-14, pos.y-15);
  2924. }
  2925. void CBonusSelection::loadPositionsOfGraphics()
  2926. {
  2927. const JsonNode config(ResourceID("config/campaign_regions.json"));
  2928. int idx = 0;
  2929. for(const JsonNode &campaign : config["campaign_regions"].Vector())
  2930. {
  2931. SCampPositions sc;
  2932. sc.campPrefix = campaign["prefix"].String();
  2933. sc.colorSuffixLength = campaign["color_suffix_length"].Float();
  2934. for(const JsonNode &desc : campaign["desc"].Vector())
  2935. {
  2936. SCampPositions::SRegionDesc rd;
  2937. rd.infix = desc["infix"].String();
  2938. rd.xpos = desc["x"].Float();
  2939. rd.ypos = desc["y"].Float();
  2940. sc.regions.push_back(rd);
  2941. }
  2942. campDescriptions.push_back(sc);
  2943. idx++;
  2944. }
  2945. assert(idx == CGI->generaltexth->campaignMapNames.size());
  2946. }
  2947. void CBonusSelection::selectMap(int mapNr, bool initialSelect)
  2948. {
  2949. if(initialSelect || selectedMap != mapNr)
  2950. {
  2951. // initialize restart / start button
  2952. if(!ourCampaign->currentMap || *ourCampaign->currentMap != mapNr)
  2953. {
  2954. // draw start button
  2955. restartB->disable();
  2956. startB->enable();
  2957. if (!ourCampaign->mapsConquered.empty())
  2958. backB->block(true);
  2959. else
  2960. backB->block(false);
  2961. }
  2962. else
  2963. {
  2964. // draw restart button
  2965. startB->disable();
  2966. restartB->enable();
  2967. backB->block(false);
  2968. }
  2969. startInfo.difficulty = ourCampaign->camp->scenarios[mapNr].difficulty;
  2970. selectedMap = mapNr;
  2971. selectedBonus = boost::none;
  2972. std::string scenarioName = ourCampaign->camp->header.filename.substr(0, ourCampaign->camp->header.filename.find('.'));
  2973. boost::to_lower(scenarioName);
  2974. scenarioName += ':' + boost::lexical_cast<std::string>(selectedMap);
  2975. //get header
  2976. std::string & headerStr = ourCampaign->camp->mapPieces.find(mapNr)->second;
  2977. auto buffer = reinterpret_cast<const ui8 *>(headerStr.data());
  2978. ourHeader = CMapService::loadMapHeader(buffer, headerStr.size(), scenarioName);
  2979. std::map<ui8, std::string> names;
  2980. names[1] = settings["general"]["playerName"].String();
  2981. updateStartInfo(ourCampaign->camp->header.filename, startInfo, ourHeader, names);
  2982. mapDescription->setText(ourHeader->description);
  2983. updateBonusSelection();
  2984. GH.totalRedraw();
  2985. }
  2986. }
  2987. void CBonusSelection::show(SDL_Surface * to)
  2988. {
  2989. //map name
  2990. std::string mapName = ourHeader->name;
  2991. if (mapName.length())
  2992. printAtLoc(mapName, 481, 219, FONT_BIG, Colors::YELLOW, to);
  2993. else
  2994. printAtLoc("Unnamed", 481, 219, FONT_BIG, Colors::YELLOW, to);
  2995. //map description
  2996. printAtLoc(CGI->generaltexth->allTexts[496], 481, 253, FONT_SMALL, Colors::YELLOW, to);
  2997. mapDescription->showAll(to); //showAll because CTextBox has no show()
  2998. //map size icon
  2999. int temp;
  3000. switch (ourHeader->width)
  3001. {
  3002. case 36:
  3003. temp=0;
  3004. break;
  3005. case 72:
  3006. temp=1;
  3007. break;
  3008. case 108:
  3009. temp=2;
  3010. break;
  3011. case 144:
  3012. temp=3;
  3013. break;
  3014. default:
  3015. temp=4;
  3016. break;
  3017. }
  3018. sizes->setFrame(temp);
  3019. sizes->showAll(to);
  3020. //flags
  3021. int fx = 496 + graphics->fonts[FONT_SMALL]->getStringWidth(CGI->generaltexth->allTexts[390]);
  3022. int ex = 629 + graphics->fonts[FONT_SMALL]->getStringWidth(CGI->generaltexth->allTexts[391]);
  3023. TeamID myT;
  3024. myT = ourHeader->players[playerColor.getNum()].team;
  3025. for (auto i = startInfo.playerInfos.cbegin(); i != startInfo.playerInfos.cend(); i++)
  3026. {
  3027. int *myx = ((i->first == playerColor || ourHeader->players[i->first.getNum()].team == myT) ? &fx : &ex);
  3028. IImage * flag = sFlags->getImage(i->first.getNum(),0);
  3029. flag->draw(to, pos.x + *myx, pos.y + 405);
  3030. *myx += flag->width();
  3031. flag->decreaseRef();
  3032. }
  3033. //difficulty
  3034. diffPics[startInfo.difficulty]->showAll(to);
  3035. CIntObject::show(to);
  3036. }
  3037. void CBonusSelection::updateBonusSelection()
  3038. {
  3039. OBJ_CONSTRUCTION_CAPTURING_ALL;
  3040. //graphics:
  3041. //spell - SPELLBON.DEF
  3042. //monster - TWCRPORT.DEF
  3043. //building - BO*.BMP graphics
  3044. //artifact - ARTIFBON.DEF
  3045. //spell scroll - SPELLBON.DEF
  3046. //prim skill - PSKILBON.DEF
  3047. //sec skill - SSKILBON.DEF
  3048. //resource - BORES.DEF
  3049. //player - CREST58.DEF
  3050. //hero - PORTRAITSLARGE (HPL###.BMPs)
  3051. const CCampaignScenario &scenario = ourCampaign->camp->scenarios[selectedMap];
  3052. const std::vector<CScenarioTravel::STravelBonus> & bonDescs = scenario.travelOptions.bonusesToChoose;
  3053. updateStartButtonState(-1);
  3054. delete bonuses;
  3055. bonuses = new CToggleGroup(std::bind(&CBonusSelection::selectBonus, this, _1));
  3056. static const char *bonusPics[] = {"SPELLBON.DEF", "TWCRPORT.DEF", "", "ARTIFBON.DEF", "SPELLBON.DEF",
  3057. "PSKILBON.DEF", "SSKILBON.DEF", "BORES.DEF", "PORTRAITSLARGE", "PORTRAITSLARGE"};
  3058. for(int i = 0; i < bonDescs.size(); i++)
  3059. {
  3060. std::string picName=bonusPics[bonDescs[i].type];
  3061. size_t picNumber=bonDescs[i].info2;
  3062. std::string desc;
  3063. switch(bonDescs[i].type)
  3064. {
  3065. case CScenarioTravel::STravelBonus::SPELL:
  3066. desc = CGI->generaltexth->allTexts[715];
  3067. boost::algorithm::replace_first(desc, "%s", CGI->spellh->objects[bonDescs[i].info2]->name);
  3068. break;
  3069. case CScenarioTravel::STravelBonus::MONSTER:
  3070. picNumber = bonDescs[i].info2 + 2;
  3071. desc = CGI->generaltexth->allTexts[717];
  3072. boost::algorithm::replace_first(desc, "%d", boost::lexical_cast<std::string>(bonDescs[i].info3));
  3073. boost::algorithm::replace_first(desc, "%s", CGI->creh->creatures[bonDescs[i].info2]->namePl);
  3074. break;
  3075. case CScenarioTravel::STravelBonus::BUILDING:
  3076. {
  3077. int faction = -1;
  3078. for(auto & elem : startInfo.playerInfos)
  3079. {
  3080. if (elem.second.playerID)
  3081. {
  3082. faction = elem.second.castle;
  3083. break;
  3084. }
  3085. }
  3086. assert(faction != -1);
  3087. BuildingID buildID = CBuildingHandler::campToERMU(bonDescs[i].info1, faction, std::set<BuildingID>());
  3088. picName = graphics->ERMUtoPicture[faction][buildID];
  3089. picNumber = -1;
  3090. if (vstd::contains(CGI->townh->factions[faction]->town->buildings, buildID))
  3091. desc = CGI->townh->factions[faction]->town->buildings.find(buildID)->second->Name();
  3092. }
  3093. break;
  3094. case CScenarioTravel::STravelBonus::ARTIFACT:
  3095. desc = CGI->generaltexth->allTexts[715];
  3096. boost::algorithm::replace_first(desc, "%s", CGI->arth->artifacts[bonDescs[i].info2]->Name());
  3097. break;
  3098. case CScenarioTravel::STravelBonus::SPELL_SCROLL:
  3099. desc = CGI->generaltexth->allTexts[716];
  3100. boost::algorithm::replace_first(desc, "%s", CGI->spellh->objects[bonDescs[i].info2]->name);
  3101. break;
  3102. case CScenarioTravel::STravelBonus::PRIMARY_SKILL:
  3103. {
  3104. int leadingSkill = -1;
  3105. std::vector<std::pair<int, int> > toPrint; //primary skills to be listed <num, val>
  3106. const ui8* ptr = reinterpret_cast<const ui8*>(&bonDescs[i].info2);
  3107. for (int g=0; g<GameConstants::PRIMARY_SKILLS; ++g)
  3108. {
  3109. if (leadingSkill == -1 || ptr[g] > ptr[leadingSkill])
  3110. {
  3111. leadingSkill = g;
  3112. }
  3113. if (ptr[g] != 0)
  3114. {
  3115. toPrint.push_back(std::make_pair(g, ptr[g]));
  3116. }
  3117. }
  3118. picNumber = leadingSkill;
  3119. desc = CGI->generaltexth->allTexts[715];
  3120. std::string substitute; //text to be printed instead of %s
  3121. for (int v=0; v<toPrint.size(); ++v)
  3122. {
  3123. substitute += boost::lexical_cast<std::string>(toPrint[v].second);
  3124. substitute += " " + CGI->generaltexth->primarySkillNames[toPrint[v].first];
  3125. if(v != toPrint.size() - 1)
  3126. {
  3127. substitute += ", ";
  3128. }
  3129. }
  3130. boost::algorithm::replace_first(desc, "%s", substitute);
  3131. break;
  3132. }
  3133. case CScenarioTravel::STravelBonus::SECONDARY_SKILL:
  3134. desc = CGI->generaltexth->allTexts[718];
  3135. boost::algorithm::replace_first(desc, "%s", CGI->generaltexth->levels[bonDescs[i].info3 - 1]); //skill level
  3136. boost::algorithm::replace_first(desc, "%s", CGI->generaltexth->skillName[bonDescs[i].info2]); //skill name
  3137. picNumber = bonDescs[i].info2 * 3 + bonDescs[i].info3 - 1;
  3138. break;
  3139. case CScenarioTravel::STravelBonus::RESOURCE:
  3140. {
  3141. int serialResID = 0;
  3142. switch(bonDescs[i].info1)
  3143. {
  3144. case 0: case 1: case 2: case 3: case 4: case 5: case 6:
  3145. serialResID = bonDescs[i].info1;
  3146. break;
  3147. case 0xFD: //wood + ore
  3148. serialResID = 7;
  3149. break;
  3150. case 0xFE: //rare resources
  3151. serialResID = 8;
  3152. break;
  3153. }
  3154. picNumber = serialResID;
  3155. desc = CGI->generaltexth->allTexts[717];
  3156. boost::algorithm::replace_first(desc, "%d", boost::lexical_cast<std::string>(bonDescs[i].info2));
  3157. std::string replacement;
  3158. if (serialResID <= 6)
  3159. {
  3160. replacement = CGI->generaltexth->restypes[serialResID];
  3161. }
  3162. else
  3163. {
  3164. replacement = CGI->generaltexth->allTexts[714 + serialResID];
  3165. }
  3166. boost::algorithm::replace_first(desc, "%s", replacement);
  3167. }
  3168. break;
  3169. case CScenarioTravel::STravelBonus::HEROES_FROM_PREVIOUS_SCENARIO:
  3170. {
  3171. auto superhero = ourCampaign->camp->scenarios[bonDescs[i].info2].strongestHero(PlayerColor(bonDescs[i].info1));
  3172. if (!superhero) logGlobal->warnStream() << "No superhero! How could it be transferred?";
  3173. picNumber = superhero ? superhero->portrait : 0;
  3174. desc = CGI->generaltexth->allTexts[719];
  3175. boost::algorithm::replace_first(desc, "%s", ourCampaign->camp->scenarios[bonDescs[i].info2].scenarioName); //scenario
  3176. }
  3177. break;
  3178. case CScenarioTravel::STravelBonus::HERO:
  3179. desc = CGI->generaltexth->allTexts[718];
  3180. boost::algorithm::replace_first(desc, "%s", CGI->generaltexth->capColors[bonDescs[i].info1]); //hero's color
  3181. if (bonDescs[i].info2 == 0xFFFF)
  3182. {
  3183. boost::algorithm::replace_first(desc, "%s", CGI->generaltexth->allTexts[101]); //hero's name
  3184. picNumber = -1;
  3185. picName = "CBONN1A3.BMP";
  3186. }
  3187. else
  3188. {
  3189. boost::algorithm::replace_first(desc, "%s", CGI->heroh->heroes[bonDescs[i].info2]->name); //hero's name
  3190. }
  3191. break;
  3192. }
  3193. CToggleButton *bonusButton = new CToggleButton(Point(475 + i*68, 455), "", CButton::tooltip(desc, desc));
  3194. if (picNumber != -1)
  3195. picName += ":" + boost::lexical_cast<std::string>(picNumber);
  3196. auto anim = std::make_shared<CAnimation>();
  3197. anim->setCustom(picName, 0);
  3198. bonusButton->setImage(anim);
  3199. const SDL_Color brightYellow = { 242, 226, 110, 0 };
  3200. bonusButton->borderColor = brightYellow;
  3201. bonuses->addToggle(i, bonusButton);
  3202. }
  3203. // set bonus if already chosen
  3204. if(vstd::contains(ourCampaign->chosenCampaignBonuses, selectedMap))
  3205. {
  3206. bonuses->setSelected(ourCampaign->chosenCampaignBonuses[selectedMap]);
  3207. }
  3208. }
  3209. void CBonusSelection::updateCampaignState()
  3210. {
  3211. ourCampaign->currentMap = selectedMap;
  3212. if (selectedBonus)
  3213. ourCampaign->chosenCampaignBonuses[selectedMap] = *selectedBonus;
  3214. }
  3215. void CBonusSelection::startMap()
  3216. {
  3217. auto si = new StartInfo(startInfo);
  3218. auto showPrologVideo = [=]()
  3219. {
  3220. auto exitCb = [=]()
  3221. {
  3222. logGlobal->infoStream() << "Starting scenario " << selectedMap;
  3223. CGP->showLoadingScreen(std::bind(&startGame, si, (CConnection *)nullptr));
  3224. };
  3225. const CCampaignScenario & scenario = ourCampaign->camp->scenarios[selectedMap];
  3226. if (scenario.prolog.hasPrologEpilog)
  3227. {
  3228. GH.pushInt(new CPrologEpilogVideo(scenario.prolog, exitCb));
  3229. }
  3230. else
  3231. {
  3232. exitCb();
  3233. }
  3234. };
  3235. if(LOCPLINT) // we're currently ingame, so ask for starting new map and end game
  3236. {
  3237. GH.popInt(this);
  3238. LOCPLINT->showYesNoDialog(CGI->generaltexth->allTexts[67], [=]
  3239. {
  3240. updateCampaignState();
  3241. endGame();
  3242. GH.curInt = CGPreGame::create();
  3243. showPrologVideo();
  3244. }, 0);
  3245. }
  3246. else
  3247. {
  3248. updateCampaignState();
  3249. showPrologVideo();
  3250. }
  3251. }
  3252. void CBonusSelection::restartMap()
  3253. {
  3254. GH.popInt(this);
  3255. LOCPLINT->showYesNoDialog(CGI->generaltexth->allTexts[67], [=]
  3256. {
  3257. updateCampaignState();
  3258. auto si = new StartInfo(startInfo);
  3259. SDL_Event event;
  3260. event.type = SDL_USEREVENT;
  3261. event.user.code = PREPARE_RESTART_CAMPAIGN;
  3262. event.user.data1 = si;
  3263. SDL_PushEvent(&event);
  3264. }, 0);
  3265. }
  3266. void CBonusSelection::selectBonus(int id)
  3267. {
  3268. // Total redraw is needed because the border around the bonus images
  3269. // have to be undrawn/drawn.
  3270. if (!selectedBonus || *selectedBonus != id)
  3271. {
  3272. selectedBonus = id;
  3273. GH.totalRedraw();
  3274. updateStartButtonState(id);
  3275. }
  3276. const CCampaignScenario &scenario = ourCampaign->camp->scenarios[selectedMap];
  3277. const std::vector<CScenarioTravel::STravelBonus> & bonDescs = scenario.travelOptions.bonusesToChoose;
  3278. if (bonDescs[id].type == CScenarioTravel::STravelBonus::HERO)
  3279. {
  3280. std::map<ui8, std::string> names;
  3281. names[1] = settings["general"]["playerName"].String();
  3282. for(auto & elem : startInfo.playerInfos)
  3283. {
  3284. if(elem.first == PlayerColor(bonDescs[id].info1))
  3285. ::setPlayer(elem.second, 1, names);
  3286. else
  3287. ::setPlayer(elem.second, 0, names);
  3288. }
  3289. }
  3290. }
  3291. void CBonusSelection::increaseDifficulty()
  3292. {
  3293. startInfo.difficulty = std::min(startInfo.difficulty + 1, 4);
  3294. }
  3295. void CBonusSelection::decreaseDifficulty()
  3296. {
  3297. startInfo.difficulty = std::max(startInfo.difficulty - 1, 0);
  3298. }
  3299. void CBonusSelection::updateStartButtonState(int selected)
  3300. {
  3301. if(selected == -1)
  3302. {
  3303. startB->block(ourCampaign->camp->scenarios[selectedMap].travelOptions.bonusesToChoose.size());
  3304. }
  3305. else if(startB->isBlocked())
  3306. {
  3307. startB->block(false);
  3308. }
  3309. }
  3310. CBonusSelection::CRegion::CRegion( CBonusSelection * _owner, bool _accessible, bool _selectable, int _myNumber )
  3311. : owner(_owner), accessible(_accessible), selectable(_selectable), myNumber(_myNumber)
  3312. {
  3313. OBJ_CONSTRUCTION;
  3314. addUsedEvents(LCLICK | RCLICK);
  3315. static const std::string colors[2][8] = {
  3316. {"R", "B", "N", "G", "O", "V", "T", "P"},
  3317. {"Re", "Bl", "Br", "Gr", "Or", "Vi", "Te", "Pi"}};
  3318. const SCampPositions & campDsc = owner->campDescriptions[owner->ourCampaign->camp->header.mapVersion];
  3319. const SCampPositions::SRegionDesc & desc = campDsc.regions[myNumber];
  3320. pos.x += desc.xpos;
  3321. pos.y += desc.ypos;
  3322. //loading of graphics
  3323. std::string prefix = campDsc.campPrefix + desc.infix + "_";
  3324. std::string suffix = colors[campDsc.colorSuffixLength - 1][owner->ourCampaign->camp->scenarios[myNumber].regionColor];
  3325. static const std::string infix [] = {"En", "Se", "Co"};
  3326. for (int g = 0; g < ARRAY_COUNT(infix); g++)
  3327. {
  3328. graphics[g] = BitmapHandler::loadBitmap(prefix + infix[g] + suffix + ".BMP");
  3329. }
  3330. pos.w = graphics[0]->w;
  3331. pos.h = graphics[0]->h;
  3332. }
  3333. CBonusSelection::CRegion::~CRegion()
  3334. {
  3335. for (auto & elem : graphics)
  3336. {
  3337. SDL_FreeSurface(elem);
  3338. }
  3339. }
  3340. void CBonusSelection::CRegion::clickLeft( tribool down, bool previousState )
  3341. {
  3342. //select if selectable & clicked inside our graphic
  3343. if ( indeterminate(down) )
  3344. {
  3345. return;
  3346. }
  3347. if( !down && selectable && !CSDL_Ext::isTransparent(graphics[0], GH.current->motion.x-pos.x, GH.current->motion.y-pos.y) )
  3348. {
  3349. owner->selectMap(myNumber, false);
  3350. owner->highlightedRegion = this;
  3351. parent->showAll(screen);
  3352. }
  3353. }
  3354. void CBonusSelection::CRegion::clickRight( tribool down, bool previousState )
  3355. {
  3356. //show r-click text
  3357. if( down && !CSDL_Ext::isTransparent(graphics[0], GH.current->motion.x-pos.x, GH.current->motion.y-pos.y) &&
  3358. rclickText.size() )
  3359. {
  3360. CRClickPopup::createAndPush(rclickText);
  3361. }
  3362. }
  3363. void CBonusSelection::CRegion::show(SDL_Surface * to)
  3364. {
  3365. //const SCampPositions::SRegionDesc & desc = owner->campDescriptions[owner->ourCampaign->camp->header.mapVersion].regions[myNumber];
  3366. if (!accessible)
  3367. {
  3368. //show as striped
  3369. blitAtLoc(graphics[2], 0, 0, to);
  3370. }
  3371. else if (this == owner->highlightedRegion)
  3372. {
  3373. //show as selected
  3374. blitAtLoc(graphics[1], 0, 0, to);
  3375. }
  3376. else
  3377. {
  3378. //show as not selected selected
  3379. blitAtLoc(graphics[0], 0, 0, to);
  3380. }
  3381. }
  3382. CSavingScreen::CSavingScreen(bool hotseat)
  3383. : CSelectionScreen(
  3384. CMenuScreen::saveGame,
  3385. hotseat ? CMenuScreen::MULTI_HOT_SEAT : (LOCPLINT->cb->getStartInfo()->mode == StartInfo::CAMPAIGN ? CMenuScreen::SINGLE_CAMPAIGN : CMenuScreen::SINGLE_PLAYER)
  3386. )
  3387. {
  3388. ourGame = mapInfoFromGame();
  3389. sInfo = *LOCPLINT->cb->getStartInfo();
  3390. setPlayersFromGame();
  3391. }
  3392. CSavingScreen::~CSavingScreen()
  3393. {
  3394. }
  3395. ISelectionScreenInfo::ISelectionScreenInfo(const std::map<ui8, std::string> * Names)
  3396. {
  3397. gameMode = CMenuScreen::SINGLE_PLAYER;
  3398. screenType = CMenuScreen::mainMenu;
  3399. assert(!SEL);
  3400. SEL = this;
  3401. current = nullptr;
  3402. if(Names && !Names->empty()) //if have custom set of player names - use it
  3403. playerNames = *Names;
  3404. else
  3405. playerNames[1] = settings["general"]["playerName"].String(); //by default we have only one player and his name is "Player" (or whatever the last used name was)
  3406. }
  3407. ISelectionScreenInfo::~ISelectionScreenInfo()
  3408. {
  3409. assert(SEL == this);
  3410. SEL = nullptr;
  3411. }
  3412. void ISelectionScreenInfo::updateStartInfo(std::string filename, StartInfo & sInfo, const std::unique_ptr<CMapHeader> & mapHeader)
  3413. {
  3414. ::updateStartInfo(filename, sInfo, mapHeader, playerNames);
  3415. }
  3416. void ISelectionScreenInfo::setPlayer(PlayerSettings &pset, ui8 player)
  3417. {
  3418. ::setPlayer(pset, player, playerNames);
  3419. }
  3420. ui8 ISelectionScreenInfo::getIdOfFirstUnallocatedPlayer()
  3421. {
  3422. for(auto i = playerNames.cbegin(); i != playerNames.cend(); i++)
  3423. if(!sInfo.getPlayersSettings(i->first)) //
  3424. return i->first;
  3425. return 0;
  3426. }
  3427. bool ISelectionScreenInfo::isGuest() const
  3428. {
  3429. return gameMode == CMenuScreen::MULTI_NETWORK_GUEST;
  3430. }
  3431. bool ISelectionScreenInfo::isHost() const
  3432. {
  3433. return gameMode == CMenuScreen::MULTI_NETWORK_HOST;
  3434. }
  3435. void ChatMessage::apply(CSelectionScreen *selScreen)
  3436. {
  3437. selScreen->card->chat->addNewMessage(playerName + ": " + message);
  3438. GH.totalRedraw();
  3439. }
  3440. void QuitMenuWithoutStarting::apply(CSelectionScreen *selScreen)
  3441. {
  3442. if(!selScreen->ongoingClosing)
  3443. {
  3444. *selScreen->serv << this; //resend to confirm
  3445. GH.popIntTotally(selScreen); //will wait with deleting us before this thread ends
  3446. }
  3447. vstd::clear_pointer(selScreen->serv);
  3448. }
  3449. void PlayerJoined::apply(CSelectionScreen *selScreen)
  3450. {
  3451. //assert(SEL->playerNames.size() == connectionID); //temporary, TODO when player exits
  3452. SEL->playerNames[connectionID] = playerName;
  3453. //put new player in first slot with AI
  3454. for(auto & elem : SEL->sInfo.playerInfos)
  3455. {
  3456. if(!elem.second.playerID && !elem.second.compOnly)
  3457. {
  3458. selScreen->setPlayer(elem.second, connectionID);
  3459. selScreen->opt->entries[elem.second.color]->selectButtons();
  3460. break;
  3461. }
  3462. }
  3463. selScreen->propagateNames();
  3464. selScreen->propagateOptions();
  3465. selScreen->toggleTab(selScreen->curTab);
  3466. GH.totalRedraw();
  3467. }
  3468. void SelectMap::apply(CSelectionScreen *selScreen)
  3469. {
  3470. if(selScreen->isGuest())
  3471. {
  3472. free = false;
  3473. selScreen->changeSelection(mapInfo);
  3474. }
  3475. }
  3476. void UpdateStartOptions::apply(CSelectionScreen *selScreen)
  3477. {
  3478. if(!selScreen->isGuest())
  3479. return;
  3480. selScreen->setSInfo(*options);
  3481. }
  3482. void PregameGuiAction::apply(CSelectionScreen *selScreen)
  3483. {
  3484. if(!selScreen->isGuest())
  3485. return;
  3486. switch(action)
  3487. {
  3488. case NO_TAB:
  3489. selScreen->toggleTab(selScreen->curTab);
  3490. break;
  3491. case OPEN_OPTIONS:
  3492. selScreen->toggleTab(selScreen->opt);
  3493. break;
  3494. case OPEN_SCENARIO_LIST:
  3495. selScreen->toggleTab(selScreen->sel);
  3496. break;
  3497. case OPEN_RANDOM_MAP_OPTIONS:
  3498. selScreen->toggleTab(selScreen->randMapTab);
  3499. break;
  3500. }
  3501. }
  3502. void RequestOptionsChange::apply(CSelectionScreen *selScreen)
  3503. {
  3504. if(!selScreen->isHost())
  3505. return;
  3506. PlayerColor color = selScreen->sInfo.getPlayersSettings(playerID)->color;
  3507. switch(what)
  3508. {
  3509. case TOWN:
  3510. selScreen->opt->nextCastle(color, direction);
  3511. break;
  3512. case HERO:
  3513. selScreen->opt->nextHero(color, direction);
  3514. break;
  3515. case BONUS:
  3516. selScreen->opt->nextBonus(color, direction);
  3517. break;
  3518. }
  3519. }
  3520. void PlayerLeft::apply(CSelectionScreen *selScreen)
  3521. {
  3522. if(selScreen->isGuest())
  3523. return;
  3524. SEL->playerNames.erase(playerID);
  3525. if(PlayerSettings *s = selScreen->sInfo.getPlayersSettings(playerID)) //it's possible that player was unallocated
  3526. {
  3527. selScreen->setPlayer(*s, 0);
  3528. selScreen->opt->entries[s->color]->selectButtons();
  3529. }
  3530. selScreen->propagateNames();
  3531. selScreen->propagateOptions();
  3532. GH.totalRedraw();
  3533. }
  3534. void PlayersNames::apply(CSelectionScreen *selScreen)
  3535. {
  3536. if(selScreen->isGuest())
  3537. selScreen->playerNames = playerNames;
  3538. }
  3539. void StartWithCurrentSettings::apply(CSelectionScreen *selScreen)
  3540. {
  3541. startingInfo.reset();
  3542. startingInfo.serv = selScreen->serv;
  3543. startingInfo.sInfo = new StartInfo(selScreen->sInfo);
  3544. if(!selScreen->ongoingClosing)
  3545. {
  3546. *selScreen->serv << this; //resend to confirm
  3547. }
  3548. selScreen->serv = nullptr; //hide it so it won't be deleted
  3549. vstd::clear_pointer(selScreen->serverHandlingThread); //detach us
  3550. saveGameName.clear();
  3551. CGP->showLoadingScreen(std::bind(&startGame, startingInfo.sInfo, startingInfo.serv));
  3552. throw 666; //EVIL, EVIL, EVIL workaround to kill thread (does "goto catch" outside listening loop)
  3553. }
  3554. CCampaignScreen::CCampaignButton::CCampaignButton(const JsonNode &config )
  3555. {
  3556. OBJ_CONSTRUCTION_CAPTURING_ALL;
  3557. pos.x += config["x"].Float();
  3558. pos.y += config["y"].Float();
  3559. pos.w = 200;
  3560. pos.h = 116;
  3561. campFile = config["file"].String();
  3562. video = config["video"].String();
  3563. status = config["open"].Bool() ? CCampaignScreen::ENABLED : CCampaignScreen::DISABLED;
  3564. CCampaignHeader header = CCampaignHandler::getHeader(campFile);
  3565. hoverText = header.name;
  3566. hoverLabel = nullptr;
  3567. if (status != CCampaignScreen::DISABLED)
  3568. {
  3569. addUsedEvents(LCLICK | HOVER);
  3570. new CPicture(config["image"].String());
  3571. hoverLabel = new CLabel(pos.w / 2, pos.h + 20, FONT_MEDIUM, CENTER, Colors::YELLOW, "");
  3572. parent->addChild(hoverLabel);
  3573. }
  3574. if (status == CCampaignScreen::COMPLETED)
  3575. new CPicture("CAMPCHK");
  3576. }
  3577. void CCampaignScreen::CCampaignButton::clickLeft(tribool down, bool previousState)
  3578. {
  3579. if (down)
  3580. {
  3581. // Close running video and open the selected campaign
  3582. CCS->videoh->close();
  3583. GH.pushInt( new CBonusSelection(campFile) );
  3584. }
  3585. }
  3586. void CCampaignScreen::CCampaignButton::hover(bool on)
  3587. {
  3588. if (hoverLabel)
  3589. {
  3590. if (on)
  3591. hoverLabel->setText(hoverText); // Shows the name of the campaign when you get into the bounds of the button
  3592. else
  3593. hoverLabel->setText(" ");
  3594. }
  3595. }
  3596. void CCampaignScreen::CCampaignButton::show(SDL_Surface * to)
  3597. {
  3598. if (status == CCampaignScreen::DISABLED)
  3599. return;
  3600. CIntObject::show(to);
  3601. // Play the campaign button video when the mouse cursor is placed over the button
  3602. if (hovered)
  3603. {
  3604. if (CCS->videoh->fname != video)
  3605. CCS->videoh->open(video);
  3606. CCS->videoh->update(pos.x, pos.y, to, true, false); // plays sequentially frame by frame, starts at the beginning when the video is over
  3607. }
  3608. else if (CCS->videoh->fname == video) // When you got out of the bounds of the button then close the video
  3609. {
  3610. CCS->videoh->close();
  3611. redraw();
  3612. }
  3613. }
  3614. CButton* CCampaignScreen::createExitButton(const JsonNode& button)
  3615. {
  3616. std::pair<std::string, std::string> help;
  3617. if (!button["help"].isNull() && button["help"].Float() > 0)
  3618. help = CGI->generaltexth->zelp[button["help"].Float()];
  3619. std::function<void()> close = std::bind(&CGuiHandler::popIntTotally, &GH, this);
  3620. return new CButton(Point(button["x"].Float(), button["y"].Float()), button["name"].String(), help, close, button["hotkey"].Float());
  3621. }
  3622. CCampaignScreen::CCampaignScreen(const JsonNode &config)
  3623. {
  3624. OBJ_CONSTRUCTION_CAPTURING_ALL;
  3625. for(const JsonNode& node : config["images"].Vector())
  3626. images.push_back(createPicture(node));
  3627. if (!images.empty())
  3628. {
  3629. images[0]->center(); // move background to center
  3630. moveTo(images[0]->pos.topLeft()); // move everything else to center
  3631. images[0]->moveTo(pos.topLeft()); // restore moved twice background
  3632. pos = images[0]->pos; // fix height\width of this window
  3633. }
  3634. if (!config["exitbutton"].isNull())
  3635. {
  3636. CButton * back = createExitButton(config["exitbutton"]);
  3637. back->hoverable = true;
  3638. }
  3639. for(const JsonNode& node : config["items"].Vector())
  3640. campButtons.push_back(new CCampaignButton(node));
  3641. }
  3642. void CCampaignScreen::showAll(SDL_Surface *to)
  3643. {
  3644. CIntObject::showAll(to);
  3645. if (pos.h != to->h || pos.w != to->w)
  3646. CMessage::drawBorder(PlayerColor(1), to, pos.w+28, pos.h+30, pos.x-14, pos.y-15);
  3647. }
  3648. void CGPreGame::showLoadingScreen(std::function<void()> loader)
  3649. {
  3650. if (GH.listInt.size() && GH.listInt.front() == CGP) //pregame active
  3651. CGP->removeFromGui();
  3652. GH.pushInt(new CLoadingScreen(loader));
  3653. }
  3654. std::string CLoadingScreen::getBackground()
  3655. {
  3656. const auto & conf = CGPreGameConfig::get().getConfig()["loading"].Vector();
  3657. if(conf.empty())
  3658. {
  3659. return "loadbar";
  3660. }
  3661. else
  3662. {
  3663. return RandomGeneratorUtil::nextItem(conf, CRandomGenerator::getDefault())->String();
  3664. }
  3665. }
  3666. CLoadingScreen::CLoadingScreen(std::function<void ()> loader):
  3667. CWindowObject(BORDERED, getBackground()),
  3668. loadingThread(loader)
  3669. {
  3670. CCS->musich->stopMusic(5000);
  3671. }
  3672. CLoadingScreen::~CLoadingScreen()
  3673. {
  3674. loadingThread.join();
  3675. }
  3676. void CLoadingScreen::showAll(SDL_Surface *to)
  3677. {
  3678. Rect rect(0,0,to->w, to->h);
  3679. SDL_FillRect(to, &rect, 0);
  3680. CWindowObject::showAll(to);
  3681. }
  3682. CPrologEpilogVideo::CPrologEpilogVideo( CCampaignScenario::SScenarioPrologEpilog _spe, std::function<void()> callback ):
  3683. CWindowObject(BORDERED),
  3684. spe(_spe),
  3685. positionCounter(0),
  3686. voiceSoundHandle(-1),
  3687. exitCb(callback)
  3688. {
  3689. OBJ_CONSTRUCTION_CAPTURING_ALL;
  3690. addUsedEvents(LCLICK);
  3691. pos = center(Rect(0,0, 800, 600));
  3692. updateShadow();
  3693. CCS->videoh->open(CCampaignHandler::prologVideoName(spe.prologVideo));
  3694. CCS->musich->playMusic("Music/" + CCampaignHandler::prologMusicName(spe.prologMusic), true);
  3695. voiceSoundHandle = CCS->soundh->playSound(CCampaignHandler::prologVoiceName(spe.prologVideo));
  3696. text = new CMultiLineLabel(Rect(100, 500, 600, 100), EFonts::FONT_BIG, CENTER, Colors::METALLIC_GOLD, spe.prologText );
  3697. text->scrollTextTo(-100);
  3698. }
  3699. void CPrologEpilogVideo::show( SDL_Surface * to )
  3700. {
  3701. CSDL_Ext::fillRectBlack(to, &pos);
  3702. //BUG: some videos are 800x600 in size while some are 800x400
  3703. //VCMI should center them in the middle of the screen. Possible but needs modification
  3704. //of video player API which I'd like to avoid until we'll get rid of Windows-specific player
  3705. CCS->videoh->update(pos.x, pos.y, to, true, false);
  3706. //move text every 5 calls/frames; seems to be good enough
  3707. ++positionCounter;
  3708. if(positionCounter % 5 == 0)
  3709. {
  3710. text->scrollTextBy(1);
  3711. }
  3712. else
  3713. text->showAll(to);// blit text over video, if needed
  3714. if (text->textSize.y + 100 < positionCounter / 5)
  3715. clickLeft(false, false);
  3716. }
  3717. void CPrologEpilogVideo::clickLeft( tribool down, bool previousState )
  3718. {
  3719. GH.popInt(this);
  3720. CCS->soundh->stopSound(voiceSoundHandle);
  3721. exitCb();
  3722. }
  3723. CSimpleJoinScreen::CSimpleJoinScreen(CMenuScreen::EGameMode mode)
  3724. {
  3725. OBJ_CONSTRUCTION_CAPTURING_ALL;
  3726. bg = new CPicture("MUDIALOG.bmp"); // address background
  3727. pos = bg->center(); //center, window has size of bg graphic (x,y = 396,278 w=232 h=212)
  3728. Rect boxRect(20, 20, 205, 50);
  3729. title = new CTextBox("Enter address:", boxRect, 0, FONT_BIG, CENTER, Colors::WHITE);
  3730. address = new CTextInput(Rect(25, 68, 175, 16), *bg);
  3731. address->cb += std::bind(&CSimpleJoinScreen::onChange, this, _1);
  3732. port = new CTextInput(Rect(25, 115, 175, 16), *bg);
  3733. port->cb += std::bind(&CSimpleJoinScreen::onChange, this, _1);
  3734. port->filters += std::bind(&CTextInput::numberFilter, _1, _2, 0, 65535);
  3735. ok = new CButton(Point( 26, 142), "MUBCHCK.DEF", CGI->generaltexth->zelp[560], std::bind(&CSimpleJoinScreen::enterSelectionScreen, this, mode), SDLK_RETURN);
  3736. cancel = new CButton(Point(142, 142), "MUBCANC.DEF", CGI->generaltexth->zelp[561], std::bind(&CGuiHandler::popIntTotally, std::ref(GH), this), SDLK_ESCAPE);
  3737. bar = new CGStatusBar(new CPicture(Rect(7, 186, 218, 18), 0));
  3738. port->setText(CServerHandler::getDefaultPortStr(), true);
  3739. address->setText(settings["server"]["server"].String(), true);
  3740. address->giveFocus();
  3741. }
  3742. void CSimpleJoinScreen::enterSelectionScreen(CMenuScreen::EGameMode mode)
  3743. {
  3744. std::string textAddress = address->text;
  3745. std::string textPort = port->text;
  3746. GH.popIntTotally(this);
  3747. GH.pushInt(new CSelectionScreen(CMenuScreen::newGame, mode, nullptr, textAddress, boost::lexical_cast<ui16>(textPort)));
  3748. }
  3749. void CSimpleJoinScreen::onChange(const std::string & newText)
  3750. {
  3751. ok->block(address->text.empty() || port->text.empty());
  3752. }