CGameHandler.cpp 68 KB

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