CGameHandler.cpp 75 KB

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