CGameHandler.cpp 68 KB

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