CGameHandler.cpp 67 KB

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