CGameHandler.cpp 96 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373
  1. #include "../StartInfo.h"
  2. #include "../hch/CArtHandler.h"
  3. #include "../hch/CBuildingHandler.h"
  4. #include "../hch/CDefObjInfoHandler.h"
  5. #include "../hch/CHeroHandler.h"
  6. #include "../hch/CObjectHandler.h"
  7. #include "../hch/CSpellHandler.h"
  8. #include "../hch/CTownHandler.h"
  9. #include "../lib/CGameState.h"
  10. #include "../lib/CondSh.h"
  11. #include "../lib/NetPacks.h"
  12. #include "../lib/VCMI_Lib.h"
  13. #include "../lib/map.h"
  14. #include "CGameHandler.h"
  15. #include <boost/bind.hpp>
  16. #include <boost/date_time/posix_time/posix_time_types.hpp> //no i/o just types
  17. #include <boost/foreach.hpp>
  18. #include <boost/thread.hpp>
  19. #include <boost/thread/shared_mutex.hpp>
  20. #include <boost/assign/list_of.hpp>
  21. #include <fstream>
  22. #include <boost/system/system_error.hpp>
  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. CMP_stack cmpst ;
  80. static inline double distance(int3 a, int3 b)
  81. {
  82. return std::sqrt( (double)(a.x-b.x)*(a.x-b.x) + (a.y-b.y)*(a.y-b.y) );
  83. }
  84. static void giveExp(BattleResult &r)
  85. {
  86. r.exp[0] = 0;
  87. r.exp[1] = 0;
  88. for(std::map<ui32,si32>::iterator i = r.casualties[!r.winner].begin(); i!=r.casualties[!r.winner].end(); i++)
  89. {
  90. r.exp[r.winner] += VLC->creh->creatures[i->first].hitPoints * i->second;
  91. }
  92. }
  93. PlayerStatus PlayerStatuses::operator[](ui8 player)
  94. {
  95. boost::unique_lock<boost::mutex> l(mx);
  96. if(players.find(player) != players.end())
  97. {
  98. return players[player];
  99. }
  100. else
  101. {
  102. throw std::string("No such player!");
  103. }
  104. }
  105. void PlayerStatuses::addPlayer(ui8 player)
  106. {
  107. boost::unique_lock<boost::mutex> l(mx);
  108. players[player];
  109. }
  110. bool PlayerStatuses::hasQueries(ui8 player)
  111. {
  112. boost::unique_lock<boost::mutex> l(mx);
  113. if(players.find(player) != players.end())
  114. {
  115. return players[player].queries.size();
  116. }
  117. else
  118. {
  119. throw std::string("No such player!");
  120. }
  121. }
  122. bool PlayerStatuses::checkFlag(ui8 player, bool PlayerStatus::*flag)
  123. {
  124. boost::unique_lock<boost::mutex> l(mx);
  125. if(players.find(player) != players.end())
  126. {
  127. return players[player].*flag;
  128. }
  129. else
  130. {
  131. throw std::string("No such player!");
  132. }
  133. }
  134. void PlayerStatuses::setFlag(ui8 player, bool PlayerStatus::*flag, bool val)
  135. {
  136. boost::unique_lock<boost::mutex> l(mx);
  137. if(players.find(player) != players.end())
  138. {
  139. players[player].*flag = val;
  140. }
  141. else
  142. {
  143. throw std::string("No such player!");
  144. }
  145. cv.notify_all();
  146. }
  147. void PlayerStatuses::addQuery(ui8 player, ui32 id)
  148. {
  149. boost::unique_lock<boost::mutex> l(mx);
  150. if(players.find(player) != players.end())
  151. {
  152. players[player].queries.insert(id);
  153. }
  154. else
  155. {
  156. throw std::string("No such player!");
  157. }
  158. cv.notify_all();
  159. }
  160. void PlayerStatuses::removeQuery(ui8 player, ui32 id)
  161. {
  162. boost::unique_lock<boost::mutex> l(mx);
  163. if(players.find(player) != players.end())
  164. {
  165. players[player].queries.erase(id);
  166. }
  167. else
  168. {
  169. throw std::string("No such player!");
  170. }
  171. cv.notify_all();
  172. }
  173. template <typename T>
  174. void callWith(std::vector<T> args, boost::function<void(T)> fun, ui32 which)
  175. {
  176. fun(args[which]);
  177. }
  178. void CGameHandler::changeSecSkill( int ID, int which, int val, bool abs/*=false*/ )
  179. {
  180. SetSecSkill sss;
  181. sss.id = ID;
  182. sss.which = which;
  183. sss.val = val;
  184. sss.abs = abs;
  185. sendAndApply(&sss);
  186. if(which == 7) //Wisdom
  187. {
  188. const CGHeroInstance *h = getHero(ID);
  189. if(h && h->visitedTown)
  190. giveSpells(h->visitedTown, h);
  191. }
  192. }
  193. void CGameHandler::changePrimSkill(int ID, int which, si64 val, bool abs)
  194. {
  195. SetPrimSkill sps;
  196. sps.id = ID;
  197. sps.which = which;
  198. sps.abs = abs;
  199. sps.val = val;
  200. sendAndApply(&sps);
  201. if(which==4) //only for exp - hero may level up
  202. {
  203. CGHeroInstance *hero = static_cast<CGHeroInstance *>(gs->map->objects[ID]);
  204. while (hero->exp >= VLC->heroh->reqExp(hero->level+1)) //new level
  205. {
  206. //give prim skill
  207. tlog5 << hero->name <<" got level "<<hero->level<<std::endl;
  208. int r = rand()%100, pom=0, x=0;
  209. int std::pair<int,int>::*g = (hero->level>9) ? (&std::pair<int,int>::second) : (&std::pair<int,int>::first);
  210. for(;x<PRIMARY_SKILLS;x++)
  211. {
  212. pom += hero->type->heroClass->primChance[x].*g;
  213. if(r<pom)
  214. break;
  215. }
  216. tlog5 << "Bohater dostaje umiejetnosc pierwszorzedna " << x << " (wynik losowania "<<r<<")"<<std::endl;
  217. SetPrimSkill sps;
  218. sps.id = ID;
  219. sps.which = x;
  220. sps.abs = false;
  221. sps.val = 1;
  222. sendAndApply(&sps);
  223. HeroLevelUp hlu;
  224. hlu.heroid = ID;
  225. hlu.primskill = x;
  226. hlu.level = hero->level+1;
  227. //picking sec. skills for choice
  228. std::set<int> basicAndAdv, expert, none;
  229. for(int i=0;i<SKILL_QUANTITY;i++) none.insert(i);
  230. for(unsigned i=0;i<hero->secSkills.size();i++)
  231. {
  232. if(hero->secSkills[i].second < 3)
  233. basicAndAdv.insert(hero->secSkills[i].first);
  234. else
  235. expert.insert(hero->secSkills[i].first);
  236. none.erase(hero->secSkills[i].first);
  237. }
  238. //first offered skill
  239. if(hero->secSkills.size() < hero->type->heroClass->skillLimit) //free skill slot
  240. {
  241. hlu.skills.push_back(hero->type->heroClass->chooseSecSkill(none)); //new skill
  242. none.erase(hlu.skills.back());
  243. }
  244. else if(basicAndAdv.size())
  245. {
  246. int s = hero->type->heroClass->chooseSecSkill(basicAndAdv);
  247. hlu.skills.push_back(s);
  248. basicAndAdv.erase(s);
  249. }
  250. //second offered skill
  251. if(basicAndAdv.size())
  252. {
  253. hlu.skills.push_back(hero->type->heroClass->chooseSecSkill(basicAndAdv)); //new skill
  254. }
  255. else if(hero->secSkills.size() < hero->type->heroClass->skillLimit)
  256. {
  257. hlu.skills.push_back(hero->type->heroClass->chooseSecSkill(none)); //new skill
  258. }
  259. if(hlu.skills.size() > 1) //apply and ask for secondary skill
  260. {
  261. 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));
  262. applyAndAsk(&hlu,hero->tempOwner,callback); //call changeSecSkill with appropriate args when client responds
  263. }
  264. else if(hlu.skills.size() == 1) //apply, give only possible skill and send info
  265. {
  266. sendAndApply(&hlu);
  267. changeSecSkill(ID,hlu.skills.back(),1,false);
  268. }
  269. else //apply and send info
  270. {
  271. sendAndApply(&hlu);
  272. }
  273. }
  274. }
  275. }
  276. static CCreatureSet takeCasualties(int color, const CCreatureSet &set, BattleInfo *bat)
  277. {
  278. if(color == 254)
  279. color = 255;
  280. CCreatureSet ret(set);
  281. for(int i=0; i<bat->stacks.size();i++)
  282. {
  283. if(bat->stacks[i]->hasFeatureOfType(StackFeature::SUMMONED)) //don't take into account sumoned stacks
  284. continue;
  285. CStack *st = bat->stacks[i];
  286. if(st->owner==color && vstd::contains(set.slots,st->slot) && st->amount < set.slots.find(st->slot)->second.second)
  287. {
  288. if(st->alive())
  289. ret.slots[st->slot].second = st->amount;
  290. else
  291. ret.slots.erase(st->slot);
  292. }
  293. }
  294. return ret;
  295. }
  296. void CGameHandler::startBattle(const CArmedInstance *army1, const CArmedInstance * army2, int3 tile, const CGHeroInstance *hero1, const CGHeroInstance *hero2, bool creatureBank, boost::function<void(BattleResult*)> cb, const CGTownInstance *town)
  297. {
  298. battleEndCallback = new boost::function<void(BattleResult*)>(cb);
  299. bEndArmy1 = army1;
  300. bEndArmy2 = army2;
  301. {
  302. BattleInfo *curB = new BattleInfo;
  303. curB->side1 = army1->tempOwner;
  304. curB->side2 = army2->tempOwner;
  305. if(curB->side2 == 254)
  306. curB->side2 = 255;
  307. setupBattle(curB, tile, army1->army, army2->army, hero1, hero2, creatureBank, town); //initializes stacks, places creatures on battlefield, blocks and informs player interfaces
  308. }
  309. NEW_ROUND;
  310. //TODO: pre-tactic stuff, call scripts etc.
  311. //tactic round
  312. {
  313. NEW_ROUND;
  314. if( (hero1 && hero1->getSecSkillLevel(19)>0) ||
  315. ( hero2 && hero2->getSecSkillLevel(19)>0) )//someone has tactics
  316. {
  317. //TODO: tactic round (round -1)
  318. }
  319. }
  320. //main loop
  321. while(!battleResult.get()) //till the end of the battle ;]
  322. {
  323. NEW_ROUND;
  324. std::vector<CStack*> & stacks = (gs->curB->stacks);
  325. const BattleInfo & curB = *gs->curB;
  326. //stack loop
  327. const CStack *next;
  328. while(!battleResult.get() && (next = curB.getNextStack()) && next->willMove())
  329. {
  330. //check for bad morale => freeze
  331. if(next->Morale() < 0 &&
  332. !((hero1 && hero1->hasBonusOfType(HeroBonus::BLOCK_MORALE)) || (hero2 && hero2->hasBonusOfType(HeroBonus::BLOCK_MORALE))) //checking if heroes have (or don't have) morale blocking bonuses)
  333. )
  334. {
  335. if( rand()%24 < (-next->Morale())*2 )
  336. {
  337. //unit loses its turn - empty freeze action
  338. BattleAction ba;
  339. ba.actionType = 11;
  340. ba.additionalInfo = 1;
  341. ba.side = !next->attackerOwned;
  342. ba.stackNumber = next->ID;
  343. sendAndApply(&StartAction(ba));
  344. sendAndApply(&EndAction());
  345. checkForBattleEnd(stacks); //check if this "action" ended the battle (not likely but who knows...)
  346. continue;
  347. }
  348. }
  349. if(next->hasFeatureOfType(StackFeature::ATTACKS_NEAREST_CREATURE)) //while in berserk
  350. {
  351. std::pair<const CStack *, int> attackInfo = curB.getNearestStack(next, boost::logic::indeterminate);
  352. if(attackInfo.first != NULL)
  353. {
  354. BattleAction attack;
  355. attack.actionType = 6;
  356. attack.side = !next->attackerOwned;
  357. attack.stackNumber = next->ID;
  358. attack.additionalInfo = attackInfo.first->position;
  359. attack.destinationTile = attackInfo.second;
  360. makeBattleAction(attack);
  361. checkForBattleEnd(stacks);
  362. }
  363. continue;
  364. }
  365. const CGHeroInstance * curOwner = gs->battleGetOwner(next->ID);
  366. if(next->position < 0 && (!curOwner || curOwner->getSecSkillLevel(10) == 0)) //arrow turret, hero has no ballistics
  367. {
  368. BattleAction attack;
  369. attack.actionType = 7;
  370. attack.side = !next->attackerOwned;
  371. attack.stackNumber = next->ID;
  372. for(int g=0; g<gs->curB->stacks.size(); ++g)
  373. {
  374. if(gs->curB->stacks[g]->attackerOwned)
  375. {
  376. attack.destinationTile = gs->curB->stacks[g]->position;
  377. break;
  378. }
  379. }
  380. makeBattleAction(attack);
  381. checkForBattleEnd(stacks);
  382. continue;
  383. }
  384. if(next->creature->idNumber == 145 && (!curOwner || curOwner->getSecSkillLevel(10) == 0)) //catapult, hero has no ballistics
  385. {
  386. BattleAction attack;
  387. static const int wallHexes[] = {50, 183, 182, 130, 62, 29, 12, 95};
  388. attack.destinationTile = wallHexes[ rand()%ARRAY_COUNT(wallHexes) ];
  389. attack.actionType = 9;
  390. attack.additionalInfo = 0;
  391. attack.side = !next->attackerOwned;
  392. attack.stackNumber = next->ID;
  393. makeBattleAction(attack);
  394. continue;
  395. }
  396. askInterfaceForMove:
  397. //ask interface and wait for answer
  398. if(!battleResult.get())
  399. {
  400. BattleSetActiveStack sas;
  401. sas.stack = next->ID;
  402. sendAndApply(&sas);
  403. boost::unique_lock<boost::mutex> lock(battleMadeAction.mx);
  404. while(!battleMadeAction.data && !battleResult.get()) //active stack hasn't made its action and battle is still going
  405. battleMadeAction.cond.wait(lock);
  406. battleMadeAction.data = false;
  407. }
  408. else
  409. {
  410. break;
  411. }
  412. //we're after action, all results applied
  413. checkForBattleEnd(stacks); //check if this action ended the battle
  414. //check for good morale
  415. if(!vstd::contains(next->state,HAD_MORALE) //only one extra move per turn possible
  416. && !vstd::contains(next->state,DEFENDING)
  417. && !vstd::contains(next->state,WAITING)
  418. && next->alive()
  419. && next->Morale() > 0
  420. && !((hero1 && hero1->hasBonusOfType(HeroBonus::BLOCK_MORALE)) || (hero2 && hero2->hasBonusOfType(HeroBonus::BLOCK_MORALE)) ) //checking if heroes have (or don't have) morale blocking bonuses
  421. )
  422. if(rand()%24 < next->Morale()) //this stack hasn't got morale this turn
  423. goto askInterfaceForMove; //move this stack once more
  424. }
  425. }
  426. endBattle(tile, hero1, hero2);
  427. }
  428. void CGameHandler::endBattle(int3 tile, const CGHeroInstance *hero1, const CGHeroInstance *hero2)
  429. {
  430. BattleResultsApplied resultsApplied;
  431. resultsApplied.player1 = bEndArmy1->tempOwner;
  432. resultsApplied.player2 = bEndArmy2->tempOwner;
  433. //unblock engaged players
  434. if(bEndArmy1->tempOwner<PLAYER_LIMIT)
  435. states.setFlag(bEndArmy1->tempOwner, &PlayerStatus::engagedIntoBattle, false);
  436. if(bEndArmy2 && bEndArmy2->tempOwner<PLAYER_LIMIT)
  437. states.setFlag(bEndArmy2->tempOwner, &PlayerStatus::engagedIntoBattle, false);
  438. //casualties among heroes armies
  439. SetGarrisons sg;
  440. sg.garrs[bEndArmy1->id] = takeCasualties(bEndArmy1->tempOwner, bEndArmy1->army, gs->curB);
  441. sg.garrs[bEndArmy2->id] = takeCasualties(bEndArmy2->tempOwner, bEndArmy2->army, gs->curB);
  442. sendAndApply(&sg);
  443. //end battle, remove all info, free memory
  444. giveExp(*battleResult.data);
  445. sendAndApply(battleResult.data);
  446. //if one hero has lost we will erase him
  447. if(battleResult.data->winner!=0 && hero1)
  448. {
  449. RemoveObject ro(hero1->id);
  450. sendAndApply(&ro);
  451. }
  452. if(battleResult.data->winner!=1 && hero2)
  453. {
  454. RemoveObject ro(hero2->id);
  455. sendAndApply(&ro);
  456. }
  457. //give exp
  458. if(battleResult.data->exp[0] && hero1)
  459. changePrimSkill(hero1->id,4,battleResult.data->exp[0]);
  460. if(battleResult.data->exp[1] && hero2)
  461. changePrimSkill(hero2->id,4,battleResult.data->exp[1]);
  462. if(battleEndCallback && *battleEndCallback)
  463. {
  464. (*battleEndCallback)(battleResult.data);
  465. delete battleEndCallback;
  466. battleEndCallback = 0;
  467. }
  468. sendAndApply(&resultsApplied);
  469. // Necromancy if applicable.
  470. const CGHeroInstance *winnerHero = battleResult.data->winner != 0 ? hero2 : hero1;
  471. if (winnerHero) {
  472. std::pair<ui32, si32> raisedStack = winnerHero->calculateNecromancy(*battleResult.data);
  473. // Give raised units to winner and show dialog, if any were raised.
  474. if (raisedStack.first != -1) {
  475. int slot = winnerHero->army.getSlotFor(raisedStack.first);
  476. if (slot != -1) {
  477. SetGarrisons sg;
  478. sg.garrs[winnerHero->id] = winnerHero->army;
  479. if (vstd::contains(winnerHero->army.slots, slot)) // Add to existing stack.
  480. sg.garrs[winnerHero->id].slots[slot].second += raisedStack.second;
  481. else // Create a new stack.
  482. sg.garrs[winnerHero->id].slots[slot] = raisedStack;
  483. winnerHero->showNecromancyDialog(raisedStack);
  484. sendAndApply(&sg);
  485. }
  486. }
  487. }
  488. delete battleResult.data;
  489. }
  490. void CGameHandler::prepareAttacked(BattleStackAttacked &bsa, const CStack *def)
  491. {
  492. bsa.killedAmount = bsa.damageAmount / def->MaxHealth();
  493. unsigned damageFirst = bsa.damageAmount % def->MaxHealth();
  494. if( def->firstHPleft <= damageFirst )
  495. {
  496. bsa.killedAmount++;
  497. bsa.newHP = def->firstHPleft + def->MaxHealth() - damageFirst;
  498. }
  499. else
  500. {
  501. bsa.newHP = def->firstHPleft - damageFirst;
  502. }
  503. if(def->amount <= bsa.killedAmount) //stack killed
  504. {
  505. bsa.newAmount = 0;
  506. bsa.flags |= 1;
  507. bsa.killedAmount = def->amount; //we cannot kill more creatures than we have
  508. }
  509. else
  510. {
  511. bsa.newAmount = def->amount - bsa.killedAmount;
  512. }
  513. }
  514. void CGameHandler::prepareAttack(BattleAttack &bat, const CStack *att, const CStack *def, int distance)
  515. {
  516. bat.bsa.clear();
  517. bat.stackAttacking = att->ID;
  518. std::set<BattleStackAttacked>::iterator i = bat.bsa.insert(BattleStackAttacked()).first;
  519. #ifdef __GNUC__
  520. BattleStackAttacked *bsa = (BattleStackAttacked *)&*i;
  521. #else
  522. BattleStackAttacked *bsa = &*i;
  523. #endif
  524. bsa->stackAttacked = def->ID;
  525. bsa->attackerID = att->ID;
  526. bsa->damageAmount = BattleInfo::calculateDmg(att, def, gs->battleGetOwner(att->ID), gs->battleGetOwner(def->ID), bat.shot(), distance);//counting dealt damage
  527. if(att->Luck() > 0 && rand()%24 < att->Luck())
  528. {
  529. bsa->damageAmount *= 2;
  530. bat.flags |= 4;
  531. }
  532. prepareAttacked(*bsa, def);
  533. }
  534. void CGameHandler::handleConnection(std::set<int> players, CConnection &c)
  535. {
  536. srand(time(NULL));
  537. CPack *pack = NULL;
  538. try
  539. {
  540. while(!end2)
  541. {
  542. {
  543. boost::unique_lock<boost::mutex> lock(*c.rmx);
  544. c >> pack; //get the package
  545. tlog5 << "Received client message of type " << typeid(*pack).name() << std::endl;
  546. }
  547. int packType = typeList.getTypeID(pack); //get the id of type
  548. CBaseForGHApply *apply = applier->apps[packType]; //and appropriae applier object
  549. if(apply)
  550. {
  551. bool result = apply->applyOnGH(this,&c,pack);
  552. tlog5 << "Message successfully applied (result=" << result << ")!\n";
  553. //send confirmation that we've applied the package
  554. if(pack->type != 6000) //WORKAROUND - not confirm query replies TODO: reconsider
  555. {
  556. PackageApplied applied;
  557. applied.result = result;
  558. applied.packType = packType;
  559. {
  560. boost::unique_lock<boost::mutex> lock(*c.wmx);
  561. c << &applied;
  562. }
  563. }
  564. }
  565. else
  566. {
  567. tlog1 << "Message cannot be applied, cannot find applier (unregistered type)!\n";
  568. }
  569. delete pack;
  570. pack = NULL;
  571. }
  572. }
  573. catch(boost::system::system_error &e) //for boost errors just log, not crash - probably client shut down connection
  574. {
  575. tlog1 << e.what() << std::endl;
  576. end2 = true;
  577. }
  578. HANDLE_EXCEPTION(end2 = true);
  579. handleConEnd:
  580. tlog1 << "Ended handling connection\n";
  581. #undef SPELL_CAST_TEMPLATE_1
  582. #undef SPELL_CAST_TEMPLATE_2
  583. }
  584. int CGameHandler::moveStack(int stack, int dest)
  585. {
  586. int ret = 0;
  587. CStack *curStack = gs->curB->getStack(stack),
  588. *stackAtEnd = gs->curB->getStackT(dest);
  589. assert(curStack);
  590. assert(dest < BFIELD_SIZE);
  591. //initing necessary tables
  592. bool accessibility[BFIELD_SIZE];
  593. std::vector<int> accessible = gs->curB->getAccessibility(curStack->ID, false);
  594. for(int b=0; b<BFIELD_SIZE; ++b)
  595. {
  596. accessibility[b] = false;
  597. }
  598. for(int g=0; g<accessible.size(); ++g)
  599. {
  600. accessibility[accessible[g]] = true;
  601. }
  602. //shifting destination (if we have double wide stack and we can occupy dest but not be exactly there)
  603. if(!stackAtEnd && curStack->hasFeatureOfType(StackFeature::DOUBLE_WIDE) && !accessibility[dest])
  604. {
  605. if(curStack->attackerOwned)
  606. {
  607. if(accessibility[dest+1])
  608. dest+=1;
  609. }
  610. else
  611. {
  612. if(accessibility[dest-1])
  613. dest-=1;
  614. }
  615. }
  616. if((stackAtEnd && stackAtEnd!=curStack && stackAtEnd->alive()) || !accessibility[dest])
  617. return 0;
  618. bool accessibilityWithOccupyable[BFIELD_SIZE];
  619. std::vector<int> accOc = gs->curB->getAccessibility(curStack->ID, true);
  620. for(int b=0; b<BFIELD_SIZE; ++b)
  621. {
  622. accessibilityWithOccupyable[b] = false;
  623. }
  624. for(int g=0; g<accOc.size(); ++g)
  625. {
  626. accessibilityWithOccupyable[accOc[g]] = true;
  627. }
  628. //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
  629. // return false;
  630. std::pair< std::vector<int>, int > path = gs->curB->getPath(curStack->position, dest, accessibilityWithOccupyable, curStack->hasFeatureOfType(StackFeature::FLYING), curStack->hasFeatureOfType(StackFeature::DOUBLE_WIDE), curStack->attackerOwned);
  631. ret = path.second;
  632. if(curStack->hasFeatureOfType(StackFeature::FLYING))
  633. {
  634. if(path.second <= curStack->Speed() && path.first.size() > 0)
  635. {
  636. //inform clients about move
  637. BattleStackMoved sm;
  638. sm.stack = curStack->ID;
  639. sm.tile = path.first[0];
  640. sm.distance = path.second;
  641. sm.ending = true;
  642. sendAndApply(&sm);
  643. }
  644. }
  645. else //for non-flying creatures
  646. {
  647. int tilesToMove = std::max((int)(path.first.size() - curStack->Speed()), 0);
  648. for(int v=path.first.size()-1; v>=tilesToMove; --v)
  649. {
  650. //inform clients about move
  651. BattleStackMoved sm;
  652. sm.stack = curStack->ID;
  653. sm.tile = path.first[v];
  654. sm.distance = path.second;
  655. sm.ending = v==tilesToMove;
  656. sendAndApply(&sm);
  657. }
  658. }
  659. return ret;
  660. }
  661. CGameHandler::CGameHandler(void)
  662. {
  663. QID = 1;
  664. gs = NULL;
  665. IObjectInterface::cb = this;
  666. applier = new CGHApplier;
  667. }
  668. CGameHandler::~CGameHandler(void)
  669. {
  670. delete applier;
  671. applier = NULL;
  672. delete gs;
  673. }
  674. void CGameHandler::init(StartInfo *si, int Seed)
  675. {
  676. Mapa *map = new Mapa(si->mapname);
  677. tlog0 << "Map loaded!" << std::endl;
  678. gs = new CGameState();
  679. tlog0 << "Gamestate created!" << std::endl;
  680. gs->init(si,map,Seed);
  681. tlog0 << "Gamestate initialized!" << std::endl;
  682. for(std::map<ui8,PlayerState>::iterator i = gs->players.begin(); i != gs->players.end(); i++)
  683. states.addPlayer(i->first);
  684. }
  685. static bool evntCmp(const CMapEvent *a, const CMapEvent *b)
  686. {
  687. return *a < *b;
  688. }
  689. void CGameHandler::newTurn()
  690. {
  691. tlog5 << "Turn " << gs->day+1 << std::endl;
  692. NewTurn n;
  693. n.day = gs->day + 1;
  694. n.resetBuilded = true;
  695. std::map<ui32,CGHeroInstance *> pool = gs->hpool.heroesPool;
  696. for ( std::map<ui8, PlayerState>::iterator i=gs->players.begin() ; i!=gs->players.end();i++)
  697. {
  698. if(i->first == 255) continue;
  699. if(gs->getDate(1)==7) //first day of week - new heroes in tavern
  700. {
  701. SetAvailableHeroes sah;
  702. sah.player = i->first;
  703. CGHeroInstance *h = gs->hpool.pickHeroFor(true,i->first,&VLC->townh->towns[gs->scenarioOps->getIthPlayersSettings(i->first).castle], pool);
  704. if(h)
  705. sah.hid1 = h->subID;
  706. else
  707. sah.hid1 = -1;
  708. h = gs->hpool.pickHeroFor(false,i->first,&VLC->townh->towns[gs->scenarioOps->getIthPlayersSettings(i->first).castle], pool);
  709. if(h)
  710. sah.hid2 = h->subID;
  711. else
  712. sah.hid2 = -1;
  713. sendAndApply(&sah);
  714. }
  715. if(i->first>=PLAYER_LIMIT) continue;
  716. SetResources r;
  717. r.player = i->first;
  718. for(int j=0;j<RESOURCE_QUANTITY;j++)
  719. r.res[j] = i->second.resources[j];
  720. BOOST_FOREACH(CGHeroInstance *h, (*i).second.heroes)
  721. {
  722. if(h->visitedTown)
  723. giveSpells(h->visitedTown, h);
  724. NewTurn::Hero hth;
  725. hth.id = h->id;
  726. hth.move = h->maxMovePoints(gs->map->getTile(h->getPosition(false)).tertype != TerrainTile::water);
  727. if(h->visitedTown && vstd::contains(h->visitedTown->builtBuildings,0)) //if hero starts turn in town with mage guild
  728. hth.mana = h->manaLimit(); //restore all mana
  729. else
  730. hth.mana = std::max(si32(0), std::min(h->mana + h->manaRegain(), h->manaLimit()) );
  731. n.heroes.insert(hth);
  732. if(gs->day) //not first day
  733. {
  734. switch(h->getSecSkillLevel(13)) //handle estates - give gold
  735. {
  736. case 1: //basic
  737. r.res[6] += 125;
  738. break;
  739. case 2: //advanced
  740. r.res[6] += 250;
  741. break;
  742. case 3: //expert
  743. r.res[6] += 500;
  744. break;
  745. }
  746. for(std::list<HeroBonus>::iterator i = h->bonuses.begin(); i != h->bonuses.end(); i++)
  747. if(i->type == HeroBonus::GENERATE_RESOURCE)
  748. r.res[i->subtype] += i->val;
  749. }
  750. }
  751. for(std::vector<CGTownInstance *>::iterator j=i->second.towns.begin();j!=i->second.towns.end();j++)//handle towns
  752. {
  753. if(gs->day && vstd::contains((**j).builtBuildings,15)) //not first day and there is resource silo
  754. {
  755. if((**j).town->primaryRes == 127) //we'll give wood and ore
  756. {
  757. r.res[0] += 1;
  758. r.res[2] += 1;
  759. }
  760. else
  761. {
  762. r.res[(**j).town->primaryRes] += 1;
  763. }
  764. }
  765. if(gs->getDate(1)==7) //first day of week
  766. {
  767. SetAvailableCreatures sac;
  768. sac.tid = (**j).id;
  769. sac.creatures = (**j).creatures;
  770. for(int k=0;k<CREATURES_PER_TOWN;k++) //creature growths
  771. {
  772. if((**j).creatureDwelling(k))//there is dwelling (k-level)
  773. {
  774. sac.creatures[k].first += (**j).creatureGrowth(k);
  775. if(!gs->getDate(0)) //first day of game: use only basic growths
  776. amin(sac.creatures[k].first, VLC->creh->creatures[(*j)->town->basicCreatures[k]].growth);
  777. }
  778. }
  779. n.cres.push_back(sac);
  780. }
  781. if(gs->day && i->first<PLAYER_LIMIT)//not the first day and town not neutral
  782. r.res[6] += (**j).dailyIncome();
  783. }
  784. n.res.push_back(r);
  785. }
  786. sendAndApply(&n);
  787. tlog5 << "Info about turn " << n.day << "has been sent!" << std::endl;
  788. handleTimeEvents();
  789. //call objects
  790. for(size_t i = 0; i<gs->map->objects.size(); i++)
  791. if(gs->map->objects[i])
  792. gs->map->objects[i]->newTurn();
  793. }
  794. void CGameHandler::run(bool resume)
  795. {
  796. BOOST_FOREACH(CConnection *cc, conns)
  797. {//init conn.
  798. ui8 quantity, pom;
  799. //ui32 seed;
  800. if(!resume)
  801. (*cc) << gs->scenarioOps->mapname << gs->map->checksum << gs->seed;
  802. (*cc) >> quantity; //how many players will be handled at that client
  803. for(int i=0;i<quantity;i++)
  804. {
  805. (*cc) >> pom; //read player color
  806. {
  807. boost::unique_lock<boost::recursive_mutex> lock(gsm);
  808. connections[pom] = cc;
  809. }
  810. }
  811. }
  812. for(std::set<CConnection*>::iterator i = conns.begin(); i!=conns.end();i++)
  813. {
  814. std::set<int> pom;
  815. for(std::map<int,CConnection*>::iterator j = connections.begin(); j!=connections.end();j++)
  816. if(j->second == *i)
  817. pom.insert(j->first);
  818. boost::thread(boost::bind(&CGameHandler::handleConnection,this,pom,boost::ref(**i)));
  819. }
  820. while (!end2)
  821. {
  822. if(!resume)
  823. newTurn();
  824. else
  825. resume = false;
  826. std::map<ui8,PlayerState>::iterator i;
  827. if(!resume)
  828. i = gs->players.begin();
  829. else
  830. i = gs->players.find(gs->currentPlayer);
  831. for(; i != gs->players.end(); i++)
  832. {
  833. 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
  834. states.setFlag(i->first,&PlayerStatus::makingTurn,true);
  835. gs->currentPlayer = i->first;
  836. {
  837. YourTurn yt;
  838. yt.player = i->first;
  839. boost::unique_lock<boost::mutex> lock(*connections[i->first]->wmx);
  840. *connections[i->first] << &yt;
  841. }
  842. //wait till turn is done
  843. boost::unique_lock<boost::mutex> lock(states.mx);
  844. while(states.players[i->first].makingTurn && !end2)
  845. {
  846. boost::posix_time::time_duration p;
  847. p = boost::posix_time::milliseconds(200);
  848. states.cv.timed_wait(lock,p);
  849. }
  850. }
  851. }
  852. }
  853. namespace CGH
  854. {
  855. using namespace std;
  856. static void readItTo(ifstream & input, vector< vector<int> > & dest) //reads 7 lines, i-th one containing i integers, and puts it to dest
  857. {
  858. for(int j=0; j<7; ++j)
  859. {
  860. std::vector<int> pom;
  861. for(int g=0; g<j+1; ++g)
  862. {
  863. int hlp; input>>hlp;
  864. pom.push_back(hlp);
  865. }
  866. dest.push_back(pom);
  867. }
  868. }
  869. }
  870. void CGameHandler::setupBattle( BattleInfo * curB, int3 tile, const CCreatureSet &army1, const CCreatureSet &army2, const CGHeroInstance * hero1, const CGHeroInstance * hero2, bool creatureBank, const CGTownInstance *town)
  871. {
  872. battleResult.set(NULL);
  873. std::vector<CStack*> & stacks = (curB->stacks);
  874. curB->tile = tile;
  875. curB->army1=army1;
  876. curB->army2=army2;
  877. curB->hero1=(hero1)?(hero1->id):(-1);
  878. curB->hero2=(hero2)?(hero2->id):(-1);
  879. curB->round = -2;
  880. curB->activeStack = -1;
  881. if(town)
  882. {
  883. curB->tid = town->id;
  884. curB->siege = town->fortLevel();
  885. }
  886. else
  887. {
  888. curB->tid = -1;
  889. curB->siege = 0;
  890. }
  891. //reading battleStartpos
  892. std::ifstream positions;
  893. positions.open("config" PATHSEPARATOR "battleStartpos.txt", std::ios_base::in|std::ios_base::binary);
  894. if(!positions.is_open())
  895. {
  896. tlog1<<"Unable to open battleStartpos.txt!"<<std::endl;
  897. }
  898. std::string dump;
  899. positions>>dump; positions>>dump;
  900. std::vector< std::vector<int> > attackerLoose, defenderLoose, attackerTight, defenderTight, attackerCreBank, defenderCreBank;
  901. CGH::readItTo(positions, attackerLoose);
  902. positions>>dump;
  903. CGH::readItTo(positions, defenderLoose);
  904. positions>>dump;
  905. positions>>dump;
  906. CGH::readItTo(positions, attackerTight);
  907. positions>>dump;
  908. CGH::readItTo(positions, defenderTight);
  909. positions>>dump;
  910. positions>>dump;
  911. CGH::readItTo(positions, attackerCreBank);
  912. positions>>dump;
  913. CGH::readItTo(positions, defenderCreBank);
  914. positions.close();
  915. //battleStartpos read
  916. int k = 0; //stack serial
  917. for(std::map<si32,std::pair<ui32,si32> >::const_iterator i = army1.slots.begin(); i!=army1.slots.end(); i++, k++)
  918. {
  919. int pos;
  920. if(creatureBank)
  921. pos = attackerCreBank[army1.slots.size()-1][k];
  922. else if(army1.formation)
  923. pos = attackerTight[army1.slots.size()-1][k];
  924. else
  925. pos = attackerLoose[army1.slots.size()-1][k];
  926. CStack * stack = curB->generateNewStack(hero1, i->second.first, i->second.second, stacks.size(), true, i->first, gs->map->terrain[tile.x][tile.y][tile.z].tertype, pos);
  927. stacks.push_back(stack);
  928. }
  929. k = 0;
  930. for(std::map<si32,std::pair<ui32,si32> >::const_iterator i = army2.slots.begin(); i!=army2.slots.end(); i++, k++)
  931. {
  932. int pos;
  933. if(creatureBank)
  934. pos = defenderCreBank[army2.slots.size()-1][k];
  935. else if(army2.formation)
  936. pos = defenderTight[army2.slots.size()-1][k];
  937. else
  938. pos = defenderLoose[army2.slots.size()-1][k];
  939. CStack * stack = curB->generateNewStack(hero2, i->second.first, i->second.second, stacks.size(), false, i->first, gs->map->terrain[tile.x][tile.y][tile.z].tertype, pos);
  940. stacks.push_back(stack);
  941. }
  942. for(unsigned g=0; g<stacks.size(); ++g) //shifting positions of two-hex creatures
  943. {
  944. if((stacks[g]->position%17)==1 && stacks[g]->hasFeatureOfType(StackFeature::DOUBLE_WIDE) && stacks[g]->attackerOwned)
  945. {
  946. stacks[g]->position += 1;
  947. }
  948. else if((stacks[g]->position%17)==15 && stacks[g]->hasFeatureOfType(StackFeature::DOUBLE_WIDE) && !stacks[g]->attackerOwned)
  949. {
  950. stacks[g]->position -= 1;
  951. }
  952. }
  953. //adding war machines
  954. if(hero1)
  955. {
  956. if(hero1->getArt(13)) //ballista
  957. {
  958. CStack * stack = curB->generateNewStack(hero1, 146, 1, stacks.size(), true, 255, gs->map->terrain[tile.x][tile.y][tile.z].tertype, 52);
  959. stacks.push_back(stack);
  960. }
  961. if(hero1->getArt(14)) //ammo cart
  962. {
  963. CStack * stack = curB->generateNewStack(hero1, 148, 1, stacks.size(), true, 255, gs->map->terrain[tile.x][tile.y][tile.z].tertype, 18);
  964. stacks.push_back(stack);
  965. }
  966. if(hero1->getArt(15)) //first aid tent
  967. {
  968. CStack * stack = curB->generateNewStack(hero1, 147, 1, stacks.size(), true, 255, gs->map->terrain[tile.x][tile.y][tile.z].tertype, 154);
  969. stacks.push_back(stack);
  970. }
  971. }
  972. if(hero2)
  973. {
  974. if(hero2->getArt(13)) //ballista
  975. {
  976. CStack * stack = curB->generateNewStack(hero2, 146, 1, stacks.size(), false, 255, gs->map->terrain[tile.x][tile.y][tile.z].tertype, 66);
  977. stacks.push_back(stack);
  978. }
  979. if(hero2->getArt(14)) //ammo cart
  980. {
  981. CStack * stack = curB->generateNewStack(hero2, 148, 1, stacks.size(), false, 255, gs->map->terrain[tile.x][tile.y][tile.z].tertype, 32);
  982. stacks.push_back(stack);
  983. }
  984. if(hero2->getArt(15)) //first aid tent
  985. {
  986. CStack * stack = curB->generateNewStack(hero2, 147, 1, stacks.size(), false, 255, gs->map->terrain[tile.x][tile.y][tile.z].tertype, 168);
  987. stacks.push_back(stack);
  988. }
  989. }
  990. if(town && hero1) //catapult
  991. {
  992. CStack * stack = curB->generateNewStack(hero1, 145, 1, stacks.size(), true, 255, gs->map->terrain[tile.x][tile.y][tile.z].tertype, 120);
  993. stacks.push_back(stack);
  994. }
  995. //war machines added
  996. switch(curB->siege) //adding towers
  997. {
  998. case 3: //castle
  999. {//lower tower / upper tower
  1000. CStack * stack = curB->generateNewStack(hero2, 149, 1, stacks.size(), false, 255, gs->map->terrain[tile.x][tile.y][tile.z].tertype, -4);
  1001. stacks.push_back(stack);
  1002. stack = curB->generateNewStack(hero2, 149, 1, stacks.size(), false, 255, gs->map->terrain[tile.x][tile.y][tile.z].tertype, -3);
  1003. stacks.push_back(stack);
  1004. }
  1005. case 2: //citadel
  1006. {//main tower
  1007. CStack * stack = curB->generateNewStack(hero2, 149, 1, stacks.size(), false, 255, gs->map->terrain[tile.x][tile.y][tile.z].tertype, -2);
  1008. stacks.push_back(stack);
  1009. }
  1010. }
  1011. std::stable_sort(stacks.begin(),stacks.end(),cmpst);
  1012. //seting up siege
  1013. if(town)
  1014. {
  1015. for(int b=0; b<ARRAY_COUNT(curB->si.wallState); ++b)
  1016. {
  1017. curB->si.wallState[b] = 1;
  1018. }
  1019. }
  1020. int terType = gs->battleGetBattlefieldType(tile);
  1021. //randomize obstacles
  1022. if(town == NULL && !creatureBank) //do it only when it's not siege and not creature bank
  1023. {
  1024. bool obAv[BFIELD_SIZE]; //availability of hexes for obstacles;
  1025. std::vector<int> possibleObstacles;
  1026. for(int i=0; i<BFIELD_SIZE; ++i)
  1027. {
  1028. if(i%17 < 4 || i%17 > 12)
  1029. {
  1030. obAv[i] = false;
  1031. }
  1032. else
  1033. {
  1034. obAv[i] = true;
  1035. }
  1036. }
  1037. for(std::map<int, CObstacleInfo>::const_iterator g=VLC->heroh->obstacles.begin(); g!=VLC->heroh->obstacles.end(); ++g)
  1038. {
  1039. 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
  1040. {
  1041. possibleObstacles.push_back(g->first);
  1042. }
  1043. }
  1044. srand(time(NULL));
  1045. if(possibleObstacles.size() > 0) //we cannot place any obstacles when we don't have them
  1046. {
  1047. int toBlock = rand()%6 + 6; //how many hexes should be blocked by obstacles
  1048. while(toBlock>0)
  1049. {
  1050. CObstacleInstance coi;
  1051. coi.uniqueID = curB->obstacles.size();
  1052. coi.ID = possibleObstacles[rand()%possibleObstacles.size()];
  1053. coi.pos = rand()%BFIELD_SIZE;
  1054. std::vector<int> block = VLC->heroh->obstacles[coi.ID].getBlocked(coi.pos);
  1055. bool badObstacle = false;
  1056. for(int b=0; b<block.size(); ++b)
  1057. {
  1058. if(block[b] < 0 || block[b] >= BFIELD_SIZE || !obAv[block[b]])
  1059. {
  1060. badObstacle = true;
  1061. break;
  1062. }
  1063. }
  1064. if(badObstacle) continue;
  1065. //obstacle can be placed
  1066. curB->obstacles.push_back(coi);
  1067. for(int b=0; b<block.size(); ++b)
  1068. {
  1069. if(block[b] >= 0 && block[b] < BFIELD_SIZE)
  1070. obAv[block[b]] = false;
  1071. }
  1072. toBlock -= block.size();
  1073. }
  1074. }
  1075. }
  1076. //giving terrain premies for heroes & stacks
  1077. int bonusSubtype = -1;
  1078. switch(terType)
  1079. {
  1080. case 9: //magic plains
  1081. {
  1082. bonusSubtype = 0;
  1083. }
  1084. case 14: //fiery fields
  1085. {
  1086. if(bonusSubtype == -1) bonusSubtype = 1;
  1087. }
  1088. case 15: //rock lands
  1089. {
  1090. if(bonusSubtype == -1) bonusSubtype = 8;
  1091. }
  1092. case 16: //magic clouds
  1093. {
  1094. if(bonusSubtype == -1) bonusSubtype = 2;
  1095. }
  1096. case 17: //lucid pools
  1097. {
  1098. if(bonusSubtype == -1) bonusSubtype = 4;
  1099. }
  1100. { //common part for cases 9, 14, 15, 16, 17
  1101. const CGHeroInstance * cHero = NULL;
  1102. for(int i=0; i<2; ++i)
  1103. {
  1104. if(i == 0) cHero = hero1;
  1105. else cHero = hero2;
  1106. if(cHero == NULL) continue;
  1107. GiveBonus gs;
  1108. gs.bonus = HeroBonus(HeroBonus::ONE_BATTLE, HeroBonus::MAGIC_SCHOOL_SKILL, HeroBonus::OBJECT, 3, -1, "", bonusSubtype);
  1109. gs.hid = cHero->id;
  1110. sendAndApply(&gs);
  1111. }
  1112. break;
  1113. }
  1114. case 18: //holy ground
  1115. {
  1116. for(int g=0; g<stacks.size(); ++g) //+1 morale bonus for good creatures, -1 morale bonus for evil creatures
  1117. {
  1118. if (stacks[g]->creature->isGood())
  1119. stacks[g]->features.push_back(makeFeature(StackFeature::MORALE_BONUS, StackFeature::WHOLE_BATTLE, 0, 1, StackFeature::OTHER_SOURCE));
  1120. else if (stacks[g]->creature->isEvil())
  1121. stacks[g]->features.push_back(makeFeature(StackFeature::MORALE_BONUS, StackFeature::WHOLE_BATTLE, 0, -1, StackFeature::OTHER_SOURCE));
  1122. }
  1123. break;
  1124. }
  1125. case 19: //clover field
  1126. {
  1127. for(int g=0; g<stacks.size(); ++g)
  1128. {
  1129. if(stacks[g]->creature->faction == -1) //+2 luck bonus for neutral creatures
  1130. {
  1131. stacks[g]->features.push_back(makeFeature(StackFeature::LUCK_BONUS, StackFeature::WHOLE_BATTLE, 0, 2, StackFeature::OTHER_SOURCE));
  1132. }
  1133. }
  1134. break;
  1135. }
  1136. case 20: //evil fog
  1137. {
  1138. for(int g=0; g<stacks.size(); ++g) //-1 morale bonus for good creatures, +1 morale bonus for evil creatures
  1139. {
  1140. if (stacks[g]->creature->isGood())
  1141. stacks[g]->features.push_back(makeFeature(StackFeature::MORALE_BONUS, StackFeature::WHOLE_BATTLE, 0, -1, StackFeature::OTHER_SOURCE));
  1142. else if (stacks[g]->creature->isEvil())
  1143. stacks[g]->features.push_back(makeFeature(StackFeature::MORALE_BONUS, StackFeature::WHOLE_BATTLE, 0, 1, StackFeature::OTHER_SOURCE));
  1144. }
  1145. break;
  1146. }
  1147. case 22: //cursed ground
  1148. {
  1149. for(int g=0; g<stacks.size(); ++g) //no luck nor morale
  1150. {
  1151. stacks[g]->features.push_back(makeFeature(StackFeature::NO_MORALE, StackFeature::WHOLE_BATTLE, 0, 0, StackFeature::OTHER_SOURCE));
  1152. stacks[g]->features.push_back(makeFeature(StackFeature::NO_LUCK, StackFeature::WHOLE_BATTLE, 0, 0, StackFeature::OTHER_SOURCE));
  1153. }
  1154. const CGHeroInstance * cHero = NULL;
  1155. for(int i=0; i<2; ++i) //blocking spells above level 1
  1156. {
  1157. if(i == 0) cHero = hero1;
  1158. else cHero = hero2;
  1159. if(cHero == NULL) continue;
  1160. GiveBonus gs;
  1161. gs.bonus = HeroBonus(HeroBonus::ONE_BATTLE, HeroBonus::BLOCK_SPELLS_ABOVE_LEVEL, HeroBonus::OBJECT, 1, -1, "", bonusSubtype);
  1162. gs.hid = cHero->id;
  1163. sendAndApply(&gs);
  1164. }
  1165. break;
  1166. }
  1167. }
  1168. //premies given
  1169. //send info about battles
  1170. BattleStart bs;
  1171. bs.info = curB;
  1172. sendAndApply(&bs);
  1173. }
  1174. void CGameHandler::checkForBattleEnd( std::vector<CStack*> &stacks )
  1175. {
  1176. //checking winning condition
  1177. bool hasStack[2]; //hasStack[0] - true if attacker has a living stack; defender similarily
  1178. hasStack[0] = hasStack[1] = false;
  1179. for(int b = 0; b<stacks.size(); ++b)
  1180. {
  1181. if(stacks[b]->alive() && !stacks[b]->hasFeatureOfType(StackFeature::SIEGE_WEAPON))
  1182. {
  1183. hasStack[1-stacks[b]->attackerOwned] = true;
  1184. }
  1185. }
  1186. if(!hasStack[0] || !hasStack[1]) //somebody has won
  1187. {
  1188. BattleResult *br = new BattleResult; //will be deleted at the end of startBattle(...)
  1189. br->result = 0;
  1190. br->winner = hasStack[1]; //fleeing side loses
  1191. gs->curB->calculateCasualties(br->casualties);
  1192. battleResult.set(br);
  1193. }
  1194. }
  1195. void CGameHandler::giveSpells( const CGTownInstance *t, const CGHeroInstance *h )
  1196. {
  1197. if(!vstd::contains(h->artifWorn,17))
  1198. return; //hero hasn't spellbok
  1199. ChangeSpells cs;
  1200. cs.hid = h->id;
  1201. cs.learn = true;
  1202. for(int i=0; i<std::min(t->mageGuildLevel(),h->getSecSkillLevel(7)+2);i++)
  1203. {
  1204. for(int j=0; j<t->spellsAtLevel(i+1,true) && j<t->spells[i].size(); j++)
  1205. {
  1206. if(!vstd::contains(h->spells,t->spells[i][j]))
  1207. cs.spells.insert(t->spells[i][j]);
  1208. }
  1209. }
  1210. if(cs.spells.size())
  1211. sendAndApply(&cs);
  1212. }
  1213. void CGameHandler::setBlockVis(int objid, bool bv)
  1214. {
  1215. SetObjectProperty sop(objid,2,bv);
  1216. sendAndApply(&sop);
  1217. }
  1218. bool CGameHandler::removeObject( int objid )
  1219. {
  1220. if(!getObj(objid))
  1221. {
  1222. tlog1 << "Something wrong, that object already has been removed or hasn't existed!\n";
  1223. return false;
  1224. }
  1225. RemoveObject ro;
  1226. ro.id = objid;
  1227. sendAndApply(&ro);
  1228. return true;
  1229. }
  1230. void CGameHandler::setAmount(int objid, ui32 val)
  1231. {
  1232. SetObjectProperty sop(objid,3,val);
  1233. sendAndApply(&sop);
  1234. }
  1235. bool CGameHandler::moveHero( si32 hid, int3 dst, ui8 instant, ui8 asker /*= 255*/ )
  1236. {
  1237. bool blockvis = false;
  1238. const CGHeroInstance *h = getHero(hid);
  1239. 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)
  1240. )
  1241. {
  1242. tlog1 << "Illegal call to move hero!\n";
  1243. return false;
  1244. }
  1245. tlog5 << "Player " <<int(asker) << " wants to move hero "<< hid << " from "<< h->pos << " to " << dst << std::endl;
  1246. int3 hmpos = dst + int3(-1,0,0);
  1247. if(!gs->map->isInTheMap(hmpos))
  1248. {
  1249. tlog1 << "Destination tile os out of the map!\n";
  1250. return false;
  1251. }
  1252. TerrainTile t = gs->map->terrain[hmpos.x][hmpos.y][hmpos.z];
  1253. int cost = gs->getMovementCost(h,h->getPosition(false),CGHeroInstance::convertPosition(dst,false),h->movement);
  1254. //result structure for start - movement failed, no move points used
  1255. TryMoveHero tmh;
  1256. tmh.id = hid;
  1257. tmh.start = h->pos;
  1258. tmh.end = dst;
  1259. tmh.result = TryMoveHero::FAILED;
  1260. tmh.movePoints = h->movement;
  1261. //check if destination tile is available
  1262. //it's a rock or blocked and not visitable tile
  1263. //OR hero is on land and dest is water and (there is not present only one object - boat)
  1264. if((t.tertype == TerrainTile::rock || (t.blocked && !t.visitable))
  1265. && complain("Cannot move hero, destination tile is blocked!")
  1266. || (!h->boat && !h->canWalkOnSea() && t.tertype == TerrainTile::water && (t.visitableObjects.size() != 1 || (t.visitableObjects.front()->ID != 8 && t.visitableObjects.front()->ID != HEROI_TYPE))) //hero is not on boat/water walking and dst water tile doesn't contain boat/hero (objs visitable from land)
  1267. && complain("Cannot move hero, destination tile is on water!")
  1268. || (h->boat && t.tertype != TerrainTile::water && t.blocked)
  1269. && complain("Cannot disembark hero, tile is blocked!")
  1270. || (h->movement < cost && dst != h->pos)
  1271. && complain("Hero don't have any movement points left!")
  1272. || states.checkFlag(h->tempOwner, &PlayerStatus::engagedIntoBattle)
  1273. && complain("Cannot move hero during the battle"))
  1274. {
  1275. //send info about movement failure
  1276. sendAndApply(&tmh);
  1277. return false;
  1278. }
  1279. //hero enters the boat
  1280. if(!h->boat && t.visitableObjects.size() && t.visitableObjects.front()->ID == 8)
  1281. {
  1282. tmh.result = TryMoveHero::EMBARK;
  1283. tmh.movePoints = 0; //embarking takes all move points
  1284. //TODO: check for bonus that removes that penalty
  1285. getTilesInRange(tmh.fowRevealed,h->getSightCenter()+(tmh.end-tmh.start),h->getSightRadious(),h->tempOwner,1);
  1286. sendAndApply(&tmh);
  1287. return true;
  1288. }
  1289. //hero leaves the boat
  1290. else if(h->boat && t.tertype != TerrainTile::water && !t.blocked)
  1291. {
  1292. tmh.result = TryMoveHero::DISEMBARK;
  1293. tmh.movePoints = 0; //disembarking takes all move points
  1294. //TODO: check for bonus that removes that penalty
  1295. getTilesInRange(tmh.fowRevealed,h->getSightCenter()+(tmh.end-tmh.start),h->getSightRadious(),h->tempOwner,1);
  1296. sendAndApply(&tmh);
  1297. return true;
  1298. }
  1299. //checks for standard movement
  1300. if(!instant)
  1301. {
  1302. if( distance(h->pos,dst) >= 1.5 && complain("Tiles are not neighbouring!")
  1303. || h->movement < cost && h->movement < 100 && complain("Not enough move points!"))
  1304. {
  1305. sendAndApply(&tmh);
  1306. return false;
  1307. }
  1308. //check if there is blocking visitable object
  1309. blockvis = false;
  1310. tmh.movePoints = std::max(si32(0),h->movement-cost); //take move points
  1311. BOOST_FOREACH(CGObjectInstance *obj, t.visitableObjects)
  1312. {
  1313. if(obj != h && obj->blockVisit)
  1314. {
  1315. blockvis = true;
  1316. break;
  1317. }
  1318. }
  1319. //we start moving
  1320. if(blockvis)//interaction with blocking object (like resources)
  1321. {
  1322. tmh.result = TryMoveHero::BLOCKING_VISIT;
  1323. sendAndApply(&tmh);
  1324. //failed to move to that tile but we visit object
  1325. BOOST_FOREACH(CGObjectInstance *obj, t.visitableObjects)
  1326. {
  1327. if (obj->blockVisit)
  1328. {
  1329. objectVisited(obj, h);
  1330. }
  1331. }
  1332. tlog5 << "Blocking visit at " << hmpos << std::endl;
  1333. return true;
  1334. }
  1335. else //normal move
  1336. {
  1337. tmh.result = TryMoveHero::SUCCESS;
  1338. BOOST_FOREACH(CGObjectInstance *obj, gs->map->terrain[h->pos.x-1][h->pos.y][h->pos.z].visitableObjects)
  1339. {
  1340. obj->onHeroLeave(h);
  1341. }
  1342. getTilesInRange(tmh.fowRevealed,h->getSightCenter()+(tmh.end-tmh.start),h->getSightRadious(),h->tempOwner,1);
  1343. sendAndApply(&tmh);
  1344. tlog5 << "Moved to " <<tmh.end<<std::endl;
  1345. //call objects if they are visited
  1346. BOOST_FOREACH(CGObjectInstance *obj, t.visitableObjects)
  1347. {
  1348. objectVisited(obj, h);
  1349. }
  1350. }
  1351. tlog5 << "Movement end!\n";
  1352. return true;
  1353. }
  1354. else //instant move - teleportation
  1355. {
  1356. BOOST_FOREACH(CGObjectInstance* obj, t.blockingObjects)
  1357. {
  1358. if(obj->ID==HEROI_TYPE)
  1359. {
  1360. CGHeroInstance *dh = static_cast<CGHeroInstance *>(obj);
  1361. if(obj->tempOwner==h->tempOwner)
  1362. {
  1363. heroExchange(dh->id, h->id);
  1364. return true;
  1365. }
  1366. //TODO: check for ally
  1367. startBattleI(h, dh);
  1368. return true;
  1369. }
  1370. }
  1371. tmh.result = TryMoveHero::TELEPORTATION;
  1372. getTilesInRange(tmh.fowRevealed,h->getSightCenter()+(tmh.end-tmh.start),h->getSightRadious(),h->tempOwner,1);
  1373. sendAndApply(&tmh);
  1374. return true;
  1375. }
  1376. }
  1377. void CGameHandler::setOwner(int objid, ui8 owner)
  1378. {
  1379. SetObjectProperty sop(objid,1,owner);
  1380. sendAndApply(&sop);
  1381. }
  1382. void CGameHandler::setHoverName(int objid, MetaString* name)
  1383. {
  1384. SetHoverName shn(objid, *name);
  1385. sendAndApply(&shn);
  1386. }
  1387. void CGameHandler::showInfoDialog(InfoWindow *iw)
  1388. {
  1389. sendToAllClients(iw);
  1390. }
  1391. void CGameHandler::showBlockingDialog( BlockingDialog *iw, const CFunctionList<void(ui32)> &callback )
  1392. {
  1393. ask(iw,iw->player,callback);
  1394. }
  1395. ui32 CGameHandler::showBlockingDialog( BlockingDialog *iw )
  1396. {
  1397. //TODO
  1398. //gsm.lock();
  1399. //int query = QID++;
  1400. //states.addQuery(player,query);
  1401. //sendToAllClients(iw);
  1402. //gsm.unlock();
  1403. //ui32 ret = getQueryResult(iw->player, query);
  1404. //gsm.lock();
  1405. //states.removeQuery(player, query);
  1406. //gsm.unlock();
  1407. return 0;
  1408. }
  1409. int CGameHandler::getCurrentPlayer()
  1410. {
  1411. return gs->currentPlayer;
  1412. }
  1413. void CGameHandler::giveResource(int player, int which, int val)
  1414. {
  1415. if(!val) return; //don't waste time on empty call
  1416. SetResource sr;
  1417. sr.player = player;
  1418. sr.resid = which;
  1419. sr.val = gs->players.find(player)->second.resources[which]+val;
  1420. sendAndApply(&sr);
  1421. }
  1422. void CGameHandler::giveCreatures (int objid, const CGHeroInstance * h, CCreatureSet creatures)
  1423. {
  1424. if (creatures.slots.size() <= 0)
  1425. return;
  1426. CCreatureSet heroArmy = h->army;
  1427. while (creatures.slots.size() > 0)
  1428. {
  1429. int slot = heroArmy.getSlotFor (creatures.slots.begin()->second.first);
  1430. if (slot < 0)
  1431. break;
  1432. heroArmy.slots[slot].first = creatures.slots.begin()->second.first;
  1433. heroArmy.slots[slot].second += creatures.slots.begin()->second.second;
  1434. creatures.slots.erase (creatures.slots.begin());
  1435. }
  1436. if (creatures.slots.size() == 0) //all creatures can be moved to hero army - do that
  1437. {
  1438. SetGarrisons sg;
  1439. sg.garrs[h->id] = heroArmy;
  1440. sendAndApply(&sg);
  1441. }
  1442. else //show garrison window and let player pick creatures
  1443. {
  1444. SetGarrisons sg;
  1445. sg.garrs[objid] = creatures;
  1446. sendAndApply (&sg);
  1447. showGarrisonDialog (objid, h->id, true, 0);
  1448. return;
  1449. }
  1450. }
  1451. void CGameHandler::showCompInfo(ShowInInfobox * comp)
  1452. {
  1453. sendToAllClients(comp);
  1454. }
  1455. void CGameHandler::heroVisitCastle(int obj, int heroID)
  1456. {
  1457. HeroVisitCastle vc;
  1458. vc.hid = heroID;
  1459. vc.tid = obj;
  1460. vc.flags |= 1;
  1461. sendAndApply(&vc);
  1462. giveSpells(getTown(obj),getHero(heroID));
  1463. }
  1464. void CGameHandler::stopHeroVisitCastle(int obj, int heroID)
  1465. {
  1466. HeroVisitCastle vc;
  1467. vc.hid = heroID;
  1468. vc.tid = obj;
  1469. sendAndApply(&vc);
  1470. }
  1471. void CGameHandler::giveHeroArtifact(int artid, int hid, int position) //pos==-1 - first free slot in backpack
  1472. {
  1473. const CGHeroInstance* h = getHero(hid);
  1474. const CArtifact &art = VLC->arth->artifacts[artid];
  1475. SetHeroArtifacts sha;
  1476. sha.hid = hid;
  1477. sha.artifacts = h->artifacts;
  1478. sha.artifWorn = h->artifWorn;
  1479. if(position<0)
  1480. {
  1481. if(position == -2)
  1482. {
  1483. int i;
  1484. for(i=0; i<art.possibleSlots.size(); i++) //try to put artifact into first available slot
  1485. {
  1486. if( !vstd::contains(sha.artifWorn,art.possibleSlots[i]) )
  1487. {
  1488. //we've found a free suitable slot
  1489. sha.artifWorn[art.possibleSlots[i]] = artid;
  1490. break;
  1491. }
  1492. }
  1493. if(i == art.possibleSlots.size()) //if haven't find proper slot, use backpack
  1494. sha.artifacts.push_back(artid);
  1495. }
  1496. else //should be -1 => put artifact into backpack
  1497. {
  1498. sha.artifacts.push_back(artid);
  1499. }
  1500. }
  1501. else
  1502. {
  1503. if(!vstd::contains(sha.artifWorn,ui16(position)))
  1504. {
  1505. sha.artifWorn[position] = artid;
  1506. }
  1507. else
  1508. {
  1509. sha.artifacts.push_back(artid);
  1510. }
  1511. }
  1512. sendAndApply(&sha);
  1513. }
  1514. void CGameHandler::startBattleI(const CArmedInstance *army1, const CArmedInstance *army2, int3 tile, const CGHeroInstance *hero1, const CGHeroInstance *hero2, bool creatureBank, boost::function<void(BattleResult*)> cb, const CGTownInstance *town) //use hero=NULL for no hero
  1515. {
  1516. engageIntoBattle(army1->tempOwner);
  1517. engageIntoBattle(army2->tempOwner);
  1518. //block engaged players
  1519. if(army2->tempOwner < PLAYER_LIMIT)
  1520. states.setFlag(army2->tempOwner,&PlayerStatus::engagedIntoBattle,true);
  1521. boost::thread(boost::bind(&CGameHandler::startBattle, this, army1, army2, tile, hero1, hero2, creatureBank, cb, town));
  1522. }
  1523. void CGameHandler::startBattleI( const CArmedInstance *army1, const CArmedInstance *army2, int3 tile, boost::function<void(BattleResult*)> cb, bool creatureBank )
  1524. {
  1525. startBattleI(army1, army2, tile,
  1526. army1->ID == HEROI_TYPE ? static_cast<const CGHeroInstance*>(army1) : NULL,
  1527. army2->ID == HEROI_TYPE ? static_cast<const CGHeroInstance*>(army2) : NULL,
  1528. creatureBank, cb);
  1529. }
  1530. void CGameHandler::startBattleI( const CArmedInstance *army1, const CArmedInstance *army2, boost::function<void(BattleResult*)> cb, bool creatureBank)
  1531. {
  1532. startBattleI(army1, army2, army2->pos - army2->getVisitableOffset(), cb, creatureBank);
  1533. }
  1534. //void CGameHandler::startBattleI(int heroID, CCreatureSet army, int3 tile, boost::function<void(BattleResult*)> cb) //for hero<=>neutral army
  1535. //{
  1536. // CGHeroInstance* h = const_cast<CGHeroInstance*>(getHero(heroID));
  1537. // startBattleI(&h->army,&army,tile,h,NULL,cb);
  1538. // //battle(&h->army,army,tile,h,NULL);
  1539. //}
  1540. void CGameHandler::changeSpells( int hid, bool give, const std::set<ui32> &spells )
  1541. {
  1542. ChangeSpells cs;
  1543. cs.hid = hid;
  1544. cs.spells = spells;
  1545. cs.learn = give;
  1546. sendAndApply(&cs);
  1547. }
  1548. int CGameHandler::getSelectedHero()
  1549. {
  1550. return IGameCallback::getSelectedHero(getCurrentPlayer())->id;
  1551. }
  1552. void CGameHandler::setObjProperty( int objid, int prop, si64 val )
  1553. {
  1554. SetObjectProperty sob;
  1555. sob.id = objid;
  1556. sob.what = prop;
  1557. sob.val = val;
  1558. sendAndApply(&sob);
  1559. }
  1560. void CGameHandler::sendMessageTo( CConnection &c, const std::string &message )
  1561. {
  1562. SystemMessage sm;
  1563. sm.text = message;
  1564. c << &sm;
  1565. }
  1566. void CGameHandler::giveHeroBonus( GiveBonus * bonus )
  1567. {
  1568. sendAndApply(bonus);
  1569. }
  1570. void CGameHandler::setMovePoints( SetMovePoints * smp )
  1571. {
  1572. sendAndApply(smp);
  1573. }
  1574. void CGameHandler::setManaPoints( int hid, int val )
  1575. {
  1576. SetMana sm;
  1577. sm.hid = hid;
  1578. sm.val = val;
  1579. sendAndApply(&sm);
  1580. }
  1581. void CGameHandler::giveHero( int id, int player )
  1582. {
  1583. GiveHero gh;
  1584. gh.id = id;
  1585. gh.player = player;
  1586. sendAndApply(&gh);
  1587. }
  1588. void CGameHandler::changeObjPos( int objid, int3 newPos, ui8 flags )
  1589. {
  1590. ChangeObjPos cop;
  1591. cop.objid = objid;
  1592. cop.nPos = newPos;
  1593. cop.flags = flags;
  1594. sendAndApply(&cop);
  1595. }
  1596. void CGameHandler::heroExchange(si32 hero1, si32 hero2)
  1597. {
  1598. ui8 player1 = getHero(hero1)->tempOwner;
  1599. ui8 player2 = getHero(hero2)->tempOwner;
  1600. if(player1 == player2)
  1601. {
  1602. OpenWindow hex;
  1603. hex.window = OpenWindow::EXCHANGE_WINDOW;
  1604. hex.id1 = hero1;
  1605. hex.id2 = hero2;
  1606. sendAndApply(&hex);
  1607. }
  1608. }
  1609. void CGameHandler::applyAndAsk( Query * sel, ui8 player, boost::function<void(ui32)> &callback )
  1610. {
  1611. boost::unique_lock<boost::recursive_mutex> lock(gsm);
  1612. sel->id = QID;
  1613. callbacks[QID] = callback;
  1614. states.addQuery(player,QID);
  1615. QID++;
  1616. sendAndApply(sel);
  1617. }
  1618. void CGameHandler::ask( Query * sel, ui8 player, const CFunctionList<void(ui32)> &callback )
  1619. {
  1620. boost::unique_lock<boost::recursive_mutex> lock(gsm);
  1621. sel->id = QID;
  1622. callbacks[QID] = callback;
  1623. states.addQuery(player,QID);
  1624. sendToAllClients(sel);
  1625. QID++;
  1626. }
  1627. void CGameHandler::sendToAllClients( CPackForClient * info )
  1628. {
  1629. tlog5 << "Sending to all clients a package of type " << typeid(*info).name() << std::endl;
  1630. for(std::set<CConnection*>::iterator i=conns.begin(); i!=conns.end();i++)
  1631. {
  1632. (*i)->wmx->lock();
  1633. **i << info;
  1634. (*i)->wmx->unlock();
  1635. }
  1636. }
  1637. void CGameHandler::sendAndApply( CPackForClient * info )
  1638. {
  1639. gs->apply(info);
  1640. sendToAllClients(info);
  1641. }
  1642. void CGameHandler::save( const std::string &fname )
  1643. {
  1644. {
  1645. tlog0 << "Ordering clients to serialize...\n";
  1646. SaveGame sg(fname);
  1647. sendToAllClients(&sg);
  1648. }
  1649. {
  1650. tlog0 << "Serializing game info...\n";
  1651. CSaveFile save(std::string("Games") + PATHSEPARATOR + fname + ".vlgm1");
  1652. char hlp[8] = "VCMISVG";
  1653. save << hlp << static_cast<CMapHeader&>(*gs->map) << gs->scenarioOps->difficulty << *VLC << gs;
  1654. }
  1655. {
  1656. tlog0 << "Serializing server info...\n";
  1657. CSaveFile save(std::string("Games") + PATHSEPARATOR + fname + ".vsgm1");
  1658. save << *this;
  1659. }
  1660. tlog0 << "Game has been succesfully saved!\n";
  1661. }
  1662. void CGameHandler::close()
  1663. {
  1664. tlog0 << "We have been requested to close.\n";
  1665. //BOOST_FOREACH(CConnection *cc, conns)
  1666. // if(cc && cc->socket && cc->socket->is_open())
  1667. // cc->socket->close();
  1668. //exit(0);
  1669. }
  1670. bool CGameHandler::arrangeStacks( si32 id1, si32 id2, ui8 what, ui8 p1, ui8 p2, si32 val )
  1671. {
  1672. CArmedInstance *s1 = static_cast<CArmedInstance*>(gs->map->objects[id1]),
  1673. *s2 = static_cast<CArmedInstance*>(gs->map->objects[id2]);
  1674. CCreatureSet temp1 = s1->army, temp2 = s2->army,
  1675. &S1 = temp1, &S2 = (s1!=s2)?(temp2):(temp1);
  1676. if(!isAllowedExchange(id1,id2))
  1677. {
  1678. complain("Cannot exchange stacks between these two objects!\n");
  1679. return false;
  1680. }
  1681. if(what==1) //swap
  1682. {
  1683. std::swap(S1.slots[p1],S2.slots[p2]); //swap slots
  1684. //if one of them is empty, remove entry
  1685. if(!S1.slots[p1].second)
  1686. S1.slots.erase(p1);
  1687. if(!S2.slots[p2].second)
  1688. S2.slots.erase(p2);
  1689. }
  1690. else if(what==2)//merge
  1691. {
  1692. if(S1.slots[p1].first != S2.slots[p2].first) //not same creature
  1693. {
  1694. complain("Cannot merge different creatures stacks!");
  1695. return false;
  1696. }
  1697. S2.slots[p2].second += S1.slots[p1].second;
  1698. S1.slots.erase(p1);
  1699. }
  1700. else if(what==3) //split
  1701. {
  1702. //general conditions checking
  1703. if((!vstd::contains(S1.slots,p1) && complain("no creatures to split"))
  1704. || (val<1 && complain("no creatures to split")) )
  1705. {
  1706. return false;
  1707. }
  1708. if(vstd::contains(S2.slots,p2)) //dest. slot not free - it must be "rebalancing"...
  1709. {
  1710. int total = S1.slots[p1].second + S2.slots[p2].second;
  1711. if( (total < val && complain("Cannot split that stack, not enough creatures!"))
  1712. || (S2.slots[p2].first != S1.slots[p1].first && complain("Cannot rebalance different creatures stacks!"))
  1713. )
  1714. {
  1715. return false;
  1716. }
  1717. S2.slots[p2].second = val;
  1718. S1.slots[p1].second = total - val;
  1719. }
  1720. else //split one stack to the two
  1721. {
  1722. if(S1.slots[p1].second < val)//not enough creatures
  1723. {
  1724. complain("Cannot split that stack, not enough creatures!");
  1725. return false;
  1726. }
  1727. S2.slots[p2].first = S1.slots[p1].first;
  1728. S2.slots[p2].second = val;
  1729. S1.slots[p1].second -= val;
  1730. }
  1731. if(!S1.slots[p1].second) //if we've moved all creatures
  1732. S1.slots.erase(p1);
  1733. }
  1734. if((s1->needsLastStack() && !S1.slots.size()) //it's not allowed to take last stack from hero army!
  1735. || (s2->needsLastStack() && !S2.slots.size())
  1736. )
  1737. {
  1738. complain("Cannot take the last stack!");
  1739. return false; //leave without applying changes to garrison
  1740. }
  1741. //apply changes
  1742. SetGarrisons sg;
  1743. sg.garrs[id1] = S1;
  1744. if(s1 != s2)
  1745. sg.garrs[id2] = S2;
  1746. sendAndApply(&sg);
  1747. return true;
  1748. }
  1749. int CGameHandler::getPlayerAt( CConnection *c ) const
  1750. {
  1751. std::set<int> all;
  1752. for(std::map<int,CConnection*>::const_iterator i=connections.begin(); i!=connections.end(); i++)
  1753. if(i->second == c)
  1754. all.insert(i->first);
  1755. switch(all.size())
  1756. {
  1757. case 0:
  1758. return 255;
  1759. case 1:
  1760. return *all.begin();
  1761. default:
  1762. {
  1763. //if we have more than one player at this connection, try to pick active one
  1764. if(vstd::contains(all,int(gs->currentPlayer)))
  1765. return gs->currentPlayer;
  1766. else
  1767. return 253; //cannot say which player is it
  1768. }
  1769. }
  1770. }
  1771. bool CGameHandler::disbandCreature( si32 id, ui8 pos )
  1772. {
  1773. CArmedInstance *s1 = static_cast<CArmedInstance*>(gs->map->objects[id]);
  1774. if(!vstd::contains(s1->army.slots,pos))
  1775. {
  1776. complain("Illegal call to disbandCreature - no such stack in army!");
  1777. return false;
  1778. }
  1779. s1->army.slots.erase(pos);
  1780. SetGarrisons sg;
  1781. sg.garrs[id] = s1->army;
  1782. sendAndApply(&sg);
  1783. return true;
  1784. }
  1785. bool CGameHandler::buildStructure( si32 tid, si32 bid )
  1786. {
  1787. CGTownInstance * t = static_cast<CGTownInstance*>(gs->map->objects[tid]);
  1788. CBuilding * b = VLC->buildh->buildings[t->subID][bid];
  1789. if(gs->canBuildStructure(t,bid) != 7)
  1790. {
  1791. complain("Cannot raze that building!");
  1792. return false;
  1793. }
  1794. NewStructures ns;
  1795. ns.tid = tid;
  1796. if(bid>36) //upg dwelling
  1797. {
  1798. if(t->getHordeLevel(0) == (bid-37))
  1799. ns.bid.insert(19);
  1800. else if(t->getHordeLevel(1) == (bid-37))
  1801. ns.bid.insert(25);
  1802. SetAvailableCreatures ssi;
  1803. ssi.tid = tid;
  1804. ssi.creatures = t->creatures;
  1805. ssi.creatures[bid-37].second.push_back(t->town->upgradedCreatures[bid-37]);
  1806. sendAndApply(&ssi);
  1807. }
  1808. else if(bid >= 30) //bas. dwelling
  1809. {
  1810. int crid = t->town->basicCreatures[bid-30];
  1811. SetAvailableCreatures ssi;
  1812. ssi.tid = tid;
  1813. ssi.creatures = t->creatures;
  1814. ssi.creatures[bid-30].first = VLC->creh->creatures[crid].growth;
  1815. ssi.creatures[bid-30].second.push_back(crid);
  1816. sendAndApply(&ssi);
  1817. }
  1818. ns.bid.insert(bid);
  1819. ns.builded = t->builded + 1;
  1820. sendAndApply(&ns);
  1821. SetResources sr;
  1822. sr.player = t->tempOwner;
  1823. sr.res = gs->getPlayer(t->tempOwner)->resources;
  1824. for(int i=0;i<b->resources.size();i++)
  1825. sr.res[i]-=b->resources[i];
  1826. sendAndApply(&sr);
  1827. if(bid<5) //it's mage guild
  1828. {
  1829. if(t->visitingHero)
  1830. giveSpells(t,t->visitingHero);
  1831. if(t->garrisonHero)
  1832. giveSpells(t,t->garrisonHero);
  1833. }
  1834. return true;
  1835. }
  1836. bool CGameHandler::razeStructure (si32 tid, si32 bid)
  1837. {
  1838. ///incomplete, simply erases target building
  1839. CGTownInstance * t = static_cast<CGTownInstance*>(gs->map->objects[tid]);
  1840. if (t->builtBuildings.find(bid) == t->builtBuildings.end())
  1841. return false;
  1842. RazeStructures rs;
  1843. rs.tid = tid;
  1844. rs.bid.insert(bid);
  1845. rs.destroyed = t->destroyed + 1;
  1846. sendAndApply(&rs);
  1847. return true;
  1848. }
  1849. void CGameHandler::sendMessageToAll( const std::string &message )
  1850. {
  1851. SystemMessage sm;
  1852. sm.text = message;
  1853. sendToAllClients(&sm);
  1854. }
  1855. bool CGameHandler::recruitCreatures( si32 objid, ui32 crid, ui32 cram )
  1856. {
  1857. const CGDwelling *dw = static_cast<CGDwelling*>(gs->map->objects[objid]);
  1858. const CArmedInstance *dst = NULL;
  1859. if(dw->ID == TOWNI_TYPE)
  1860. dst = dw;
  1861. else if(dw->ID == 17 || dw->ID == 20) //advmap dwelling
  1862. dst = getHero(gs->getPlayer(dw->tempOwner)->currentSelection); //TODO: check if current hero is really visiting dwelling
  1863. assert(dw && dst);
  1864. //verify
  1865. bool found = false;
  1866. int level = -1;
  1867. typedef std::pair<const int,int> Parka;
  1868. for(level = 0; level < dw->creatures.size(); level++) //iterate through all levels
  1869. {
  1870. const std::pair<ui32, std::vector<ui32> > &cur = dw->creatures[level]; //current level info <amount, list of cr. ids>
  1871. int i = 0;
  1872. for(; i < cur.second.size(); i++) //look for crid among available creatures list on current level
  1873. if(cur.second[i] == crid)
  1874. break;
  1875. if(i < cur.second.size())
  1876. {
  1877. found = true;
  1878. cram = std::min(cram, cur.first); //reduce recruited amount up to available amount
  1879. break;
  1880. }
  1881. }
  1882. int slot = dst->army.getSlotFor(crid);
  1883. if(!found && complain("Cannot recruit: no such creatures!")
  1884. || cram > VLC->creh->creatures[crid].maxAmount(gs->getPlayer(dst->tempOwner)->resources) && complain("Cannot recruit: lack of resources!")
  1885. || cram<=0 && complain("Cannot recruit: cram <= 0!")
  1886. || slot<0 && complain("Cannot recruit: no available slot!"))
  1887. {
  1888. return false;
  1889. }
  1890. //recruit
  1891. SetResources sr;
  1892. sr.player = dst->tempOwner;
  1893. for(int i=0;i<RESOURCE_QUANTITY;i++)
  1894. sr.res[i] = gs->getPlayer(dst->tempOwner)->resources[i] - (VLC->creh->creatures[crid].cost[i] * cram);
  1895. SetAvailableCreatures sac;
  1896. sac.tid = objid;
  1897. sac.creatures = dw->creatures;
  1898. sac.creatures[level].first -= cram;
  1899. SetGarrisons sg;
  1900. sg.garrs[dst->id] = dst->army;
  1901. if(sg.garrs[dst->id].slots.find(slot) == sg.garrs[dst->id].slots.end()) //take a free slot
  1902. {
  1903. sg.garrs[dst->id].slots[slot] = std::make_pair(crid,cram);
  1904. }
  1905. else //add creatures to a already existing stack
  1906. {
  1907. sg.garrs[dst->id].slots[slot].second += cram;
  1908. }
  1909. sendAndApply(&sr);
  1910. sendAndApply(&sac);
  1911. sendAndApply(&sg);
  1912. return true;
  1913. }
  1914. bool CGameHandler::upgradeCreature( ui32 objid, ui8 pos, ui32 upgID )
  1915. {
  1916. CArmedInstance *obj = static_cast<CArmedInstance*>(gs->map->objects[objid]);
  1917. UpgradeInfo ui = gs->getUpgradeInfo(obj,pos);
  1918. int player = obj->tempOwner;
  1919. int crQuantity = obj->army.slots[pos].second;
  1920. //check if upgrade is possible
  1921. if((ui.oldID<0 || !vstd::contains(ui.newID,upgID)) && complain("That upgrade is not possible!"))
  1922. {
  1923. return false;
  1924. }
  1925. //check if player has enough resources
  1926. for(int i=0;i<ui.cost.size();i++)
  1927. {
  1928. for (std::set<std::pair<int,int> >::iterator j=ui.cost[i].begin(); j!=ui.cost[i].end(); j++)
  1929. {
  1930. if(gs->getPlayer(player)->resources[j->first] < j->second*crQuantity)
  1931. {
  1932. complain("Cannot upgrade, not enough resources!");
  1933. return false;
  1934. }
  1935. }
  1936. }
  1937. //take resources
  1938. for(int i=0;i<ui.cost.size();i++)
  1939. {
  1940. for (std::set<std::pair<int,int> >::iterator j=ui.cost[i].begin(); j!=ui.cost[i].end(); j++)
  1941. {
  1942. SetResource sr;
  1943. sr.player = player;
  1944. sr.resid = j->first;
  1945. sr.val = gs->getPlayer(player)->resources[j->first] - j->second*crQuantity;
  1946. sendAndApply(&sr);
  1947. }
  1948. }
  1949. //upgrade creature
  1950. SetGarrisons sg;
  1951. sg.garrs[objid] = obj->army;
  1952. sg.garrs[objid].slots[pos].first = upgID;
  1953. sendAndApply(&sg);
  1954. return true;
  1955. }
  1956. bool CGameHandler::garrisonSwap( si32 tid )
  1957. {
  1958. CGTownInstance *town = gs->getTown(tid);
  1959. if(!town->garrisonHero && town->visitingHero) //visiting => garrison, merge armies
  1960. {
  1961. CCreatureSet csn = town->visitingHero->army, cso = town->army;
  1962. while(!cso.slots.empty())//while there are unmoved creatures
  1963. {
  1964. int pos = csn.getSlotFor(cso.slots.begin()->second.first);
  1965. if(pos<0)
  1966. {
  1967. //try to merge two other stacks to make place
  1968. std::pair<TSlot, TSlot> toMerge;
  1969. if(csn.mergableStacks(toMerge, cso.slots.begin()->first))
  1970. {
  1971. //merge
  1972. csn.slots[toMerge.second].second += csn.slots[toMerge.first].second;
  1973. csn.slots[toMerge.first] = cso.slots.begin()->second;
  1974. }
  1975. else
  1976. {
  1977. complain("Cannot make garrison swap, not enough free slots!");
  1978. return false;
  1979. }
  1980. }
  1981. else if(csn.slots.find(pos) != csn.slots.end()) //add creatures to the existing stack
  1982. {
  1983. csn.slots[pos].second += cso.slots.begin()->second.second;
  1984. }
  1985. else //move stack on the free pos
  1986. {
  1987. csn.slots[pos].first = cso.slots.begin()->second.first;
  1988. csn.slots[pos].second = cso.slots.begin()->second.second;
  1989. }
  1990. cso.slots.erase(cso.slots.begin());
  1991. }
  1992. SetGarrisons sg;
  1993. sg.garrs[town->visitingHero->id] = csn;
  1994. sg.garrs[town->id] = csn;
  1995. sendAndApply(&sg);
  1996. SetHeroesInTown intown;
  1997. intown.tid = tid;
  1998. intown.visiting = -1;
  1999. intown.garrison = town->visitingHero->id;
  2000. sendAndApply(&intown);
  2001. return true;
  2002. }
  2003. else if (town->garrisonHero && !town->visitingHero) //move hero out of the garrison
  2004. {
  2005. //check if moving hero out of town will break 8 wandering heroes limit
  2006. if(getHeroCount(town->garrisonHero->tempOwner,false) >= 8)
  2007. {
  2008. complain("Cannot move hero out of the garrison, there are already 8 wandering heroes!");
  2009. return false;
  2010. }
  2011. SetHeroesInTown intown;
  2012. intown.tid = tid;
  2013. intown.garrison = -1;
  2014. intown.visiting = town->garrisonHero->id;
  2015. sendAndApply(&intown);
  2016. //town will be empty
  2017. SetGarrisons sg;
  2018. sg.garrs[tid] = CCreatureSet();
  2019. sendAndApply(&sg);
  2020. return true;
  2021. }
  2022. else if (town->garrisonHero && town->visitingHero) //swap visiting and garrison hero
  2023. {
  2024. SetGarrisons sg;
  2025. sg.garrs[town->id] = town->visitingHero->army;
  2026. sg.garrs[town->garrisonHero->id] = town->garrisonHero->army;
  2027. SetHeroesInTown intown;
  2028. intown.tid = tid;
  2029. intown.garrison = town->visitingHero->id;
  2030. intown.visiting = town->garrisonHero->id;
  2031. sendAndApply(&intown);
  2032. sendAndApply(&sg);
  2033. return true;
  2034. }
  2035. else
  2036. {
  2037. complain("Cannot swap garrison hero!");
  2038. return false;
  2039. }
  2040. }
  2041. bool CGameHandler::swapArtifacts( si32 hid1, si32 hid2, ui16 slot1, ui16 slot2 )
  2042. {
  2043. CGHeroInstance *h1 = gs->getHero(hid1), *h2 = gs->getHero(hid2);
  2044. if((distance(h1->pos,h2->pos) > 1.5) || (h1->tempOwner != h2->tempOwner))
  2045. return false;
  2046. const CArtifact *a1 = h1->getArt(slot1),
  2047. *a2=h2->getArt(slot2);
  2048. //check if
  2049. // 1) slots are appropriate for that artifacts
  2050. // 2) they are not war machine
  2051. if((a1 && slot2<19 && !vstd::contains(a1->possibleSlots,slot2) || (a2 && slot1<19 && !vstd::contains(a2->possibleSlots,slot1))) && complain("Cannot swap artifacts!")
  2052. || (slot1>=13 && slot1<=16 || slot2>=13 && slot2<=16) && complain("Cannot move war machine!")
  2053. )
  2054. {
  2055. return false;
  2056. }
  2057. SetHeroArtifacts sha;
  2058. sha.hid = hid1;
  2059. sha.artifacts = h1->artifacts;
  2060. sha.artifWorn = h1->artifWorn;
  2061. sha.setArtAtPos(slot1,h2->getArtAtPos(slot2));
  2062. if(h1 == h2) sha.setArtAtPos(slot2,h1->getArtAtPos(slot1));
  2063. sendAndApply(&sha);
  2064. if(hid1 != hid2)
  2065. {
  2066. sha.hid = hid2;
  2067. sha.artifacts = h2->artifacts;
  2068. sha.artifWorn = h2->artifWorn;
  2069. sha.setArtAtPos(slot2, a1 ? a1->id : -1);
  2070. sendAndApply(&sha);
  2071. }
  2072. return true;
  2073. }
  2074. bool CGameHandler::buyArtifact( ui32 hid, si32 aid )
  2075. {
  2076. CGHeroInstance *hero = gs->getHero(hid);
  2077. CGTownInstance *town = hero->visitedTown;
  2078. if(aid==0) //spellbook
  2079. {
  2080. if(!vstd::contains(town->builtBuildings,si32(0)) && complain("Cannot buy a spellbook, no mage guild in the town!")
  2081. || getResource(hero->getOwner(),6)<500 && complain("Cannot buy a spellbook, not enough gold!")
  2082. || hero->getArt(17) && complain("Cannot buy a spellbook, hero already has a one!")
  2083. )
  2084. return false;
  2085. giveResource(hero->getOwner(),6,-500);
  2086. giveHeroArtifact(0,hid,17);
  2087. giveSpells(town,hero);
  2088. return true;
  2089. }
  2090. else if(aid < 7 && aid > 3) //war machine
  2091. {
  2092. int price = VLC->arth->artifacts[aid].price;
  2093. if(vstd::contains(hero->artifWorn,ui16(9+aid)) && complain("Hero already has this machine!")
  2094. || !vstd::contains(town->builtBuildings,si32(16)) && complain("No blackismith!")
  2095. || gs->getPlayer(hero->getOwner())->resources[6] < price && complain("Not enough gold!") //no gold
  2096. || town->town->warMachine!= aid && complain("This machine is unavailale here!") ) //TODO: ballista yard in Stronghold
  2097. {
  2098. return false;
  2099. }
  2100. giveResource(hero->getOwner(),6,-price);
  2101. giveHeroArtifact(aid,hid,9+aid);
  2102. return true;
  2103. }
  2104. return false;
  2105. }
  2106. bool CGameHandler::tradeResources( ui32 val, ui8 player, ui32 id1, ui32 id2 )
  2107. {
  2108. val = std::min(si32(val),gs->getPlayer(player)->resources[id1]);
  2109. double yield = (double)gs->resVals[id1] * val * gs->getMarketEfficiency(player);
  2110. yield /= gs->resVals[id2];
  2111. SetResource sr;
  2112. sr.player = player;
  2113. sr.resid = id1;
  2114. sr.val = gs->getPlayer(player)->resources[id1] - val;
  2115. sendAndApply(&sr);
  2116. sr.resid = id2;
  2117. sr.val = gs->getPlayer(player)->resources[id2] + (int)yield;
  2118. sendAndApply(&sr);
  2119. return true;
  2120. }
  2121. bool CGameHandler::setFormation( si32 hid, ui8 formation )
  2122. {
  2123. gs->getHero(hid)->army.formation = formation;
  2124. return true;
  2125. }
  2126. bool CGameHandler::hireHero( ui32 tid, ui8 hid )
  2127. {
  2128. CGTownInstance *t = gs->getTown(tid);
  2129. if(!vstd::contains(t->builtBuildings,5) && complain("No tavern!")
  2130. || gs->getPlayer(t->tempOwner)->resources[6]<2500 && complain("Not enough gold for buying hero!")
  2131. || t->visitingHero && complain("There is visiting hero - no place!")
  2132. || getHeroCount(t->tempOwner,false) >= 8 && complain("Cannot hire hero, only 8 wandering heroes are allowed!")
  2133. )
  2134. return false;
  2135. CGHeroInstance *nh = gs->getPlayer(t->tempOwner)->availableHeroes[hid];
  2136. assert(nh);
  2137. HeroRecruited hr;
  2138. hr.tid = tid;
  2139. hr.hid = nh->subID;
  2140. hr.player = t->tempOwner;
  2141. hr.tile = t->pos - int3(1,0,0);
  2142. sendAndApply(&hr);
  2143. std::map<ui32,CGHeroInstance *> pool = gs->hpool.heroesPool;
  2144. for ( std::map<ui8, PlayerState>::iterator i=gs->players.begin() ; i!=gs->players.end();i++)
  2145. for(std::vector<CGHeroInstance *>::iterator j = i->second.availableHeroes.begin(); j != i->second.availableHeroes.end(); j++)
  2146. if(*j)
  2147. pool.erase((**j).subID);
  2148. SetAvailableHeroes sah;
  2149. CGHeroInstance *h1 = gs->hpool.pickHeroFor(false,t->tempOwner,t->town, pool),
  2150. *h2 = gs->getPlayer(t->tempOwner)->availableHeroes[!hid];
  2151. (hid ? sah.hid2 : sah.hid1) = h1 ? h1->subID : -1;
  2152. (hid ? sah.hid1 : sah.hid2) = h2 ? h2->subID : -1;
  2153. sah.player = t->tempOwner;
  2154. sah.flags = hid+1;
  2155. sendAndApply(&sah);
  2156. SetResource sr;
  2157. sr.player = t->tempOwner;
  2158. sr.resid = 6;
  2159. sr.val = gs->getPlayer(t->tempOwner)->resources[6] - 2500;
  2160. sendAndApply(&sr);
  2161. giveSpells(t,nh);
  2162. return true;
  2163. }
  2164. bool CGameHandler::queryReply( ui32 qid, ui32 answer )
  2165. {
  2166. boost::unique_lock<boost::recursive_mutex> lock(gsm);
  2167. if(vstd::contains(callbacks,qid))
  2168. {
  2169. CFunctionList<void(ui32)> callb = callbacks[qid];
  2170. callbacks.erase(qid);
  2171. if(callb)
  2172. callb(answer);
  2173. }
  2174. else if(vstd::contains(garrisonCallbacks,qid))
  2175. {
  2176. if(garrisonCallbacks[qid])
  2177. garrisonCallbacks[qid]();
  2178. garrisonCallbacks.erase(qid);
  2179. allowedExchanges.erase(qid);
  2180. }
  2181. else
  2182. {
  2183. tlog1 << "Unknown query reply...\n";
  2184. return false;
  2185. }
  2186. return true;
  2187. }
  2188. bool CGameHandler::makeBattleAction( BattleAction &ba )
  2189. {
  2190. bool ok = true;
  2191. switch(ba.actionType)
  2192. {
  2193. case 2: //walk
  2194. {
  2195. sendAndApply(&StartAction(ba)); //start movement
  2196. moveStack(ba.stackNumber,ba.destinationTile); //move
  2197. sendAndApply(&EndAction());
  2198. break;
  2199. }
  2200. case 3: //defend
  2201. case 8: //wait
  2202. {
  2203. sendAndApply(&StartAction(ba));
  2204. sendAndApply(&EndAction());
  2205. break;
  2206. }
  2207. case 4: //retreat/flee
  2208. {
  2209. if( !gs->battleCanFlee(ba.side ? gs->curB->side2 : gs->curB->side1) )
  2210. break;
  2211. //TODO: remove retreating hero from map and place it in recruitment list
  2212. BattleResult *br = new BattleResult;
  2213. br->result = 1;
  2214. br->winner = !ba.side; //fleeing side loses
  2215. gs->curB->calculateCasualties(br->casualties);
  2216. giveExp(*br);
  2217. battleResult.set(br);
  2218. break;
  2219. }
  2220. case 6: //walk or attack
  2221. {
  2222. sendAndApply(&StartAction(ba)); //start movement and attack
  2223. int startingPos = gs->curB->getStack(ba.stackNumber)->position;
  2224. int distance = moveStack(ba.stackNumber, ba.destinationTile);
  2225. CStack *curStack = gs->curB->getStack(ba.stackNumber),
  2226. *stackAtEnd = gs->curB->getStackT(ba.additionalInfo);
  2227. if(curStack->position != ba.destinationTile //we wasn't able to reach destination tile
  2228. && !(curStack->hasFeatureOfType(StackFeature::DOUBLE_WIDE)
  2229. && ( curStack->position == ba.destinationTile + (curStack->attackerOwned ? +1 : -1 ) )
  2230. ) //nor occupy specified hex
  2231. )
  2232. {
  2233. std::string problem = "We cannot move this stack to its destination " + curStack->creature->namePl;
  2234. tlog3 << problem << std::endl;
  2235. complain(problem);
  2236. ok = false;
  2237. sendAndApply(&EndAction());
  2238. break;
  2239. }
  2240. if(curStack->ID == stackAtEnd->ID) //we should just move, it will be handled by following check
  2241. {
  2242. stackAtEnd = NULL;
  2243. }
  2244. if(!stackAtEnd)
  2245. {
  2246. std::ostringstream problem;
  2247. problem << "There is no stack on " << ba.additionalInfo << " tile (no attack)!";
  2248. std::string probl = problem.str();
  2249. tlog3 << probl << std::endl;
  2250. complain(probl);
  2251. ok = false;
  2252. sendAndApply(&EndAction());
  2253. break;
  2254. }
  2255. ui16 curpos = curStack->position,
  2256. enemypos = stackAtEnd->position;
  2257. if( !(
  2258. (BattleInfo::mutualPosition(curpos, enemypos) >= 0) //front <=> front
  2259. || (curStack->hasFeatureOfType(StackFeature::DOUBLE_WIDE) //back <=> front
  2260. && BattleInfo::mutualPosition(curpos + (curStack->attackerOwned ? -1 : 1), enemypos) >= 0)
  2261. || (stackAtEnd->hasFeatureOfType(StackFeature::DOUBLE_WIDE) //front <=> back
  2262. && BattleInfo::mutualPosition(curpos, enemypos + (stackAtEnd->attackerOwned ? -1 : 1)) >= 0)
  2263. || (stackAtEnd->hasFeatureOfType(StackFeature::DOUBLE_WIDE) && curStack->hasFeatureOfType(StackFeature::DOUBLE_WIDE)//back <=> back
  2264. && BattleInfo::mutualPosition(curpos + (curStack->attackerOwned ? -1 : 1), enemypos + (stackAtEnd->attackerOwned ? -1 : 1)) >= 0)
  2265. )
  2266. )
  2267. {
  2268. tlog3 << "Attack cannot be performed!";
  2269. sendAndApply(&EndAction());
  2270. ok = false;
  2271. }
  2272. //attack
  2273. BattleAttack bat;
  2274. prepareAttack(bat, curStack, stackAtEnd, distance);
  2275. sendAndApply(&bat);
  2276. //counterattack
  2277. if(!curStack->hasFeatureOfType(StackFeature::BLOCKS_RETALIATION)
  2278. && stackAtEnd->alive()
  2279. && ( stackAtEnd->counterAttacks > 0 || stackAtEnd->hasFeatureOfType(StackFeature::UNLIMITED_RETALIATIONS) )
  2280. && !stackAtEnd->hasFeatureOfType(StackFeature::SIEGE_WEAPON)
  2281. && !stackAtEnd->hasFeatureOfType(StackFeature::HYPNOTIZED))
  2282. {
  2283. prepareAttack(bat, stackAtEnd, curStack, 0);
  2284. bat.flags |= 2;
  2285. sendAndApply(&bat);
  2286. }
  2287. //second attack
  2288. if(curStack->valOfFeatures(StackFeature::ADDITIONAL_ATTACK) > 0
  2289. && !curStack->hasFeatureOfType(StackFeature::SHOOTER)
  2290. && curStack->alive()
  2291. && stackAtEnd->alive() )
  2292. {
  2293. bat.flags = 0;
  2294. prepareAttack(bat, curStack, stackAtEnd, 0);
  2295. sendAndApply(&bat);
  2296. }
  2297. //return
  2298. if(curStack->hasFeatureOfType(StackFeature::RETURN_AFTER_STRIKE) && startingPos != curStack->position)
  2299. {
  2300. moveStack(ba.stackNumber, startingPos);
  2301. }
  2302. sendAndApply(&EndAction());
  2303. break;
  2304. }
  2305. case 7: //shoot
  2306. {
  2307. CStack *curStack = gs->curB->getStack(ba.stackNumber),
  2308. *destStack= gs->curB->getStackT(ba.destinationTile);
  2309. if( !gs->battleCanShoot(ba.stackNumber, ba.destinationTile) )
  2310. break;
  2311. sendAndApply(&StartAction(ba)); //start shooting
  2312. BattleAttack bat;
  2313. prepareAttack(bat, curStack, destStack, 0);
  2314. bat.flags |= 1;
  2315. sendAndApply(&bat);
  2316. if(curStack->valOfFeatures(StackFeature::ADDITIONAL_ATTACK) > 0 //if unit shots twice let's make another shot
  2317. && curStack->alive()
  2318. && destStack->alive()
  2319. && curStack->shots
  2320. )
  2321. {
  2322. prepareAttack(bat, curStack, destStack, 0);
  2323. sendAndApply(&bat);
  2324. }
  2325. sendAndApply(&EndAction());
  2326. break;
  2327. }
  2328. case 9: //catapult
  2329. {
  2330. sendAndApply(&StartAction(ba));
  2331. const CGHeroInstance * attackingHero = (ba.side) ? gs->getHero(gs->curB->hero2) : gs->getHero(gs->curB->hero1);
  2332. CHeroHandler::SBallisticsLevelInfo sbi = VLC->heroh->ballistics[attackingHero->getSecSkillLevel(20)]; //artillery
  2333. int attackedPart = gs->curB->hexToWallPart(ba.destinationTile);
  2334. if(attackedPart == -1)
  2335. {
  2336. complain("catapult tried to attack non-catapultable hex!");
  2337. break;
  2338. }
  2339. for(int g=0; g<sbi.shots; ++g)
  2340. {
  2341. if(gs->curB->si.wallState[attackedPart] == 3) //it's not destroyed
  2342. continue;
  2343. CatapultAttack ca; //package for clients
  2344. std::pair< std::pair< ui8, si16 >, ui8> attack;
  2345. attack.first.first = attackedPart;
  2346. attack.first.second = ba.destinationTile;
  2347. attack.second = 0;
  2348. int chanceForHit = 0;
  2349. int dmgChance[3] = {sbi.noDmg, sbi.oneDmg, sbi.twoDmg}; //dmgChance[i] - chance for doing i dmg when hit is successful
  2350. switch(attackedPart)
  2351. {
  2352. case 0: //keep
  2353. chanceForHit = sbi.keep;
  2354. break;
  2355. case 1: //bottom tower
  2356. case 6: //upper tower
  2357. chanceForHit = sbi.tower;
  2358. break;
  2359. case 2: //bottom wall
  2360. case 3: //below gate
  2361. case 4: //over gate
  2362. case 5: //upper wall
  2363. chanceForHit = sbi.wall;
  2364. break;
  2365. case 7: //gate
  2366. chanceForHit = sbi.gate;
  2367. break;
  2368. }
  2369. if(rand()%100 <= chanceForHit) //hit is successful
  2370. {
  2371. int dmgRand = rand()%100;
  2372. //accumulating dmgChance
  2373. dmgChance[1] += dmgChance[0];
  2374. dmgChance[2] += dmgChance[1];
  2375. //calculating dealt damage
  2376. for(int v = 0; v < ARRAY_COUNT(dmgChance); ++v)
  2377. {
  2378. if(dmgRand <= dmgChance[v])
  2379. {
  2380. attack.second = v;
  2381. break;
  2382. }
  2383. }
  2384. if(attack.second > 0 && (attackedPart == 0 || attackedPart == 1 || attackedPart == 6))
  2385. {
  2386. int posRemove = -1;
  2387. switch(attackedPart)
  2388. {
  2389. case 0: //keep
  2390. posRemove = -2;
  2391. break;
  2392. case 1: //bottom tower
  2393. posRemove = -3;
  2394. break;
  2395. case 6: //upper tower
  2396. posRemove = -4;
  2397. break;
  2398. }
  2399. BattleStacksRemoved bsr;
  2400. for(int g=0; g<gs->curB->stacks.size(); ++g)
  2401. {
  2402. if(gs->curB->stacks[g]->position == posRemove)
  2403. {
  2404. bsr.stackIDs.insert( gs->curB->stacks[g]->ID );
  2405. break;
  2406. }
  2407. }
  2408. sendAndApply(&bsr);
  2409. }
  2410. }
  2411. ca.attacker = ba.stackNumber;
  2412. ca.attackedParts.insert(attack);
  2413. sendAndApply(&ca);
  2414. }
  2415. sendAndApply(&EndAction());
  2416. break;
  2417. }
  2418. }
  2419. battleMadeAction.setn(true);
  2420. return ok;
  2421. }
  2422. void CGameHandler::playerMessage( ui8 player, const std::string &message )
  2423. {
  2424. bool cheated=true;
  2425. sendAndApply(&PlayerMessage(player,message));
  2426. if(message == "vcmiistari") //give all spells and 999 mana
  2427. {
  2428. SetMana sm;
  2429. ChangeSpells cs;
  2430. SetHeroArtifacts sha;
  2431. CGHeroInstance *h = gs->getHero(gs->getPlayer(player)->currentSelection);
  2432. if(!h && complain("Cannot realize cheat, no hero selected!")) return;
  2433. sm.hid = cs.hid = h->id;
  2434. //give all spells
  2435. cs.learn = 1;
  2436. for(int i=0;i<VLC->spellh->spells.size();i++)
  2437. {
  2438. if(!VLC->spellh->spells[i].creatureAbility)
  2439. cs.spells.insert(i);
  2440. }
  2441. //give mana
  2442. sm.val = 999;
  2443. if(!h->getArt(17)) //hero doesn't have spellbook
  2444. {
  2445. //give spellbook
  2446. sha.hid = h->id;
  2447. sha.artifacts = h->artifacts;
  2448. sha.artifWorn = h->artifWorn;
  2449. sha.artifWorn[17] = 0;
  2450. sendAndApply(&sha);
  2451. }
  2452. sendAndApply(&cs);
  2453. sendAndApply(&sm);
  2454. }
  2455. else if(message == "vcmiainur") //gives 5 archangels into each slot
  2456. {
  2457. SetGarrisons sg;
  2458. CGHeroInstance *hero = gs->getHero(gs->getPlayer(player)->currentSelection);
  2459. if(!hero) return;
  2460. sg.garrs[hero->id] = hero->army;
  2461. for(int i=0;i<7;i++)
  2462. if(!vstd::contains(sg.garrs[hero->id].slots,i))
  2463. sg.garrs[hero->id].slots[i] = std::pair<ui32,si32>(13,5);
  2464. sendAndApply(&sg);
  2465. }
  2466. else if(message == "vcmiangband") //gives 10 black knight into each slot
  2467. {
  2468. SetGarrisons sg;
  2469. CGHeroInstance *hero = gs->getHero(gs->getPlayer(player)->currentSelection);
  2470. if(!hero) return;
  2471. sg.garrs[hero->id] = hero->army;
  2472. for(int i=0;i<7;i++)
  2473. if(!vstd::contains(sg.garrs[hero->id].slots,i))
  2474. sg.garrs[hero->id].slots[i] = std::pair<ui32,si32>(66,10);
  2475. sendAndApply(&sg);
  2476. }
  2477. else if(message == "vcminoldor") //all war machines
  2478. {
  2479. CGHeroInstance *hero = gs->getHero(gs->getPlayer(player)->currentSelection);
  2480. if(!hero) return;
  2481. SetHeroArtifacts sha;
  2482. sha.hid = hero->id;
  2483. sha.artifacts = hero->artifacts;
  2484. sha.artifWorn = hero->artifWorn;
  2485. sha.artifWorn[13] = 4;
  2486. sha.artifWorn[14] = 5;
  2487. sha.artifWorn[15] = 6;
  2488. sendAndApply(&sha);
  2489. }
  2490. else if(message == "vcminahar") //1000000 movement points
  2491. {
  2492. CGHeroInstance *hero = gs->getHero(gs->getPlayer(player)->currentSelection);
  2493. if(!hero) return;
  2494. SetMovePoints smp;
  2495. smp.hid = hero->id;
  2496. smp.val = 1000000;
  2497. sendAndApply(&smp);
  2498. }
  2499. else if(message == "vcmiformenos") //give resources
  2500. {
  2501. SetResources sr;
  2502. sr.player = player;
  2503. sr.res = gs->getPlayer(player)->resources;
  2504. for(int i=0;i<7;i++)
  2505. sr.res[i] += 100;
  2506. sr.res[6] += 19900;
  2507. sendAndApply(&sr);
  2508. }
  2509. else if(message == "vcmieagles") //reveal FoW
  2510. {
  2511. FoWChange fc;
  2512. fc.mode = 1;
  2513. fc.player = player;
  2514. for(int i=0;i<gs->map->width;i++)
  2515. for(int j=0;j<gs->map->height;j++)
  2516. for(int k=0;k<gs->map->twoLevel+1;k++)
  2517. if(!gs->getPlayer(fc.player)->fogOfWarMap[i][j][k])
  2518. fc.tiles.insert(int3(i,j,k));
  2519. sendAndApply(&fc);
  2520. }
  2521. else if(message == "vcmiglorfindel")
  2522. {
  2523. CGHeroInstance *hero = gs->getHero(gs->getPlayer(player)->currentSelection);
  2524. changePrimSkill(hero->id,4,VLC->heroh->reqExp(hero->level+1) - VLC->heroh->reqExp(hero->level));
  2525. }
  2526. else
  2527. cheated = false;
  2528. if(cheated)
  2529. {
  2530. sendAndApply(&SystemMessage("CHEATER!!!"));
  2531. }
  2532. }
  2533. static ui32 calculateSpellDmg(const CSpell * sp, const CGHeroInstance * caster, const CStack * affectedCreature)
  2534. {
  2535. ui32 ret = 0; //value to return
  2536. //15 - magic arrows, 16 - ice bolt, 17 - lightning bolt, 18 - implosion, 20 - frost ring, 21 - fireball, 22 - inferno, 23 - meteor shower,
  2537. //24 - death ripple, 25 - destroy undead, 26 - armageddon
  2538. static std::map <int, int> dmgMultipliers = boost::assign::map_list_of(15, 10)(16, 20)(17, 25)(18, 75)(20, 10)(21, 10)(22, 10)(23, 10)(24, 5)(25, 10)(26, 50);
  2539. ret = caster->getPrimSkillLevel(2) * dmgMultipliers[sp->id] + sp->powers[caster->getSpellSchoolLevel(sp)];
  2540. //applying sorcerery secondary skill
  2541. switch(caster->getSecSkillLevel(25))
  2542. {
  2543. case 1: //basic
  2544. ret *= 1.05f;
  2545. break;
  2546. case 2: //advanced
  2547. ret *= 1.1f;
  2548. break;
  2549. case 3: //expert
  2550. ret *= 1.15f;
  2551. break;
  2552. }
  2553. //applying hero bonuses
  2554. if(sp->air && caster->valOfBonuses(HeroBonus::AIR_SPELL_DMG_PREMY) != 0)
  2555. {
  2556. ret *= (100.0f + caster->valOfBonuses(HeroBonus::AIR_SPELL_DMG_PREMY) / 100.0f);
  2557. }
  2558. else if(sp->fire && caster->valOfBonuses(HeroBonus::FIRE_SPELL_DMG_PREMY) != 0)
  2559. {
  2560. ret *= (100.0f + caster->valOfBonuses(HeroBonus::FIRE_SPELL_DMG_PREMY) / 100.0f);
  2561. }
  2562. else if(sp->water && caster->valOfBonuses(HeroBonus::WATER_SPELL_DMG_PREMY) != 0)
  2563. {
  2564. ret *= (100.0f + caster->valOfBonuses(HeroBonus::WATER_SPELL_DMG_PREMY) / 100.0f);
  2565. }
  2566. else if(sp->earth && caster->valOfBonuses(HeroBonus::EARTH_SPELL_DMG_PREMY) != 0)
  2567. {
  2568. ret *= (100.0f + caster->valOfBonuses(HeroBonus::EARTH_SPELL_DMG_PREMY) / 100.0f);
  2569. }
  2570. //applying protections - when spell has more then one elements, only one protection should be applied (I think)
  2571. if(sp->air && affectedCreature->hasFeatureOfType(StackFeature::SPELL_DAMAGE_REDUCTION, 0)) //air spell & protection from air
  2572. {
  2573. ret *= affectedCreature->valOfFeatures(StackFeature::SPELL_DAMAGE_REDUCTION, 0);
  2574. ret /= 100;
  2575. }
  2576. else if(sp->fire && affectedCreature->hasFeatureOfType(StackFeature::SPELL_DAMAGE_REDUCTION, 1)) //fire spell & protection from fire
  2577. {
  2578. ret *= affectedCreature->valOfFeatures(StackFeature::SPELL_DAMAGE_REDUCTION, 1);
  2579. ret /= 100;
  2580. }
  2581. else if(sp->water && affectedCreature->hasFeatureOfType(StackFeature::SPELL_DAMAGE_REDUCTION, 2)) //water spell & protection from water
  2582. {
  2583. ret *= affectedCreature->valOfFeatures(StackFeature::SPELL_DAMAGE_REDUCTION, 2);
  2584. ret /= 100;
  2585. }
  2586. else if (sp->earth && affectedCreature->hasFeatureOfType(StackFeature::SPELL_DAMAGE_REDUCTION, 3)) //earth spell & protection from earth
  2587. {
  2588. ret *= affectedCreature->valOfFeatures(StackFeature::SPELL_DAMAGE_REDUCTION, 3);
  2589. ret /= 100;
  2590. }
  2591. //general spell dmg reduction
  2592. if(sp->air && affectedCreature->hasFeatureOfType(StackFeature::SPELL_DAMAGE_REDUCTION, -1)) //air spell & protection from air
  2593. {
  2594. ret *= affectedCreature->valOfFeatures(StackFeature::SPELL_DAMAGE_REDUCTION, -1);
  2595. ret /= 100;
  2596. }
  2597. //dmg increasing
  2598. if( affectedCreature->hasFeatureOfType(StackFeature::MORE_DAMAGE_FROM_SPELL, sp->id) )
  2599. {
  2600. ret *= 100 + affectedCreature->valOfFeatures(StackFeature::MORE_DAMAGE_FROM_SPELL, sp->id);
  2601. ret /= 100;
  2602. }
  2603. return ret;
  2604. }
  2605. static ui32 calculateHealedHP(const CGHeroInstance * caster, const CSpell * spell, const CStack * stack)
  2606. {
  2607. switch(spell->id)
  2608. {
  2609. case 37: //cure
  2610. {
  2611. int healedHealth = caster->getPrimSkillLevel(2) * 5 + spell->powers[caster->getSpellSchoolLevel(spell)];
  2612. return std::min<ui32>(healedHealth, stack->MaxHealth() - stack->firstHPleft);
  2613. break;
  2614. }
  2615. case 38: //resurrection
  2616. {
  2617. int healedHealth = caster->getPrimSkillLevel(2) * 50 + spell->powers[caster->getSpellSchoolLevel(spell)];
  2618. return std::min<ui32>(healedHealth, stack->MaxHealth() - stack->firstHPleft + stack->baseAmount * stack->MaxHealth());
  2619. break;
  2620. }
  2621. case 39: //animate dead
  2622. {
  2623. int healedHealth = caster->getPrimSkillLevel(2) * 50 + spell->powers[caster->getSpellSchoolLevel(spell)];
  2624. return std::min<ui32>(healedHealth, stack->MaxHealth() - stack->firstHPleft + stack->baseAmount * stack->MaxHealth());
  2625. break;
  2626. }
  2627. }
  2628. //we shouldn't be here
  2629. tlog1 << "calculateHealedHP called for non-healing spell: " << spell->name << std::endl;
  2630. return 0;
  2631. }
  2632. static std::vector<ui32> calculateResistedStacks(const CSpell * sp, const CGHeroInstance * caster, const CGHeroInstance * hero2, const std::set<CStack*> affectedCreatures)
  2633. {
  2634. std::vector<ui32> ret;
  2635. for(std::set<CStack*>::const_iterator it = affectedCreatures.begin(); it != affectedCreatures.end(); ++it)
  2636. {
  2637. if ((*it)->hasFeatureOfType(StackFeature::SPELL_IMMUNITY, sp->id) //100% sure spell immunity
  2638. || ((*it)->valOfFeatures(StackFeature::LEVEL_SPELL_IMMUNITY) >= sp->level))
  2639. {
  2640. ret.push_back((*it)->ID);
  2641. continue;
  2642. }
  2643. //non-negative spells on friendly stacks should always succeed, unless immune
  2644. if(sp->positiveness >= 0 && (*it)->owner == caster->tempOwner)
  2645. continue;
  2646. const CGHeroInstance * bonusHero; //hero we should take bonuses from
  2647. if((*it)->owner == caster->tempOwner)
  2648. bonusHero = caster;
  2649. else
  2650. bonusHero = hero2;
  2651. int prob = (*it)->valOfFeatures(StackFeature::MAGIC_RESISTANCE); //probability of resistance in %
  2652. if(bonusHero)
  2653. {
  2654. //bonusHero's resistance support (secondary skils and artifacts)
  2655. prob += bonusHero->valOfBonuses(HeroBonus::MAGIC_RESISTANCE);
  2656. switch(bonusHero->getSecSkillLevel(26)) //resistance
  2657. {
  2658. case 1: //basic
  2659. prob += 5;
  2660. break;
  2661. case 2: //advanced
  2662. prob += 10;
  2663. break;
  2664. case 3: //expert
  2665. prob += 20;
  2666. break;
  2667. }
  2668. }
  2669. if(prob > 100) prob = 100;
  2670. if(rand()%100 < prob) //immunity from resistance
  2671. ret.push_back((*it)->ID);
  2672. }
  2673. if(sp->id == 60) //hypnotize
  2674. {
  2675. for(std::set<CStack*>::const_iterator it = affectedCreatures.begin(); it != affectedCreatures.end(); ++it)
  2676. {
  2677. if( (*it)->hasFeatureOfType(StackFeature::SPELL_IMMUNITY, sp->id) //100% sure spell immunity
  2678. || ( (*it)->amount - 1 ) * (*it)->MaxHealth() + (*it)->firstHPleft
  2679. >
  2680. caster->getPrimSkillLevel(2) * 25 + sp->powers[caster->getSpellSchoolLevel(sp)]
  2681. )
  2682. {
  2683. ret.push_back((*it)->ID);
  2684. }
  2685. }
  2686. }
  2687. return ret;
  2688. }
  2689. bool CGameHandler::makeCustomAction( BattleAction &ba )
  2690. {
  2691. switch(ba.actionType)
  2692. {
  2693. case 1: //hero casts spell
  2694. {
  2695. CGHeroInstance *h = (ba.side) ? gs->getHero(gs->curB->hero2) : gs->getHero(gs->curB->hero1);
  2696. CGHeroInstance *secondHero = (!ba.side) ? gs->getHero(gs->curB->hero2) : gs->getHero(gs->curB->hero1);
  2697. if(!h)
  2698. {
  2699. tlog2 << "Wrong caster!\n";
  2700. return false;
  2701. }
  2702. if(ba.additionalInfo >= VLC->spellh->spells.size())
  2703. {
  2704. tlog2 << "Wrong spell id (" << ba.additionalInfo << ")!\n";
  2705. return false;
  2706. }
  2707. CSpell *s = &VLC->spellh->spells[ba.additionalInfo];
  2708. ui8 skill = h->getSpellSchoolLevel(s); //skill level
  2709. if( !(h->canCastThisSpell(s)) //hero cannot cast this spell at all
  2710. || (h->mana < gs->curB->getSpellCost(s, h)) //not enough mana
  2711. || (ba.additionalInfo < 10) //it's adventure spell (not combat)
  2712. || (gs->curB->castSpells[ba.side]) //spell has been cast
  2713. || (secondHero && secondHero->hasBonusOfType(HeroBonus::SPELL_IMMUNITY, s->id)) //non - casting hero provides immunity for this spell
  2714. || (gs->battleMaxSpellLevel() < s->level) //non - casting hero stops caster from casting this spell
  2715. )
  2716. {
  2717. tlog2 << "Spell cannot be cast!\n";
  2718. return false;
  2719. }
  2720. sendAndApply(&StartAction(ba)); //start spell casting
  2721. SpellCast sc;
  2722. sc.side = ba.side;
  2723. sc.id = ba.additionalInfo;
  2724. sc.skill = skill;
  2725. sc.tile = ba.destinationTile;
  2726. //calculating affected creatures for all spells
  2727. std::set<CStack*> attackedCres = gs->curB->getAttackedCreatures(s, h, ba.destinationTile);
  2728. for(std::set<CStack*>::const_iterator it = attackedCres.begin(); it != attackedCres.end(); ++it)
  2729. {
  2730. sc.affectedCres.insert((*it)->ID);
  2731. }
  2732. //checking if creatures resist
  2733. sc.resisted = calculateResistedStacks(s, h, secondHero, attackedCres);
  2734. sendAndApply(&sc);
  2735. //applying effects
  2736. switch(ba.additionalInfo) //spell id
  2737. {
  2738. case 15: //magic arrow
  2739. case 16: //ice bolt
  2740. case 17: //lightning bolt
  2741. case 18: //implosion
  2742. case 20: //frost ring
  2743. case 21: //fireball
  2744. case 22: //inferno
  2745. case 23: //meteor shower
  2746. case 24: //death ripple
  2747. case 25: //destroy undead
  2748. case 26: //armageddon
  2749. {
  2750. StacksInjured si;
  2751. for(std::set<CStack*>::iterator it = attackedCres.begin(); it != attackedCres.end(); ++it)
  2752. {
  2753. if(vstd::contains(sc.resisted, (*it)->ID)) //this creature resisted the spell
  2754. continue;
  2755. BattleStackAttacked bsa;
  2756. bsa.flags |= 2;
  2757. bsa.effect = VLC->spellh->spells[ba.additionalInfo].mainEffectAnim;
  2758. bsa.damageAmount = calculateSpellDmg(s, h, *it);
  2759. bsa.stackAttacked = (*it)->ID;
  2760. bsa.attackerID = -1;
  2761. prepareAttacked(bsa,*it);
  2762. si.stacks.insert(bsa);
  2763. }
  2764. if(!si.stacks.empty())
  2765. sendAndApply(&si);
  2766. break;
  2767. }
  2768. case 27: //shield
  2769. case 28: //air shield
  2770. case 30: //protection from air
  2771. case 31: //protection from fire
  2772. case 32: //protection from water
  2773. case 33: //protection from earth
  2774. case 34: //anti-magic
  2775. case 41: //bless
  2776. case 42: //curse
  2777. case 43: //bloodlust
  2778. case 44: //precision
  2779. case 45: //weakness
  2780. case 46: //stone skin
  2781. case 47: //disrupting ray
  2782. case 48: //prayer
  2783. case 49: //mirth
  2784. case 50: //sorrow
  2785. case 51: //fortune
  2786. case 52: //misfortune
  2787. case 53: //haste
  2788. case 54: //slow
  2789. case 55: //slayer
  2790. case 56: //frenzy
  2791. case 58: //counterstrike
  2792. case 59: //berserk
  2793. case 60: //hypnotize
  2794. case 61: //forgetfulness
  2795. case 62: //blind
  2796. {
  2797. SetStackEffect sse;
  2798. for(std::set<CStack*>::iterator it = attackedCres.begin(); it != attackedCres.end(); ++it)
  2799. {
  2800. if(vstd::contains(sc.resisted, (*it)->ID)) //this creature resisted the spell
  2801. continue;
  2802. sse.stacks.insert((*it)->ID);
  2803. }
  2804. sse.effect.id = ba.additionalInfo;
  2805. sse.effect.level = h->getSpellSchoolLevel(s);
  2806. sse.effect.turnsRemain = BattleInfo::calculateSpellDuration(s, h);
  2807. if(!sse.stacks.empty())
  2808. sendAndApply(&sse);
  2809. break;
  2810. }
  2811. case 37: //cure
  2812. case 38: //resurrection
  2813. case 39: //animate dead
  2814. {
  2815. StacksHealedOrResurrected shr;
  2816. for(std::set<CStack*>::iterator it = attackedCres.begin(); it != attackedCres.end(); ++it)
  2817. {
  2818. if(vstd::contains(sc.resisted, (*it)->ID) //this creature resisted the spell
  2819. || (s->id == 39 && !(*it)->hasFeatureOfType(StackFeature::UNDEAD)) //we try to cast animate dead on living stack
  2820. )
  2821. continue;
  2822. StacksHealedOrResurrected::HealInfo hi;
  2823. hi.stackID = (*it)->ID;
  2824. hi.healedHP = calculateHealedHP(h, s, *it);
  2825. shr.healedStacks.push_back(hi);
  2826. }
  2827. if(!shr.healedStacks.empty())
  2828. sendAndApply(&shr);
  2829. break;
  2830. }
  2831. case 64: //remove obstacle
  2832. {
  2833. ObstaclesRemoved obr;
  2834. for(int g=0; g<gs->curB->obstacles.size(); ++g)
  2835. {
  2836. std::vector<int> blockedHexes = VLC->heroh->obstacles[gs->curB->obstacles[g].ID].getBlocked(gs->curB->obstacles[g].pos);
  2837. if(vstd::contains(blockedHexes, ba.destinationTile)) //this obstacle covers given hex
  2838. {
  2839. obr.obstacles.insert(gs->curB->obstacles[g].uniqueID);
  2840. }
  2841. }
  2842. if(!obr.obstacles.empty())
  2843. sendAndApply(&obr);
  2844. break;
  2845. }
  2846. }
  2847. sendAndApply(&EndAction());
  2848. checkForBattleEnd(gs->curB->stacks);
  2849. if(battleResult.get())
  2850. {
  2851. endBattle(gs->curB->tile, getHero(gs->curB->hero1), getHero(gs->curB->hero2));
  2852. }
  2853. return true;
  2854. }
  2855. }
  2856. return false;
  2857. }
  2858. void CGameHandler::handleTimeEvents()
  2859. {
  2860. gs->map->events.sort(evntCmp);
  2861. while(gs->map->events.size() && gs->map->events.front()->firstOccurence+1 == gs->day)
  2862. {
  2863. CMapEvent *ev = gs->map->events.front();
  2864. for(int player = 0; player < PLAYER_LIMIT; player++)
  2865. {
  2866. PlayerState *pinfo = gs->getPlayer(player);
  2867. if( pinfo //player exists
  2868. && (ev->players & 1<<player) //event is enabled to this player
  2869. && ((ev->computerAffected && !pinfo->human)
  2870. || (ev->humanAffected && pinfo->human)
  2871. )
  2872. )
  2873. {
  2874. //give resources
  2875. SetResources sr;
  2876. sr.player = player;
  2877. sr.res = pinfo->resources;
  2878. //prepare dialog
  2879. InfoWindow iw;
  2880. iw.player = player;
  2881. iw.text << ev->message;
  2882. for (int i=0; i<ev->resources.size(); i++)
  2883. {
  2884. if(ev->resources[i]) //if resource is changed, we add it to the dialog
  2885. {
  2886. // If removing too much resources, adjust the
  2887. // amount so the total doesn't become negative.
  2888. if (sr.res[i] + ev->resources[i] < 0)
  2889. ev->resources[i] = -sr.res[i];
  2890. if(ev->resources[i]) //if non-zero res change
  2891. {
  2892. iw.components.push_back(Component(Component::RESOURCE,i,ev->resources[i],0));
  2893. sr.res[i] += ev->resources[i];
  2894. }
  2895. }
  2896. }
  2897. if (iw.components.size())
  2898. {
  2899. sendAndApply(&sr); //update player resources if changed
  2900. }
  2901. sendAndApply(&iw); //show dialog
  2902. }
  2903. } //PLAYERS LOOP
  2904. if(ev->nextOccurence)
  2905. {
  2906. ev->firstOccurence += ev->nextOccurence;
  2907. gs->map->events.sort(evntCmp);
  2908. }
  2909. else
  2910. {
  2911. delete ev;
  2912. gs->map->events.pop_front();
  2913. }
  2914. }
  2915. }
  2916. bool CGameHandler::complain( const std::string &problem )
  2917. {
  2918. sendMessageToAll("Server encountered a problem: " + problem);
  2919. tlog1 << problem << std::endl;
  2920. return true;
  2921. }
  2922. ui32 CGameHandler::getQueryResult( ui8 player, int queryID )
  2923. {
  2924. //TODO: write
  2925. return 0;
  2926. }
  2927. void CGameHandler::showGarrisonDialog( int upobj, int hid, bool removableUnits, const boost::function<void()> &cb )
  2928. {
  2929. ui8 player = getOwner(hid);
  2930. GarrisonDialog gd;
  2931. gd.hid = hid;
  2932. gd.objid = upobj;
  2933. {
  2934. boost::unique_lock<boost::recursive_mutex> lock(gsm);
  2935. gd.id = QID;
  2936. garrisonCallbacks[QID] = cb;
  2937. allowedExchanges[QID] = std::pair<si32,si32>(upobj,hid);
  2938. states.addQuery(player,QID);
  2939. QID++;
  2940. gd.removableUnits = removableUnits;
  2941. sendAndApply(&gd);
  2942. }
  2943. }
  2944. bool CGameHandler::isAllowedExchange( int id1, int id2 )
  2945. {
  2946. if(id1 == id2)
  2947. return true;
  2948. {
  2949. boost::unique_lock<boost::recursive_mutex> lock(gsm);
  2950. for(std::map<ui32, std::pair<si32,si32> >::const_iterator i = allowedExchanges.begin(); i!=allowedExchanges.end(); i++)
  2951. if(id1 == i->second.first && id2 == i->second.second || id2 == i->second.first && id1 == i->second.second)
  2952. return true;
  2953. }
  2954. const CGObjectInstance *o1 = getObj(id1), *o2 = getObj(id2);
  2955. if(o1->ID == TOWNI_TYPE)
  2956. {
  2957. const CGTownInstance *t = static_cast<const CGTownInstance*>(o1);
  2958. if(t->visitingHero == o2 || t->garrisonHero == o2)
  2959. return true;
  2960. }
  2961. if(o2->ID == TOWNI_TYPE)
  2962. {
  2963. const CGTownInstance *t = static_cast<const CGTownInstance*>(o2);
  2964. if(t->visitingHero == o1 || t->garrisonHero == o1)
  2965. return true;
  2966. }
  2967. if(o1->ID == HEROI_TYPE && o2->ID == HEROI_TYPE
  2968. && distance(o1->pos, o2->pos) < 2) //hero stands on the same tile or on the neighbouring tiles
  2969. {
  2970. //TODO: it's workaround, we should check if first hero visited second and player hasn't closed exchange window
  2971. //(to block moving stacks for free [without visiting] beteen heroes)
  2972. return true;
  2973. }
  2974. return false;
  2975. }
  2976. void CGameHandler::objectVisited( const CGObjectInstance * obj, const CGHeroInstance * h )
  2977. {
  2978. obj->onHeroVisit(h);
  2979. }
  2980. bool CGameHandler::buildBoat( ui32 objid )
  2981. {
  2982. const IShipyard *obj = IShipyard::castFrom(getObj(objid));
  2983. if(obj->state())
  2984. {
  2985. complain("Cannot build boat in this shipyard!");
  2986. return false;
  2987. }
  2988. else if(obj->o->ID == TOWNI_TYPE
  2989. && !vstd::contains((static_cast<const CGTownInstance*>(obj))->builtBuildings,6))
  2990. {
  2991. complain("Cannot build boat in the town - no shipyard!");
  2992. return false;
  2993. }
  2994. //TODO use "real" cost via obj->getBoatCost
  2995. if(getResource(obj->o->tempOwner, 6) < 1000 || getResource(obj->o->tempOwner, 0) < 10)
  2996. {
  2997. complain("Not enough resources to build a boat!");
  2998. return false;
  2999. }
  3000. int3 tile = obj->bestLocation();
  3001. if(!gs->map->isInTheMap(tile))
  3002. {
  3003. complain("Cannot find appropriate tile for a boat!");
  3004. return false;
  3005. }
  3006. //take boat cost
  3007. SetResources sr;
  3008. sr.player = obj->o->tempOwner;
  3009. sr.res = gs->getPlayer(obj->o->tempOwner)->resources;
  3010. sr.res[0] -= 10;
  3011. sr.res[6] -= 1000;
  3012. sendAndApply(&sr);
  3013. //create boat
  3014. NewObject no;
  3015. no.ID = 8;
  3016. no.subID = 1;
  3017. no.pos = tile + int3(1,0,0);
  3018. sendAndApply(&no);
  3019. return true;
  3020. }
  3021. void CGameHandler::engageIntoBattle( ui8 player )
  3022. {
  3023. if(vstd::contains(states.players, player))
  3024. states.setFlag(player,&PlayerStatus::engagedIntoBattle,true);
  3025. //notify interfaces
  3026. PlayerBlocked pb;
  3027. pb.player = player;
  3028. pb.reason = PlayerBlocked::UPCOMING_BATTLE;
  3029. sendAndApply(&pb);
  3030. }