CGameHandler.cpp 68 KB

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