CGameHandler.cpp 67 KB

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