CGameHandler.cpp 72 KB

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