CGameHandler.cpp 73 KB

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