CGameHandler.cpp 65 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361
  1. #include "../StartInfo.h"
  2. #include "../hch/CArtHandler.h"
  3. #include "../hch/CBuildingHandler.h"
  4. #include "../hch/CDefObjInfoHandler.h"
  5. #include "../hch/CGeneralTextHandler.h"
  6. #include "../hch/CHeroHandler.h"
  7. #include "../hch/CObjectHandler.h"
  8. #include "../hch/CSpellHandler.h"
  9. #include "../hch/CTownHandler.h"
  10. #include "../CGameState.h"
  11. #include "../lib/CondSh.h"
  12. #include "../lib/NetPacks.h"
  13. #include "../lib/Connection.h"
  14. #include "../lib/VCMI_Lib.h"
  15. #include "../map.h"
  16. #include "CGameHandler.h"
  17. #include <boost/bind.hpp>
  18. #include <boost/date_time/posix_time/posix_time_types.hpp> //no i/o just types
  19. #include <boost/foreach.hpp>
  20. #include <boost/thread.hpp>
  21. #include <boost/thread/shared_mutex.hpp>
  22. #include <fstream>
  23. #undef DLL_EXPORT
  24. #define DLL_EXPORT
  25. #include "../lib/RegisterTypes.cpp"
  26. #ifndef _MSC_VER
  27. #include <boost/thread/xtime.hpp>
  28. #endif
  29. extern bool end2;
  30. #ifdef min
  31. #undef min
  32. #endif
  33. #ifdef max
  34. #undef max
  35. #endif
  36. #define NEW_ROUND BattleNextRound bnr;\
  37. bnr.round = gs->curB->round + 1;\
  38. sendAndApply(&bnr);
  39. boost::mutex gsm;
  40. ui32 CGameHandler::QID = 1;
  41. CondSh<bool> battleMadeAction;
  42. CondSh<BattleResult *> battleResult(NULL);
  43. std::map<ui32, CFunctionList<void(ui32)> > callbacks; //question id => callback function - for selection dialogs
  44. class CBaseForGHApply
  45. {
  46. public:
  47. virtual void applyOnGH(CGameHandler *gh, CConnection *c, void *pack) const =0;
  48. };
  49. template <typename T> class CApplyOnGH : public CBaseForGHApply
  50. {
  51. public:
  52. void applyOnGH(CGameHandler *gh, CConnection *c, void *pack) const
  53. {
  54. T *ptr = static_cast<T*>(pack);
  55. ptr->c = c;
  56. ptr->applyGh(gh);
  57. }
  58. };
  59. class CGHApplier
  60. {
  61. public:
  62. std::map<ui16,CBaseForGHApply*> apps;
  63. CGHApplier()
  64. {
  65. registerTypes3(*this);
  66. }
  67. template<typename T> void registerType(const T * t=NULL)
  68. {
  69. ui16 ID = typeList.registerType(t);
  70. apps[ID] = new CApplyOnGH<T>;
  71. }
  72. } *applier = NULL;
  73. class CMP_stack
  74. {
  75. public:
  76. inline bool operator ()(const CStack* a, const CStack* b)
  77. {
  78. return (a->speed())>(b->speed());
  79. }
  80. } cmpst ;
  81. double distance(int3 a, int3 b)
  82. {
  83. return std::sqrt( (double)(a.x-b.x)*(a.x-b.x) + (a.y-b.y)*(a.y-b.y) );
  84. }
  85. int getSchoolLevel(const CGHeroInstance *h, const CSpell *s)
  86. {
  87. ui8 ret = 0;
  88. if(s->fire)
  89. ret = std::max(ret,h->getSecSkillLevel(14));
  90. if(s->air)
  91. ret = std::max(ret,h->getSecSkillLevel(15));
  92. if(s->water)
  93. ret = std::max(ret,h->getSecSkillLevel(16));
  94. if(s->earth)
  95. ret = std::max(ret,h->getSecSkillLevel(17));
  96. return ret;
  97. }
  98. void giveExp(BattleResult &r)
  99. {
  100. r.exp[0] = 0;
  101. r.exp[1] = 0;
  102. for(std::set<std::pair<ui32,si32> >::iterator i = r.casualties[!r.winner].begin(); i!=r.casualties[!r.winner].end(); i++)
  103. {
  104. r.exp[r.winner] += VLC->creh->creatures[i->first].hitPoints * i->second;
  105. }
  106. }
  107. PlayerStatus PlayerStatuses::operator[](ui8 player)
  108. {
  109. boost::unique_lock<boost::mutex> l(mx);
  110. if(players.find(player) != players.end())
  111. {
  112. return players[player];
  113. }
  114. else
  115. {
  116. throw std::string("No such player!");
  117. }
  118. }
  119. void PlayerStatuses::addPlayer(ui8 player)
  120. {
  121. boost::unique_lock<boost::mutex> l(mx);
  122. players[player];
  123. }
  124. bool PlayerStatuses::hasQueries(ui8 player)
  125. {
  126. boost::unique_lock<boost::mutex> l(mx);
  127. if(players.find(player) != players.end())
  128. {
  129. return players[player].queries.size();
  130. }
  131. else
  132. {
  133. throw std::string("No such player!");
  134. }
  135. }
  136. bool PlayerStatuses::checkFlag(ui8 player, bool PlayerStatus::*flag)
  137. {
  138. boost::unique_lock<boost::mutex> l(mx);
  139. if(players.find(player) != players.end())
  140. {
  141. return players[player].*flag;
  142. }
  143. else
  144. {
  145. throw std::string("No such player!");
  146. }
  147. }
  148. void PlayerStatuses::setFlag(ui8 player, bool PlayerStatus::*flag, bool val)
  149. {
  150. boost::unique_lock<boost::mutex> l(mx);
  151. if(players.find(player) != players.end())
  152. {
  153. players[player].*flag = val;
  154. }
  155. else
  156. {
  157. throw std::string("No such player!");
  158. }
  159. cv.notify_all();
  160. }
  161. void PlayerStatuses::addQuery(ui8 player, ui32 id)
  162. {
  163. boost::unique_lock<boost::mutex> l(mx);
  164. if(players.find(player) != players.end())
  165. {
  166. players[player].queries.insert(id);
  167. }
  168. else
  169. {
  170. throw std::string("No such player!");
  171. }
  172. cv.notify_all();
  173. }
  174. void PlayerStatuses::removeQuery(ui8 player, ui32 id)
  175. {
  176. boost::unique_lock<boost::mutex> l(mx);
  177. if(players.find(player) != players.end())
  178. {
  179. players[player].queries.erase(id);
  180. }
  181. else
  182. {
  183. throw std::string("No such player!");
  184. }
  185. cv.notify_all();
  186. }
  187. template <typename T>
  188. void callWith(std::vector<T> args, boost::function<void(T)> fun, ui32 which)
  189. {
  190. fun(args[which]);
  191. }
  192. void CGameHandler::changeSecSkill( int ID, int which, int val, bool abs/*=false*/ )
  193. {
  194. SetSecSkill sss;
  195. sss.id = ID;
  196. sss.which = which;
  197. sss.val = val;
  198. sss.abs = abs;
  199. sendAndApply(&sss);
  200. }
  201. void CGameHandler::changePrimSkill(int ID, int which, int val, bool abs)
  202. {
  203. SetPrimSkill sps;
  204. sps.id = ID;
  205. sps.which = which;
  206. sps.abs = abs;
  207. sps.val = val;
  208. sendAndApply(&sps);
  209. if(which==4) //only for exp - hero may level up
  210. {
  211. CGHeroInstance *hero = static_cast<CGHeroInstance *>(gs->map->objects[ID]);
  212. if(hero->exp >= VLC->heroh->reqExp(hero->level+1)) //new level
  213. {
  214. //give prim skill
  215. tlog5 << hero->name <<" got level "<<hero->level<<std::endl;
  216. int r = rand()%100, pom=0, x=0;
  217. int std::pair<int,int>::*g = (hero->level>9) ? (&std::pair<int,int>::second) : (&std::pair<int,int>::first);
  218. for(;x<PRIMARY_SKILLS;x++)
  219. {
  220. pom += hero->type->heroClass->primChance[x].*g;
  221. if(r<pom)
  222. break;
  223. }
  224. tlog5 << "Bohater dostaje umiejetnosc pierwszorzedna " << x << " (wynik losowania "<<r<<")"<<std::endl;
  225. SetPrimSkill sps;
  226. sps.id = ID;
  227. sps.which = x;
  228. sps.abs = false;
  229. sps.val = 1;
  230. sendAndApply(&sps);
  231. HeroLevelUp hlu;
  232. hlu.heroid = ID;
  233. hlu.primskill = x;
  234. hlu.level = hero->level+1;
  235. //picking sec. skills for choice
  236. std::set<int> basicAndAdv, expert, none;
  237. for(int i=0;i<SKILL_QUANTITY;i++) none.insert(i);
  238. for(unsigned i=0;i<hero->secSkills.size();i++)
  239. {
  240. if(hero->secSkills[i].second < 3)
  241. basicAndAdv.insert(hero->secSkills[i].first);
  242. else
  243. expert.insert(hero->secSkills[i].first);
  244. none.erase(hero->secSkills[i].first);
  245. }
  246. //first offered skill
  247. if(hero->secSkills.size() < hero->type->heroClass->skillLimit) //free skill slot
  248. {
  249. hlu.skills.push_back(hero->type->heroClass->chooseSecSkill(none)); //new skill
  250. none.erase(hlu.skills.back());
  251. }
  252. else if(basicAndAdv.size())
  253. {
  254. int s = hero->type->heroClass->chooseSecSkill(basicAndAdv);
  255. hlu.skills.push_back(s);
  256. basicAndAdv.erase(s);
  257. }
  258. //second offered skill
  259. if(basicAndAdv.size())
  260. {
  261. hlu.skills.push_back(hero->type->heroClass->chooseSecSkill(basicAndAdv)); //new skill
  262. }
  263. else if(hero->secSkills.size() < hero->type->heroClass->skillLimit)
  264. {
  265. hlu.skills.push_back(hero->type->heroClass->chooseSecSkill(none)); //new skill
  266. }
  267. if(hlu.skills.size() > 1) //apply and ask for secondary skill
  268. {
  269. boost::function<void(ui32)> callback = boost::function<void(ui32)>(boost::bind(callWith<ui16>,hlu.skills,boost::function<void(ui16)>(boost::bind(&CGameHandler::changeSecSkill,this,ID,_1,1,0)),_1));
  270. applyAndAsk(&hlu,hero->tempOwner,callback); //call changeSecSkill with appropriate args when client responds
  271. }
  272. else if(hlu.skills.size() == 1) //apply, give only possible skill and send info
  273. {
  274. changeSecSkill(ID,hlu.skills.back(),1,false);
  275. sendAndApply(&hlu);
  276. }
  277. else //apply and send info
  278. {
  279. sendAndApply(&hlu);
  280. }
  281. }
  282. }
  283. }
  284. CCreatureSet takeCasualties(int color, const CCreatureSet &set, BattleInfo *bat)
  285. {
  286. CCreatureSet ret(set);
  287. for(int i=0; i<bat->stacks.size();i++)
  288. {
  289. CStack *st = bat->stacks[i];
  290. if(st->owner==color && vstd::contains(set.slots,st->slot) && st->amount < set.slots.find(st->slot)->second.second)
  291. {
  292. if(st->alive())
  293. ret.slots[st->slot].second = st->amount;
  294. else
  295. ret.slots.erase(st->slot);
  296. }
  297. }
  298. return ret;
  299. }
  300. void CGameHandler::startBattle(CCreatureSet army1, CCreatureSet army2, int3 tile, CGHeroInstance *hero1, CGHeroInstance *hero2, boost::function<void(BattleResult*)> cb)
  301. {
  302. BattleInfo *curB = new BattleInfo;
  303. setupBattle(curB, tile, army1, army2, hero1, hero2); //initializes stacks, places creatures on battlefield, blocks and informs player interfaces
  304. NEW_ROUND;
  305. //TODO: pre-tactic stuff, call scripts etc.
  306. //tactic round
  307. {
  308. NEW_ROUND;
  309. if( (hero1 && hero1->getSecSkillLevel(19)>0) ||
  310. ( hero2 && hero2->getSecSkillLevel(19)>0) )//someone has tactics
  311. {
  312. //TODO: tactic round (round -1)
  313. }
  314. }
  315. //main loop
  316. while(!battleResult.get()) //till the end of the battle ;]
  317. {
  318. NEW_ROUND;
  319. std::vector<CStack*> & stacks = (gs->curB->stacks);
  320. const BattleInfo & curB = *gs->curB;
  321. //stack loop
  322. CStack *next;
  323. while(!battleResult.get() && (next=gs->curB->getNextStack()))
  324. {
  325. next->state -= WAITING; //if stack was waiting it'll now make move, so it won't be "waiting" anymore
  326. //check for bad morale => freeze
  327. if(next->Morale() < 0)
  328. {
  329. if( rand()%24 < (-next->Morale())*2 )
  330. {
  331. //unit loses its turn - empty freeze action
  332. BattleAction ba;
  333. ba.actionType = 11;
  334. ba.additionalInfo = 1;
  335. ba.side = !next->attackerOwned;
  336. ba.stackNumber = next->ID;
  337. sendAndApply(&StartAction(ba));
  338. sendAndApply(&EndAction());
  339. checkForBattleEnd(stacks); //check if this "action" ended the battle (not likely but who knows...)
  340. continue;
  341. }
  342. }
  343. askInterfaceForMove:
  344. //ask interface and wait for answer
  345. if(!battleResult.get())
  346. {
  347. BattleSetActiveStack sas;
  348. sas.stack = next->ID;
  349. sendAndApply(&sas);
  350. boost::unique_lock<boost::mutex> lock(battleMadeAction.mx);
  351. while(!battleMadeAction.data && !battleResult.get()) //active stack hasn't made its action and battle is still going
  352. battleMadeAction.cond.wait(lock);
  353. battleMadeAction.data = false;
  354. }
  355. else
  356. {
  357. break;
  358. }
  359. //we're after action, all results applied
  360. checkForBattleEnd(stacks); //check if this action ended the battle
  361. //check for good morale
  362. if(!vstd::contains(next->state,HAD_MORALE) //only one extra move per turn possible
  363. && !vstd::contains(next->state,DEFENDING)
  364. && !vstd::contains(next->state,WAITING)
  365. && next->alive()
  366. && next->Morale() > 0
  367. )
  368. if(rand()%24 < next->Morale()) //this stack hasn't got morale this turn
  369. goto askInterfaceForMove; //move this stack once more
  370. }
  371. }
  372. //unblock engaged players
  373. if(hero1->tempOwner<PLAYER_LIMIT)
  374. states.setFlag(hero1->tempOwner,&PlayerStatus::engagedIntoBattle,false);
  375. if(hero2 && hero2->tempOwner<PLAYER_LIMIT)
  376. states.setFlag(hero2->tempOwner,&PlayerStatus::engagedIntoBattle,false);
  377. //casualties among heroes armies
  378. SetGarrisons sg;
  379. if(hero1)
  380. sg.garrs[hero1->id] = takeCasualties(hero1->tempOwner,hero1->army,gs->curB);
  381. if(hero2)
  382. sg.garrs[hero2->id] = takeCasualties(hero2->tempOwner,hero2->army,gs->curB);
  383. sendAndApply(&sg);
  384. //end battle, remove all info, free memory
  385. giveExp(*battleResult.data);
  386. sendAndApply(battleResult.data);
  387. if(cb)
  388. cb(battleResult.data);
  389. //if one hero has lost we will erase him
  390. if(battleResult.data->winner!=0 && hero1)
  391. {
  392. RemoveObject ro(hero1->id);
  393. sendAndApply(&ro);
  394. }
  395. if(battleResult.data->winner!=1 && hero2)
  396. {
  397. RemoveObject ro(hero2->id);
  398. sendAndApply(&ro);
  399. }
  400. //give exp
  401. if(battleResult.data->exp[0] && hero1)
  402. changePrimSkill(hero1->id,4,battleResult.data->exp[0]);
  403. if(battleResult.data->exp[1] && hero2)
  404. changePrimSkill(hero2->id,4,battleResult.data->exp[1]);
  405. delete battleResult.data;
  406. }
  407. void CGameHandler::prepareAttacked(BattleStackAttacked &bsa, CStack *def)
  408. {
  409. bsa.killedAmount = bsa.damageAmount / def->creature->hitPoints;
  410. unsigned damageFirst = bsa.damageAmount % def->creature->hitPoints;
  411. if( def->firstHPleft <= damageFirst )
  412. {
  413. bsa.killedAmount++;
  414. bsa.newHP = def->firstHPleft + def->creature->hitPoints - damageFirst;
  415. }
  416. else
  417. {
  418. bsa.newHP = def->firstHPleft - damageFirst;
  419. }
  420. if(def->amount <= bsa.killedAmount) //stack killed
  421. {
  422. bsa.newAmount = 0;
  423. bsa.flags |= 1;
  424. bsa.killedAmount = def->amount; //we cannot kill more creatures than we have
  425. }
  426. else
  427. {
  428. bsa.newAmount = def->amount - bsa.killedAmount;
  429. }
  430. }
  431. void CGameHandler::prepareAttack(BattleAttack &bat, CStack *att, CStack *def)
  432. {
  433. bat.bsa.clear();
  434. bat.stackAttacking = att->ID;
  435. std::set<BattleStackAttacked>::iterator i = bat.bsa.insert(BattleStackAttacked()).first;
  436. BattleStackAttacked *bsa = (BattleStackAttacked *) &*i;
  437. bsa->stackAttacked = def->ID;
  438. bsa->damageAmount = BattleInfo::calculateDmg(att, def, gs->getHero(att->attackerOwned ? gs->curB->hero1 : gs->curB->hero2), gs->getHero(def->attackerOwned ? gs->curB->hero1 : gs->curB->hero2), bat.shot());//counting dealt damage
  439. if(att->Luck() > 0 && rand()%24 < att->Luck())
  440. {
  441. bsa->damageAmount *= 2;
  442. bsa->flags |= 4;
  443. }
  444. prepareAttacked(*bsa,def);
  445. }
  446. void CGameHandler::handleConnection(std::set<int> players, CConnection &c)
  447. {
  448. CPack *pack = NULL;
  449. try
  450. {
  451. while(!end2)
  452. {
  453. c >> pack;
  454. tlog5 << "Received client message of type " << typeid(*pack).name() << std::endl;
  455. CBaseForGHApply *apply = applier->apps[typeList.getTypeID(pack)];
  456. if(apply)
  457. {
  458. apply->applyOnGH(this,&c,pack);
  459. tlog5 << "Message successfully applied!\n";
  460. }
  461. else
  462. {
  463. tlog5 << "Message cannot be applied, cannot find applier!\n";
  464. }
  465. delete pack;
  466. pack = NULL;
  467. }
  468. }
  469. HANDLE_EXCEPTION(end2 = true);
  470. handleConEnd:
  471. tlog1 << "Ended handling connection\n";
  472. #undef SPELL_CAST_TEMPLATE_1
  473. }
  474. void CGameHandler::moveStack(int stack, int dest)
  475. {
  476. CStack *curStack = gs->curB->getStack(stack),
  477. *stackAtEnd = gs->curB->getStackT(dest);
  478. //initing necessary tables
  479. bool accessibility[BFIELD_SIZE];
  480. std::vector<int> accessible = gs->curB->getAccessibility(curStack->ID, false);
  481. for(int b=0; b<BFIELD_SIZE; ++b)
  482. {
  483. accessibility[b] = false;
  484. }
  485. for(int g=0; g<accessible.size(); ++g)
  486. {
  487. accessibility[accessible[g]] = true;
  488. }
  489. //shifting destination (if we have double wide stack and we can occupy dest but not be exactly there)
  490. if(!stackAtEnd && curStack->creature->isDoubleWide() && !accessibility[dest])
  491. {
  492. if(curStack->attackerOwned)
  493. {
  494. if(accessibility[dest+1])
  495. dest+=1;
  496. }
  497. else
  498. {
  499. if(accessibility[dest-1])
  500. dest-=1;
  501. }
  502. }
  503. if((stackAtEnd && stackAtEnd!=curStack && stackAtEnd->alive()) || !accessibility[dest])
  504. return;
  505. //if(dists[dest] > curStack->creature->speed && !(stackAtEnd && dists[dest] == curStack->creature->speed+1)) //we can attack a stack if we can go to adjacent hex
  506. // return false;
  507. std::pair< std::vector<int>, int > path = gs->curB->getPath(curStack->position, dest, accessibility, curStack->creature->isFlying());
  508. if(curStack->creature->isFlying())
  509. {
  510. if(path.second <= curStack->speed() && path.first.size() > 0)
  511. {
  512. //inform clients about move
  513. BattleStackMoved sm;
  514. sm.stack = curStack->ID;
  515. sm.tile = path.first[0];
  516. sm.distance = path.second;
  517. sm.ending = true;
  518. sendAndApply(&sm);
  519. }
  520. }
  521. else //for non-flying creatures
  522. {
  523. int tilesToMove = std::max((int)(path.first.size() - curStack->speed()), 0);
  524. for(int v=path.first.size()-1; v>=tilesToMove; --v)
  525. {
  526. //inform clients about move
  527. BattleStackMoved sm;
  528. sm.stack = curStack->ID;
  529. sm.tile = path.first[v];
  530. sm.distance = path.second;
  531. sm.ending = v==tilesToMove;
  532. sendAndApply(&sm);
  533. }
  534. }
  535. }
  536. CGameHandler::CGameHandler(void)
  537. {
  538. gs = NULL;
  539. IObjectInterface::cb = this;
  540. applier = new CGHApplier;
  541. }
  542. CGameHandler::~CGameHandler(void)
  543. {
  544. delete applier;
  545. applier = NULL;
  546. delete gs;
  547. }
  548. void CGameHandler::init(StartInfo *si, int Seed)
  549. {
  550. Mapa *map = new Mapa(si->mapname);
  551. tlog0 << "Map loaded!" << std::endl;
  552. gs = new CGameState();
  553. tlog0 << "Gamestate created!" << std::endl;
  554. gs->init(si,map,Seed);
  555. tlog0 << "Gamestate initialized!" << std::endl;
  556. for(std::map<ui8,PlayerState>::iterator i = gs->players.begin(); i != gs->players.end(); i++)
  557. states.addPlayer(i->first);
  558. }
  559. bool evntCmp(const CMapEvent *a, const CMapEvent *b)
  560. {
  561. return *a < *b;
  562. }
  563. void CGameHandler::newTurn()
  564. {
  565. tlog5 << "Turn " << gs->day+1 << std::endl;
  566. NewTurn n;
  567. n.day = gs->day + 1;
  568. n.resetBuilded = true;
  569. for ( std::map<ui8, PlayerState>::iterator i=gs->players.begin() ; i!=gs->players.end();i++)
  570. {
  571. if(i->first == 255) continue;
  572. if(gs->getDate(1)==7) //first day of week - new heroes in tavern
  573. {
  574. SetAvailableHeroes sah;
  575. sah.player = i->first;
  576. CGHeroInstance *h = gs->hpool.pickHeroFor(true,i->first,&VLC->townh->towns[gs->scenarioOps->getIthPlayersSettings(i->first).castle]);
  577. if(h)
  578. sah.hid1 = h->subID;
  579. else
  580. sah.hid1 = -1;
  581. h = gs->hpool.pickHeroFor(false,i->first,&VLC->townh->towns[gs->scenarioOps->getIthPlayersSettings(i->first).castle],sah.hid1);
  582. if(h)
  583. sah.hid2 = h->subID;
  584. else
  585. sah.hid2 = -1;
  586. sendAndApply(&sah);
  587. }
  588. if(i->first>=PLAYER_LIMIT) continue;
  589. SetResources r;
  590. r.player = i->first;
  591. for(int j=0;j<RESOURCE_QUANTITY;j++)
  592. r.res[j] = i->second.resources[j];
  593. BOOST_FOREACH(CGHeroInstance *h, (*i).second.heroes)
  594. {
  595. NewTurn::Hero hth;
  596. hth.id = h->id;
  597. hth.move = h->maxMovePoints(true); //TODO: check if hero is really on the land
  598. hth.mana = std::max(h->mana,std::min(h->mana+1+h->getSecSkillLevel(8), h->manaLimit())); //hero regains 1 mana point + mysticism lvel
  599. n.heroes.insert(hth);
  600. switch(h->getSecSkillLevel(13)) //handle estates - give gold
  601. {
  602. case 1: //basic
  603. r.res[6] += 125;
  604. break;
  605. case 2: //advanced
  606. r.res[6] += 250;
  607. break;
  608. case 3: //expert
  609. r.res[6] += 500;
  610. break;
  611. }
  612. }
  613. for(std::vector<CGTownInstance *>::iterator j=i->second.towns.begin();j!=i->second.towns.end();j++)//handle towns
  614. {
  615. if(vstd::contains((**j).builtBuildings,15)) //there is resource silo
  616. {
  617. if((**j).town->primaryRes == 127) //we'll give wood and ore
  618. {
  619. r.res[0] += 1;
  620. r.res[2] += 1;
  621. }
  622. else
  623. {
  624. r.res[(**j).town->primaryRes] += 1;
  625. }
  626. }
  627. if(gs->getDate(1)==7) //first day of week
  628. {
  629. SetAvailableCreatures sac;
  630. sac.tid = (**j).id;
  631. sac.creatures = (**j).strInfo.creatures;
  632. for(int k=0;k<CREATURES_PER_TOWN;k++) //creature growths
  633. {
  634. if((**j).creatureDwelling(k))//there is dwelling (k-level)
  635. sac.creatures[k] += (**j).creatureGrowth(k);
  636. }
  637. n.cres.push_back(sac);
  638. }
  639. if((gs->day) && i->first<PLAYER_LIMIT)//not the first day and town not neutral
  640. r.res[6] += (**j).dailyIncome();
  641. }
  642. n.res.push_back(r);
  643. }
  644. sendAndApply(&n);
  645. tlog5 << "Info about turn " << n.day << "has been sent!" << std::endl;
  646. handleTimeEvents();
  647. //call objects
  648. for(size_t i = 0; i<gs->map->objects.size(); i++)
  649. if(gs->map->objects[i])
  650. gs->map->objects[i]->newTurn();
  651. }
  652. void CGameHandler::run(bool resume)
  653. {
  654. BOOST_FOREACH(CConnection *cc, conns)
  655. {//init conn.
  656. ui8 quantity, pom;
  657. //ui32 seed;
  658. if(!resume)
  659. (*cc) << gs->scenarioOps->mapname << gs->map->checksum << gs->seed;
  660. (*cc) >> quantity; //how many players will be handled at that client
  661. for(int i=0;i<quantity;i++)
  662. {
  663. (*cc) >> pom; //read player color
  664. gsm.lock();
  665. connections[pom] = cc;
  666. gsm.unlock();
  667. }
  668. }
  669. for(std::set<CConnection*>::iterator i = conns.begin(); i!=conns.end();i++)
  670. {
  671. std::set<int> pom;
  672. for(std::map<int,CConnection*>::iterator j = connections.begin(); j!=connections.end();j++)
  673. if(j->second == *i)
  674. pom.insert(j->first);
  675. boost::thread(boost::bind(&CGameHandler::handleConnection,this,pom,boost::ref(**i)));
  676. }
  677. while (!end2)
  678. {
  679. if(!resume)
  680. newTurn();
  681. else
  682. resume = false;
  683. std::map<ui8,PlayerState>::iterator i;
  684. if(!resume)
  685. i = gs->players.begin();
  686. else
  687. i = gs->players.find(gs->currentPlayer);
  688. for(; i != gs->players.end(); i++)
  689. {
  690. if((i->second.towns.size()==0 && i->second.heroes.size()==0) || i->second.color<0 || i->first>=PLAYER_LIMIT ) continue; //players has not towns/castle - loser
  691. states.setFlag(i->first,&PlayerStatus::makingTurn,true);
  692. gs->currentPlayer = i->first;
  693. {
  694. YourTurn yt;
  695. yt.player = i->first;
  696. *connections[i->first] << &yt;
  697. }
  698. //wait till turn is done
  699. boost::unique_lock<boost::mutex> lock(states.mx);
  700. while(states.players[i->first].makingTurn && !end2)
  701. {
  702. boost::posix_time::time_duration p;
  703. p = boost::posix_time::milliseconds(200);
  704. states.cv.timed_wait(lock,p);
  705. }
  706. }
  707. }
  708. }
  709. namespace CGH
  710. {
  711. using namespace std;
  712. void readItTo(ifstream & input, vector< vector<int> > & dest)
  713. {
  714. for(int j=0; j<7; ++j)
  715. {
  716. std::vector<int> pom;
  717. for(int g=0; g<j+1; ++g)
  718. {
  719. int hlp; input>>hlp;
  720. pom.push_back(hlp);
  721. }
  722. dest.push_back(pom);
  723. }
  724. }
  725. }
  726. void CGameHandler::setupBattle( BattleInfo * curB, int3 tile, CCreatureSet &army1, CCreatureSet &army2, CGHeroInstance * hero1, CGHeroInstance * hero2 )
  727. {
  728. battleResult.set(NULL);
  729. std::vector<CStack*> & stacks = (curB->stacks);
  730. curB->tile = tile;
  731. curB->siege = 0; //TODO: add sieges
  732. curB->army1=army1;
  733. curB->army2=army2;
  734. curB->hero1=(hero1)?(hero1->id):(-1);
  735. curB->hero2=(hero2)?(hero2->id):(-1);
  736. curB->side1=(hero1)?(hero1->tempOwner):(-1);
  737. curB->side2=(hero2)?(hero2->tempOwner):(-1);
  738. curB->round = -2;
  739. curB->activeStack = -1;
  740. for(std::map<si32,std::pair<ui32,si32> >::iterator i = army1.slots.begin(); i!=army1.slots.end(); i++)
  741. {
  742. stacks.push_back(new CStack(&VLC->creh->creatures[i->second.first],i->second.second,hero1->tempOwner, stacks.size(), true,i->first));
  743. //base luck/morale calculations
  744. //TODO: check if terrain is native, add bonuses for neutral stacks, bonuses from town
  745. if(hero1)
  746. {
  747. stacks.back()->morale = hero1->getCurrentMorale(i->first,false);
  748. stacks.back()->luck = hero1->getCurrentLuck(i->first,false);
  749. }
  750. else
  751. {
  752. stacks.back()->morale = 0;
  753. stacks.back()->luck = 0;
  754. }
  755. stacks[stacks.size()-1]->ID = stacks.size()-1;
  756. }
  757. //initialization of positions
  758. std::ifstream positions;
  759. positions.open("config" PATHSEPARATOR "battleStartpos.txt", std::ios_base::in|std::ios_base::binary);
  760. if(!positions.is_open())
  761. {
  762. tlog1<<"Unable to open battleStartpos.txt!"<<std::endl;
  763. }
  764. std::string dump;
  765. positions>>dump; positions>>dump;
  766. std::vector< std::vector<int> > attackerLoose, defenderLoose, attackerTight, defenderTight;
  767. CGH::readItTo(positions, attackerLoose);
  768. positions>>dump;
  769. CGH::readItTo(positions, defenderLoose);
  770. positions>>dump;
  771. positions>>dump;
  772. CGH::readItTo(positions, attackerTight);
  773. positions>>dump;
  774. CGH::readItTo(positions, defenderTight);
  775. positions.close();
  776. if(army1.formation)
  777. for(int b=0; b<army1.slots.size(); ++b) //tight
  778. {
  779. stacks[b]->position = attackerTight[army1.slots.size()-1][b];
  780. }
  781. else
  782. for(int b=0; b<army1.slots.size(); ++b) //loose
  783. {
  784. stacks[b]->position = attackerLoose[army1.slots.size()-1][b];
  785. }
  786. for(std::map<si32,std::pair<ui32,si32> >::iterator i = army2.slots.begin(); i!=army2.slots.end(); i++)
  787. {
  788. stacks.push_back(new CStack(&VLC->creh->creatures[i->second.first],i->second.second,hero2 ? hero2->tempOwner : 255, stacks.size(), false, i->first));
  789. //base luck/morale calculations
  790. //TODO: check if terrain is native, add bonuses for neutral stacks, bonuses from town
  791. if(hero2)
  792. {
  793. stacks.back()->morale = hero2->getCurrentMorale(i->first,false);
  794. stacks.back()->luck = hero2->getCurrentLuck(i->first,false);
  795. }
  796. else
  797. {
  798. stacks.back()->morale = 0;
  799. stacks.back()->luck = 0;
  800. }
  801. }
  802. if(army2.formation)
  803. for(int b=0; b<army2.slots.size(); ++b) //tight
  804. {
  805. stacks[b+army1.slots.size()]->position = defenderTight[army2.slots.size()-1][b];
  806. }
  807. else
  808. for(int b=0; b<army2.slots.size(); ++b) //loose
  809. {
  810. stacks[b+army1.slots.size()]->position = defenderLoose[army2.slots.size()-1][b];
  811. }
  812. for(unsigned g=0; g<stacks.size(); ++g) //shifting positions of two-hex creatures
  813. {
  814. if((stacks[g]->position%17)==1 && stacks[g]->creature->isDoubleWide())
  815. {
  816. stacks[g]->position += 1;
  817. }
  818. else if((stacks[g]->position%17)==15 && stacks[g]->creature->isDoubleWide())
  819. {
  820. stacks[g]->position -= 1;
  821. }
  822. }
  823. //adding war machines
  824. if(hero1)
  825. {
  826. if(hero1->getArt(13)) //ballista
  827. {
  828. stacks.push_back(new CStack(&VLC->creh->creatures[146], 1, hero1->tempOwner, stacks.size(), true, 255));
  829. stacks[stacks.size()-1]->position = 52;
  830. stacks.back()->morale = hero1->getCurrentMorale(stacks.back()->ID,false);
  831. stacks.back()->luck = hero1->getCurrentLuck(stacks.back()->ID,false);
  832. }
  833. if(hero1->getArt(14)) //ammo cart
  834. {
  835. stacks.push_back(new CStack(&VLC->creh->creatures[148], 1, hero1->tempOwner, stacks.size(), true, 255));
  836. stacks[stacks.size()-1]->position = 18;
  837. stacks.back()->morale = hero1->getCurrentMorale(stacks.back()->ID,false);
  838. stacks.back()->luck = hero1->getCurrentLuck(stacks.back()->ID,false);
  839. }
  840. if(hero1->getArt(15)) //first aid tent
  841. {
  842. stacks.push_back(new CStack(&VLC->creh->creatures[147], 1, hero1->tempOwner, stacks.size(), true, 255));
  843. stacks[stacks.size()-1]->position = 154;
  844. stacks.back()->morale = hero1->getCurrentMorale(stacks.back()->ID,false);
  845. stacks.back()->luck = hero1->getCurrentLuck(stacks.back()->ID,false);
  846. }
  847. }
  848. if(hero2)
  849. {
  850. if(hero2->getArt(13)) //ballista
  851. {
  852. stacks.push_back(new CStack(&VLC->creh->creatures[146], 1, hero2->tempOwner, stacks.size(), false, 255));
  853. stacks[stacks.size()-1]->position = 66;
  854. stacks.back()->morale = hero2->getCurrentMorale(stacks.back()->ID,false);
  855. stacks.back()->luck = hero2->getCurrentLuck(stacks.back()->ID,false);
  856. }
  857. if(hero2->getArt(14)) //ammo cart
  858. {
  859. stacks.push_back(new CStack(&VLC->creh->creatures[148], 1, hero2->tempOwner, stacks.size(), false, 255));
  860. stacks[stacks.size()-1]->position = 32;
  861. stacks.back()->morale = hero2->getCurrentMorale(stacks.back()->ID,false);
  862. stacks.back()->luck = hero2->getCurrentLuck(stacks.back()->ID,false);
  863. }
  864. if(hero2->getArt(15)) //first aid tent
  865. {
  866. stacks.push_back(new CStack(&VLC->creh->creatures[147], 1, hero2->tempOwner, stacks.size(), false, 255));
  867. stacks[stacks.size()-1]->position = 168;
  868. stacks.back()->morale = hero2->getCurrentMorale(stacks.back()->ID,false);
  869. stacks.back()->luck = hero2->getCurrentLuck(stacks.back()->ID,false);
  870. }
  871. }
  872. //war machiens added
  873. std::stable_sort(stacks.begin(),stacks.end(),cmpst);
  874. //randomize obstacles
  875. bool obAv[BFIELD_SIZE]; //availability of hexes for obstacles;
  876. std::vector<int> possibleObstacles;
  877. for(int i=0; i<BFIELD_SIZE; ++i)
  878. {
  879. if(i%17 < 4 || i%17 > 12)
  880. {
  881. obAv[i] = false;
  882. }
  883. else
  884. {
  885. obAv[i] = true;
  886. }
  887. }
  888. int terType = gs->battleGetBattlefieldType(tile);
  889. for(std::map<int, CObstacleInfo>::const_iterator g=VLC->heroh->obstacles.begin(); g!=VLC->heroh->obstacles.end(); ++g)
  890. {
  891. if(g->second.allowedTerrains[terType] == '1')
  892. {
  893. possibleObstacles.push_back(g->first);
  894. }
  895. }
  896. srand(time(NULL));
  897. if(possibleObstacles.size() > 0) //we cannot place any obstacles when we don't have them
  898. {
  899. int toBlock = rand()%6 + 6; //how many hexes should be blocked by obstacles
  900. while(toBlock>0)
  901. {
  902. CObstacleInstance coi;
  903. coi.ID = possibleObstacles[rand()%possibleObstacles.size()];
  904. coi.pos = rand()%BFIELD_SIZE;
  905. std::vector<int> block = VLC->heroh->obstacles[coi.ID].getBlocked(coi.pos);
  906. bool badObstacle = false;
  907. for(int b=0; b<block.size(); ++b)
  908. {
  909. if(!obAv[block[b]])
  910. {
  911. badObstacle = true;
  912. break;
  913. }
  914. }
  915. if(badObstacle) continue;
  916. //obstacle can be placed
  917. curB->obstacles.push_back(coi);
  918. for(int b=0; b<block.size(); ++b)
  919. {
  920. if(block[b] >= 0 && block[b] < BFIELD_SIZE)
  921. obAv[block[b]] = false;
  922. }
  923. toBlock -= block.size();
  924. }
  925. }
  926. //block engaged players
  927. if(hero1->tempOwner<PLAYER_LIMIT)
  928. states.setFlag(hero1->tempOwner,&PlayerStatus::engagedIntoBattle,true);
  929. if(hero2 && hero2->tempOwner<PLAYER_LIMIT)
  930. states.setFlag(hero2->tempOwner,&PlayerStatus::engagedIntoBattle,true);
  931. //send info about battles
  932. BattleStart bs;
  933. bs.info = curB;
  934. sendAndApply(&bs);
  935. }
  936. void CGameHandler::checkForBattleEnd( std::vector<CStack*> &stacks )
  937. {
  938. //checking winning condition
  939. bool hasStack[2]; //hasStack[0] - true if attacker has a living stack; defender similarily
  940. hasStack[0] = hasStack[1] = false;
  941. for(int b = 0; b<stacks.size(); ++b)
  942. {
  943. if(stacks[b]->alive())
  944. {
  945. hasStack[1-stacks[b]->attackerOwned] = true;
  946. }
  947. }
  948. if(!hasStack[0] || !hasStack[1]) //somebody has won
  949. {
  950. BattleResult *br = new BattleResult; //will be deleted at the end of startBattle(...)
  951. br->result = 0;
  952. br->winner = hasStack[1]; //fleeing side loses
  953. gs->curB->calculateCasualties(br->casualties);
  954. battleResult.set(br);
  955. }
  956. }
  957. void CGameHandler::giveSpells( const CGTownInstance *t, const CGHeroInstance *h )
  958. {
  959. if(!vstd::contains(h->artifWorn,17))
  960. return; //hero hasn't spellbok
  961. ChangeSpells cs;
  962. cs.hid = h->id;
  963. cs.learn = true;
  964. for(int i=0; i<std::min(t->mageGuildLevel(),h->getSecSkillLevel(7)+2);i++)
  965. {
  966. for(int j=0; j<t->spellsAtLevel(i+1,true) && j<t->spells[i].size(); j++)
  967. {
  968. if(!vstd::contains(h->spells,t->spells[i][j]))
  969. cs.spells.insert(t->spells[i][j]);
  970. }
  971. }
  972. if(cs.spells.size())
  973. sendAndApply(&cs);
  974. }
  975. void CGameHandler::setBlockVis(int objid, bool bv)
  976. {
  977. SetObjectProperty sop(objid,2,bv);
  978. sendAndApply(&sop);
  979. }
  980. void CGameHandler::removeObject(int objid)
  981. {
  982. RemoveObject ro;
  983. ro.id = objid;
  984. sendAndApply(&ro);
  985. }
  986. void CGameHandler::setAmount(int objid, ui32 val)
  987. {
  988. SetObjectProperty sop(objid,3,val);
  989. sendAndApply(&sop);
  990. }
  991. void CGameHandler::moveHero(si32 hid, int3 dst, ui8 instant, ui8 asker)
  992. {
  993. bool blockvis = false;
  994. const CGHeroInstance *h = getHero(hid);
  995. if(!h || asker != 255 && (instant || h->getOwner() != gs->currentPlayer) //not turn of that hero or player can't simply teleport hero (at least not with this function)
  996. )
  997. {
  998. tlog1 << "Illegal call to move hero!\n";
  999. return;
  1000. }
  1001. tlog5 << "Player " <<int(asker) << " wants to move hero "<< hid << " from "<< h->pos << " to " << dst << std::endl;
  1002. int3 hmpos = dst + int3(-1,0,0);
  1003. TerrainTile t = gs->map->terrain[hmpos.x][hmpos.y][hmpos.z];
  1004. int cost = gs->getMovementCost(h,h->getPosition(false),CGHeroInstance::convertPosition(dst,false),h->movement);
  1005. //result structure for start - movement failed, no move points used
  1006. TryMoveHero tmh;
  1007. tmh.id = hid;
  1008. tmh.start = h->pos;
  1009. tmh.end = dst;
  1010. tmh.result = 0;
  1011. tmh.movePoints = h->movement;
  1012. //check if destination tile is available
  1013. if( t.tertype == rock
  1014. || (!h->canWalkOnSea() && t.tertype == water)
  1015. || (t.blocked && !t.visitable) //tile is blocked andnot visitable
  1016. )
  1017. {
  1018. tlog2 << "Cannot move hero, destination tile is blocked!\n";
  1019. sendAndApply(&tmh);
  1020. return;
  1021. }
  1022. //checks for standard movement
  1023. if(!instant)
  1024. {
  1025. if( (distance(h->pos,dst)>=1.5) //tiles are not neighouring
  1026. || (h->movement < cost && h->movement < 100) //lack of movement points
  1027. )
  1028. {
  1029. tlog2 << "Cannot move hero, not enough move points or tiles are not neighbouring!\n";
  1030. sendAndApply(&tmh);
  1031. return;
  1032. }
  1033. //check if there is blocking visitable object
  1034. blockvis = false;
  1035. tmh.movePoints = std::max(si32(0),h->movement-cost); //take move points
  1036. BOOST_FOREACH(CGObjectInstance *obj, t.visitableObjects)
  1037. {
  1038. if(obj != h && obj->blockVisit)
  1039. {
  1040. blockvis = true;
  1041. break;
  1042. }
  1043. }
  1044. //we start moving
  1045. if(blockvis)//interaction with blocking object (like resources)
  1046. {
  1047. sendAndApply(&tmh);
  1048. //failed to move to that tile but we visit object
  1049. BOOST_FOREACH(CGObjectInstance *obj, t.visitableObjects)
  1050. {
  1051. if (obj->blockVisit)
  1052. {
  1053. obj->onHeroVisit(h);
  1054. }
  1055. }
  1056. tlog5 << "Blocking visit at " << hmpos << std::endl;
  1057. return;
  1058. }
  1059. else //normal move
  1060. {
  1061. tmh.result = 1;
  1062. BOOST_FOREACH(CGObjectInstance *obj, gs->map->terrain[h->pos.x-1][h->pos.y][h->pos.z].visitableObjects)
  1063. {
  1064. obj->onHeroLeave(h);
  1065. }
  1066. getTilesInRange(tmh.fowRevealed,h->getSightCenter()+(tmh.end-tmh.start),h->getSightRadious(),h->tempOwner,1);
  1067. sendAndApply(&tmh);
  1068. tlog5 << "Moved to " <<tmh.end<<std::endl;
  1069. //call objects if they are visited
  1070. BOOST_FOREACH(CGObjectInstance *obj, t.visitableObjects)
  1071. {
  1072. obj->onHeroVisit(h);
  1073. }
  1074. }
  1075. tlog5 << "Movement end!\n";
  1076. }
  1077. else //instant move - teleportation
  1078. {
  1079. BOOST_FOREACH(CGObjectInstance* obj, t.blockingObjects)
  1080. {
  1081. if(obj->ID==HEROI_TYPE)
  1082. {
  1083. if(obj->tempOwner==h->tempOwner)
  1084. return;//TODO: exchange
  1085. //TODO: check for ally
  1086. CGHeroInstance *dh = static_cast<CGHeroInstance *>(obj);
  1087. startBattleI(&h->army,&dh->army,dst,h,dh,0);
  1088. return;
  1089. }
  1090. }
  1091. tmh.result = instant+1;
  1092. getTilesInRange(tmh.fowRevealed,h->getSightCenter()+(tmh.end-tmh.start),h->getSightRadious(),h->tempOwner,1);
  1093. sendAndApply(&tmh);
  1094. }
  1095. }
  1096. void CGameHandler::setOwner(int objid, ui8 owner)
  1097. {
  1098. SetObjectProperty sop(objid,1,owner);
  1099. sendAndApply(&sop);
  1100. }
  1101. void CGameHandler::setHoverName(int objid, MetaString* name)
  1102. {
  1103. SetHoverName shn(objid, *name);
  1104. sendAndApply(&shn);
  1105. }
  1106. void CGameHandler::showInfoDialog(InfoWindow *iw)
  1107. {
  1108. sendToAllClients(iw);
  1109. }
  1110. void CGameHandler::showYesNoDialog( YesNoDialog *iw, const CFunctionList<void(ui32)> &callback )
  1111. {
  1112. ask(iw,iw->player,callback);
  1113. }
  1114. void CGameHandler::showSelectionDialog(SelectionDialog *iw, const CFunctionList<void(ui32)> &callback)
  1115. {
  1116. ask(iw,iw->player,callback);
  1117. }
  1118. int CGameHandler::getCurrentPlayer()
  1119. {
  1120. return gs->currentPlayer;
  1121. }
  1122. void CGameHandler::giveResource(int player, int which, int val)
  1123. {
  1124. SetResource sr;
  1125. sr.player = player;
  1126. sr.resid = which;
  1127. sr.val = (gs->players.find(player)->second.resources[which]+val);
  1128. sendAndApply(&sr);
  1129. }
  1130. void CGameHandler::showCompInfo(ShowInInfobox * comp)
  1131. {
  1132. sendToAllClients(comp);
  1133. }
  1134. void CGameHandler::heroVisitCastle(int obj, int heroID)
  1135. {
  1136. HeroVisitCastle vc;
  1137. vc.hid = heroID;
  1138. vc.tid = obj;
  1139. vc.flags |= 1;
  1140. sendAndApply(&vc);
  1141. giveSpells(getTown(obj),getHero(heroID));
  1142. }
  1143. void CGameHandler::stopHeroVisitCastle(int obj, int heroID)
  1144. {
  1145. HeroVisitCastle vc;
  1146. vc.hid = heroID;
  1147. vc.tid = obj;
  1148. sendAndApply(&vc);
  1149. }
  1150. void CGameHandler::giveHeroArtifact(int artid, int hid, int position) //pos==-1 - first free slot in backpack
  1151. {
  1152. const CGHeroInstance* h = getHero(hid);
  1153. SetHeroArtifacts sha;
  1154. sha.hid = hid;
  1155. sha.artifacts = h->artifacts;
  1156. sha.artifWorn = h->artifWorn;
  1157. if(position<0)
  1158. {
  1159. if(position == -2)
  1160. {
  1161. int i;
  1162. for(i=0; i<VLC->arth->artifacts[artid].possibleSlots.size(); i++) //try to put artifact into first avaialble slot
  1163. {
  1164. if( !vstd::contains(sha.artifWorn,VLC->arth->artifacts[artid].possibleSlots[i]) )
  1165. {
  1166. sha.artifWorn[VLC->arth->artifacts[artid].possibleSlots[i]] = artid;
  1167. break;
  1168. }
  1169. }
  1170. if(i==VLC->arth->artifacts[artid].possibleSlots.size()) //if haven't find proper slot, use backpack
  1171. sha.artifacts.push_back(artid);
  1172. }
  1173. else //should be -1 => putartifact into backpack
  1174. {
  1175. sha.artifacts.push_back(artid);
  1176. }
  1177. }
  1178. else
  1179. {
  1180. if(!vstd::contains(sha.artifWorn,ui16(position)))
  1181. sha.artifWorn[position] = artid;
  1182. else
  1183. sha.artifacts.push_back(artid);
  1184. }
  1185. sendAndApply(&sha);
  1186. }
  1187. void CGameHandler::startBattleI(const CCreatureSet * army1, const CCreatureSet * army2, int3 tile, const CGHeroInstance *hero1, const CGHeroInstance *hero2, boost::function<void(BattleResult*)> cb) //use hero=NULL for no hero
  1188. {
  1189. boost::thread(boost::bind(&CGameHandler::startBattle,this,*(CCreatureSet *)army1,*(CCreatureSet *)army2,tile,(CGHeroInstance *)hero1,(CGHeroInstance *)hero2,cb));
  1190. }
  1191. void CGameHandler::startBattleI(int heroID, CCreatureSet army, int3 tile, boost::function<void(BattleResult*)> cb) //for hero<=>neutral army
  1192. {
  1193. CGHeroInstance* h = const_cast<CGHeroInstance*>(getHero(heroID));
  1194. startBattleI(&h->army,&army,tile,h,NULL,cb);
  1195. //battle(&h->army,army,tile,h,NULL);
  1196. }
  1197. void CGameHandler::changeSpells( int hid, bool give, const std::set<ui32> &spells )
  1198. {
  1199. ChangeSpells cs;
  1200. cs.hid = hid;
  1201. cs.spells = spells;
  1202. cs.learn = give;
  1203. sendAndApply(&cs);
  1204. }
  1205. int CGameHandler::getSelectedHero()
  1206. {
  1207. return IGameCallback::getSelectedHero(getCurrentPlayer())->id;
  1208. }
  1209. void CGameHandler::setObjProperty( int objid, int prop, int val )
  1210. {
  1211. SetObjectProperty sob;
  1212. sob.id = objid;
  1213. sob.what = prop;
  1214. sob.val = val;
  1215. sendAndApply(&sob);
  1216. }
  1217. void CGameHandler::sendMessageTo( CConnection &c, const std::string &message )
  1218. {
  1219. SystemMessage sm;
  1220. sm.text = message;
  1221. c << &sm;
  1222. }
  1223. void CGameHandler::giveHeroBonus( GiveBonus * bonus )
  1224. {
  1225. sendAndApply(bonus);
  1226. }
  1227. void CGameHandler::setMovePoints( SetMovePoints * smp )
  1228. {
  1229. sendAndApply(smp);
  1230. }
  1231. void CGameHandler::setManaPoints( int hid, int val )
  1232. {
  1233. SetMana sm;
  1234. sm.hid = hid;
  1235. sm.val = val;
  1236. sendAndApply(&sm);
  1237. }
  1238. void CGameHandler::giveHero( int id, int player )
  1239. {
  1240. GiveHero gh;
  1241. gh.id = id;
  1242. gh.player = player;
  1243. sendAndApply(&gh);
  1244. }
  1245. void CGameHandler::changeObjPos( int objid, int3 newPos, ui8 flags )
  1246. {
  1247. ChangeObjPos cop;
  1248. cop.objid = objid;
  1249. cop.nPos = newPos;
  1250. cop.flags = flags;
  1251. sendAndApply(&cop);
  1252. }
  1253. void CGameHandler::applyAndAsk( Query * sel, ui8 player, boost::function<void(ui32)> &callback )
  1254. {
  1255. gsm.lock();
  1256. sel->id = QID;
  1257. callbacks[QID] = callback;
  1258. states.addQuery(player,QID);
  1259. QID++;
  1260. sendAndApply(sel);
  1261. gsm.unlock();
  1262. }
  1263. void CGameHandler::ask( Query * sel, ui8 player, const CFunctionList<void(ui32)> &callback )
  1264. {
  1265. gsm.lock();
  1266. sel->id = QID;
  1267. callbacks[QID] = callback;
  1268. states.addQuery(player,QID);
  1269. sendToAllClients(sel);
  1270. QID++;
  1271. gsm.unlock();
  1272. }
  1273. void CGameHandler::sendToAllClients( CPackForClient * info )
  1274. {
  1275. tlog5 << "Sending to all clients a package of type " << typeid(*info).name() << std::endl;
  1276. for(std::set<CConnection*>::iterator i=conns.begin(); i!=conns.end();i++)
  1277. {
  1278. (*i)->wmx->lock();
  1279. **i << info;
  1280. (*i)->wmx->unlock();
  1281. }
  1282. }
  1283. void CGameHandler::sendAndApply( CPackForClient * info )
  1284. {
  1285. gs->apply(info);
  1286. sendToAllClients(info);
  1287. }
  1288. void CGameHandler::save( const std::string &fname )
  1289. {
  1290. {
  1291. tlog0 << "Ordering clients to serialize...\n";
  1292. SaveGame sg(fname);
  1293. //TODO: uncomment when client saving is ready
  1294. //sendToAllClients(&sg);
  1295. }
  1296. {
  1297. tlog0 << "Serializing game info...\n";
  1298. CSaveFile save(std::string("Games") + PATHSEPARATOR + fname + ".vlgm1");
  1299. char hlp[8] = "VCMISVG";
  1300. save << hlp << version << static_cast<CMapHeader&>(*gs->map) << gs->scenarioOps->difficulty << *VLC << gs;
  1301. }
  1302. {
  1303. tlog0 << "Serializing server info...\n";
  1304. CSaveFile save(std::string("Games") + PATHSEPARATOR + fname + ".vsgm1");
  1305. save << *this;
  1306. }
  1307. tlog0 << "Game has been succesfully saved!\n";
  1308. }
  1309. void CGameHandler::close()
  1310. {
  1311. tlog0 << "We have been requested to close.\n";
  1312. exit(0);
  1313. }
  1314. void CGameHandler::arrangeStacks(si32 id1, si32 id2, ui8 what, ui8 p1, ui8 p2, si32 val)
  1315. {
  1316. CArmedInstance *s1 = static_cast<CArmedInstance*>(gs->map->objects[id1]),
  1317. *s2 = static_cast<CArmedInstance*>(gs->map->objects[id2]);
  1318. CCreatureSet temp1 = s1->army, temp2 = s2->army,
  1319. &S1 = temp1, &S2 = (s1!=s2)?(temp2):(temp1);
  1320. if(what==1) //swap
  1321. {
  1322. std::swap(S1.slots[p1],S2.slots[p2]); //swap slots
  1323. //if one of them is empty, remove entry
  1324. if(!S1.slots[p1].second)
  1325. S1.slots.erase(p1);
  1326. if(!S2.slots[p2].second)
  1327. S2.slots.erase(p2);
  1328. }
  1329. else if(what==2)//merge
  1330. {
  1331. if(S1.slots[p1].first != S2.slots[p2].first) //not same creature
  1332. {
  1333. complain("Cannot merge different creatures stacks!");
  1334. return;
  1335. }
  1336. S2.slots[p2].second += S1.slots[p1].second;
  1337. S1.slots.erase(p1);
  1338. }
  1339. else if(what==3) //split
  1340. {
  1341. //general conditions checking
  1342. if((!vstd::contains(S1.slots,p1) && complain("no creatures to split"))
  1343. || (val<1 && complain("no creatures to split")) )
  1344. {
  1345. return;
  1346. }
  1347. if(vstd::contains(S2.slots,p2)) //dest. slot not free - it must be "rebalancing"...
  1348. {
  1349. int total = S1.slots[p1].second + S2.slots[p2].second;
  1350. if( (total < val && complain("Cannot split that stack, not enough creatures!"))
  1351. || (S2.slots[p2].first != S1.slots[p1].first && complain("Cannot rebalance different creatures stacks!"))
  1352. )
  1353. {
  1354. return;
  1355. }
  1356. S2.slots[p2].second = val;
  1357. S1.slots[p1].second = total - val;
  1358. }
  1359. else //split one stack to the two
  1360. {
  1361. if(S1.slots[p1].second < val)//not enough creatures
  1362. {
  1363. complain("Cannot split that stack, not enough creatures!");
  1364. return;
  1365. }
  1366. S2.slots[p2].first = S1.slots[p1].first;
  1367. S2.slots[p2].second = val;
  1368. S1.slots[p1].second -= val;
  1369. }
  1370. if(!S1.slots[p1].second) //if we've moved all creatures
  1371. S1.slots.erase(p1);
  1372. }
  1373. if((s1->needsLastStack() && !S1.slots.size()) //it's not allowed to take last stack from hero army!
  1374. || (s2->needsLastStack() && !S2.slots.size())
  1375. )
  1376. {
  1377. complain("Cannot take the last stack!");
  1378. return; //leave without applying changes to garrison
  1379. }
  1380. //apply changes
  1381. SetGarrisons sg;
  1382. sg.garrs[id1] = S1;
  1383. if(s1 != s2)
  1384. sg.garrs[id2] = S2;
  1385. sendAndApply(&sg);
  1386. }
  1387. int CGameHandler::getPlayerAt( CConnection *c ) const
  1388. {
  1389. std::set<int> all;
  1390. for(std::map<int,CConnection*>::const_iterator i=connections.begin(); i!=connections.end(); i++)
  1391. if(i->second == c)
  1392. all.insert(i->first);
  1393. switch(all.size())
  1394. {
  1395. case 0:
  1396. return 255;
  1397. case 1:
  1398. return *all.begin();
  1399. default:
  1400. {
  1401. //if we have more than one player at this connection, try to pick active one
  1402. if(vstd::contains(all,int(gs->currentPlayer)))
  1403. return gs->currentPlayer;
  1404. else
  1405. return 253; //cannot say which player is it
  1406. }
  1407. }
  1408. }
  1409. void CGameHandler::disbandCreature(si32 id, ui8 pos)
  1410. {
  1411. CArmedInstance *s1 = static_cast<CArmedInstance*>(gs->map->objects[id]);
  1412. if(!vstd::contains(s1->army.slots,pos))
  1413. {
  1414. complain("Illegal call to disbandCreature - no such stack in army!");
  1415. return;
  1416. }
  1417. s1->army.slots.erase(pos);
  1418. SetGarrisons sg;
  1419. sg.garrs[id] = s1->army;
  1420. sendAndApply(&sg);
  1421. }
  1422. void CGameHandler::buildStructure(si32 tid, si32 bid)
  1423. {
  1424. CGTownInstance * t = static_cast<CGTownInstance*>(gs->map->objects[tid]);
  1425. CBuilding * b = VLC->buildh->buildings[t->subID][bid];
  1426. if(gs->canBuildStructure(t,bid) != 7)
  1427. {
  1428. complain("Cannot build that building!");
  1429. return;
  1430. }
  1431. NewStructures ns;
  1432. ns.tid = tid;
  1433. if(bid>36) //upg dwelling
  1434. {
  1435. if(t->getHordeLevel(0) == (bid-37))
  1436. ns.bid.insert(19);
  1437. else if(t->getHordeLevel(1) == (bid-37))
  1438. ns.bid.insert(25);
  1439. }
  1440. else if(bid >= 30) //bas. dwelling
  1441. {
  1442. SetAvailableCreatures ssi;
  1443. ssi.tid = tid;
  1444. ssi.creatures = t->strInfo.creatures;
  1445. ssi.creatures[bid-30] = VLC->creh->creatures[t->town->basicCreatures[bid-30]].growth;
  1446. sendAndApply(&ssi);
  1447. }
  1448. ns.bid.insert(bid);
  1449. ns.builded = t->builded + 1;
  1450. sendAndApply(&ns);
  1451. SetResources sr;
  1452. sr.player = t->tempOwner;
  1453. sr.res = gs->getPlayer(t->tempOwner)->resources;
  1454. for(int i=0;i<7;i++)
  1455. sr.res[i]-=b->resources[i];
  1456. sendAndApply(&sr);
  1457. if(bid<5) //it's mage guild
  1458. {
  1459. if(t->visitingHero)
  1460. giveSpells(t,t->visitingHero);
  1461. if(t->garrisonHero)
  1462. giveSpells(t,t->garrisonHero);
  1463. }
  1464. }
  1465. void CGameHandler::sendMessageToAll( const std::string &message )
  1466. {
  1467. SystemMessage sm;
  1468. sm.text = message;
  1469. sendToAllClients(&sm);
  1470. }
  1471. void CGameHandler::recruitCreatures( si32 objid, ui32 crid, ui32 cram )
  1472. {
  1473. si32 ser = -1;
  1474. CGTownInstance * t = static_cast<CGTownInstance*>(gs->map->objects[objid]);
  1475. //verify
  1476. bool found = false;
  1477. typedef std::pair<const int,int> Parka;
  1478. for(std::map<si32,ui32>::iterator av = t->strInfo.creatures.begin(); av!=t->strInfo.creatures.end(); av++)
  1479. {
  1480. if( ( found = (crid == t->town->basicCreatures[av->first]) ) //creature is available among basic cretures
  1481. || (found = (crid == t->town->upgradedCreatures[av->first])) )//creature is available among upgraded cretures
  1482. {
  1483. cram = std::min(cram,av->second); //reduce recruited amount up to available amount
  1484. ser = av->first;
  1485. break;
  1486. }
  1487. }
  1488. int slot = t->army.getSlotFor(crid);
  1489. if(!found || //no such creature
  1490. cram > VLC->creh->creatures[crid].maxAmount(gs->getPlayer(t->tempOwner)->resources) || //lack of resources
  1491. cram<=0 ||
  1492. slot<0 )
  1493. return;
  1494. //recruit
  1495. SetResources sr;
  1496. sr.player = t->tempOwner;
  1497. for(int i=0;i<RESOURCE_QUANTITY;i++)
  1498. sr.res[i] = gs->getPlayer(t->tempOwner)->resources[i] - (VLC->creh->creatures[crid].cost[i] * cram);
  1499. SetAvailableCreatures sac;
  1500. sac.tid = objid;
  1501. sac.creatures = t->strInfo.creatures;
  1502. sac.creatures[ser] -= cram;
  1503. SetGarrisons sg;
  1504. sg.garrs[objid] = t->army;
  1505. if(sg.garrs[objid].slots.find(slot) == sg.garrs[objid].slots.end()) //take a free slot
  1506. {
  1507. sg.garrs[objid].slots[slot] = std::make_pair(crid,cram);
  1508. }
  1509. else //add creatures to a already existing stack
  1510. {
  1511. sg.garrs[objid].slots[slot].second += cram;
  1512. }
  1513. sendAndApply(&sr);
  1514. sendAndApply(&sac);
  1515. sendAndApply(&sg);
  1516. }
  1517. void CGameHandler::upgradeCreature( ui32 objid, ui8 pos, ui32 upgID )
  1518. {
  1519. CArmedInstance *obj = static_cast<CArmedInstance*>(gs->map->objects[objid]);
  1520. UpgradeInfo ui = gs->getUpgradeInfo(obj,pos);
  1521. int player = obj->tempOwner;
  1522. int crQuantity = obj->army.slots[pos].second;
  1523. //check if upgrade is possible
  1524. if(ui.oldID<0 || !vstd::contains(ui.newID,upgID))
  1525. return;
  1526. //check if player has enough resources
  1527. for(int i=0;i<ui.cost.size();i++)
  1528. {
  1529. for (std::set<std::pair<int,int> >::iterator j=ui.cost[i].begin(); j!=ui.cost[i].end(); j++)
  1530. {
  1531. if(gs->getPlayer(player)->resources[j->first] < j->second*crQuantity)
  1532. return;
  1533. }
  1534. }
  1535. //take resources
  1536. for(int i=0;i<ui.cost.size();i++)
  1537. {
  1538. for (std::set<std::pair<int,int> >::iterator j=ui.cost[i].begin(); j!=ui.cost[i].end(); j++)
  1539. {
  1540. SetResource sr;
  1541. sr.player = player;
  1542. sr.resid = j->first;
  1543. sr.val = gs->getPlayer(player)->resources[j->first] - j->second*crQuantity;
  1544. sendAndApply(&sr);
  1545. }
  1546. }
  1547. //upgrade creature
  1548. SetGarrisons sg;
  1549. sg.garrs[objid] = obj->army;
  1550. sg.garrs[objid].slots[pos].first = upgID;
  1551. sendAndApply(&sg);
  1552. }
  1553. void CGameHandler::garrisonSwap(si32 tid)
  1554. {
  1555. CGTownInstance *town = gs->getTown(tid);
  1556. if(!town->garrisonHero && town->visitingHero) //visiting => garrison, merge armies
  1557. {
  1558. CCreatureSet csn = town->visitingHero->army, cso = town->army;
  1559. while(!cso.slots.empty())//while there are unmoved creatures
  1560. {
  1561. int pos = csn.getSlotFor(cso.slots.begin()->second.first);
  1562. if(pos<0)
  1563. return;
  1564. if(csn.slots.find(pos)!=csn.slots.end()) //add creatures to the existing stack
  1565. {
  1566. csn.slots[pos].second += cso.slots.begin()->second.second;
  1567. }
  1568. else //move stack on the free pos
  1569. {
  1570. csn.slots[pos].first = cso.slots.begin()->second.first;
  1571. csn.slots[pos].second = cso.slots.begin()->second.second;
  1572. }
  1573. cso.slots.erase(cso.slots.begin());
  1574. }
  1575. SetGarrisons sg;
  1576. sg.garrs[town->visitingHero->id] = csn;
  1577. sg.garrs[town->id] = csn;
  1578. sendAndApply(&sg);
  1579. SetHeroesInTown intown;
  1580. intown.tid = tid;
  1581. intown.visiting = -1;
  1582. intown.garrison = town->visitingHero->id;
  1583. sendAndApply(&intown);
  1584. }
  1585. else if (town->garrisonHero && !town->visitingHero) //move hero out of the garrison
  1586. {
  1587. SetHeroesInTown intown;
  1588. intown.tid = tid;
  1589. intown.garrison = -1;
  1590. intown.visiting = town->garrisonHero->id;
  1591. sendAndApply(&intown);
  1592. //town will be empty
  1593. SetGarrisons sg;
  1594. sg.garrs[tid] = CCreatureSet();
  1595. sendAndApply(&sg);
  1596. }
  1597. else if (town->garrisonHero && town->visitingHero) //swap visiting and garrison hero
  1598. {
  1599. SetGarrisons sg;
  1600. sg.garrs[town->id] = town->visitingHero->army;
  1601. sg.garrs[town->garrisonHero->id] = town->garrisonHero->army;
  1602. SetHeroesInTown intown;
  1603. intown.tid = tid;
  1604. intown.garrison = town->visitingHero->id;
  1605. intown.visiting = town->garrisonHero->id;
  1606. sendAndApply(&intown);
  1607. sendAndApply(&sg);
  1608. }
  1609. else
  1610. {
  1611. complain("Cannot swap garrison hero!");
  1612. }
  1613. }
  1614. void CGameHandler::swapArtifacts( si32 hid1, si32 hid2, ui16 slot1, ui16 slot2 )
  1615. {
  1616. CGHeroInstance *h1 = gs->getHero(hid1), *h2 = gs->getHero(hid2);
  1617. if((distance(h1->pos,h2->pos) > 1.0) || (h1->tempOwner != h2->tempOwner))
  1618. return;
  1619. int a1=h1->getArtAtPos(slot1), a2=h2->getArtAtPos(slot2);
  1620. h2->setArtAtPos(slot2,a1);
  1621. h1->setArtAtPos(slot1,a2);
  1622. SetHeroArtifacts sha;
  1623. sha.hid = hid1;
  1624. sha.artifacts = h1->artifacts;
  1625. sha.artifWorn = h1->artifWorn;
  1626. sendAndApply(&sha);
  1627. if(hid1 != hid2)
  1628. {
  1629. sha.hid = hid2;
  1630. sha.artifacts = h2->artifacts;
  1631. sha.artifWorn = h2->artifWorn;
  1632. sendAndApply(&sha);
  1633. }
  1634. }
  1635. void CGameHandler::buyArtifact( ui32 hid, si32 aid )
  1636. {
  1637. CGHeroInstance *hero = gs->getHero(hid);
  1638. CGTownInstance *town = hero->visitedTown;
  1639. if(aid==0) //spellbook
  1640. {
  1641. if(!vstd::contains(town->builtBuildings,si32(0)))
  1642. return;
  1643. SetResource sr;
  1644. sr.player = hero->tempOwner;
  1645. sr.resid = 6;
  1646. sr.val = gs->getPlayer(hero->getOwner())->resources[6] - 500;
  1647. sendAndApply(&sr);
  1648. SetHeroArtifacts sha;
  1649. sha.hid = hid;
  1650. sha.artifacts = hero->artifacts;
  1651. sha.artifWorn = hero->artifWorn;
  1652. sha.artifWorn[17] = 0;
  1653. sendAndApply(&sha);
  1654. giveSpells(town,hero);
  1655. }
  1656. else if(aid < 7 && aid > 3) //war machine
  1657. {
  1658. int price = VLC->arth->artifacts[aid].price;
  1659. if(vstd::contains(hero->artifWorn,ui16(9+aid)) //hero already has this machine
  1660. || !vstd::contains(town->builtBuildings,si32(16)) //no blackismith
  1661. || gs->getPlayer(hero->getOwner())->resources[6] < price //no gold
  1662. || town->town->warMachine!= aid ) //this machine is not available here (//TODO: support ballista yard in stronghold)
  1663. {
  1664. return;
  1665. }
  1666. SetResource sr;
  1667. sr.player = hero->tempOwner;
  1668. sr.resid = 6;
  1669. sr.val = gs->getPlayer(hero->getOwner())->resources[6] - price;
  1670. sendAndApply(&sr);
  1671. SetHeroArtifacts sha;
  1672. sha.hid = hid;
  1673. sha.artifacts = hero->artifacts;
  1674. sha.artifWorn = hero->artifWorn;
  1675. sha.artifWorn[9+aid] = aid;
  1676. sendAndApply(&sha);
  1677. }
  1678. }
  1679. void CGameHandler::tradeResources( ui32 val, ui8 player, ui32 id1, ui32 id2 )
  1680. {
  1681. val = std::min(si32(val),gs->getPlayer(player)->resources[id1]);
  1682. double uzysk = (double)gs->resVals[id1] * val * gs->getMarketEfficiency(player);
  1683. uzysk /= gs->resVals[id2];
  1684. SetResource sr;
  1685. sr.player = player;
  1686. sr.resid = id1;
  1687. sr.val = gs->getPlayer(player)->resources[id1] - val;
  1688. sendAndApply(&sr);
  1689. sr.resid = id2;
  1690. sr.val = gs->getPlayer(player)->resources[id2] + (int)uzysk;
  1691. sendAndApply(&sr);
  1692. }
  1693. void CGameHandler::setFormation( si32 hid, ui8 formation )
  1694. {
  1695. gs->getHero(hid)->army.formation = formation;
  1696. }
  1697. void CGameHandler::hireHero( ui32 tid, ui8 hid )
  1698. {
  1699. CGTownInstance *t = gs->getTown(tid);
  1700. if(!vstd::contains(t->builtBuildings,5) //no tavern in the town
  1701. || gs->getPlayer(t->tempOwner)->resources[6]<2500 //not enough gold
  1702. || t->visitingHero //there is visiting hero - no place
  1703. || gs->getPlayer(t->tempOwner)->heroes.size()>7 //8 hero limit
  1704. )
  1705. return;
  1706. CGHeroInstance *nh = gs->getPlayer(t->tempOwner)->availableHeroes[hid];
  1707. HeroRecruited hr;
  1708. hr.tid = tid;
  1709. hr.hid = nh->subID;
  1710. hr.player = t->tempOwner;
  1711. hr.tile = t->pos - int3(1,0,0);
  1712. sendAndApply(&hr);
  1713. SetAvailableHeroes sah;
  1714. (hid ? sah.hid2 : sah.hid1) = gs->hpool.pickHeroFor(false,t->tempOwner,t->town)->subID;
  1715. (hid ? sah.hid1 : sah.hid2) = gs->getPlayer(t->tempOwner)->availableHeroes[!hid]->subID;
  1716. sah.player = t->tempOwner;
  1717. sah.flags = hid+1;
  1718. sendAndApply(&sah);
  1719. SetResource sr;
  1720. sr.player = t->tempOwner;
  1721. sr.resid = 6;
  1722. sr.val = gs->getPlayer(t->tempOwner)->resources[6] - 2500;
  1723. sendAndApply(&sr);
  1724. giveSpells(t,nh);
  1725. }
  1726. void CGameHandler::queryReply( ui32 qid, ui32 answer )
  1727. {
  1728. gsm.lock();
  1729. CFunctionList<void(ui32)> callb = callbacks[qid];
  1730. callbacks.erase(qid);
  1731. gsm.unlock();
  1732. callb(answer);
  1733. }
  1734. void CGameHandler::makeBattleAction( BattleAction &ba )
  1735. {
  1736. switch(ba.actionType)
  1737. {
  1738. case 2: //walk
  1739. {
  1740. sendAndApply(&StartAction(ba)); //start movement
  1741. moveStack(ba.stackNumber,ba.destinationTile); //move
  1742. sendAndApply(&EndAction());
  1743. break;
  1744. }
  1745. case 3: //defend
  1746. case 8: //wait
  1747. {
  1748. sendAndApply(&StartAction(ba));
  1749. sendAndApply(&EndAction());
  1750. break;
  1751. }
  1752. case 4: //retreat/flee
  1753. {
  1754. //TODO: check if fleeing is possible (e.g. enemy may have Shackles of War)
  1755. //TODO: calculate casualties
  1756. //TODO: remove retreating hero from map and place it in recruitment list
  1757. BattleResult *br = new BattleResult;
  1758. br->result = 1;
  1759. br->winner = !ba.side; //fleeing side loses
  1760. gs->curB->calculateCasualties(br->casualties);
  1761. giveExp(*br);
  1762. battleResult.set(br);
  1763. break;
  1764. }
  1765. case 6: //walk or attack
  1766. {
  1767. sendAndApply(&StartAction(ba)); //start movement and attack
  1768. moveStack(ba.stackNumber,ba.destinationTile);
  1769. CStack *curStack = gs->curB->getStack(ba.stackNumber),
  1770. *stackAtEnd = gs->curB->getStackT(ba.additionalInfo);
  1771. if(curStack->position != ba.destinationTile) //we wasn't able to reach destination tile
  1772. {
  1773. tlog3<<"We cannot move this stack to its destination "<<curStack->creature->namePl<<std::endl;
  1774. }
  1775. if(!stackAtEnd)
  1776. {
  1777. tlog3 << "There is no stack on " << ba.additionalInfo << " tile (no attack)!";
  1778. break;
  1779. }
  1780. ui16 curpos = curStack->position,
  1781. enemypos = stackAtEnd->position;
  1782. if( !(
  1783. (BattleInfo::mutualPosition(curpos, enemypos) >= 0) //front <=> front
  1784. || (curStack->creature->isDoubleWide() //back <=> front
  1785. && BattleInfo::mutualPosition(curpos + (curStack->attackerOwned ? -1 : 1), enemypos) >= 0)
  1786. || (stackAtEnd->creature->isDoubleWide() //front <=> back
  1787. && BattleInfo::mutualPosition(curpos, enemypos + (stackAtEnd->attackerOwned ? -1 : 1)) >= 0)
  1788. || (stackAtEnd->creature->isDoubleWide() && curStack->creature->isDoubleWide()//back <=> back
  1789. && BattleInfo::mutualPosition(curpos + (curStack->attackerOwned ? -1 : 1), enemypos + (stackAtEnd->attackerOwned ? -1 : 1)) >= 0)
  1790. )
  1791. )
  1792. {
  1793. tlog3 << "Attack cannot be performed!";
  1794. sendAndApply(&EndAction());
  1795. break;
  1796. }
  1797. //attack
  1798. BattleAttack bat;
  1799. prepareAttack(bat,curStack,stackAtEnd);
  1800. sendAndApply(&bat);
  1801. //counterattack
  1802. if(!vstd::contains(curStack->abilities,NO_ENEMY_RETALIATION)
  1803. && stackAtEnd->alive()
  1804. && stackAtEnd->counterAttacks
  1805. && !vstd::contains(stackAtEnd->abilities, SIEGE_WEAPON)) //TODO: support for multiple retaliatons per turn
  1806. {
  1807. prepareAttack(bat,stackAtEnd,curStack);
  1808. bat.flags |= 2;
  1809. sendAndApply(&bat);
  1810. }
  1811. //second attack
  1812. if(vstd::contains(curStack->abilities,TWICE_ATTACK)
  1813. && curStack->alive()
  1814. && stackAtEnd->alive() )
  1815. {
  1816. bat.flags = 0;
  1817. prepareAttack(bat,curStack,stackAtEnd);
  1818. sendAndApply(&bat);
  1819. }
  1820. sendAndApply(&EndAction());
  1821. break;
  1822. }
  1823. case 7: //shoot
  1824. {
  1825. CStack *curStack = gs->curB->getStack(ba.stackNumber),
  1826. *destStack= gs->curB->getStackT(ba.destinationTile);
  1827. if(!curStack //our stack exists
  1828. || !destStack //there is a stack at destination tile
  1829. || !curStack->shots //stack has shots
  1830. || gs->curB->isStackBlocked(curStack->ID) //we are not blocked
  1831. || !vstd::contains(curStack->abilities,SHOOTER) //our stack is shooting unit
  1832. )
  1833. break;
  1834. for(int g=0; g<curStack->effects.size(); ++g)
  1835. {
  1836. if(61 == curStack->effects[g].id) //forgetfulness
  1837. break;
  1838. }
  1839. sendAndApply(&StartAction(ba)); //start shooting
  1840. BattleAttack bat;
  1841. prepareAttack(bat,curStack,destStack);
  1842. bat.flags |= 1;
  1843. sendAndApply(&bat);
  1844. if(vstd::contains(curStack->abilities,TWICE_ATTACK) //if unit shots twice let's make another shot
  1845. && curStack->alive()
  1846. && destStack->alive()
  1847. && curStack->shots
  1848. )
  1849. {
  1850. prepareAttack(bat,curStack,destStack);
  1851. sendAndApply(&bat);
  1852. }
  1853. sendAndApply(&EndAction());
  1854. break;
  1855. }
  1856. }
  1857. battleMadeAction.setn(true);
  1858. }
  1859. void CGameHandler::playerMessage( ui8 player, const std::string &message )
  1860. {
  1861. bool cheated=true;
  1862. sendAndApply(&PlayerMessage(player,message));
  1863. if(message == "vcmiistari") //give all spells and 999 mana
  1864. {
  1865. SetMana sm;
  1866. ChangeSpells cs;
  1867. cs.learn = 1;
  1868. for(int i=0;i<VLC->spellh->spells.size();i++)
  1869. {
  1870. if(!VLC->spellh->spells[i].creatureAbility)
  1871. cs.spells.insert(i);
  1872. }
  1873. sm.hid = cs.hid = gs->players[player].currentSelection;
  1874. sm.val = 999;
  1875. if(gs->getHero(cs.hid))
  1876. {
  1877. sendAndApply(&cs);
  1878. sendAndApply(&sm);
  1879. }
  1880. }
  1881. else if(message == "vcmiainur") //gives 5 archangels into each slot
  1882. {
  1883. SetGarrisons sg;
  1884. CGHeroInstance *hero = gs->getHero(gs->getPlayer(player)->currentSelection);
  1885. if(!hero) return;
  1886. sg.garrs[hero->id] = hero->army;
  1887. for(int i=0;i<7;i++)
  1888. if(!vstd::contains(sg.garrs[hero->id].slots,i))
  1889. sg.garrs[hero->id].slots[i] = std::pair<ui32,si32>(13,5);
  1890. sendAndApply(&sg);
  1891. }
  1892. else if(message == "vcmiangband") //gives 10 black knightinto each slot
  1893. {
  1894. SetGarrisons sg;
  1895. CGHeroInstance *hero = gs->getHero(gs->getPlayer(player)->currentSelection);
  1896. if(!hero) return;
  1897. sg.garrs[hero->id] = hero->army;
  1898. for(int i=0;i<7;i++)
  1899. if(!vstd::contains(sg.garrs[hero->id].slots,i))
  1900. sg.garrs[hero->id].slots[i] = std::pair<ui32,si32>(66,10);
  1901. sendAndApply(&sg);
  1902. }
  1903. else if(message == "vcminoldor") //all war machines
  1904. {
  1905. CGHeroInstance *hero = gs->getHero(gs->getPlayer(player)->currentSelection);
  1906. if(!hero) return;
  1907. SetHeroArtifacts sha;
  1908. sha.hid = hero->id;
  1909. sha.artifacts = hero->artifacts;
  1910. sha.artifWorn = hero->artifWorn;
  1911. sha.artifWorn[13] = 4;
  1912. sha.artifWorn[14] = 5;
  1913. sha.artifWorn[15] = 6;
  1914. sendAndApply(&sha);
  1915. }
  1916. else if(message == "vcminahar") //1000000 movement points
  1917. {
  1918. CGHeroInstance *hero = gs->getHero(gs->getPlayer(player)->currentSelection);
  1919. if(!hero) return;
  1920. SetMovePoints smp;
  1921. smp.hid = hero->id;
  1922. smp.val = 1000000;
  1923. sendAndApply(&smp);
  1924. }
  1925. else if(message == "vcmiformenos") //give resources
  1926. {
  1927. SetResources sr;
  1928. sr.player = player;
  1929. sr.res = gs->getPlayer(player)->resources;
  1930. for(int i=0;i<7;i++)
  1931. sr.res[i] += 100;
  1932. sr.res[6] += 19900;
  1933. sendAndApply(&sr);
  1934. }
  1935. else if(message == "vcmieagles") //reveal FoW
  1936. {
  1937. FoWChange fc;
  1938. fc.player = player;
  1939. for(int i=0;i<gs->map->width;i++)
  1940. for(int j=0;j<gs->map->height;j++)
  1941. for(int k=0;k<gs->map->twoLevel+1;k++)
  1942. if(!gs->getPlayer(fc.player)->fogOfWarMap[i][j][k])
  1943. fc.tiles.insert(int3(i,j,k));
  1944. sendAndApply(&fc);
  1945. }
  1946. else if(message == "vcmiglorfindel")
  1947. {
  1948. CGHeroInstance *hero = gs->getHero(gs->getPlayer(player)->currentSelection);
  1949. changePrimSkill(hero->id,4,VLC->heroh->reqExp(hero->level+1) - VLC->heroh->reqExp(hero->level));
  1950. }
  1951. else
  1952. cheated = false;
  1953. if(cheated)
  1954. {
  1955. sendAndApply(&SystemMessage("CHEATER!!!"));
  1956. }
  1957. }
  1958. void CGameHandler::makeCustomAction( BattleAction &ba )
  1959. {
  1960. switch(ba.actionType)
  1961. {
  1962. case 1: //hero casts spell
  1963. {
  1964. CGHeroInstance *h = (ba.side) ? gs->getHero(gs->curB->hero2) : gs->getHero(gs->curB->hero1);
  1965. if(!h)
  1966. {
  1967. tlog2 << "Wrong caster!\n";
  1968. return;
  1969. }
  1970. if(ba.additionalInfo >= VLC->spellh->spells.size())
  1971. {
  1972. tlog2 << "Wrong spell id (" << ba.additionalInfo << ")!\n";
  1973. return;
  1974. }
  1975. CSpell *s = &VLC->spellh->spells[ba.additionalInfo];
  1976. ui8 skill = 0; //skill level
  1977. if(s->fire)
  1978. skill = std::max(skill,h->getSecSkillLevel(14));
  1979. if(s->air)
  1980. skill = std::max(skill,h->getSecSkillLevel(15));
  1981. if(s->water)
  1982. skill = std::max(skill,h->getSecSkillLevel(16));
  1983. if(s->earth)
  1984. skill = std::max(skill,h->getSecSkillLevel(17));
  1985. //TODO: skill level may be different on special terrain
  1986. if( !(vstd::contains(h->spells,ba.additionalInfo)) //hero doesn't know this spell
  1987. || (h->mana < s->costs[skill]) //not enough mana
  1988. || (ba.additionalInfo < 10) //it's adventure spell (not combat)
  1989. || (gs->curB->castedSpells[ba.side])
  1990. )
  1991. {
  1992. tlog2 << "Spell cannot be casted!\n";
  1993. return;
  1994. }
  1995. sendAndApply(&StartAction(ba)); //start spell casting
  1996. //TODO: check resistances
  1997. #define SPELL_CAST_TEMPLATE_1(NUMBER, DURATION) SetStackEffect sse; \
  1998. if(getSchoolLevel(h,s) < 3) /*not expert */ \
  1999. { \
  2000. sse.stacks.insert(gs->curB->getStackT(ba.destinationTile)->ID); \
  2001. sse.effect.id = (NUMBER); \
  2002. sse.effect.level = getSchoolLevel(h,s); \
  2003. sse.effect.turnsRemain = (DURATION); /*! - any duration */ \
  2004. sendAndApply(&sse); \
  2005. } \
  2006. else \
  2007. { \
  2008. for(int it=0; it<gs->curB->stacks.size(); ++it) \
  2009. { \
  2010. /*if it's non negative spell and our unit or non positive spell and hostile unit */ \
  2011. if((VLC->spellh->spells[ba.additionalInfo].positiveness >= 0 && gs->curB->stacks[it]->owner == h->tempOwner) \
  2012. ||(VLC->spellh->spells[ba.additionalInfo].positiveness <= 0 && gs->curB->stacks[it]->owner != h->tempOwner ) \
  2013. ) \
  2014. { \
  2015. sse.stacks.insert(gs->curB->stacks[it]->ID); \
  2016. } \
  2017. } \
  2018. sse.effect.id = (NUMBER); \
  2019. sse.effect.level = getSchoolLevel(h,s); \
  2020. sse.effect.turnsRemain = (DURATION); \
  2021. sendAndApply(&sse); \
  2022. }
  2023. SpellCasted sc;
  2024. sc.side = ba.side;
  2025. sc.id = ba.additionalInfo;
  2026. sc.skill = skill;
  2027. sc.tile = ba.destinationTile;
  2028. sendAndApply(&sc);
  2029. switch(ba.additionalInfo) //spell id
  2030. {
  2031. case 15: //magic arrow
  2032. {
  2033. CStack * attacked = gs->curB->getStackT(ba.destinationTile);
  2034. if(!attacked) break;
  2035. BattleStackAttacked bsa;
  2036. bsa.flags |= 2;
  2037. bsa.effect = 64;
  2038. bsa.damageAmount = h->getPrimSkillLevel(2) * 10 + s->powers[getSchoolLevel(h,s)];
  2039. bsa.stackAttacked = attacked->ID;
  2040. prepareAttacked(bsa,attacked);
  2041. sendAndApply(&bsa);
  2042. break;
  2043. }
  2044. case 16: //ice bolt
  2045. {
  2046. CStack * attacked = gs->curB->getStackT(ba.destinationTile);
  2047. if(!attacked) break;
  2048. BattleStackAttacked bsa;
  2049. bsa.flags |= 2;
  2050. bsa.effect = 46;
  2051. bsa.damageAmount = h->getPrimSkillLevel(2) * 20 + s->powers[getSchoolLevel(h,s)];
  2052. bsa.stackAttacked = attacked->ID;
  2053. prepareAttacked(bsa,attacked);
  2054. sendAndApply(&bsa);
  2055. break;
  2056. }
  2057. case 17: //lightning bolt
  2058. {
  2059. CStack * attacked = gs->curB->getStackT(ba.destinationTile);
  2060. if(!attacked) break;
  2061. BattleStackAttacked bsa;
  2062. bsa.flags |= 2;
  2063. bsa.effect = 38;
  2064. bsa.damageAmount = h->getPrimSkillLevel(2) * 25 + s->powers[getSchoolLevel(h,s)];
  2065. bsa.stackAttacked = attacked->ID;
  2066. prepareAttacked(bsa,attacked);
  2067. sendAndApply(&bsa);
  2068. break;
  2069. }
  2070. case 18: //implosion
  2071. {
  2072. CStack * attacked = gs->curB->getStackT(ba.destinationTile);
  2073. if(!attacked) break;
  2074. BattleStackAttacked bsa;
  2075. bsa.flags |= 2;
  2076. bsa.effect = 10;
  2077. bsa.damageAmount = h->getPrimSkillLevel(2) * 75 + s->powers[getSchoolLevel(h,s)];
  2078. bsa.stackAttacked = attacked->ID;
  2079. prepareAttacked(bsa,attacked);
  2080. sendAndApply(&bsa);
  2081. break;
  2082. }
  2083. case 27: //shield
  2084. case 28: //air shield
  2085. case 41: //bless
  2086. case 42: //curse
  2087. case 43: //bloodlust
  2088. case 45: //weakness
  2089. case 46: //stone skin
  2090. case 48: //prayer
  2091. case 49: //mirth
  2092. case 50: //sorrow
  2093. case 51: //fortune
  2094. case 52: //misfortune
  2095. case 53: //haste
  2096. case 54: //slow
  2097. {
  2098. SPELL_CAST_TEMPLATE_1(ba.additionalInfo, h->getPrimSkillLevel(2))
  2099. break;
  2100. }
  2101. case 56: //frenzy
  2102. {
  2103. SPELL_CAST_TEMPLATE_1(ba.additionalInfo, 1)
  2104. break;
  2105. }
  2106. case 61: //forgetfulness
  2107. {
  2108. SPELL_CAST_TEMPLATE_1(ba.additionalInfo, h->getPrimSkillLevel(2))
  2109. break;
  2110. }
  2111. }
  2112. sendAndApply(&EndAction());
  2113. }
  2114. }
  2115. }
  2116. void CGameHandler::handleTimeEvents()
  2117. {
  2118. while(gs->map->events.size() && gs->map->events.front()->firstOccurence+1 == gs->day)
  2119. {
  2120. CMapEvent *ev = gs->map->events.front();
  2121. for(int player = 0; player < PLAYER_LIMIT; player++)
  2122. {
  2123. PlayerState *pinfo = gs->getPlayer(player);
  2124. if( pinfo //player exists
  2125. && (ev->players & 1<<player) //event is enabled to this player
  2126. && ((ev->computerAffected && !pinfo->human)
  2127. || (ev->humanAffected && pinfo->human)
  2128. )
  2129. )
  2130. {
  2131. //give resources
  2132. SetResources sr;
  2133. sr.player = player;
  2134. sr.res = pinfo->resources;
  2135. //prepare dialog
  2136. InfoWindow iw;
  2137. iw.player = player;
  2138. iw.text << ev->message;
  2139. for (int i=0; i<ev->resources.size(); i++)
  2140. {
  2141. if(ev->resources[i]) //if resource is changed, we add it to the dialog
  2142. {
  2143. iw.components.push_back(Component(Component::RESOURCE,i,ev->resources[i],0));
  2144. sr.res[i] += ev->resources[i];
  2145. }
  2146. }
  2147. if (iw.components.size())
  2148. {
  2149. sendAndApply(&sr); //update player resources if changed
  2150. }
  2151. sendAndApply(&iw); //show dialog
  2152. }
  2153. } //PLAYERS LOOP
  2154. if(ev->nextOccurence)
  2155. {
  2156. ev->firstOccurence += ev->nextOccurence;
  2157. gs->map->events.sort(evntCmp);
  2158. }
  2159. else
  2160. {
  2161. delete ev;
  2162. gs->map->events.pop_front();
  2163. }
  2164. }
  2165. }
  2166. bool CGameHandler::complain( const std::string &problem )
  2167. {
  2168. sendMessageToAll("Server encountered a problem: " + problem);
  2169. tlog1 << problem << std::endl;
  2170. return true;
  2171. }