CGameHandler.cpp 129 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447
  1. #include "../hch/CCampaignHandler.h"
  2. #include "../StartInfo.h"
  3. #include "../hch/CArtHandler.h"
  4. #include "../hch/CBuildingHandler.h"
  5. #include "../hch/CDefObjInfoHandler.h"
  6. #include "../hch/CHeroHandler.h"
  7. #include "../hch/CObjectHandler.h"
  8. #include "../hch/CSpellHandler.h"
  9. #include "../hch/CGeneralTextHandler.h"
  10. #include "../hch/CTownHandler.h"
  11. #include "../lib/CGameState.h"
  12. #include "../lib/CondSh.h"
  13. #include "../lib/NetPacks.h"
  14. #include "../lib/VCMI_Lib.h"
  15. #include "../lib/map.h"
  16. #include "../lib/VCMIDirs.h"
  17. #include "CGameHandler.h"
  18. #include <boost/bind.hpp>
  19. #include <boost/date_time/posix_time/posix_time_types.hpp> //no i/o just types
  20. #include <boost/foreach.hpp>
  21. #include <boost/thread.hpp>
  22. #include <boost/thread/shared_mutex.hpp>
  23. #include <boost/assign/list_of.hpp>
  24. #include <fstream>
  25. #include <boost/system/system_error.hpp>
  26. /*
  27. * CGameHandler.cpp, part of VCMI engine
  28. *
  29. * Authors: listed in file AUTHORS in main folder
  30. *
  31. * License: GNU General Public License v2.0 or later
  32. * Full text of license available in license.txt file, in main folder
  33. *
  34. */
  35. #undef DLL_EXPORT
  36. #define DLL_EXPORT
  37. #include "../lib/RegisterTypes.cpp"
  38. #ifndef _MSC_VER
  39. #include <boost/thread/xtime.hpp>
  40. #endif
  41. extern bool end2;
  42. #ifdef min
  43. #undef min
  44. #endif
  45. #ifdef max
  46. #undef max
  47. #endif
  48. #define COMPLAIN_RET(txt) {complain(txt); return false;}
  49. #define NEW_ROUND BattleNextRound bnr;\
  50. bnr.round = gs->curB->round + 1;\
  51. sendAndApply(&bnr);
  52. CondSh<bool> battleMadeAction;
  53. CondSh<BattleResult *> battleResult(NULL);
  54. class CBaseForGHApply
  55. {
  56. public:
  57. virtual bool applyOnGH(CGameHandler *gh, CConnection *c, void *pack) const =0;
  58. };
  59. template <typename T> class CApplyOnGH : public CBaseForGHApply
  60. {
  61. public:
  62. bool applyOnGH(CGameHandler *gh, CConnection *c, void *pack) const
  63. {
  64. T *ptr = static_cast<T*>(pack);
  65. ptr->c = c;
  66. return ptr->applyGh(gh);
  67. }
  68. };
  69. class CGHApplier
  70. {
  71. public:
  72. std::map<ui16,CBaseForGHApply*> apps;
  73. CGHApplier()
  74. {
  75. registerTypes3(*this);
  76. }
  77. template<typename T> void registerType(const T * t=NULL)
  78. {
  79. ui16 ID = typeList.registerType(t);
  80. apps[ID] = new CApplyOnGH<T>;
  81. }
  82. } *applier = NULL;
  83. CMP_stack cmpst ;
  84. static inline double distance(int3 a, int3 b)
  85. {
  86. return std::sqrt( (double)(a.x-b.x)*(a.x-b.x) + (a.y-b.y)*(a.y-b.y) );
  87. }
  88. static void giveExp(BattleResult &r)
  89. {
  90. r.exp[0] = 0;
  91. r.exp[1] = 0;
  92. for(std::map<ui32,si32>::iterator i = r.casualties[!r.winner].begin(); i!=r.casualties[!r.winner].end(); i++)
  93. {
  94. r.exp[r.winner] += VLC->creh->creatures[i->first]->valOfBonuses(Bonus::STACK_HEALTH) * i->second;
  95. }
  96. }
  97. PlayerStatus PlayerStatuses::operator[](ui8 player)
  98. {
  99. boost::unique_lock<boost::mutex> l(mx);
  100. if(players.find(player) != players.end())
  101. {
  102. return players[player];
  103. }
  104. else
  105. {
  106. throw std::string("No such player!");
  107. }
  108. }
  109. void PlayerStatuses::addPlayer(ui8 player)
  110. {
  111. boost::unique_lock<boost::mutex> l(mx);
  112. players[player];
  113. }
  114. bool PlayerStatuses::hasQueries(ui8 player)
  115. {
  116. boost::unique_lock<boost::mutex> l(mx);
  117. if(players.find(player) != players.end())
  118. {
  119. return players[player].queries.size();
  120. }
  121. else
  122. {
  123. throw std::string("No such player!");
  124. }
  125. }
  126. bool PlayerStatuses::checkFlag(ui8 player, bool PlayerStatus::*flag)
  127. {
  128. boost::unique_lock<boost::mutex> l(mx);
  129. if(players.find(player) != players.end())
  130. {
  131. return players[player].*flag;
  132. }
  133. else
  134. {
  135. throw std::string("No such player!");
  136. }
  137. }
  138. void PlayerStatuses::setFlag(ui8 player, bool PlayerStatus::*flag, bool val)
  139. {
  140. boost::unique_lock<boost::mutex> l(mx);
  141. if(players.find(player) != players.end())
  142. {
  143. players[player].*flag = val;
  144. }
  145. else
  146. {
  147. throw std::string("No such player!");
  148. }
  149. cv.notify_all();
  150. }
  151. void PlayerStatuses::addQuery(ui8 player, ui32 id)
  152. {
  153. boost::unique_lock<boost::mutex> l(mx);
  154. if(players.find(player) != players.end())
  155. {
  156. players[player].queries.insert(id);
  157. }
  158. else
  159. {
  160. throw std::string("No such player!");
  161. }
  162. cv.notify_all();
  163. }
  164. void PlayerStatuses::removeQuery(ui8 player, ui32 id)
  165. {
  166. boost::unique_lock<boost::mutex> l(mx);
  167. if(players.find(player) != players.end())
  168. {
  169. players[player].queries.erase(id);
  170. }
  171. else
  172. {
  173. throw std::string("No such player!");
  174. }
  175. cv.notify_all();
  176. }
  177. template <typename T>
  178. void callWith(std::vector<T> args, boost::function<void(T)> fun, ui32 which)
  179. {
  180. fun(args[which]);
  181. }
  182. void CGameHandler::changeSecSkill( int ID, int which, int val, bool abs/*=false*/ )
  183. {
  184. SetSecSkill sss;
  185. sss.id = ID;
  186. sss.which = which;
  187. sss.val = val;
  188. sss.abs = abs;
  189. sendAndApply(&sss);
  190. if(which == 7) //Wisdom
  191. {
  192. const CGHeroInstance *h = getHero(ID);
  193. if(h && h->visitedTown)
  194. giveSpells(h->visitedTown, h);
  195. }
  196. }
  197. void CGameHandler::changePrimSkill(int ID, int which, si64 val, bool abs)
  198. {
  199. SetPrimSkill sps;
  200. sps.id = ID;
  201. sps.which = which;
  202. sps.abs = abs;
  203. sps.val = val;
  204. sendAndApply(&sps);
  205. if(which==4) //only for exp - hero may level up
  206. {
  207. CGHeroInstance *hero = static_cast<CGHeroInstance *>(gs->map->objects[ID]);
  208. while (hero->exp >= VLC->heroh->reqExp(hero->level+1)) //new level
  209. {
  210. //give prim skill
  211. tlog5 << hero->name <<" got level "<<hero->level<<std::endl;
  212. int r = rand()%100, pom=0, x=0;
  213. int std::pair<int,int>::*g = (hero->level>9) ? (&std::pair<int,int>::second) : (&std::pair<int,int>::first);
  214. for(;x<PRIMARY_SKILLS;x++)
  215. {
  216. pom += hero->type->heroClass->primChance[x].*g;
  217. if(r<pom)
  218. break;
  219. }
  220. tlog5 << "Bohater dostaje umiejetnosc pierwszorzedna " << x << " (wynik losowania "<<r<<")"<<std::endl;
  221. SetPrimSkill sps;
  222. sps.id = ID;
  223. sps.which = x;
  224. sps.abs = false;
  225. sps.val = 1;
  226. sendAndApply(&sps);
  227. HeroLevelUp hlu;
  228. hlu.heroid = ID;
  229. hlu.primskill = x;
  230. hlu.level = hero->level+1;
  231. //picking sec. skills for choice
  232. std::set<int> basicAndAdv, expert, none;
  233. for(int i=0;i<SKILL_QUANTITY;i++) none.insert(i);
  234. for(unsigned i=0;i<hero->secSkills.size();i++)
  235. {
  236. if(hero->secSkills[i].second < 3)
  237. basicAndAdv.insert(hero->secSkills[i].first);
  238. else
  239. expert.insert(hero->secSkills[i].first);
  240. none.erase(hero->secSkills[i].first);
  241. }
  242. //first offered skill
  243. if(hero->secSkills.size() < hero->type->heroClass->skillLimit) //free skill slot
  244. {
  245. hlu.skills.push_back(hero->type->heroClass->chooseSecSkill(none)); //new skill
  246. none.erase(hlu.skills.back());
  247. }
  248. else if(basicAndAdv.size())
  249. {
  250. int s = hero->type->heroClass->chooseSecSkill(basicAndAdv);
  251. hlu.skills.push_back(s);
  252. basicAndAdv.erase(s);
  253. }
  254. //second offered skill
  255. if(basicAndAdv.size())
  256. {
  257. hlu.skills.push_back(hero->type->heroClass->chooseSecSkill(basicAndAdv)); //new skill
  258. }
  259. else if(hero->secSkills.size() < hero->type->heroClass->skillLimit)
  260. {
  261. hlu.skills.push_back(hero->type->heroClass->chooseSecSkill(none)); //new skill
  262. }
  263. if(hlu.skills.size() > 1) //apply and ask for secondary skill
  264. {
  265. 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));
  266. applyAndAsk(&hlu,hero->tempOwner,callback); //call changeSecSkill with appropriate args when client responds
  267. }
  268. else if(hlu.skills.size() == 1) //apply, give only possible skill and send info
  269. {
  270. sendAndApply(&hlu);
  271. changeSecSkill(ID,hlu.skills.back(),1,false);
  272. }
  273. else //apply and send info
  274. {
  275. sendAndApply(&hlu);
  276. }
  277. }
  278. }
  279. }
  280. static CCreatureSet takeCasualties(int color, const CCreatureSet &set, BattleInfo *bat)
  281. {
  282. if(color == 254)
  283. color = 255;
  284. CCreatureSet ret(set);
  285. for(int i=0; i<bat->stacks.size();i++)
  286. {
  287. CStack *st = bat->stacks[i];
  288. if(vstd::contains(st->state, SUMMONED)) //don't take into account sumoned stacks
  289. continue;
  290. if(st->owner==color && !set.slotEmpty(st->slot) && st->count < set.getAmount(st->slot))
  291. {
  292. if(st->alive())
  293. ret.setStackCount(st->slot, st->count);
  294. else
  295. ret.eraseStack(st->slot);
  296. }
  297. }
  298. return ret;
  299. }
  300. void CGameHandler::startBattle(const CArmedInstance *army1, const CArmedInstance * army2, int3 tile, const CGHeroInstance *hero1, const CGHeroInstance *hero2, bool creatureBank, boost::function<void(BattleResult*)> cb, const CGTownInstance *town)
  301. {
  302. battleEndCallback = new boost::function<void(BattleResult*)>(cb);
  303. bEndArmy1 = army1;
  304. bEndArmy2 = army2;
  305. {
  306. BattleInfo *curB = new BattleInfo;
  307. curB->side1 = army1->tempOwner;
  308. curB->side2 = army2->tempOwner;
  309. if(curB->side2 == 254)
  310. curB->side2 = 255;
  311. setupBattle(curB, tile, army1, army2, hero1, hero2, creatureBank, town); //initializes stacks, places creatures on battlefield, blocks and informs player interfaces
  312. }
  313. NEW_ROUND;
  314. //TODO: pre-tactic stuff, call scripts etc.
  315. //tactic round
  316. {
  317. NEW_ROUND;
  318. if( (hero1 && hero1->getSecSkillLevel(19)>0) ||
  319. ( hero2 && hero2->getSecSkillLevel(19)>0) )//someone has tactics
  320. {
  321. //TODO: tactic round (round -1)
  322. }
  323. }
  324. //main loop
  325. while(!battleResult.get()) //till the end of the battle ;]
  326. {
  327. NEW_ROUND;
  328. std::vector<CStack*> & stacks = (gs->curB->stacks);
  329. const BattleInfo & curB = *gs->curB;
  330. //stack loop
  331. const CStack *next;
  332. while(!battleResult.get() && (next = curB.getNextStack()) && next->willMove())
  333. {
  334. //check for bad morale => freeze
  335. int nextStackMorale = next->MoraleVal();
  336. if( nextStackMorale < 0 &&
  337. !(NBonus::hasOfType(hero1, Bonus::BLOCK_MORALE) || NBonus::hasOfType(hero2, Bonus::BLOCK_MORALE)) //checking if heroes have (or don't have) morale blocking bonuses)
  338. )
  339. {
  340. if( rand()%24 < -2 * nextStackMorale)
  341. {
  342. //unit loses its turn - empty freeze action
  343. BattleAction ba;
  344. ba.actionType = 11;
  345. ba.additionalInfo = 1;
  346. ba.side = !next->attackerOwned;
  347. ba.stackNumber = next->ID;
  348. sendAndApply(&StartAction(ba));
  349. sendAndApply(&EndAction());
  350. checkForBattleEnd(stacks); //check if this "action" ended the battle (not likely but who knows...)
  351. continue;
  352. }
  353. }
  354. if(next->hasBonusOfType(Bonus::ATTACKS_NEAREST_CREATURE)) //while in berserk
  355. {
  356. std::pair<const CStack *, int> attackInfo = curB.getNearestStack(next, boost::logic::indeterminate);
  357. if(attackInfo.first != NULL)
  358. {
  359. BattleAction attack;
  360. attack.actionType = 6;
  361. attack.side = !next->attackerOwned;
  362. attack.stackNumber = next->ID;
  363. attack.additionalInfo = attackInfo.first->position;
  364. attack.destinationTile = attackInfo.second;
  365. makeBattleAction(attack);
  366. checkForBattleEnd(stacks);
  367. }
  368. continue;
  369. }
  370. const CGHeroInstance * curOwner = gs->battleGetOwner(next->ID);
  371. if( (next->position < 0 && (!curOwner || curOwner->getSecSkillLevel(10) == 0)) //arrow turret, hero has no ballistics
  372. || (next->type->idNumber == 146 && curOwner->getSecSkillLevel(20) == 0)) //ballista, hero has no artillery
  373. {
  374. BattleAction attack;
  375. attack.actionType = 7;
  376. attack.side = !next->attackerOwned;
  377. attack.stackNumber = next->ID;
  378. for(int g=0; g<gs->curB->stacks.size(); ++g)
  379. {
  380. if(gs->curB->stacks[g]->owner != curOwner->tempOwner && gs->curB->stacks[g]->alive())
  381. {
  382. attack.destinationTile = gs->curB->stacks[g]->position;
  383. break;
  384. }
  385. }
  386. makeBattleAction(attack);
  387. checkForBattleEnd(stacks);
  388. continue;
  389. }
  390. if(next->type->idNumber == 145 && (!curOwner || curOwner->getSecSkillLevel(10) == 0)) //catapult, hero has no ballistics
  391. {
  392. BattleAction attack;
  393. static const int wallHexes[] = {50, 183, 182, 130, 62, 29, 12, 95};
  394. attack.destinationTile = wallHexes[ rand()%ARRAY_COUNT(wallHexes) ];
  395. attack.actionType = 9;
  396. attack.additionalInfo = 0;
  397. attack.side = !next->attackerOwned;
  398. attack.stackNumber = next->ID;
  399. makeBattleAction(attack);
  400. continue;
  401. }
  402. if(next->type->idNumber == 147 && (!curOwner || curOwner->getSecSkillLevel(27) == 0)) //first aid tent, hero has no first aid
  403. {
  404. BattleAction heal;
  405. std::vector< const CStack * > possibleStacks;
  406. for (int v=0; v<gs->curB->stacks.size(); ++v)
  407. {
  408. const CStack * cstack = gs->curB->stacks[v];
  409. if (cstack->owner == next->owner && cstack->firstHPleft < cstack->MaxHealth() && cstack->alive()) //it's friendly and not fully healthy
  410. {
  411. possibleStacks.push_back(cstack);
  412. }
  413. }
  414. if(possibleStacks.size() == 0)
  415. {
  416. //nothing to heal
  417. BattleAction doNothing;
  418. doNothing.actionType = 0;
  419. doNothing.additionalInfo = 0;
  420. doNothing.destinationTile = -1;
  421. doNothing.side = !next->attackerOwned;
  422. doNothing.stackNumber = next->ID;
  423. sendAndApply(&StartAction(doNothing));
  424. sendAndApply(&EndAction());
  425. continue;
  426. }
  427. else
  428. {
  429. //heal random creature
  430. const CStack * toBeHealed = possibleStacks[ rand()%possibleStacks.size() ];
  431. heal.actionType = 12;
  432. heal.additionalInfo = 0;
  433. heal.destinationTile = toBeHealed->position;
  434. heal.side = !next->attackerOwned;
  435. heal.stackNumber = next->ID;
  436. makeBattleAction(heal);
  437. }
  438. continue;
  439. }
  440. askInterfaceForMove:
  441. //ask interface and wait for answer
  442. if(!battleResult.get())
  443. {
  444. BattleSetActiveStack sas;
  445. sas.stack = next->ID;
  446. sendAndApply(&sas);
  447. boost::unique_lock<boost::mutex> lock(battleMadeAction.mx);
  448. while(next->alive() && (!battleMadeAction.data && !battleResult.get())) //active stack hasn't made its action and battle is still going
  449. battleMadeAction.cond.wait(lock);
  450. battleMadeAction.data = false;
  451. }
  452. else
  453. {
  454. break;
  455. }
  456. //we're after action, all results applied
  457. checkForBattleEnd(stacks); //check if this action ended the battle
  458. //check for good morale
  459. nextStackMorale = next->MoraleVal();
  460. if(!vstd::contains(next->state,HAD_MORALE) //only one extra move per turn possible
  461. && !vstd::contains(next->state,DEFENDING)
  462. && !vstd::contains(next->state,WAITING)
  463. && next->alive()
  464. && nextStackMorale > 0
  465. && !(NBonus::hasOfType(hero1, Bonus::BLOCK_MORALE) || NBonus::hasOfType(hero2, Bonus::BLOCK_MORALE)) //checking if heroes have (or don't have) morale blocking bonuses
  466. )
  467. if(rand()%24 < nextStackMorale) //this stack hasn't got morale this turn
  468. goto askInterfaceForMove; //move this stack once more
  469. }
  470. }
  471. endBattle(tile, hero1, hero2);
  472. }
  473. void CGameHandler::endBattle(int3 tile, const CGHeroInstance *hero1, const CGHeroInstance *hero2)
  474. {
  475. BattleResultsApplied resultsApplied;
  476. resultsApplied.player1 = bEndArmy1->tempOwner;
  477. resultsApplied.player2 = bEndArmy2->tempOwner;
  478. //unblock engaged players
  479. if(bEndArmy1->tempOwner<PLAYER_LIMIT)
  480. states.setFlag(bEndArmy1->tempOwner, &PlayerStatus::engagedIntoBattle, false);
  481. if(bEndArmy2 && bEndArmy2->tempOwner<PLAYER_LIMIT)
  482. states.setFlag(bEndArmy2->tempOwner, &PlayerStatus::engagedIntoBattle, false);
  483. //casualties among heroes armies
  484. SetGarrisons sg;
  485. sg.garrs[bEndArmy1->id] = takeCasualties(bEndArmy1->tempOwner, *bEndArmy1, gs->curB);
  486. sg.garrs[bEndArmy2->id] = takeCasualties(bEndArmy2->tempOwner, *bEndArmy2, gs->curB);
  487. sendAndApply(&sg);
  488. ui8 sides[2];
  489. sides[0] = gs->curB->side1;
  490. sides[1] = gs->curB->side2;
  491. //end battle, remove all info, free memory
  492. giveExp(*battleResult.data);
  493. sendAndApply(battleResult.data);
  494. //if one hero has lost we will erase him
  495. if(battleResult.data->winner!=0 && hero1)
  496. {
  497. RemoveObject ro(hero1->id);
  498. sendAndApply(&ro);
  499. }
  500. if(battleResult.data->winner!=1 && hero2)
  501. {
  502. RemoveObject ro(hero2->id);
  503. sendAndApply(&ro);
  504. }
  505. //give exp
  506. if(battleResult.data->exp[0] && hero1)
  507. changePrimSkill(hero1->id,4,battleResult.data->exp[0]);
  508. if(battleResult.data->exp[1] && hero2)
  509. changePrimSkill(hero2->id,4,battleResult.data->exp[1]);
  510. if(battleEndCallback && *battleEndCallback)
  511. {
  512. (*battleEndCallback)(battleResult.data);
  513. delete battleEndCallback;
  514. battleEndCallback = 0;
  515. }
  516. sendAndApply(&resultsApplied);
  517. // Necromancy if applicable.
  518. const CGHeroInstance *winnerHero = battleResult.data->winner != 0 ? hero2 : hero1;
  519. if (winnerHero)
  520. {
  521. CStackInstance raisedStack = winnerHero->calculateNecromancy(*battleResult.data);
  522. // Give raised units to winner and show dialog, if any were raised.
  523. if (raisedStack.type)
  524. {
  525. int slot = winnerHero->getSlotFor(raisedStack.type->idNumber);
  526. if (slot != -1)
  527. {
  528. SetGarrisons sg;
  529. sg.garrs[winnerHero->id] = winnerHero->getArmy();
  530. sg.garrs[winnerHero->id].addToSlot(slot, raisedStack);
  531. // if (vstd::contains(winnerHero->slots, slot)) // Add to existing stack.
  532. // sg.garrs[winnerHero->id].slots[slot].count += raisedStack.count;
  533. // else // Create a new stack.
  534. // sg.garrs[winnerHero->id].slots[slot] = raisedStack;
  535. winnerHero->showNecromancyDialog(raisedStack);
  536. sendAndApply(&sg);
  537. }
  538. }
  539. }
  540. winLoseHandle(1<<sides[0] | 1<<sides[1]); //handle victory/loss of engaged players
  541. delete battleResult.data;
  542. }
  543. void CGameHandler::prepareAttacked(BattleStackAttacked &bsa, const CStack *def)
  544. {
  545. bsa.killedAmount = bsa.damageAmount / def->MaxHealth();
  546. unsigned damageFirst = bsa.damageAmount % def->MaxHealth();
  547. if( def->firstHPleft <= damageFirst )
  548. {
  549. bsa.killedAmount++;
  550. bsa.newHP = def->firstHPleft + def->MaxHealth() - damageFirst;
  551. }
  552. else
  553. {
  554. bsa.newHP = def->firstHPleft - damageFirst;
  555. }
  556. if(def->count <= bsa.killedAmount) //stack killed
  557. {
  558. bsa.newAmount = 0;
  559. bsa.flags |= 1;
  560. bsa.killedAmount = def->count; //we cannot kill more creatures than we have
  561. }
  562. else
  563. {
  564. bsa.newAmount = def->count - bsa.killedAmount;
  565. }
  566. }
  567. void CGameHandler::prepareAttack(BattleAttack &bat, const CStack *att, const CStack *def, int distance)
  568. {
  569. bat.bsa.clear();
  570. bat.stackAttacking = att->ID;
  571. bat.bsa.push_back(BattleStackAttacked());
  572. BattleStackAttacked *bsa = &bat.bsa.back();
  573. bsa->stackAttacked = def->ID;
  574. bsa->attackerID = att->ID;
  575. int attackerLuck = att->LuckVal();
  576. if(attackerLuck > 0 && rand()%24 < attackerLuck) //TODO?: negative luck option?
  577. {
  578. bsa->damageAmount *= 2;
  579. bat.flags |= 4;
  580. }
  581. bsa->damageAmount = gs->curB->calculateDmg(att, def, gs->battleGetOwner(att->ID), gs->battleGetOwner(def->ID), bat.shot(), distance, bat.lucky());//counting dealt damage
  582. int dmg = bsa->damageAmount;
  583. prepareAttacked(*bsa, def);
  584. //life drain handling
  585. if (att->hasBonusOfType(Bonus::LIFE_DRAIN))
  586. {
  587. StacksHealedOrResurrected shi;
  588. shi.lifeDrain = true;
  589. shi.drainedFrom = def->ID;
  590. StacksHealedOrResurrected::HealInfo hi;
  591. hi.stackID = att->ID;
  592. hi.healedHP = std::min<int>(dmg, att->MaxHealth() - att->firstHPleft + att->MaxHealth() * (att->baseAmount - att->count) );
  593. hi.lowLevelResurrection = false;
  594. shi.healedStacks.push_back(hi);
  595. if (hi.healedHP > 0)
  596. {
  597. bsa->healedStacks.push_back(shi);
  598. }
  599. }
  600. else
  601. {
  602. }
  603. //fire shield handling
  604. if ( !bat.shot() && def->hasBonusOfType(Bonus::FIRE_SHIELD) && !bsa->killed() )
  605. {
  606. bat.bsa.push_back(BattleStackAttacked());
  607. BattleStackAttacked *bsa = &bat.bsa.back();
  608. bsa->stackAttacked = att->ID;
  609. bsa->attackerID = def->ID;
  610. bsa->flags |= 2;
  611. bsa->effect = 11;
  612. bsa->damageAmount = (dmg * def->valOfBonuses(Bonus::FIRE_SHIELD)) / 100;
  613. prepareAttacked(*bsa, att);
  614. }
  615. }
  616. void CGameHandler::handleConnection(std::set<int> players, CConnection &c)
  617. {
  618. srand(time(NULL));
  619. CPack *pack = NULL;
  620. try
  621. {
  622. while(1)//server should never shut connection first //was: while(!end2)
  623. {
  624. {
  625. boost::unique_lock<boost::mutex> lock(*c.rmx);
  626. c >> pack; //get the package
  627. tlog5 << "Received client message of type " << typeid(*pack).name() << std::endl;
  628. }
  629. int packType = typeList.getTypeID(pack); //get the id of type
  630. CBaseForGHApply *apply = applier->apps[packType]; //and appropriae applier object
  631. if(apply)
  632. {
  633. bool result = apply->applyOnGH(this,&c,pack);
  634. tlog5 << "Message successfully applied (result=" << result << ")!\n";
  635. //send confirmation that we've applied the package
  636. if(pack->type != 6000) //WORKAROUND - not confirm query replies TODO: reconsider
  637. {
  638. PackageApplied applied;
  639. applied.result = result;
  640. applied.packType = packType;
  641. {
  642. boost::unique_lock<boost::mutex> lock(*c.wmx);
  643. c << &applied;
  644. }
  645. }
  646. }
  647. else
  648. {
  649. tlog1 << "Message cannot be applied, cannot find applier (unregistered type)!\n";
  650. }
  651. delete pack;
  652. pack = NULL;
  653. }
  654. }
  655. catch(boost::system::system_error &e) //for boost errors just log, not crash - probably client shut down connection
  656. {
  657. assert(!c.connected); //make sure that connection has been marked as broken
  658. tlog1 << e.what() << std::endl;
  659. end2 = true;
  660. }
  661. HANDLE_EXCEPTION(end2 = true);
  662. tlog1 << "Ended handling connection\n";
  663. }
  664. int CGameHandler::moveStack(int stack, int dest)
  665. {
  666. int ret = 0;
  667. CStack *curStack = gs->curB->getStack(stack),
  668. *stackAtEnd = gs->curB->getStackT(dest);
  669. assert(curStack);
  670. assert(dest < BFIELD_SIZE);
  671. //initing necessary tables
  672. bool accessibility[BFIELD_SIZE];
  673. std::vector<int> accessible = gs->curB->getAccessibility(curStack->ID, false);
  674. for(int b=0; b<BFIELD_SIZE; ++b)
  675. {
  676. accessibility[b] = false;
  677. }
  678. for(int g=0; g<accessible.size(); ++g)
  679. {
  680. accessibility[accessible[g]] = true;
  681. }
  682. //shifting destination (if we have double wide stack and we can occupy dest but not be exactly there)
  683. if(!stackAtEnd && curStack->doubleWide() && !accessibility[dest])
  684. {
  685. if(curStack->attackerOwned)
  686. {
  687. if(accessibility[dest+1])
  688. dest+=1;
  689. }
  690. else
  691. {
  692. if(accessibility[dest-1])
  693. dest-=1;
  694. }
  695. }
  696. if((stackAtEnd && stackAtEnd!=curStack && stackAtEnd->alive()) || !accessibility[dest])
  697. return 0;
  698. bool accessibilityWithOccupyable[BFIELD_SIZE];
  699. std::vector<int> accOc = gs->curB->getAccessibility(curStack->ID, true);
  700. for(int b=0; b<BFIELD_SIZE; ++b)
  701. {
  702. accessibilityWithOccupyable[b] = false;
  703. }
  704. for(int g=0; g<accOc.size(); ++g)
  705. {
  706. accessibilityWithOccupyable[accOc[g]] = true;
  707. }
  708. //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
  709. // return false;
  710. std::pair< std::vector<int>, int > path = gs->curB->getPath(curStack->position, dest, accessibilityWithOccupyable, curStack->hasBonusOfType(Bonus::FLYING), curStack->doubleWide(), curStack->attackerOwned);
  711. ret = path.second;
  712. if(curStack->hasBonusOfType(Bonus::FLYING))
  713. {
  714. if(path.second <= curStack->Speed() && path.first.size() > 0)
  715. {
  716. //inform clients about move
  717. BattleStackMoved sm;
  718. sm.stack = curStack->ID;
  719. sm.tile = path.first[0];
  720. sm.distance = path.second;
  721. sm.ending = true;
  722. sm.teleporting = false;
  723. sendAndApply(&sm);
  724. }
  725. }
  726. else //for non-flying creatures
  727. {
  728. int tilesToMove = std::max((int)(path.first.size() - curStack->Speed()), 0);
  729. for(int v=path.first.size()-1; v>=tilesToMove; --v)
  730. {
  731. //inform clients about move
  732. BattleStackMoved sm;
  733. sm.stack = curStack->ID;
  734. sm.tile = path.first[v];
  735. sm.distance = path.second;
  736. sm.ending = v==tilesToMove;
  737. sm.teleporting = false;
  738. sendAndApply(&sm);
  739. }
  740. }
  741. return ret;
  742. }
  743. CGameHandler::CGameHandler(void)
  744. {
  745. QID = 1;
  746. gs = NULL;
  747. IObjectInterface::cb = this;
  748. applier = new CGHApplier;
  749. }
  750. CGameHandler::~CGameHandler(void)
  751. {
  752. delete applier;
  753. applier = NULL;
  754. delete gs;
  755. }
  756. void CGameHandler::init(StartInfo *si, int Seed)
  757. {
  758. gs = new CGameState();
  759. tlog0 << "Gamestate created!" << std::endl;
  760. gs->init(si, 0, Seed);
  761. tlog0 << "Gamestate initialized!" << std::endl;
  762. for(std::map<ui8,PlayerState>::iterator i = gs->players.begin(); i != gs->players.end(); i++)
  763. states.addPlayer(i->first);
  764. }
  765. static bool evntCmp(const CMapEvent *a, const CMapEvent *b)
  766. {
  767. return *a < *b;
  768. }
  769. void CGameHandler::newTurn()
  770. {
  771. tlog5 << "Turn " << gs->day+1 << std::endl;
  772. NewTurn n;
  773. n.day = gs->day + 1;
  774. n.resetBuilded = true;
  775. std::map<ui8, si32> hadGold;//starting gold - for buildings like dwarven treasury
  776. srand(time(NULL));
  777. std::map<ui32,CGHeroInstance *> pool = gs->hpool.heroesPool;
  778. for ( std::map<ui8, PlayerState>::iterator i=gs->players.begin() ; i!=gs->players.end();i++)
  779. {
  780. if(i->first == 255) continue;
  781. else if(i->first > PLAYER_LIMIT) assert(0); //illegal player number!
  782. std::pair<ui8,si32> playerGold(i->first,i->second.resources[6]);
  783. hadGold.insert(playerGold);
  784. if(gs->getDate(1)==7) //first day of week - new heroes in tavern
  785. {
  786. SetAvailableHeroes sah;
  787. sah.player = i->first;
  788. CGHeroInstance *h = gs->hpool.pickHeroFor(true,i->first,&VLC->townh->towns[gs->scenarioOps->getIthPlayersSettings(i->first).castle], pool);
  789. if(h)
  790. sah.hid1 = h->subID;
  791. else
  792. sah.hid1 = -1;
  793. h = gs->hpool.pickHeroFor(false,i->first,&VLC->townh->towns[gs->scenarioOps->getIthPlayersSettings(i->first).castle], pool);
  794. if(h)
  795. sah.hid2 = h->subID;
  796. else
  797. sah.hid2 = -1;
  798. sendAndApply(&sah);
  799. }
  800. if(i->first>=PLAYER_LIMIT) continue;
  801. n.res[i->first] = i->second.resources;
  802. // SetResources r;
  803. // r.player = i->first;
  804. // for(int j=0;j<RESOURCE_QUANTITY;j++)
  805. // r.res[j] = i->second.resources[j];
  806. BOOST_FOREACH(CGHeroInstance *h, (*i).second.heroes)
  807. {
  808. if(h->visitedTown)
  809. giveSpells(h->visitedTown, h);
  810. NewTurn::Hero hth;
  811. hth.id = h->id;
  812. hth.move = h->maxMovePoints(gs->map->getTile(h->getPosition(false)).tertype != TerrainTile::water);
  813. if(h->visitedTown && vstd::contains(h->visitedTown->builtBuildings,0)) //if hero starts turn in town with mage guild
  814. hth.mana = std::max(h->mana, h->manaLimit()); //restore all mana
  815. else
  816. hth.mana = std::max(si32(0), std::max(h->mana, std::min(h->mana + h->manaRegain(), h->manaLimit())) );
  817. n.heroes.insert(hth);
  818. if(gs->day) //not first day
  819. {
  820. switch(h->getSecSkillLevel(13)) //handle estates - give gold
  821. {
  822. case 1: //basic
  823. n.res[i->first][6] += 125;
  824. break;
  825. case 2: //advanced
  826. n.res[i->first][6] += 250;
  827. break;
  828. case 3: //expert
  829. n.res[i->first][6] += 500;
  830. break;
  831. }
  832. for(std::list<Bonus>::iterator j = h->bonuses.begin(); j != h->bonuses.end(); j++)
  833. if(j->type == Bonus::GENERATE_RESOURCE)
  834. n.res[i->first][j->subtype] += j->val;
  835. //TODO player bonuses
  836. }
  837. }
  838. //n.res.push_back(r);
  839. }
  840. for(std::vector<CGTownInstance *>::iterator j = gs->map->towns.begin(); j!=gs->map->towns.end(); j++)//handle towns
  841. {
  842. ui8 player = (*j)->tempOwner;
  843. if(gs->getDate(1)==7) //first day of week
  844. {
  845. if ( (**j).subID == 1 && gs->getDate(0) && player < PLAYER_LIMIT
  846. && vstd::contains((**j).builtBuildings,22) )//dwarven treasury
  847. n.res[player][6] += hadGold[player]/10; //give 10% of starting gold
  848. SetAvailableCreatures sac;
  849. sac.tid = (**j).id;
  850. sac.creatures = (**j).creatures;
  851. for(int k=0;k<CREATURES_PER_TOWN;k++) //creature growths
  852. {
  853. if((**j).creatureDwelling(k))//there is dwelling (k-level)
  854. {
  855. sac.creatures[k].first += (**j).creatureGrowth(k);
  856. if(!gs->getDate(0)) //first day of game: use only basic growths
  857. amin(sac.creatures[k].first, VLC->creh->creatures[(*j)->town->basicCreatures[k]]->growth);
  858. }
  859. }
  860. n.cres.push_back(sac);
  861. }
  862. if(gs->day && player < PLAYER_LIMIT)//not the first day and town not neutral
  863. {
  864. ////SetResources r;
  865. //r.player = (**j).tempOwner;
  866. if(vstd::contains((**j).builtBuildings,15)) //there is resource silo
  867. {
  868. if((**j).town->primaryRes == 127) //we'll give wood and ore
  869. {
  870. n.res[player][0] += 1;
  871. n.res[player][2] += 1;
  872. }
  873. else
  874. {
  875. n.res[player][(**j).town->primaryRes] += 1;
  876. }
  877. }
  878. n.res[player][6] += (**j).dailyIncome();
  879. }
  880. }
  881. sendAndApply(&n);
  882. tlog5 << "Info about turn " << n.day << "has been sent!" << std::endl;
  883. handleTimeEvents();
  884. //call objects
  885. for(size_t i = 0; i<gs->map->objects.size(); i++)
  886. if(gs->map->objects[i])
  887. gs->map->objects[i]->newTurn();
  888. winLoseHandle(0xff);
  889. //warn players without town
  890. if(gs->day)
  891. {
  892. for (std::map<ui8, PlayerState>::iterator i=gs->players.begin() ; i!=gs->players.end();i++)
  893. {
  894. if(i->second.status || i->second.towns.size() || i->second.color >= PLAYER_LIMIT)
  895. continue;
  896. InfoWindow iw;
  897. iw.player = i->first;
  898. iw.components.push_back(Component(Component::FLAG,i->first,0,0));
  899. if(!i->second.daysWithoutCastle)
  900. {
  901. iw.text.addTxt(MetaString::GENERAL_TXT,6); //%s, you have lost your last town. If you do not conquer another town in the next week, you will be eliminated.
  902. iw.text.addReplacement(MetaString::COLOR, i->first);
  903. }
  904. else if(i->second.daysWithoutCastle == 6)
  905. {
  906. iw.text.addTxt(MetaString::ARRAY_TXT,129); //%s, this is your last day to capture a town or you will be banished from this land.
  907. iw.text.addReplacement(MetaString::COLOR, i->first);
  908. }
  909. else
  910. {
  911. iw.text.addTxt(MetaString::ARRAY_TXT,128); //%s, you only have %d days left to capture a town or you will be banished from this land.
  912. iw.text.addReplacement(MetaString::COLOR, i->first);
  913. iw.text.addReplacement(7 - i->second.daysWithoutCastle);
  914. }
  915. sendAndApply(&iw);
  916. }
  917. }
  918. }
  919. void CGameHandler::run(bool resume)
  920. {
  921. using namespace boost::posix_time;
  922. BOOST_FOREACH(CConnection *cc, conns)
  923. {//init conn.
  924. ui8 quantity, pom;
  925. //ui32 seed;
  926. if(!resume)
  927. (*cc) << gs->scenarioOps << gs->map->checksum << gs->seed;
  928. (*cc) >> quantity; //how many players will be handled at that client
  929. for(int i=0;i<quantity;i++)
  930. {
  931. (*cc) >> pom; //read player color
  932. {
  933. boost::unique_lock<boost::recursive_mutex> lock(gsm);
  934. connections[pom] = cc;
  935. }
  936. }
  937. }
  938. for(std::set<CConnection*>::iterator i = conns.begin(); i!=conns.end();i++)
  939. {
  940. std::set<int> pom;
  941. for(std::map<int,CConnection*>::iterator j = connections.begin(); j!=connections.end();j++)
  942. if(j->second == *i)
  943. pom.insert(j->first);
  944. boost::thread(boost::bind(&CGameHandler::handleConnection,this,pom,boost::ref(**i)));
  945. }
  946. while (!end2)
  947. {
  948. if(!resume)
  949. newTurn();
  950. std::map<ui8,PlayerState>::iterator i;
  951. if(!resume)
  952. i = gs->players.begin();
  953. else
  954. i = gs->players.find(gs->currentPlayer);
  955. resume = false;
  956. for(; i != gs->players.end(); i++)
  957. {
  958. if(i->second.towns.size()==0 && i->second.heroes.size()==0
  959. || i->second.color<0
  960. || i->first>=PLAYER_LIMIT
  961. || i->second.status)
  962. {
  963. continue;
  964. }
  965. states.setFlag(i->first,&PlayerStatus::makingTurn,true);
  966. {
  967. YourTurn yt;
  968. yt.player = i->first;
  969. sendAndApply(&yt);
  970. }
  971. //wait till turn is done
  972. boost::unique_lock<boost::mutex> lock(states.mx);
  973. while(states.players[i->first].makingTurn && !end2)
  974. {
  975. static time_duration p = milliseconds(200);
  976. states.cv.timed_wait(lock,p);
  977. }
  978. }
  979. }
  980. while(conns.size() && (*conns.begin())->isOpen())
  981. boost::this_thread::sleep(boost::posix_time::milliseconds(5)); //give time client to close socket
  982. }
  983. namespace CGH
  984. {
  985. using namespace std;
  986. static void readItTo(ifstream & input, vector< vector<int> > & dest) //reads 7 lines, i-th one containing i integers, and puts it to dest
  987. {
  988. for(int j=0; j<7; ++j)
  989. {
  990. std::vector<int> pom;
  991. for(int g=0; g<j+1; ++g)
  992. {
  993. int hlp; input>>hlp;
  994. pom.push_back(hlp);
  995. }
  996. dest.push_back(pom);
  997. }
  998. }
  999. }
  1000. void CGameHandler::setupBattle(BattleInfo * curB, int3 tile, const CArmedInstance *army1, const CArmedInstance *army2, const CGHeroInstance * hero1, const CGHeroInstance * hero2, bool creatureBank, const CGTownInstance *town)
  1001. {
  1002. battleResult.set(NULL);
  1003. std::vector<CStack*> & stacks = (curB->stacks);
  1004. curB->tile = tile;
  1005. curB->belligerents[0] = const_cast<CArmedInstance*>(army1);
  1006. curB->belligerents[1] = const_cast<CArmedInstance*>(army2);
  1007. curB->heroes[0] = const_cast<CGHeroInstance*>(hero1);
  1008. curB->heroes[1] = const_cast<CGHeroInstance*>(hero2);
  1009. curB->round = -2;
  1010. curB->activeStack = -1;
  1011. if(town)
  1012. {
  1013. curB->tid = town->id;
  1014. curB->siege = town->fortLevel();
  1015. }
  1016. else
  1017. {
  1018. curB->tid = -1;
  1019. curB->siege = 0;
  1020. }
  1021. //reading battleStartpos
  1022. std::ifstream positions;
  1023. positions.open(DATA_DIR "/config/battleStartpos.txt", std::ios_base::in|std::ios_base::binary);
  1024. if(!positions.is_open())
  1025. {
  1026. tlog1<<"Unable to open battleStartpos.txt!"<<std::endl;
  1027. }
  1028. std::string dump;
  1029. positions>>dump; positions>>dump;
  1030. std::vector< std::vector<int> > attackerLoose, defenderLoose, attackerTight, defenderTight, attackerCreBank, defenderCreBank;
  1031. CGH::readItTo(positions, attackerLoose);
  1032. positions>>dump;
  1033. CGH::readItTo(positions, defenderLoose);
  1034. positions>>dump;
  1035. positions>>dump;
  1036. CGH::readItTo(positions, attackerTight);
  1037. positions>>dump;
  1038. CGH::readItTo(positions, defenderTight);
  1039. positions>>dump;
  1040. positions>>dump;
  1041. CGH::readItTo(positions, attackerCreBank);
  1042. positions>>dump;
  1043. CGH::readItTo(positions, defenderCreBank);
  1044. positions.close();
  1045. //battleStartpos read
  1046. int k = 0; //stack serial
  1047. for(TSlots::const_iterator i = army1->Slots().begin(); i!=army1->Slots().end(); i++, k++)
  1048. {
  1049. int pos;
  1050. if(creatureBank)
  1051. pos = attackerCreBank[army1->stacksCount()-1][k];
  1052. else if(army1->formation)
  1053. pos = attackerTight[army1->stacksCount()-1][k];
  1054. else
  1055. pos = attackerLoose[army1->stacksCount()-1][k];
  1056. CStack * stack = curB->generateNewStack(i->second, stacks.size(), true, i->first, gs->map->terrain[tile.x][tile.y][tile.z].tertype, pos);
  1057. stacks.push_back(stack);
  1058. }
  1059. k = 0;
  1060. for(TSlots::const_iterator i = army2->Slots().begin(); i!=army2->Slots().end(); i++, k++)
  1061. {
  1062. int pos;
  1063. if(creatureBank)
  1064. pos = defenderCreBank[army2->stacksCount()-1][k];
  1065. else if(army2->formation)
  1066. pos = defenderTight[army2->stacksCount()-1][k];
  1067. else
  1068. pos = defenderLoose[army2->stacksCount()-1][k];
  1069. CStack * stack = curB->generateNewStack(i->second, stacks.size(), false, i->first, gs->map->terrain[tile.x][tile.y][tile.z].tertype, pos);
  1070. stacks.push_back(stack);
  1071. }
  1072. for(unsigned g=0; g<stacks.size(); ++g) //shifting positions of two-hex creatures
  1073. {
  1074. if((stacks[g]->position%17)==1 && stacks[g]->doubleWide() && stacks[g]->attackerOwned)
  1075. {
  1076. stacks[g]->position += 1;
  1077. }
  1078. else if((stacks[g]->position%17)==15 && stacks[g]->doubleWide() && !stacks[g]->attackerOwned)
  1079. {
  1080. stacks[g]->position -= 1;
  1081. }
  1082. }
  1083. //adding war machines
  1084. if(hero1)
  1085. {
  1086. if(hero1->getArt(13)) //ballista
  1087. {
  1088. CStack * stack = curB->generateNewStack(CStackInstance(146, 1, hero1), stacks.size(), true, 255, gs->map->terrain[tile.x][tile.y][tile.z].tertype, 52);
  1089. stacks.push_back(stack);
  1090. }
  1091. if(hero1->getArt(14)) //ammo cart
  1092. {
  1093. CStack * stack = curB->generateNewStack(CStackInstance(148, 1, hero1), stacks.size(), true, 255, gs->map->terrain[tile.x][tile.y][tile.z].tertype, 18);
  1094. stacks.push_back(stack);
  1095. }
  1096. if(hero1->getArt(15)) //first aid tent
  1097. {
  1098. CStack * stack = curB->generateNewStack(CStackInstance(147, 1, hero1), stacks.size(), true, 255, gs->map->terrain[tile.x][tile.y][tile.z].tertype, 154);
  1099. stacks.push_back(stack);
  1100. }
  1101. }
  1102. if(hero2)
  1103. {
  1104. if(hero2->getArt(13)) //ballista
  1105. {
  1106. CStack * stack = curB->generateNewStack(CStackInstance(146, 1, hero2), stacks.size(), false, 255, gs->map->terrain[tile.x][tile.y][tile.z].tertype, 66);
  1107. stacks.push_back(stack);
  1108. }
  1109. if(hero2->getArt(14)) //ammo cart
  1110. {
  1111. CStack * stack = curB->generateNewStack(CStackInstance(148, 1, hero1), stacks.size(), false, 255, gs->map->terrain[tile.x][tile.y][tile.z].tertype, 32);
  1112. stacks.push_back(stack);
  1113. }
  1114. if(hero2->getArt(15)) //first aid tent
  1115. {
  1116. CStack * stack = curB->generateNewStack(CStackInstance(147, 1, hero2), stacks.size(), false, 255, gs->map->terrain[tile.x][tile.y][tile.z].tertype, 168);
  1117. stacks.push_back(stack);
  1118. }
  1119. }
  1120. if(town && hero1 && town->hasFort()) //catapult
  1121. {
  1122. CStack * stack = curB->generateNewStack(CStackInstance(145, 1, hero1), stacks.size(), true, 255, gs->map->terrain[tile.x][tile.y][tile.z].tertype, 120);
  1123. stacks.push_back(stack);
  1124. }
  1125. //war machines added
  1126. switch(curB->siege) //adding towers
  1127. {
  1128. case 3: //castle
  1129. {//lower tower / upper tower
  1130. CStack * stack = curB->generateNewStack(CStackInstance(149, 1, hero2), stacks.size(), false, 255, gs->map->terrain[tile.x][tile.y][tile.z].tertype, -4);
  1131. stacks.push_back(stack);
  1132. stack = curB->generateNewStack(CStackInstance(149, 1, hero2), stacks.size(), false, 255, gs->map->terrain[tile.x][tile.y][tile.z].tertype, -3);
  1133. stacks.push_back(stack);
  1134. }
  1135. case 2: //citadel
  1136. {//main tower
  1137. CStack * stack = curB->generateNewStack(CStackInstance(149, 1, hero2), stacks.size(), false, 255, gs->map->terrain[tile.x][tile.y][tile.z].tertype, -2);
  1138. stacks.push_back(stack);
  1139. }
  1140. }
  1141. std::stable_sort(stacks.begin(),stacks.end(),cmpst);
  1142. //seting up siege
  1143. if(town && town->hasFort())
  1144. {
  1145. for(int b=0; b<ARRAY_COUNT(curB->si.wallState); ++b)
  1146. {
  1147. curB->si.wallState[b] = 1;
  1148. }
  1149. }
  1150. int terType = gs->battleGetBattlefieldType(tile);
  1151. //randomize obstacles
  1152. if(town == NULL && !creatureBank) //do it only when it's not siege and not creature bank
  1153. {
  1154. bool obAv[BFIELD_SIZE]; //availability of hexes for obstacles;
  1155. std::vector<int> possibleObstacles;
  1156. for(int i=0; i<BFIELD_SIZE; ++i)
  1157. {
  1158. if(i%17 < 4 || i%17 > 12)
  1159. {
  1160. obAv[i] = false;
  1161. }
  1162. else
  1163. {
  1164. obAv[i] = true;
  1165. }
  1166. }
  1167. for(std::map<int, CObstacleInfo>::const_iterator g=VLC->heroh->obstacles.begin(); g!=VLC->heroh->obstacles.end(); ++g)
  1168. {
  1169. if(g->second.allowedTerrains[terType-1] == '1') //we need to take terType with -1 because terrain ids start from 1 and allowedTerrains array is indexed from 0
  1170. {
  1171. possibleObstacles.push_back(g->first);
  1172. }
  1173. }
  1174. srand(time(NULL));
  1175. if(possibleObstacles.size() > 0) //we cannot place any obstacles when we don't have them
  1176. {
  1177. int toBlock = rand()%6 + 6; //how many hexes should be blocked by obstacles
  1178. while(toBlock>0)
  1179. {
  1180. CObstacleInstance coi;
  1181. coi.uniqueID = curB->obstacles.size();
  1182. coi.ID = possibleObstacles[rand()%possibleObstacles.size()];
  1183. coi.pos = rand()%BFIELD_SIZE;
  1184. std::vector<int> block = VLC->heroh->obstacles[coi.ID].getBlocked(coi.pos);
  1185. bool badObstacle = false;
  1186. for(int b=0; b<block.size(); ++b)
  1187. {
  1188. if(block[b] < 0 || block[b] >= BFIELD_SIZE || !obAv[block[b]])
  1189. {
  1190. badObstacle = true;
  1191. break;
  1192. }
  1193. }
  1194. if(badObstacle) continue;
  1195. //obstacle can be placed
  1196. curB->obstacles.push_back(coi);
  1197. for(int b=0; b<block.size(); ++b)
  1198. {
  1199. if(block[b] >= 0 && block[b] < BFIELD_SIZE)
  1200. obAv[block[b]] = false;
  1201. }
  1202. toBlock -= block.size();
  1203. }
  1204. }
  1205. }
  1206. //giving building bonuses, if siege and we have harrisoned hero
  1207. if (town)
  1208. {
  1209. if (hero2)
  1210. {
  1211. for (int i=0; i<4; i++)
  1212. {
  1213. int val = town->defenceBonus(i);
  1214. if (val)
  1215. {
  1216. GiveBonus gs;
  1217. gs.bonus = Bonus(Bonus::ONE_BATTLE, Bonus::PRIMARY_SKILL, Bonus::OBJECT, val, -1, "", i);
  1218. gs.id = hero2->id;
  1219. sendAndApply(&gs);
  1220. }
  1221. }
  1222. }
  1223. else//if we don't have hero - apply separately, if hero present - will be taken from hero bonuses
  1224. {
  1225. if(town->subID == 0 && vstd::contains(town->builtBuildings,22)) //castle, brotherhood of sword built
  1226. for(int g=0; g<stacks.size(); ++g)
  1227. stacks[g]->bonuses.push_back(makeFeature(Bonus::MORALE, Bonus::ONE_BATTLE, 0, 2, Bonus::TOWN_STRUCTURE));
  1228. else if(vstd::contains(town->builtBuildings,5)) //tavern is built
  1229. for(int g=0; g<stacks.size(); ++g)
  1230. stacks[g]->bonuses.push_back(makeFeature(Bonus::MORALE, Bonus::ONE_BATTLE, 0, 1, Bonus::TOWN_STRUCTURE));
  1231. if(town->subID == 1 && vstd::contains(town->builtBuildings,21)) //rampart, fountain of fortune is present
  1232. for(int g=0; g<stacks.size(); ++g)
  1233. stacks[g]->bonuses.push_back(makeFeature(Bonus::LUCK, Bonus::ONE_BATTLE, 0, 2, Bonus::TOWN_STRUCTURE));
  1234. }
  1235. }
  1236. //giving terrain premies for heroes & stacks
  1237. int bonusSubtype = -1;
  1238. switch(terType)
  1239. {
  1240. case 9: //magic plains
  1241. {
  1242. bonusSubtype = 0;
  1243. }
  1244. case 14: //fiery fields
  1245. {
  1246. if(bonusSubtype == -1) bonusSubtype = 1;
  1247. }
  1248. case 15: //rock lands
  1249. {
  1250. if(bonusSubtype == -1) bonusSubtype = 8;
  1251. }
  1252. case 16: //magic clouds
  1253. {
  1254. if(bonusSubtype == -1) bonusSubtype = 2;
  1255. }
  1256. case 17: //lucid pools
  1257. {
  1258. if(bonusSubtype == -1) bonusSubtype = 4;
  1259. }
  1260. { //common part for cases 9, 14, 15, 16, 17
  1261. const CGHeroInstance * cHero = NULL;
  1262. for(int i=0; i<2; ++i)
  1263. {
  1264. if(i == 0) cHero = hero1;
  1265. else cHero = hero2;
  1266. if(cHero == NULL) continue;
  1267. GiveBonus gs;
  1268. gs.bonus = Bonus(Bonus::ONE_BATTLE, Bonus::MAGIC_SCHOOL_SKILL, Bonus::OBJECT, 3, -1, "", bonusSubtype);
  1269. gs.id = cHero->id;
  1270. sendAndApply(&gs);
  1271. }
  1272. break;
  1273. }
  1274. case 18: //holy ground
  1275. {
  1276. for(int g=0; g<stacks.size(); ++g) //+1 morale bonus for good creatures, -1 morale bonus for evil creatures
  1277. {
  1278. if (stacks[g]->type->isGood())
  1279. stacks[g]->bonuses.push_back(makeFeature(Bonus::MORALE, Bonus::ONE_BATTLE, 0, 1, Bonus::TERRAIN_OVERLAY));
  1280. else if (stacks[g]->type->isEvil())
  1281. stacks[g]->bonuses.push_back(makeFeature(Bonus::MORALE, Bonus::ONE_BATTLE, 0, -1, Bonus::TERRAIN_OVERLAY));
  1282. }
  1283. break;
  1284. }
  1285. case 19: //clover field
  1286. {
  1287. for(int g=0; g<stacks.size(); ++g)
  1288. {
  1289. if(stacks[g]->type->faction == -1) //+2 luck bonus for neutral creatures
  1290. {
  1291. stacks[g]->bonuses.push_back(makeFeature(Bonus::LUCK, Bonus::ONE_BATTLE, 0, 2, Bonus::TERRAIN_OVERLAY));
  1292. }
  1293. }
  1294. break;
  1295. }
  1296. case 20: //evil fog
  1297. {
  1298. for(int g=0; g<stacks.size(); ++g) //-1 morale bonus for good creatures, +1 morale bonus for evil creatures
  1299. {
  1300. if (stacks[g]->type->isGood())
  1301. stacks[g]->bonuses.push_back(makeFeature(Bonus::MORALE, Bonus::ONE_BATTLE, 0, -1, Bonus::TERRAIN_OVERLAY));
  1302. else if (stacks[g]->type->isEvil())
  1303. stacks[g]->bonuses.push_back(makeFeature(Bonus::MORALE, Bonus::ONE_BATTLE, 0, 1, Bonus::TERRAIN_OVERLAY));
  1304. }
  1305. break;
  1306. }
  1307. case 22: //cursed ground
  1308. {
  1309. for(int g=0; g<stacks.size(); ++g) //no luck nor morale
  1310. {
  1311. stacks[g]->bonuses.push_back(makeFeature(Bonus::NO_MORALE, Bonus::ONE_BATTLE, 0, 0, Bonus::TERRAIN_OVERLAY));
  1312. stacks[g]->bonuses.push_back(makeFeature(Bonus::NO_LUCK, Bonus::ONE_BATTLE, 0, 0, Bonus::TERRAIN_OVERLAY));
  1313. }
  1314. const CGHeroInstance * cHero = NULL;
  1315. for(int i=0; i<2; ++i) //blocking spells above level 1
  1316. {
  1317. if(i == 0) cHero = hero1;
  1318. else cHero = hero2;
  1319. if(cHero == NULL) continue;
  1320. GiveBonus gs;
  1321. gs.bonus = Bonus(Bonus::ONE_BATTLE, Bonus::BLOCK_SPELLS_ABOVE_LEVEL, Bonus::OBJECT, 1, -1, "", bonusSubtype);
  1322. gs.id = cHero->id;
  1323. sendAndApply(&gs);
  1324. }
  1325. break;
  1326. }
  1327. }
  1328. //premies given
  1329. //send info about battles
  1330. BattleStart bs;
  1331. bs.info = curB;
  1332. sendAndApply(&bs);
  1333. }
  1334. void CGameHandler::checkForBattleEnd( std::vector<CStack*> &stacks )
  1335. {
  1336. //checking winning condition
  1337. bool hasStack[2]; //hasStack[0] - true if attacker has a living stack; defender similarily
  1338. hasStack[0] = hasStack[1] = false;
  1339. for(int b = 0; b<stacks.size(); ++b)
  1340. {
  1341. if(stacks[b]->alive() && !stacks[b]->hasBonusOfType(Bonus::SIEGE_WEAPON))
  1342. {
  1343. hasStack[1-stacks[b]->attackerOwned] = true;
  1344. }
  1345. }
  1346. if(!hasStack[0] || !hasStack[1]) //somebody has won
  1347. {
  1348. BattleResult *br = new BattleResult; //will be deleted at the end of startBattle(...)
  1349. br->result = 0;
  1350. br->winner = hasStack[1]; //fleeing side loses
  1351. gs->curB->calculateCasualties(br->casualties);
  1352. battleResult.set(br);
  1353. }
  1354. }
  1355. void CGameHandler::giveSpells( const CGTownInstance *t, const CGHeroInstance *h )
  1356. {
  1357. if(!vstd::contains(h->artifWorn,17))
  1358. return; //hero hasn't spellbok
  1359. ChangeSpells cs;
  1360. cs.hid = h->id;
  1361. cs.learn = true;
  1362. for(int i=0; i<std::min(t->mageGuildLevel(),h->getSecSkillLevel(7)+2);i++)
  1363. {
  1364. for(int j=0; j<t->spellsAtLevel(i+1,true) && j<t->spells[i].size(); j++)
  1365. {
  1366. if(!vstd::contains(h->spells,t->spells[i][j]))
  1367. cs.spells.insert(t->spells[i][j]);
  1368. }
  1369. }
  1370. if(cs.spells.size())
  1371. sendAndApply(&cs);
  1372. }
  1373. void CGameHandler::setBlockVis(int objid, bool bv)
  1374. {
  1375. SetObjectProperty sop(objid,2,bv);
  1376. sendAndApply(&sop);
  1377. }
  1378. bool CGameHandler::removeObject( int objid )
  1379. {
  1380. if(!getObj(objid))
  1381. {
  1382. tlog1 << "Something wrong, that object already has been removed or hasn't existed!\n";
  1383. return false;
  1384. }
  1385. RemoveObject ro;
  1386. ro.id = objid;
  1387. sendAndApply(&ro);
  1388. winLoseHandle(255); //eg if monster escaped (removing objs after battle is done dircetly by endBattle, not this function)
  1389. return true;
  1390. }
  1391. void CGameHandler::setAmount(int objid, ui32 val)
  1392. {
  1393. SetObjectProperty sop(objid,3,val);
  1394. sendAndApply(&sop);
  1395. }
  1396. bool CGameHandler::moveHero( si32 hid, int3 dst, ui8 instant, ui8 asker /*= 255*/ )
  1397. {
  1398. bool blockvis = false;
  1399. const CGHeroInstance *h = getHero(hid);
  1400. if(!h || asker != 255 && (instant || h->getOwner() != gs->currentPlayer) //not turn of that hero or player can't simply teleport hero (at least not with this function)
  1401. )
  1402. {
  1403. tlog1 << "Illegal call to move hero!\n";
  1404. return false;
  1405. }
  1406. tlog5 << "Player " <<int(asker) << " wants to move hero "<< hid << " from "<< h->pos << " to " << dst << std::endl;
  1407. int3 hmpos = dst + int3(-1,0,0);
  1408. if(!gs->map->isInTheMap(hmpos))
  1409. {
  1410. tlog1 << "Destination tile is outside the map!\n";
  1411. return false;
  1412. }
  1413. TerrainTile t = gs->map->terrain[hmpos.x][hmpos.y][hmpos.z];
  1414. int cost = gs->getMovementCost(h,h->getPosition(false),CGHeroInstance::convertPosition(dst,false),h->movement);
  1415. //result structure for start - movement failed, no move points used
  1416. TryMoveHero tmh;
  1417. tmh.id = hid;
  1418. tmh.start = h->pos;
  1419. tmh.end = dst;
  1420. tmh.result = TryMoveHero::FAILED;
  1421. tmh.movePoints = h->movement;
  1422. //check if destination tile is available
  1423. //it's a rock or blocked and not visitable tile
  1424. //OR hero is on land and dest is water and (there is not present only one object - boat)
  1425. if((t.tertype == TerrainTile::rock || (t.blocked && !t.visitable))
  1426. && complain("Cannot move hero, destination tile is blocked!")
  1427. || (!h->boat && !h->canWalkOnSea() && t.tertype == TerrainTile::water && (t.visitableObjects.size() != 1 || (t.visitableObjects.front()->ID != 8 && t.visitableObjects.front()->ID != HEROI_TYPE))) //hero is not on boat/water walking and dst water tile doesn't contain boat/hero (objs visitable from land)
  1428. && complain("Cannot move hero, destination tile is on water!")
  1429. || (h->boat && t.tertype != TerrainTile::water && t.blocked)
  1430. && complain("Cannot disembark hero, tile is blocked!")
  1431. || (h->movement < cost && dst != h->pos && !instant)
  1432. && complain("Hero doesn't have any movement points left!")
  1433. || states.checkFlag(h->tempOwner, &PlayerStatus::engagedIntoBattle)
  1434. && complain("Cannot move hero during the battle"))
  1435. {
  1436. //send info about movement failure
  1437. sendAndApply(&tmh);
  1438. return false;
  1439. }
  1440. //hero enters the boat
  1441. if(!h->boat && t.visitableObjects.size() && t.visitableObjects.front()->ID == 8)
  1442. {
  1443. tmh.result = TryMoveHero::EMBARK;
  1444. tmh.movePoints = 0; //embarking takes all move points
  1445. //TODO: check for bonus that removes that penalty
  1446. getTilesInRange(tmh.fowRevealed,h->getSightCenter()+(tmh.end-tmh.start),h->getSightRadious(),h->tempOwner,1);
  1447. sendAndApply(&tmh);
  1448. return true;
  1449. }
  1450. //hero leaves the boat
  1451. else if(h->boat && t.tertype != TerrainTile::water && !t.blocked)
  1452. {
  1453. tmh.result = TryMoveHero::DISEMBARK;
  1454. tmh.movePoints = 0; //disembarking takes all move points
  1455. //TODO: check for bonus that removes that penalty
  1456. getTilesInRange(tmh.fowRevealed,h->getSightCenter()+(tmh.end-tmh.start),h->getSightRadious(),h->tempOwner,1);
  1457. sendAndApply(&tmh);
  1458. return true;
  1459. }
  1460. //checks for standard movement
  1461. if(!instant)
  1462. {
  1463. if( distance(h->pos,dst) >= 1.5 && complain("Tiles are not neighbouring!")
  1464. || h->movement < cost && h->movement < 100 && complain("Not enough move points!"))
  1465. {
  1466. sendAndApply(&tmh);
  1467. return false;
  1468. }
  1469. //check if there is blocking visitable object
  1470. blockvis = false;
  1471. tmh.movePoints = std::max(si32(0),h->movement-cost); //take move points
  1472. BOOST_FOREACH(CGObjectInstance *obj, t.visitableObjects)
  1473. {
  1474. if(obj != h && obj->blockVisit && !(obj->getPassableness() & 1<<h->tempOwner))
  1475. {
  1476. blockvis = true;
  1477. break;
  1478. }
  1479. }
  1480. //we start moving
  1481. if(blockvis)//interaction with blocking object (like resources)
  1482. {
  1483. tmh.result = TryMoveHero::BLOCKING_VISIT;
  1484. sendAndApply(&tmh);
  1485. //failed to move to that tile but we visit object
  1486. if(t.visitableObjects.size())
  1487. objectVisited(t.visitableObjects.back(), h);
  1488. // BOOST_FOREACH(CGObjectInstance *obj, t.visitableObjects)
  1489. // {
  1490. // if (obj->blockVisit)
  1491. // {
  1492. // objectVisited(obj, h);
  1493. // }
  1494. // }
  1495. tlog5 << "Blocking visit at " << hmpos << std::endl;
  1496. return true;
  1497. }
  1498. else //normal move
  1499. {
  1500. BOOST_FOREACH(CGObjectInstance *obj, gs->map->terrain[h->pos.x-1][h->pos.y][h->pos.z].visitableObjects)
  1501. {
  1502. obj->onHeroLeave(h);
  1503. }
  1504. getTilesInRange(tmh.fowRevealed,h->getSightCenter()+(tmh.end-tmh.start),h->getSightRadious(),h->tempOwner,1);
  1505. int3 guardPos = gs->guardingCreaturePosition(int3(hmpos.x, hmpos.y, hmpos.z));
  1506. tmh.result = TryMoveHero::SUCCESS;
  1507. tmh.attackedFrom = guardPos;
  1508. sendAndApply(&tmh);
  1509. tlog5 << "Moved to " <<tmh.end<<std::endl;
  1510. // If a creature guards the tile, block visit.
  1511. if (gs->map->isInTheMap(guardPos)) {
  1512. const TerrainTile &guardTile = gs->map->terrain[guardPos.x][guardPos.y][guardPos.z];
  1513. objectVisited(guardTile.visitableObjects.back(), h);
  1514. // TODO: Need to wait until battle is over.
  1515. // Do not visit anything else if hero died.
  1516. if (h->getArmy().stacksCount() == 0)
  1517. return true;
  1518. }
  1519. //call objects if they are visited
  1520. if(t.visitableObjects.size())
  1521. {
  1522. //to prevent self-visiting heroes on space press
  1523. if(t.visitableObjects.back() != h)
  1524. objectVisited(t.visitableObjects.back(), h);
  1525. else if(t.visitableObjects.size() > 1)
  1526. objectVisited(*(t.visitableObjects.end()-2),h);
  1527. }
  1528. // BOOST_FOREACH(CGObjectInstance *obj, t.visitableObjects)
  1529. // {
  1530. // objectVisited(obj, h);
  1531. // }
  1532. tlog5 << "Movement end!\n";
  1533. return true;
  1534. }
  1535. }
  1536. else //instant move - teleportation
  1537. {
  1538. BOOST_FOREACH(CGObjectInstance* obj, t.blockingObjects)
  1539. {
  1540. if(obj->ID==HEROI_TYPE)
  1541. {
  1542. CGHeroInstance *dh = static_cast<CGHeroInstance *>(obj);
  1543. if(obj->tempOwner==h->tempOwner)
  1544. {
  1545. heroExchange(dh->id, h->id);
  1546. return true;
  1547. }
  1548. //TODO: check for ally
  1549. startBattleI(h, dh);
  1550. return true;
  1551. }
  1552. }
  1553. tmh.result = TryMoveHero::TELEPORTATION;
  1554. getTilesInRange(tmh.fowRevealed,h->getSightCenter()+(tmh.end-tmh.start),h->getSightRadious(),h->tempOwner,1);
  1555. sendAndApply(&tmh);
  1556. return true;
  1557. }
  1558. }
  1559. void CGameHandler::setOwner(int objid, ui8 owner)
  1560. {
  1561. ui8 oldOwner = getOwner(objid);
  1562. SetObjectProperty sop(objid,1,owner);
  1563. sendAndApply(&sop);
  1564. winLoseHandle(1<<owner | 1<<oldOwner);
  1565. if(owner < PLAYER_LIMIT && getTown(objid) && !gs->getPlayer(owner)->towns.size()) //player lost last town
  1566. {
  1567. InfoWindow iw;
  1568. iw.player = oldOwner;
  1569. iw.text.addTxt(MetaString::GENERAL_TXT, 6); //%s, you have lost your last town. If you do not conquer another town in the next week, you will be eliminated.
  1570. sendAndApply(&iw);
  1571. }
  1572. }
  1573. void CGameHandler::setHoverName(int objid, MetaString* name)
  1574. {
  1575. SetHoverName shn(objid, *name);
  1576. sendAndApply(&shn);
  1577. }
  1578. void CGameHandler::showInfoDialog(InfoWindow *iw)
  1579. {
  1580. sendToAllClients(iw);
  1581. }
  1582. void CGameHandler::showBlockingDialog( BlockingDialog *iw, const CFunctionList<void(ui32)> &callback )
  1583. {
  1584. ask(iw,iw->player,callback);
  1585. }
  1586. ui32 CGameHandler::showBlockingDialog( BlockingDialog *iw )
  1587. {
  1588. //TODO
  1589. //gsm.lock();
  1590. //int query = QID++;
  1591. //states.addQuery(player,query);
  1592. //sendToAllClients(iw);
  1593. //gsm.unlock();
  1594. //ui32 ret = getQueryResult(iw->player, query);
  1595. //gsm.lock();
  1596. //states.removeQuery(player, query);
  1597. //gsm.unlock();
  1598. return 0;
  1599. }
  1600. int CGameHandler::getCurrentPlayer()
  1601. {
  1602. return gs->currentPlayer;
  1603. }
  1604. void CGameHandler::giveResource(int player, int which, int val)
  1605. {
  1606. if(!val) return; //don't waste time on empty call
  1607. SetResource sr;
  1608. sr.player = player;
  1609. sr.resid = which;
  1610. sr.val = gs->players.find(player)->second.resources[which]+val;
  1611. sendAndApply(&sr);
  1612. }
  1613. void CGameHandler::giveCreatures (int objid, const CGHeroInstance * h, CCreatureSet creatures)
  1614. {
  1615. if (creatures.stacksCount() <= 0)
  1616. return;
  1617. CCreatureSet heroArmy = h->getArmy();
  1618. while (creatures.stacksCount() > 0)
  1619. {
  1620. int slot = heroArmy.getSlotFor(creatures.Slots().begin()->second.type->idNumber);
  1621. if (slot < 0)
  1622. break;
  1623. heroArmy.addToSlot(slot, creatures.slots.begin()->second);
  1624. creatures.slots.erase (creatures.slots.begin());
  1625. }
  1626. if (creatures.stacksCount() == 0) //all creatures can be moved to hero army - do that
  1627. {
  1628. SetGarrisons sg;
  1629. sg.garrs[h->id] = heroArmy;
  1630. sendAndApply(&sg);
  1631. }
  1632. else //show garrison window and let player pick creatures
  1633. {
  1634. SetGarrisons sg;
  1635. sg.garrs[objid] = creatures;
  1636. sendAndApply (&sg);
  1637. showGarrisonDialog (objid, h->id, true, 0);
  1638. return;
  1639. }
  1640. }
  1641. void CGameHandler::takeCreatures (int objid, TSlots creatures) //probably we could use ArmedInstance as well
  1642. {
  1643. if (creatures.size() <= 0)
  1644. return;
  1645. const CArmedInstance* obj = static_cast<const CArmedInstance*>(getObj(objid));
  1646. CCreatureSet newArmy = obj->getArmy();
  1647. while (creatures.size() > 0)
  1648. {
  1649. int slot = newArmy.getSlotFor(creatures.begin()->second.type->idNumber);
  1650. if (slot < 0)
  1651. break;
  1652. newArmy.slots[slot].type = creatures.begin()->second.type;
  1653. newArmy.slots[slot].count -= creatures.begin()->second.count;
  1654. creatures.erase (creatures.begin());
  1655. }
  1656. SetGarrisons sg;
  1657. sg.garrs[objid] = newArmy;
  1658. sendAndApply(&sg);
  1659. }
  1660. void CGameHandler::showCompInfo(ShowInInfobox * comp)
  1661. {
  1662. sendToAllClients(comp);
  1663. }
  1664. void CGameHandler::heroVisitCastle(int obj, int heroID)
  1665. {
  1666. HeroVisitCastle vc;
  1667. vc.hid = heroID;
  1668. vc.tid = obj;
  1669. vc.flags |= 1;
  1670. sendAndApply(&vc);
  1671. const CGHeroInstance *h = getHero(heroID);
  1672. vistiCastleObjects (getTown(obj), h);
  1673. giveSpells (getTown(obj), getHero(heroID));
  1674. if(gs->map->victoryCondition.condition == transportItem)
  1675. checkLossVictory(h->tempOwner); //transported artifact?
  1676. }
  1677. void CGameHandler::vistiCastleObjects (const CGTownInstance *t, const CGHeroInstance *h)
  1678. {
  1679. std::vector<CGTownBuilding*>::const_iterator i;
  1680. for (i = t->bonusingBuildings.begin(); i != t->bonusingBuildings.end(); i++)
  1681. (*i)->onHeroVisit (h);
  1682. }
  1683. void CGameHandler::stopHeroVisitCastle(int obj, int heroID)
  1684. {
  1685. HeroVisitCastle vc;
  1686. vc.hid = heroID;
  1687. vc.tid = obj;
  1688. sendAndApply(&vc);
  1689. }
  1690. void CGameHandler::giveHeroArtifact(int artid, int hid, int position) //pos==-1 - first free slot in backpack
  1691. {
  1692. const CGHeroInstance* h = getHero(hid);
  1693. const CArtifact &art = VLC->arth->artifacts[artid];
  1694. SetHeroArtifacts sha;
  1695. sha.hid = hid;
  1696. sha.artifacts = h->artifacts;
  1697. sha.artifWorn = h->artifWorn;
  1698. if(position<0)
  1699. {
  1700. if(position == -2)
  1701. {
  1702. int i;
  1703. for(i=0; i<art.possibleSlots.size(); i++) //try to put artifact into first available slot
  1704. {
  1705. if( !vstd::contains(sha.artifWorn,art.possibleSlots[i]) )
  1706. {
  1707. //we've found a free suitable slot
  1708. VLC->arth->equipArtifact(sha.artifWorn, art.possibleSlots[i], artid);
  1709. break;
  1710. }
  1711. }
  1712. if(i == art.possibleSlots.size() && !art.isBig()) //if haven't find proper slot, use backpack or discard big artifact
  1713. sha.artifacts.push_back(artid);
  1714. }
  1715. else if (!art.isBig()) //should be -1 => put artifact into backpack
  1716. {
  1717. sha.artifacts.push_back(artid);
  1718. }
  1719. }
  1720. else
  1721. {
  1722. if(!vstd::contains(sha.artifWorn,ui16(position)))
  1723. {
  1724. VLC->arth->equipArtifact(sha.artifWorn, position, artid);
  1725. }
  1726. else if (!art.isBig())
  1727. {
  1728. sha.artifacts.push_back(artid);
  1729. }
  1730. }
  1731. sendAndApply(&sha);
  1732. }
  1733. void CGameHandler::removeArtifact(int artid, int hid)
  1734. {
  1735. const CGHeroInstance* h = getHero(hid);
  1736. SetHeroArtifacts sha;
  1737. sha.hid = hid;
  1738. sha.artifacts = h->artifacts;
  1739. sha.artifWorn = h->artifWorn;
  1740. std::vector<ui32>::iterator it;
  1741. if ((it = std::find(sha.artifacts.begin(), sha.artifacts.end(), artid)) != sha.artifacts.end()) //it is in backpack
  1742. sha.artifacts.erase(it);
  1743. else //worn
  1744. {
  1745. for (std::map<ui16,ui32>::iterator itr = sha.artifWorn.begin(); itr != sha.artifWorn.end(); ++itr)
  1746. {
  1747. if (itr->second == artid)
  1748. {
  1749. VLC->arth->unequipArtifact(sha.artifWorn, itr->first);
  1750. break;
  1751. }
  1752. }
  1753. }
  1754. sendAndApply(&sha);
  1755. }
  1756. void CGameHandler::startBattleI(const CArmedInstance *army1, const CArmedInstance *army2, int3 tile, const CGHeroInstance *hero1, const CGHeroInstance *hero2, bool creatureBank, boost::function<void(BattleResult*)> cb, const CGTownInstance *town) //use hero=NULL for no hero
  1757. {
  1758. engageIntoBattle(army1->tempOwner);
  1759. engageIntoBattle(army2->tempOwner);
  1760. //block engaged players
  1761. if(army2->tempOwner < PLAYER_LIMIT)
  1762. states.setFlag(army2->tempOwner,&PlayerStatus::engagedIntoBattle,true);
  1763. boost::thread(boost::bind(&CGameHandler::startBattle, this, army1, army2, tile, hero1, hero2, creatureBank, cb, town));
  1764. }
  1765. void CGameHandler::startBattleI( const CArmedInstance *army1, const CArmedInstance *army2, int3 tile, boost::function<void(BattleResult*)> cb, bool creatureBank )
  1766. {
  1767. startBattleI(army1, army2, tile,
  1768. army1->ID == HEROI_TYPE ? static_cast<const CGHeroInstance*>(army1) : NULL,
  1769. army2->ID == HEROI_TYPE ? static_cast<const CGHeroInstance*>(army2) : NULL,
  1770. creatureBank, cb);
  1771. }
  1772. void CGameHandler::startBattleI( const CArmedInstance *army1, const CArmedInstance *army2, boost::function<void(BattleResult*)> cb, bool creatureBank)
  1773. {
  1774. startBattleI(army1, army2, army2->pos - army2->getVisitableOffset(), cb, creatureBank);
  1775. }
  1776. //void CGameHandler::startBattleI(int heroID, CCreatureSet army, int3 tile, boost::function<void(BattleResult*)> cb) //for hero<=>neutral army
  1777. //{
  1778. // CGHeroInstance* h = const_cast<CGHeroInstance*>(getHero(heroID));
  1779. // startBattleI(&h->army,&army,tile,h,NULL,cb);
  1780. // //battle(&h->army,army,tile,h,NULL);
  1781. //}
  1782. void CGameHandler::changeSpells( int hid, bool give, const std::set<ui32> &spells )
  1783. {
  1784. ChangeSpells cs;
  1785. cs.hid = hid;
  1786. cs.spells = spells;
  1787. cs.learn = give;
  1788. sendAndApply(&cs);
  1789. }
  1790. int CGameHandler::getSelectedHero()
  1791. {
  1792. return IGameCallback::getSelectedHero(getCurrentPlayer())->id;
  1793. }
  1794. void CGameHandler::setObjProperty( int objid, int prop, si64 val )
  1795. {
  1796. SetObjectProperty sob;
  1797. sob.id = objid;
  1798. sob.what = prop;
  1799. sob.val = val;
  1800. sendAndApply(&sob);
  1801. }
  1802. void CGameHandler::sendMessageTo( CConnection &c, const std::string &message )
  1803. {
  1804. SystemMessage sm;
  1805. sm.text = message;
  1806. c << &sm;
  1807. }
  1808. void CGameHandler::giveHeroBonus( GiveBonus * bonus )
  1809. {
  1810. sendAndApply(bonus);
  1811. }
  1812. void CGameHandler::setMovePoints( SetMovePoints * smp )
  1813. {
  1814. sendAndApply(smp);
  1815. }
  1816. void CGameHandler::setManaPoints( int hid, int val )
  1817. {
  1818. SetMana sm;
  1819. sm.hid = hid;
  1820. sm.val = val;
  1821. sendAndApply(&sm);
  1822. }
  1823. void CGameHandler::giveHero( int id, int player )
  1824. {
  1825. GiveHero gh;
  1826. gh.id = id;
  1827. gh.player = player;
  1828. sendAndApply(&gh);
  1829. }
  1830. void CGameHandler::changeObjPos( int objid, int3 newPos, ui8 flags )
  1831. {
  1832. ChangeObjPos cop;
  1833. cop.objid = objid;
  1834. cop.nPos = newPos;
  1835. cop.flags = flags;
  1836. sendAndApply(&cop);
  1837. }
  1838. void CGameHandler::useScholarSkill(si32 fromHero, si32 toHero)
  1839. {
  1840. const CGHeroInstance * h1 = getHero(fromHero);
  1841. const CGHeroInstance * h2 = getHero(toHero);
  1842. if ( h1->getSecSkillLevel(18) < h2->getSecSkillLevel(18) )
  1843. {
  1844. std::swap (h1,h2);//1st hero need to have higher scholar level for correct message
  1845. std::swap(fromHero, toHero);
  1846. }
  1847. int ScholarLevel = h1->getSecSkillLevel(18);//heroes can trade up to this level
  1848. if (!ScholarLevel || !vstd::contains(h1->artifWorn,17) || !vstd::contains(h2->artifWorn,17) )
  1849. return;//no scholar skill or no spellbook
  1850. int h1Lvl = std::min(ScholarLevel+1, h1->getSecSkillLevel(7)+2),
  1851. h2Lvl = std::min(ScholarLevel+1, h2->getSecSkillLevel(7)+2);//heroes can receive this levels
  1852. ChangeSpells cs1;
  1853. cs1.learn = true;
  1854. cs1.hid = toHero;//giving spells to first hero
  1855. for(std::set<ui32>::const_iterator it=h1->spells.begin(); it!=h1->spells.end();it++)
  1856. if ( h2Lvl >= VLC->spellh->spells[*it].level && !vstd::contains(h2->spells, *it))//hero can learn it and don't have it yet
  1857. cs1.spells.insert(*it);//spell to learn
  1858. ChangeSpells cs2;
  1859. cs2.learn = true;
  1860. cs2.hid = fromHero;
  1861. for(std::set<ui32>::const_iterator it=h2->spells.begin(); it!=h2->spells.end();it++)
  1862. if ( h1Lvl >= VLC->spellh->spells[*it].level && !vstd::contains(h1->spells, *it))
  1863. cs2.spells.insert(*it);
  1864. if (cs1.spells.size() || cs2.spells.size())//create a message
  1865. {
  1866. InfoWindow iw;
  1867. iw.player = h1->tempOwner;
  1868. iw.components.push_back(Component(Component::SEC_SKILL, 18, ScholarLevel, 0));
  1869. iw.text.addTxt(MetaString::GENERAL_TXT, 139);//"%s, who has studied magic extensively,
  1870. iw.text.addReplacement(h1->name);
  1871. if (cs2.spells.size())//if found new spell - apply
  1872. {
  1873. iw.text.addTxt(MetaString::GENERAL_TXT, 140);//learns
  1874. int size = cs2.spells.size();
  1875. for(std::set<ui32>::const_iterator it=cs2.spells.begin(); it!=cs2.spells.end();it++)
  1876. {
  1877. iw.components.push_back(Component(Component::SPELL, (*it), 1, 0));
  1878. iw.text.addTxt(MetaString::SPELL_NAME, (*it));
  1879. switch (size--)
  1880. {
  1881. case 2: iw.text.addTxt(MetaString::GENERAL_TXT, 141);
  1882. case 1: break;
  1883. default: iw.text << ", ";
  1884. }
  1885. }
  1886. iw.text.addTxt(MetaString::GENERAL_TXT, 142);//from %s
  1887. iw.text.addReplacement(h2->name);
  1888. sendAndApply(&cs2);
  1889. }
  1890. if (cs1.spells.size() && cs2.spells.size() )
  1891. {
  1892. iw.text.addTxt(MetaString::GENERAL_TXT, 141);//and
  1893. }
  1894. if (cs1.spells.size())
  1895. {
  1896. iw.text.addTxt(MetaString::GENERAL_TXT, 147);//teaches
  1897. int size = cs1.spells.size();
  1898. for(std::set<ui32>::const_iterator it=cs1.spells.begin(); it!=cs1.spells.end();it++)
  1899. {
  1900. iw.components.push_back(Component(Component::SPELL, (*it), 1, 0));
  1901. iw.text.addTxt(MetaString::SPELL_NAME, (*it));
  1902. switch (size--)
  1903. {
  1904. case 2: iw.text.addTxt(MetaString::GENERAL_TXT, 141);
  1905. case 1: break;
  1906. default: iw.text << ", ";
  1907. } }
  1908. iw.text.addTxt(MetaString::GENERAL_TXT, 148);//from %s
  1909. iw.text.addReplacement(h2->name);
  1910. sendAndApply(&cs1);
  1911. }
  1912. sendAndApply(&iw);
  1913. }
  1914. }
  1915. void CGameHandler::heroExchange(si32 hero1, si32 hero2)
  1916. {
  1917. ui8 player1 = getHero(hero1)->tempOwner;
  1918. ui8 player2 = getHero(hero2)->tempOwner;
  1919. if(player1 == player2)//TODO: allies
  1920. {
  1921. OpenWindow hex;
  1922. hex.window = OpenWindow::EXCHANGE_WINDOW;
  1923. hex.id1 = hero1;
  1924. hex.id2 = hero2;
  1925. sendAndApply(&hex);
  1926. useScholarSkill(hero1,hero2);
  1927. }
  1928. }
  1929. void CGameHandler::applyAndAsk( Query * sel, ui8 player, boost::function<void(ui32)> &callback )
  1930. {
  1931. boost::unique_lock<boost::recursive_mutex> lock(gsm);
  1932. sel->id = QID;
  1933. callbacks[QID] = callback;
  1934. states.addQuery(player,QID);
  1935. QID++;
  1936. sendAndApply(sel);
  1937. }
  1938. void CGameHandler::ask( Query * sel, ui8 player, const CFunctionList<void(ui32)> &callback )
  1939. {
  1940. boost::unique_lock<boost::recursive_mutex> lock(gsm);
  1941. sel->id = QID;
  1942. callbacks[QID] = callback;
  1943. states.addQuery(player,QID);
  1944. sendToAllClients(sel);
  1945. QID++;
  1946. }
  1947. void CGameHandler::sendToAllClients( CPackForClient * info )
  1948. {
  1949. tlog5 << "Sending to all clients a package of type " << typeid(*info).name() << std::endl;
  1950. for(std::set<CConnection*>::iterator i=conns.begin(); i!=conns.end();i++)
  1951. {
  1952. (*i)->wmx->lock();
  1953. **i << info;
  1954. (*i)->wmx->unlock();
  1955. }
  1956. }
  1957. void CGameHandler::sendAndApply( CPackForClient * info )
  1958. {
  1959. gs->apply(info);
  1960. sendToAllClients(info);
  1961. }
  1962. void CGameHandler::sendAndApply( SetGarrisons * info )
  1963. {
  1964. sendAndApply((CPackForClient*)info);
  1965. if(gs->map->victoryCondition.condition == gatherTroop)
  1966. for(std::map<ui32,CCreatureSet>::const_iterator i = info->garrs.begin(); i != info->garrs.end(); i++)
  1967. checkLossVictory(getObj(i->first)->tempOwner);
  1968. }
  1969. void CGameHandler::sendAndApply( SetResource * info )
  1970. {
  1971. sendAndApply((CPackForClient*)info);
  1972. if(gs->map->victoryCondition.condition == gatherResource)
  1973. checkLossVictory(info->player);
  1974. }
  1975. void CGameHandler::sendAndApply( SetResources * info )
  1976. {
  1977. sendAndApply((CPackForClient*)info);
  1978. if(gs->map->victoryCondition.condition == gatherResource)
  1979. checkLossVictory(info->player);
  1980. }
  1981. void CGameHandler::sendAndApply( NewStructures * info )
  1982. {
  1983. sendAndApply((CPackForClient*)info);
  1984. if(gs->map->victoryCondition.condition == buildCity)
  1985. checkLossVictory(getTown(info->tid)->tempOwner);
  1986. }
  1987. void CGameHandler::save( const std::string &fname )
  1988. {
  1989. {
  1990. tlog0 << "Ordering clients to serialize...\n";
  1991. SaveGame sg(fname);
  1992. sendToAllClients(&sg);
  1993. }
  1994. {
  1995. tlog0 << "Serializing game info...\n";
  1996. CSaveFile save(GVCMIDirs.UserPath + "/Games/" + fname + ".vlgm1");
  1997. char hlp[8] = "VCMISVG";
  1998. save << hlp << static_cast<CMapHeader&>(*gs->map) << gs->scenarioOps << *VLC << gs;
  1999. }
  2000. {
  2001. tlog0 << "Serializing server info...\n";
  2002. CSaveFile save(GVCMIDirs.UserPath + "/Games/" + fname + ".vsgm1");
  2003. save << *this;
  2004. }
  2005. tlog0 << "Game has been successfully saved!\n";
  2006. }
  2007. void CGameHandler::close()
  2008. {
  2009. tlog0 << "We have been requested to close.\n";
  2010. //BOOST_FOREACH(CConnection *cc, conns)
  2011. // if(cc && cc->socket && cc->socket->is_open())
  2012. // cc->socket->close();
  2013. //exit(0);
  2014. }
  2015. bool CGameHandler::arrangeStacks( si32 id1, si32 id2, ui8 what, ui8 p1, ui8 p2, si32 val )
  2016. {
  2017. CArmedInstance *s1 = static_cast<CArmedInstance*>(gs->map->objects[id1]),
  2018. *s2 = static_cast<CArmedInstance*>(gs->map->objects[id2]);
  2019. CCreatureSet temp1 = s1->getArmy(), temp2 = s2->getArmy(),
  2020. &S1 = temp1, &S2 = (s1!=s2)?(temp2):(temp1);
  2021. if(!isAllowedExchange(id1,id2))
  2022. {
  2023. complain("Cannot exchange stacks between these two objects!\n");
  2024. return false;
  2025. }
  2026. if(what==1) //swap
  2027. {
  2028. std::swap(S1.slots[p1],S2.slots[p2]); //swap slots
  2029. //if one of them is empty, remove entry
  2030. if(!S1.slots[p1].count)
  2031. S1.slots.erase(p1);
  2032. if(!S2.slots[p2].count)
  2033. S2.slots.erase(p2);
  2034. }
  2035. else if(what==2)//merge
  2036. {
  2037. if(S1.slots[p1].type != S2.slots[p2].type) //not same creature
  2038. {
  2039. complain("Cannot merge different creatures stacks!");
  2040. return false;
  2041. }
  2042. S2.slots[p2].count += S1.slots[p1].count;
  2043. S1.slots.erase(p1);
  2044. }
  2045. else if(what==3) //split
  2046. {
  2047. //general conditions checking
  2048. if((!vstd::contains(S1.slots,p1) && complain("no creatures to split"))
  2049. || (val<1 && complain("no creatures to split")) )
  2050. {
  2051. return false;
  2052. }
  2053. if(vstd::contains(S2.slots,p2)) //dest. slot not free - it must be "rebalancing"...
  2054. {
  2055. int total = S1.slots[p1].count + S2.slots[p2].count;
  2056. if( (total < val && complain("Cannot split that stack, not enough creatures!"))
  2057. || (S2.slots[p2].type != S1.slots[p1].type && complain("Cannot rebalance different creatures stacks!"))
  2058. )
  2059. {
  2060. return false;
  2061. }
  2062. S2.slots[p2].count = val;
  2063. S1.slots[p1].count = total - val;
  2064. }
  2065. else //split one stack to the two
  2066. {
  2067. if(S1.slots[p1].count < val)//not enough creatures
  2068. {
  2069. complain("Cannot split that stack, not enough creatures!");
  2070. return false;
  2071. }
  2072. S2.slots[p2].type = S1.slots[p1].type;
  2073. S2.slots[p2].count = val;
  2074. S1.slots[p1].count -= val;
  2075. }
  2076. if(!S1.slots[p1].count) //if we've moved all creatures
  2077. S1.slots.erase(p1);
  2078. }
  2079. if((s1->needsLastStack() && !S1.stacksCount()) //it's not allowed to take last stack from hero army!
  2080. || (s2->needsLastStack() && !S2.stacksCount())
  2081. )
  2082. {
  2083. complain("Cannot take the last stack!");
  2084. return false; //leave without applying changes to garrison
  2085. }
  2086. //apply changes
  2087. SetGarrisons sg;
  2088. sg.garrs[id1] = S1;
  2089. if(s1 != s2)
  2090. sg.garrs[id2] = S2;
  2091. sendAndApply(&sg);
  2092. return true;
  2093. }
  2094. int CGameHandler::getPlayerAt( CConnection *c ) const
  2095. {
  2096. std::set<int> all;
  2097. for(std::map<int,CConnection*>::const_iterator i=connections.begin(); i!=connections.end(); i++)
  2098. if(i->second == c)
  2099. all.insert(i->first);
  2100. switch(all.size())
  2101. {
  2102. case 0:
  2103. return 255;
  2104. case 1:
  2105. return *all.begin();
  2106. default:
  2107. {
  2108. //if we have more than one player at this connection, try to pick active one
  2109. if(vstd::contains(all,int(gs->currentPlayer)))
  2110. return gs->currentPlayer;
  2111. else
  2112. return 253; //cannot say which player is it
  2113. }
  2114. }
  2115. }
  2116. bool CGameHandler::disbandCreature( si32 id, ui8 pos )
  2117. {
  2118. CArmedInstance *s1 = static_cast<CArmedInstance*>(gs->map->objects[id]);
  2119. if(!vstd::contains(s1->slots,pos))
  2120. {
  2121. complain("Illegal call to disbandCreature - no such stack in army!");
  2122. return false;
  2123. }
  2124. s1->slots.erase(pos);
  2125. SetGarrisons sg;
  2126. sg.garrs[id] = s1->getArmy();
  2127. sendAndApply(&sg);
  2128. return true;
  2129. }
  2130. bool CGameHandler::buildStructure( si32 tid, si32 bid )
  2131. {
  2132. CGTownInstance * t = static_cast<CGTownInstance*>(gs->map->objects[tid]);
  2133. CBuilding * b = VLC->buildh->buildings[t->subID][bid];
  2134. if(gs->canBuildStructure(t,bid) != 7)
  2135. {
  2136. complain("Cannot build that building!");
  2137. return false;
  2138. }
  2139. if(bid == 26) //grail
  2140. {
  2141. if(!t->visitingHero || !t->visitingHero->hasArt(2))
  2142. {
  2143. complain("Cannot build grail - hero doesn't have it");
  2144. return false;
  2145. }
  2146. removeArtifact(2, t->visitingHero->id);
  2147. }
  2148. NewStructures ns;
  2149. ns.tid = tid;
  2150. if ( (bid == 18) && (vstd::contains(t->builtBuildings,(t->town->hordeLvl[0]+37))) )
  2151. ns.bid.insert(19);//we have upgr. dwelling, upgr. horde will be builded as well
  2152. else if ( (bid == 24) && (vstd::contains(t->builtBuildings,(t->town->hordeLvl[1]+37))) )
  2153. ns.bid.insert(25);
  2154. else if(bid>36) //upg dwelling
  2155. {
  2156. if ( (bid-37 == t->town->hordeLvl[0]) && (vstd::contains(t->builtBuildings,18)) )
  2157. ns.bid.insert(19);//we have horde, will be upgraded as well as dwelling
  2158. if ( (bid-37 == t->town->hordeLvl[1]) && (vstd::contains(t->builtBuildings,24)) )
  2159. ns.bid.insert(25);
  2160. SetAvailableCreatures ssi;
  2161. ssi.tid = tid;
  2162. ssi.creatures = t->creatures;
  2163. ssi.creatures[bid-37].second.push_back(t->town->upgradedCreatures[bid-37]);
  2164. sendAndApply(&ssi);
  2165. }
  2166. else if(bid >= 30) //bas. dwelling
  2167. {
  2168. int crid = t->town->basicCreatures[bid-30];
  2169. SetAvailableCreatures ssi;
  2170. ssi.tid = tid;
  2171. ssi.creatures = t->creatures;
  2172. ssi.creatures[bid-30].first = VLC->creh->creatures[crid]->growth;
  2173. ssi.creatures[bid-30].second.push_back(crid);
  2174. sendAndApply(&ssi);
  2175. }
  2176. else if(bid == 11)
  2177. ns.bid.insert(27);
  2178. else if(bid == 12)
  2179. ns.bid.insert(28);
  2180. else if(bid == 13)
  2181. ns.bid.insert(29);
  2182. ns.bid.insert(bid);
  2183. ns.builded = t->builded + 1;
  2184. sendAndApply(&ns);
  2185. //reveal ground for lookout tower
  2186. FoWChange fw;
  2187. fw.player = t->tempOwner;
  2188. fw.mode = 1;
  2189. getTilesInRange(fw.tiles,t->pos,t->getSightRadious(),t->tempOwner,1);
  2190. sendAndApply(&fw);
  2191. SetResources sr;
  2192. sr.player = t->tempOwner;
  2193. sr.res = gs->getPlayer(t->tempOwner)->resources;
  2194. for(int i=0;i<b->resources.size();i++)
  2195. sr.res[i]-=b->resources[i];
  2196. sendAndApply(&sr);
  2197. if(bid<5) //it's mage guild
  2198. {
  2199. if(t->visitingHero)
  2200. giveSpells(t,t->visitingHero);
  2201. if(t->garrisonHero)
  2202. giveSpells(t,t->garrisonHero);
  2203. }
  2204. if(t->visitingHero)
  2205. vistiCastleObjects (t, t->visitingHero);
  2206. if(t->garrisonHero)
  2207. vistiCastleObjects (t, t->garrisonHero);
  2208. return true;
  2209. }
  2210. bool CGameHandler::razeStructure (si32 tid, si32 bid)
  2211. {
  2212. ///incomplete, simply erases target building
  2213. CGTownInstance * t = static_cast<CGTownInstance*>(gs->map->objects[tid]);
  2214. if (t->builtBuildings.find(bid) == t->builtBuildings.end())
  2215. return false;
  2216. RazeStructures rs;
  2217. rs.tid = tid;
  2218. rs.bid.insert(bid);
  2219. rs.destroyed = t->destroyed + 1;
  2220. sendAndApply(&rs);
  2221. return true;
  2222. }
  2223. void CGameHandler::sendMessageToAll( const std::string &message )
  2224. {
  2225. SystemMessage sm;
  2226. sm.text = message;
  2227. sendToAllClients(&sm);
  2228. }
  2229. bool CGameHandler::recruitCreatures( si32 objid, ui32 crid, ui32 cram )
  2230. {
  2231. const CGDwelling *dw = static_cast<CGDwelling*>(gs->map->objects[objid]);
  2232. const CArmedInstance *dst = NULL;
  2233. if(dw->ID == TOWNI_TYPE)
  2234. dst = dw;
  2235. else if(dw->ID == 17 || dw->ID == 20) //advmap dwelling
  2236. dst = getHero(gs->getPlayer(dw->tempOwner)->currentSelection); //TODO: check if current hero is really visiting dwelling
  2237. assert(dw && dst);
  2238. //verify
  2239. bool found = false;
  2240. int level = -1;
  2241. typedef std::pair<const int,int> Parka;
  2242. for(level = 0; level < dw->creatures.size(); level++) //iterate through all levels
  2243. {
  2244. const std::pair<ui32, std::vector<ui32> > &cur = dw->creatures[level]; //current level info <amount, list of cr. ids>
  2245. int i = 0;
  2246. for(; i < cur.second.size(); i++) //look for crid among available creatures list on current level
  2247. if(cur.second[i] == crid)
  2248. break;
  2249. if(i < cur.second.size())
  2250. {
  2251. found = true;
  2252. cram = std::min(cram, cur.first); //reduce recruited amount up to available amount
  2253. break;
  2254. }
  2255. }
  2256. int slot = dst-> getSlotFor(crid);
  2257. if(!found && complain("Cannot recruit: no such creatures!")
  2258. || cram > VLC->creh->creatures[crid]->maxAmount(gs->getPlayer(dst->tempOwner)->resources) && complain("Cannot recruit: lack of resources!")
  2259. || cram<=0 && complain("Cannot recruit: cram <= 0!")
  2260. || slot<0 && complain("Cannot recruit: no available slot!"))
  2261. {
  2262. return false;
  2263. }
  2264. //recruit
  2265. SetResources sr;
  2266. sr.player = dst->tempOwner;
  2267. for(int i=0;i<RESOURCE_QUANTITY;i++)
  2268. sr.res[i] = gs->getPlayer(dst->tempOwner)->resources[i] - (VLC->creh->creatures[crid]->cost[i] * cram);
  2269. SetAvailableCreatures sac;
  2270. sac.tid = objid;
  2271. sac.creatures = dw->creatures;
  2272. sac.creatures[level].first -= cram;
  2273. SetGarrisons sg;
  2274. sg.garrs[dst->id] = dst->getArmy();
  2275. sg.garrs[dst->id] .addToSlot(slot, crid, cram);
  2276. sendAndApply(&sr);
  2277. sendAndApply(&sac);
  2278. sendAndApply(&sg);
  2279. return true;
  2280. }
  2281. bool CGameHandler::upgradeCreature( ui32 objid, ui8 pos, ui32 upgID )
  2282. {
  2283. CArmedInstance *obj = static_cast<CArmedInstance*>(gs->map->objects[objid]);
  2284. UpgradeInfo ui = gs->getUpgradeInfo(obj,pos);
  2285. int player = obj->tempOwner;
  2286. int crQuantity = obj->slots[pos].count;
  2287. //check if upgrade is possible
  2288. if((ui.oldID<0 || !vstd::contains(ui.newID,upgID)) && complain("That upgrade is not possible!"))
  2289. {
  2290. return false;
  2291. }
  2292. //check if player has enough resources
  2293. for(int i=0;i<ui.cost.size();i++)
  2294. {
  2295. for (std::set<std::pair<int,int> >::iterator j=ui.cost[i].begin(); j!=ui.cost[i].end(); j++)
  2296. {
  2297. if(gs->getPlayer(player)->resources[j->first] < j->second*crQuantity)
  2298. {
  2299. complain("Cannot upgrade, not enough resources!");
  2300. return false;
  2301. }
  2302. }
  2303. }
  2304. //take resources
  2305. for(int i=0;i<ui.cost.size();i++)
  2306. {
  2307. for (std::set<std::pair<int,int> >::iterator j=ui.cost[i].begin(); j!=ui.cost[i].end(); j++)
  2308. {
  2309. SetResource sr;
  2310. sr.player = player;
  2311. sr.resid = j->first;
  2312. sr.val = gs->getPlayer(player)->resources[j->first] - j->second*crQuantity;
  2313. sendAndApply(&sr);
  2314. }
  2315. }
  2316. //upgrade creature
  2317. SetGarrisons sg;
  2318. sg.garrs[objid] = obj->getArmy();
  2319. sg.garrs[objid].slots[pos].setType(upgID);
  2320. sendAndApply(&sg);
  2321. return true;
  2322. }
  2323. bool CGameHandler::garrisonSwap( si32 tid )
  2324. {
  2325. CGTownInstance *town = gs->getTown(tid);
  2326. if(!town->garrisonHero && town->visitingHero) //visiting => garrison, merge armies: town army => hero army
  2327. {
  2328. CCreatureSet csn = town->visitingHero->getArmy(), cso = town->getArmy();
  2329. while(!cso.slots.empty())//while there are unmoved creatures
  2330. {
  2331. int pos = csn.getSlotFor(cso.slots.begin()->second.type->idNumber);
  2332. if(pos<0)
  2333. {
  2334. //try to merge two other stacks to make place
  2335. std::pair<TSlot, TSlot> toMerge;
  2336. if(csn.mergableStacks(toMerge, cso.slots.begin()->first))
  2337. {
  2338. //merge
  2339. csn.slots[toMerge.second].count += csn.slots[toMerge.first].count;
  2340. csn.slots[toMerge.first] = cso.slots.begin()->second;
  2341. }
  2342. else
  2343. {
  2344. complain("Cannot make garrison swap, not enough free slots!");
  2345. return false;
  2346. }
  2347. }
  2348. else if(csn.slots.find(pos) != csn.slots.end()) //add creatures to the existing stack
  2349. {
  2350. csn.slots[pos].count += cso.slots.begin()->second.count;
  2351. }
  2352. else //move stack on the free pos
  2353. {
  2354. csn.slots[pos].type = cso.slots.begin()->second.type;
  2355. csn.slots[pos].count = cso.slots.begin()->second.count;
  2356. }
  2357. cso.slots.erase(cso.slots.begin());
  2358. }
  2359. SetGarrisons sg;
  2360. sg.garrs[town->visitingHero->id] = csn;
  2361. sg.garrs[town->id] = csn;
  2362. sendAndApply(&sg);
  2363. SetHeroesInTown intown;
  2364. intown.tid = tid;
  2365. intown.visiting = -1;
  2366. intown.garrison = town->visitingHero->id;
  2367. sendAndApply(&intown);
  2368. return true;
  2369. }
  2370. else if (town->garrisonHero && !town->visitingHero) //move hero out of the garrison
  2371. {
  2372. //check if moving hero out of town will break 8 wandering heroes limit
  2373. if(getHeroCount(town->garrisonHero->tempOwner,false) >= 8)
  2374. {
  2375. complain("Cannot move hero out of the garrison, there are already 8 wandering heroes!");
  2376. return false;
  2377. }
  2378. SetHeroesInTown intown;
  2379. intown.tid = tid;
  2380. intown.garrison = -1;
  2381. intown.visiting = town->garrisonHero->id;
  2382. sendAndApply(&intown);
  2383. //town will be empty
  2384. SetGarrisons sg;
  2385. sg.garrs[tid] = CCreatureSet();
  2386. sendAndApply(&sg);
  2387. return true;
  2388. }
  2389. else if (town->garrisonHero && town->visitingHero) //swap visiting and garrison hero
  2390. {
  2391. SetGarrisons sg;
  2392. sg.garrs[town->id] = town->visitingHero->getArmy();;
  2393. sg.garrs[town->garrisonHero->id] = town->garrisonHero->getArmy();
  2394. SetHeroesInTown intown;
  2395. intown.tid = tid;
  2396. intown.garrison = town->visitingHero->id;
  2397. intown.visiting = town->garrisonHero->id;
  2398. sendAndApply(&intown);
  2399. sendAndApply(&sg);
  2400. return true;
  2401. }
  2402. else
  2403. {
  2404. complain("Cannot swap garrison hero!");
  2405. return false;
  2406. }
  2407. }
  2408. // With the amount of changes done to the function, it's more like transferArtifacts.
  2409. bool CGameHandler::swapArtifacts(si32 srcHeroID, si32 destHeroID, ui16 srcSlot, ui16 destSlot)
  2410. {
  2411. CGHeroInstance *srcHero = gs->getHero(srcHeroID);
  2412. CGHeroInstance *destHero = gs->getHero(destHeroID);
  2413. // Make sure exchange is even possible between the two heroes.
  2414. if ((distance(srcHero->pos,destHero->pos) > 1.5 )|| (srcHero->tempOwner != destHero->tempOwner))
  2415. return false;
  2416. const CArtifact *srcArtifact = srcHero->getArt(srcSlot);
  2417. const CArtifact *destArtifact = destHero->getArt(destSlot);
  2418. if (srcArtifact == NULL) {
  2419. complain("No artifact to swap!");
  2420. return false;
  2421. }
  2422. SetHeroArtifacts sha;
  2423. sha.hid = srcHeroID;
  2424. sha.artifacts = srcHero->artifacts;
  2425. sha.artifWorn = srcHero->artifWorn;
  2426. // Combinational artifacts needs to be removed first so they don't get denied movement because of their own locks.
  2427. if (srcHeroID == destHeroID && srcSlot < 19 && destSlot < 19) {
  2428. sha.setArtAtPos(srcSlot, -1);
  2429. if (!vstd::contains(sha.artifWorn, destSlot))
  2430. destArtifact = NULL;
  2431. }
  2432. // Check if src/dest slots are appropriate for the artifacts exchanged.
  2433. // Moving to the backpack is always allowed.
  2434. if ((!srcArtifact || destSlot < 19)
  2435. && (srcArtifact && !srcArtifact->fitsAt(srcHeroID == destHeroID ? sha.artifWorn : destHero->artifWorn, destSlot)))
  2436. {
  2437. complain("Cannot swap artifacts!");
  2438. return false;
  2439. }
  2440. if ((srcArtifact && srcArtifact->id == 145) || (destArtifact && destArtifact->id == 145)) {
  2441. complain("Cannot move artifact locks.");
  2442. return false;
  2443. }
  2444. if (destSlot >= 19 && srcArtifact->isBig()) {
  2445. complain("Cannot put big artifacts in backpack!");
  2446. return false;
  2447. }
  2448. if (srcSlot == 16 || destSlot == 16) {
  2449. complain("Cannot move catapult!");
  2450. return false;
  2451. }
  2452. // If dest does not fit in src, put it in dest's backpack instead.
  2453. if (srcHeroID == destHeroID) // To avoid stumbling on own locks, remove artifact first.
  2454. sha.setArtAtPos(destSlot, -1);
  2455. const bool destFits = !destArtifact || srcSlot >= 19 || destSlot >= 19 || destArtifact->fitsAt(sha.artifWorn, srcSlot);
  2456. if (srcHeroID == destHeroID && destArtifact)
  2457. sha.setArtAtPos(destSlot, destArtifact->id);
  2458. sha.setArtAtPos(srcSlot, -1);
  2459. if (destSlot < 19 && (destArtifact || srcSlot < 19) && destFits)
  2460. sha.setArtAtPos(srcSlot, destArtifact ? destArtifact->id : -1);
  2461. // Internal hero artifact arrangement.
  2462. if(srcHero == destHero) {
  2463. // Correction for destination from removing source artifact in backpack.
  2464. if (srcSlot >= 19 && destSlot >= 19 && srcSlot < destSlot)
  2465. destSlot--;
  2466. sha.setArtAtPos(destSlot, srcHero->getArtAtPos(srcSlot));
  2467. }
  2468. sendAndApply(&sha);
  2469. if (srcHeroID != destHeroID) {
  2470. // Exchange between two different heroes.
  2471. sha.hid = destHeroID;
  2472. sha.artifacts = destHero->artifacts;
  2473. sha.artifWorn = destHero->artifWorn;
  2474. sha.setArtAtPos(destSlot, srcArtifact ? srcArtifact->id : -1);
  2475. if (!destFits)
  2476. sha.setArtAtPos(sha.artifacts.size() + 19, destHero->getArtAtPos(destSlot));
  2477. sendAndApply(&sha);
  2478. }
  2479. return true;
  2480. }
  2481. /**
  2482. * Assembles or disassembles a combination artifact.
  2483. * @param heroID ID of hero holding the artifact(s).
  2484. * @param artifactSlot The worn slot ID of the combination- or constituent artifact.
  2485. * @param assemble True for assembly operation, false for disassembly.
  2486. * @param assembleTo If assemble is true, this represents the artifact ID of the combination
  2487. * artifact to assemble to. Otherwise it's not used.
  2488. */
  2489. bool CGameHandler::assembleArtifacts (si32 heroID, ui16 artifactSlot, bool assemble, ui32 assembleTo)
  2490. {
  2491. if (artifactSlot < 0 || artifactSlot > 18) {
  2492. complain("Illegal artifact slot.");
  2493. return false;
  2494. }
  2495. CGHeroInstance *hero = gs->getHero(heroID);
  2496. const CArtifact *destArtifact = hero->getArt(artifactSlot);
  2497. SetHeroArtifacts sha;
  2498. sha.hid = heroID;
  2499. sha.artifacts = hero->artifacts;
  2500. sha.artifWorn = hero->artifWorn;
  2501. if (assemble) {
  2502. if (VLC->arth->artifacts.size() < assembleTo) {
  2503. complain("Illegal artifact to assemble to.");
  2504. return false;
  2505. }
  2506. if (!destArtifact->canBeAssembledTo(hero->artifWorn, assembleTo)) {
  2507. complain("Artifact cannot be assembled.");
  2508. return false;
  2509. }
  2510. const CArtifact &artifact = VLC->arth->artifacts[assembleTo];
  2511. if (artifact.constituents == NULL) {
  2512. complain("Not a combinational artifact.");
  2513. return false;
  2514. }
  2515. // Perform assembly.
  2516. bool destConsumed = false; // Determines which constituent that will be counted for together with the artifact.
  2517. const bool destSpecific = vstd::contains(artifact.possibleSlots, artifactSlot); // Prefer the chosen slot as the location for the assembled artifact.
  2518. BOOST_FOREACH(ui32 constituentID, *artifact.constituents) {
  2519. if (destSpecific && constituentID == destArtifact->id) {
  2520. sha.artifWorn[artifactSlot] = assembleTo;
  2521. destConsumed = true;
  2522. continue;
  2523. }
  2524. bool found = false;
  2525. for (std::map<ui16, ui32>::iterator it = sha.artifWorn.begin(); it != sha.artifWorn.end(); ++it) {
  2526. if (it->second == constituentID) { // Found possible constituent to substitute.
  2527. if (destSpecific && !destConsumed && it->second == destArtifact->id) {
  2528. // Find the specified destination for assembled artifact.
  2529. if (it->first == artifactSlot) {
  2530. it->second = assembleTo;
  2531. destConsumed = true;
  2532. found = true;
  2533. break;
  2534. }
  2535. } else {
  2536. // Either put the assembled artifact in a fitting spot, or put a lock.
  2537. if (!destSpecific && !destConsumed && vstd::contains(artifact.possibleSlots, it->first)) {
  2538. it->second = assembleTo;
  2539. destConsumed = true;
  2540. } else {
  2541. it->second = 145;
  2542. }
  2543. found = true;
  2544. break;
  2545. }
  2546. }
  2547. }
  2548. if (!found) {
  2549. complain("Constituent missing.");
  2550. return false;
  2551. }
  2552. }
  2553. } else {
  2554. // Perform disassembly.
  2555. bool destConsumed = false; // Determines which constituent that will be counted for together with the artifact.
  2556. BOOST_FOREACH(ui32 constituentID, *destArtifact->constituents) {
  2557. const CArtifact &constituent = VLC->arth->artifacts[constituentID];
  2558. if (!destConsumed && vstd::contains(constituent.possibleSlots, artifactSlot)) {
  2559. sha.artifWorn[artifactSlot] = constituentID;
  2560. destConsumed = true;
  2561. } else {
  2562. BOOST_REVERSE_FOREACH(ui16 slotID, constituent.possibleSlots) {
  2563. if (vstd::contains(sha.artifWorn, slotID) && sha.artifWorn[slotID] == 145) {
  2564. sha.artifWorn[slotID] = constituentID;
  2565. break;
  2566. }
  2567. }
  2568. }
  2569. }
  2570. }
  2571. sendAndApply(&sha);
  2572. return true;
  2573. }
  2574. bool CGameHandler::buyArtifact( ui32 hid, si32 aid )
  2575. {
  2576. CGHeroInstance *hero = gs->getHero(hid);
  2577. CGTownInstance *town = hero->visitedTown;
  2578. if(aid==0) //spellbook
  2579. {
  2580. if(!vstd::contains(town->builtBuildings,si32(0)) && complain("Cannot buy a spellbook, no mage guild in the town!")
  2581. || getResource(hero->getOwner(),6)<500 && complain("Cannot buy a spellbook, not enough gold!")
  2582. || hero->getArt(17) && complain("Cannot buy a spellbook, hero already has a one!")
  2583. )
  2584. return false;
  2585. giveResource(hero->getOwner(),6,-500);
  2586. giveHeroArtifact(0,hid,17);
  2587. giveSpells(town,hero);
  2588. return true;
  2589. }
  2590. else if(aid < 7 && aid > 3) //war machine
  2591. {
  2592. int price = VLC->arth->artifacts[aid].price;
  2593. if(vstd::contains(hero->artifWorn,ui16(9+aid)) && complain("Hero already has this machine!")
  2594. || !vstd::contains(town->builtBuildings,si32(16)) && complain("No blackismith!")
  2595. || gs->getPlayer(hero->getOwner())->resources[6] < price && complain("Not enough gold!") //no gold
  2596. || (!(town->subID == 6 && vstd::contains(town->builtBuildings,si32(22) ) )
  2597. && town->town->warMachine!= aid ) && complain("This machine is unavailable here!") )
  2598. {
  2599. return false;
  2600. }
  2601. giveResource(hero->getOwner(),6,-price);
  2602. giveHeroArtifact(aid,hid,9+aid);
  2603. return true;
  2604. }
  2605. return false;
  2606. }
  2607. bool CGameHandler::tradeResources( ui32 val, ui8 player, ui32 id1, ui32 id2 )
  2608. {
  2609. val = std::min(si32(val),gs->getPlayer(player)->resources[id1]);
  2610. double yield = (double)gs->resVals[id1] * val * gs->getMarketEfficiency(player);
  2611. yield /= gs->resVals[id2];
  2612. SetResource sr;
  2613. sr.player = player;
  2614. sr.resid = id1;
  2615. sr.val = gs->getPlayer(player)->resources[id1] - val;
  2616. sendAndApply(&sr);
  2617. sr.resid = id2;
  2618. sr.val = gs->getPlayer(player)->resources[id2] + (int)yield;
  2619. sendAndApply(&sr);
  2620. return true;
  2621. }
  2622. bool CGameHandler::sendResources(ui32 val, ui8 player, ui32 r1, ui32 r2)
  2623. {
  2624. const PlayerState *p2 = gs->getPlayer(r2, false);
  2625. if(!p2 || p2->status != PlayerState::INGAME)
  2626. {
  2627. complain("Dest player must be in game!");
  2628. return false;
  2629. }
  2630. si32 curRes1 = gs->getPlayer(player)->resources[r1], curRes2 = gs->getPlayer(r2)->resources[r1];
  2631. val = std::min(si32(val),curRes1);
  2632. SetResource sr;
  2633. sr.player = player;
  2634. sr.resid = r1;
  2635. sr.val = curRes1 - val;
  2636. sendAndApply(&sr);
  2637. sr.player = r2;
  2638. sr.val = curRes2 + val;
  2639. sendAndApply(&sr);
  2640. return true;
  2641. }
  2642. bool CGameHandler::setFormation( si32 hid, ui8 formation )
  2643. {
  2644. gs->getHero(hid)-> formation = formation;
  2645. return true;
  2646. }
  2647. bool CGameHandler::hireHero( ui32 tid, ui8 hid )
  2648. {
  2649. CGTownInstance *t = gs->getTown(tid);
  2650. if(!vstd::contains(t->builtBuildings,5) && complain("No tavern!")
  2651. || gs->getPlayer(t->tempOwner)->resources[6]<2500 && complain("Not enough gold for buying hero!")
  2652. || t->visitingHero && complain("There is visiting hero - no place!")
  2653. || getHeroCount(t->tempOwner,false) >= 8 && complain("Cannot hire hero, only 8 wandering heroes are allowed!")
  2654. )
  2655. return false;
  2656. CGHeroInstance *nh = gs->getPlayer(t->tempOwner)->availableHeroes[hid];
  2657. assert(nh);
  2658. HeroRecruited hr;
  2659. hr.tid = tid;
  2660. hr.hid = nh->subID;
  2661. hr.player = t->tempOwner;
  2662. hr.tile = t->pos - int3(1,0,0);
  2663. sendAndApply(&hr);
  2664. std::map<ui32,CGHeroInstance *> pool = gs->hpool.heroesPool;
  2665. for ( std::map<ui8, PlayerState>::iterator i=gs->players.begin() ; i!=gs->players.end();i++)
  2666. for(std::vector<CGHeroInstance *>::iterator j = i->second.availableHeroes.begin(); j != i->second.availableHeroes.end(); j++)
  2667. if(*j)
  2668. pool.erase((**j).subID);
  2669. SetAvailableHeroes sah;
  2670. CGHeroInstance *h1 = gs->hpool.pickHeroFor(false,t->tempOwner,t->town, pool),
  2671. *h2 = gs->getPlayer(t->tempOwner)->availableHeroes[!hid];
  2672. (hid ? sah.hid2 : sah.hid1) = h1 ? h1->subID : -1;
  2673. (hid ? sah.hid1 : sah.hid2) = h2 ? h2->subID : -1;
  2674. sah.player = t->tempOwner;
  2675. sah.flags = hid+1;
  2676. sendAndApply(&sah);
  2677. SetResource sr;
  2678. sr.player = t->tempOwner;
  2679. sr.resid = 6;
  2680. sr.val = gs->getPlayer(t->tempOwner)->resources[6] - 2500;
  2681. sendAndApply(&sr);
  2682. vistiCastleObjects (t, nh);
  2683. giveSpells (t,nh);
  2684. return true;
  2685. }
  2686. bool CGameHandler::queryReply( ui32 qid, ui32 answer )
  2687. {
  2688. boost::unique_lock<boost::recursive_mutex> lock(gsm);
  2689. if(vstd::contains(callbacks,qid))
  2690. {
  2691. CFunctionList<void(ui32)> callb = callbacks[qid];
  2692. callbacks.erase(qid);
  2693. if(callb)
  2694. callb(answer);
  2695. }
  2696. else if(vstd::contains(garrisonCallbacks,qid))
  2697. {
  2698. if(garrisonCallbacks[qid])
  2699. garrisonCallbacks[qid]();
  2700. garrisonCallbacks.erase(qid);
  2701. allowedExchanges.erase(qid);
  2702. }
  2703. else
  2704. {
  2705. tlog1 << "Unknown query reply...\n";
  2706. return false;
  2707. }
  2708. return true;
  2709. }
  2710. bool CGameHandler::makeBattleAction( BattleAction &ba )
  2711. {
  2712. tlog1 << "\tMaking action of type " << ba.actionType << std::endl;
  2713. bool ok = true;
  2714. switch(ba.actionType)
  2715. {
  2716. case 2: //walk
  2717. {
  2718. sendAndApply(&StartAction(ba)); //start movement
  2719. moveStack(ba.stackNumber,ba.destinationTile); //move
  2720. sendAndApply(&EndAction());
  2721. break;
  2722. }
  2723. case 3: //defend
  2724. case 8: //wait
  2725. {
  2726. sendAndApply(&StartAction(ba));
  2727. sendAndApply(&EndAction());
  2728. break;
  2729. }
  2730. case 4: //retreat/flee
  2731. {
  2732. if( !gs->battleCanFlee(ba.side ? gs->curB->side2 : gs->curB->side1) )
  2733. break;
  2734. //TODO: remove retreating hero from map and place it in recruitment list
  2735. BattleResult *br = new BattleResult;
  2736. br->result = 1;
  2737. br->winner = !ba.side; //fleeing side loses
  2738. gs->curB->calculateCasualties(br->casualties);
  2739. giveExp(*br);
  2740. battleResult.set(br);
  2741. break;
  2742. }
  2743. case 6: //walk or attack
  2744. {
  2745. sendAndApply(&StartAction(ba)); //start movement and attack
  2746. int startingPos = gs->curB->getStack(ba.stackNumber)->position;
  2747. int distance = moveStack(ba.stackNumber, ba.destinationTile);
  2748. CStack *curStack = gs->curB->getStack(ba.stackNumber),
  2749. *stackAtEnd = gs->curB->getStackT(ba.additionalInfo);
  2750. if(curStack->position != ba.destinationTile //we wasn't able to reach destination tile
  2751. && !(curStack->doubleWide()
  2752. && ( curStack->position == ba.destinationTile + (curStack->attackerOwned ? +1 : -1 ) )
  2753. ) //nor occupy specified hex
  2754. )
  2755. {
  2756. std::string problem = "We cannot move this stack to its destination " + curStack->type->namePl;
  2757. tlog3 << problem << std::endl;
  2758. complain(problem);
  2759. ok = false;
  2760. sendAndApply(&EndAction());
  2761. break;
  2762. }
  2763. if(curStack->ID == stackAtEnd->ID) //we should just move, it will be handled by following check
  2764. {
  2765. stackAtEnd = NULL;
  2766. }
  2767. if(!stackAtEnd)
  2768. {
  2769. std::ostringstream problem;
  2770. problem << "There is no stack on " << ba.additionalInfo << " tile (no attack)!";
  2771. std::string probl = problem.str();
  2772. tlog3 << probl << std::endl;
  2773. complain(probl);
  2774. ok = false;
  2775. sendAndApply(&EndAction());
  2776. break;
  2777. }
  2778. ui16 curpos = curStack->position,
  2779. enemypos = stackAtEnd->position;
  2780. if( !(
  2781. (BattleInfo::mutualPosition(curpos, enemypos) >= 0) //front <=> front
  2782. || (curStack->doubleWide() //back <=> front
  2783. && BattleInfo::mutualPosition(curpos + (curStack->attackerOwned ? -1 : 1), enemypos) >= 0)
  2784. || (stackAtEnd->doubleWide() //front <=> back
  2785. && BattleInfo::mutualPosition(curpos, enemypos + (stackAtEnd->attackerOwned ? -1 : 1)) >= 0)
  2786. || (stackAtEnd->doubleWide() && curStack->doubleWide()//back <=> back
  2787. && BattleInfo::mutualPosition(curpos + (curStack->attackerOwned ? -1 : 1), enemypos + (stackAtEnd->attackerOwned ? -1 : 1)) >= 0)
  2788. )
  2789. )
  2790. {
  2791. tlog3 << "Attack cannot be performed!";
  2792. sendAndApply(&EndAction());
  2793. ok = false;
  2794. }
  2795. //attack
  2796. BattleAttack bat;
  2797. prepareAttack(bat, curStack, stackAtEnd, distance);
  2798. sendAndApply(&bat);
  2799. handleAfterAttackCasting(bat);
  2800. //counterattack
  2801. if(!curStack->hasBonusOfType(Bonus::BLOCKS_RETALIATION)
  2802. && stackAtEnd->alive()
  2803. && ( stackAtEnd->counterAttacks > 0 || stackAtEnd->hasBonusOfType(Bonus::UNLIMITED_RETALIATIONS) )
  2804. && !stackAtEnd->hasBonusOfType(Bonus::SIEGE_WEAPON)
  2805. && !stackAtEnd->hasBonusOfType(Bonus::HYPNOTIZED))
  2806. {
  2807. prepareAttack(bat, stackAtEnd, curStack, 0);
  2808. bat.flags |= 2;
  2809. sendAndApply(&bat);
  2810. handleAfterAttackCasting(bat);
  2811. }
  2812. //second attack
  2813. if(curStack->valOfBonuses(Bonus::ADDITIONAL_ATTACK) > 0
  2814. && !curStack->hasBonusOfType(Bonus::SHOOTER)
  2815. && curStack->alive()
  2816. && stackAtEnd->alive() )
  2817. {
  2818. bat.flags = 0;
  2819. prepareAttack(bat, curStack, stackAtEnd, 0);
  2820. sendAndApply(&bat);
  2821. handleAfterAttackCasting(bat);
  2822. }
  2823. //return
  2824. if(curStack->hasBonusOfType(Bonus::RETURN_AFTER_STRIKE) && startingPos != curStack->position && curStack->alive())
  2825. {
  2826. moveStack(ba.stackNumber, startingPos);
  2827. //NOTE: curStack->ID == ba.stackNumber (rev 1431)
  2828. }
  2829. sendAndApply(&EndAction());
  2830. break;
  2831. }
  2832. case 7: //shoot
  2833. {
  2834. CStack *curStack = gs->curB->getStack(ba.stackNumber),
  2835. *destStack= gs->curB->getStackT(ba.destinationTile);
  2836. if( !gs->battleCanShoot(ba.stackNumber, ba.destinationTile) )
  2837. break;
  2838. sendAndApply(&StartAction(ba)); //start shooting
  2839. BattleAttack bat;
  2840. bat.flags |= 1;
  2841. prepareAttack(bat, curStack, destStack, 0);
  2842. sendAndApply(&bat);
  2843. if(curStack->valOfBonuses(Bonus::ADDITIONAL_ATTACK) > 0 //if unit shots twice let's make another shot
  2844. && curStack->alive()
  2845. && destStack->alive()
  2846. && curStack->shots
  2847. )
  2848. {
  2849. prepareAttack(bat, curStack, destStack, 0);
  2850. sendAndApply(&bat);
  2851. handleAfterAttackCasting(bat);
  2852. }
  2853. sendAndApply(&EndAction());
  2854. break;
  2855. }
  2856. case 9: //catapult
  2857. {
  2858. sendAndApply(&StartAction(ba));
  2859. const CGHeroInstance * attackingHero = gs->curB->heroes[ba.side];
  2860. CHeroHandler::SBallisticsLevelInfo sbi = VLC->heroh->ballistics[attackingHero->getSecSkillLevel(20)]; //artillery
  2861. int attackedPart = gs->curB->hexToWallPart(ba.destinationTile);
  2862. if(attackedPart == -1)
  2863. {
  2864. complain("catapult tried to attack non-catapultable hex!");
  2865. break;
  2866. }
  2867. int wallInitHP = gs->curB->si.wallState[attackedPart];
  2868. int dmgAlreadyDealt = 0; //in successive iterations damage is dealt but not yet substracted from wall's HPs
  2869. for(int g=0; g<sbi.shots; ++g)
  2870. {
  2871. if(wallInitHP + dmgAlreadyDealt == 3) //it's not destroyed
  2872. continue;
  2873. CatapultAttack ca; //package for clients
  2874. std::pair< std::pair< ui8, si16 >, ui8> attack; //<< attackedPart , destination tile >, damageDealt >
  2875. attack.first.first = attackedPart;
  2876. attack.first.second = ba.destinationTile;
  2877. attack.second = 0;
  2878. int chanceForHit = 0;
  2879. int dmgChance[3] = {sbi.noDmg, sbi.oneDmg, sbi.twoDmg}; //dmgChance[i] - chance for doing i dmg when hit is successful
  2880. switch(attackedPart)
  2881. {
  2882. case 0: //keep
  2883. chanceForHit = sbi.keep;
  2884. break;
  2885. case 1: //bottom tower
  2886. case 6: //upper tower
  2887. chanceForHit = sbi.tower;
  2888. break;
  2889. case 2: //bottom wall
  2890. case 3: //below gate
  2891. case 4: //over gate
  2892. case 5: //upper wall
  2893. chanceForHit = sbi.wall;
  2894. break;
  2895. case 7: //gate
  2896. chanceForHit = sbi.gate;
  2897. break;
  2898. }
  2899. if(rand()%100 <= chanceForHit) //hit is successful
  2900. {
  2901. int dmgRand = rand()%100;
  2902. //accumulating dmgChance
  2903. dmgChance[1] += dmgChance[0];
  2904. dmgChance[2] += dmgChance[1];
  2905. //calculating dealt damage
  2906. for(int v = 0; v < ARRAY_COUNT(dmgChance); ++v)
  2907. {
  2908. if(dmgRand <= dmgChance[v])
  2909. {
  2910. attack.second = std::min(3 - dmgAlreadyDealt - wallInitHP, v);
  2911. dmgAlreadyDealt += attack.second;
  2912. break;
  2913. }
  2914. }
  2915. //removing creatures in turrets / keep if one is destroyed
  2916. if(attack.second > 0 && (attackedPart == 0 || attackedPart == 1 || attackedPart == 6))
  2917. {
  2918. int posRemove = -1;
  2919. switch(attackedPart)
  2920. {
  2921. case 0: //keep
  2922. posRemove = -2;
  2923. break;
  2924. case 1: //bottom tower
  2925. posRemove = -3;
  2926. break;
  2927. case 6: //upper tower
  2928. posRemove = -4;
  2929. break;
  2930. }
  2931. BattleStacksRemoved bsr;
  2932. for(int g=0; g<gs->curB->stacks.size(); ++g)
  2933. {
  2934. if(gs->curB->stacks[g]->position == posRemove)
  2935. {
  2936. bsr.stackIDs.insert( gs->curB->stacks[g]->ID );
  2937. break;
  2938. }
  2939. }
  2940. sendAndApply(&bsr);
  2941. }
  2942. }
  2943. ca.attacker = ba.stackNumber;
  2944. ca.attackedParts.insert(attack);
  2945. sendAndApply(&ca);
  2946. }
  2947. sendAndApply(&EndAction());
  2948. break;
  2949. }
  2950. case 12: //healing
  2951. {
  2952. static const int healingPerLevel[] = {50, 50, 75, 100};
  2953. sendAndApply(&StartAction(ba));
  2954. const CGHeroInstance * attackingHero = gs->curB->heroes[ba.side];
  2955. CStack *healer = gs->curB->getStack(ba.stackNumber),
  2956. *destStack = gs->curB->getStackT(ba.destinationTile);
  2957. if(healer == NULL || destStack == NULL || !healer->hasBonusOfType(Bonus::HEALER))
  2958. {
  2959. complain("There is either no healer, no destination, or healer cannot heal :P");
  2960. }
  2961. int maxHealable = destStack->MaxHealth() - destStack->firstHPleft;
  2962. int maxiumHeal = healingPerLevel[ attackingHero->getSecSkillLevel(27) ];
  2963. int healed = std::min(maxHealable, maxiumHeal);
  2964. if(healed == 0)
  2965. {
  2966. //nothing to heal.. should we complain?
  2967. }
  2968. else
  2969. {
  2970. StacksHealedOrResurrected shr;
  2971. shr.lifeDrain = false;
  2972. StacksHealedOrResurrected::HealInfo hi;
  2973. hi.healedHP = healed;
  2974. hi.lowLevelResurrection = 0;
  2975. hi.stackID = destStack->ID;
  2976. shr.healedStacks.push_back(hi);
  2977. sendAndApply(&shr);
  2978. }
  2979. sendAndApply(&EndAction());
  2980. break;
  2981. }
  2982. }
  2983. if(ba.stackNumber == gs->curB->activeStack || battleResult.get()) //active stack has moved or battle has finished
  2984. battleMadeAction.setn(true);
  2985. return ok;
  2986. }
  2987. void CGameHandler::playerMessage( ui8 player, const std::string &message )
  2988. {
  2989. bool cheated=true;
  2990. sendAndApply(&PlayerMessage(player,message));
  2991. if(message == "vcmiistari") //give all spells and 999 mana
  2992. {
  2993. SetMana sm;
  2994. ChangeSpells cs;
  2995. SetHeroArtifacts sha;
  2996. CGHeroInstance *h = gs->getHero(gs->getPlayer(player)->currentSelection);
  2997. if(!h && complain("Cannot realize cheat, no hero selected!")) return;
  2998. sm.hid = cs.hid = h->id;
  2999. //give all spells
  3000. cs.learn = 1;
  3001. for(int i=0;i<VLC->spellh->spells.size();i++)
  3002. {
  3003. if(!VLC->spellh->spells[i].creatureAbility)
  3004. cs.spells.insert(i);
  3005. }
  3006. //give mana
  3007. sm.val = 999;
  3008. if(!h->getArt(17)) //hero doesn't have spellbook
  3009. {
  3010. //give spellbook
  3011. sha.hid = h->id;
  3012. sha.artifacts = h->artifacts;
  3013. sha.artifWorn = h->artifWorn;
  3014. VLC->arth->equipArtifact(sha.artifWorn, 17, 0);
  3015. sendAndApply(&sha);
  3016. }
  3017. sendAndApply(&cs);
  3018. sendAndApply(&sm);
  3019. }
  3020. else if(message == "vcmiainur") //gives 5 archangels into each slot
  3021. {
  3022. CGHeroInstance *hero = gs->getHero(gs->getPlayer(player)->currentSelection);
  3023. if(!hero) return;
  3024. SetGarrisons sg;
  3025. CCreatureSet &newArmy = sg.garrs[hero->id];
  3026. newArmy = hero->getArmy();
  3027. for(int i=0; i<ARMY_SIZE; i++)
  3028. if(newArmy.slotEmpty(i))
  3029. newArmy.addToSlot(i, CStackInstance(13,5));
  3030. sendAndApply(&sg);
  3031. }
  3032. else if(message == "vcmiangband") //gives 10 black knight into each slot
  3033. {
  3034. CGHeroInstance *hero = gs->getHero(gs->getPlayer(player)->currentSelection);
  3035. if(!hero) return;
  3036. SetGarrisons sg;
  3037. CCreatureSet &newArmy = sg.garrs[hero->id];
  3038. newArmy = hero->getArmy();
  3039. for(int i=0; i<ARMY_SIZE; i++)
  3040. if(newArmy.slotEmpty(i))
  3041. newArmy.addToSlot(i, CStackInstance(66,10));
  3042. sendAndApply(&sg);
  3043. }
  3044. else if(message == "vcminoldor") //all war machines
  3045. {
  3046. CGHeroInstance *hero = gs->getHero(gs->getPlayer(player)->currentSelection);
  3047. if(!hero) return;
  3048. SetHeroArtifacts sha;
  3049. sha.hid = hero->id;
  3050. sha.artifacts = hero->artifacts;
  3051. sha.artifWorn = hero->artifWorn;
  3052. VLC->arth->equipArtifact(sha.artifWorn, 13, 4);
  3053. VLC->arth->equipArtifact(sha.artifWorn, 14, 5);
  3054. VLC->arth->equipArtifact(sha.artifWorn, 15, 6);
  3055. sendAndApply(&sha);
  3056. }
  3057. else if(message == "vcminahar") //1000000 movement points
  3058. {
  3059. CGHeroInstance *hero = gs->getHero(gs->getPlayer(player)->currentSelection);
  3060. if(!hero) return;
  3061. SetMovePoints smp;
  3062. smp.hid = hero->id;
  3063. smp.val = 1000000;
  3064. sendAndApply(&smp);
  3065. }
  3066. else if(message == "vcmiformenos") //give resources
  3067. {
  3068. SetResources sr;
  3069. sr.player = player;
  3070. sr.res = gs->getPlayer(player)->resources;
  3071. for(int i=0;i<7;i++)
  3072. sr.res[i] += 100;
  3073. sr.res[6] += 19900;
  3074. sendAndApply(&sr);
  3075. }
  3076. else if(message == "vcmieagles") //reveal FoW
  3077. {
  3078. FoWChange fc;
  3079. fc.mode = 1;
  3080. fc.player = player;
  3081. for(int i=0;i<gs->map->width;i++)
  3082. for(int j=0;j<gs->map->height;j++)
  3083. for(int k=0;k<gs->map->twoLevel+1;k++)
  3084. if(!gs->getPlayer(fc.player)->fogOfWarMap[i][j][k])
  3085. fc.tiles.insert(int3(i,j,k));
  3086. sendAndApply(&fc);
  3087. }
  3088. else if(message == "vcmiglorfindel")
  3089. {
  3090. CGHeroInstance *hero = gs->getHero(gs->getPlayer(player)->currentSelection);
  3091. changePrimSkill(hero->id,4,VLC->heroh->reqExp(hero->level+1) - VLC->heroh->reqExp(hero->level));
  3092. }
  3093. else
  3094. cheated = false;
  3095. if(cheated)
  3096. {
  3097. sendAndApply(&SystemMessage(VLC->generaltexth->allTexts[260]));
  3098. }
  3099. }
  3100. static ui32 calculateHealedHP(const CGHeroInstance * caster, const CSpell * spell, const CStack * stack)
  3101. {
  3102. switch(spell->id)
  3103. {
  3104. case 37: //cure
  3105. {
  3106. int healedHealth = caster->getPrimSkillLevel(2) * 5 + spell->powers[caster->getSpellSchoolLevel(spell)];
  3107. return std::min<ui32>(healedHealth, stack->MaxHealth() - stack->firstHPleft);
  3108. break;
  3109. }
  3110. case 38: //resurrection
  3111. {
  3112. int healedHealth = caster->getPrimSkillLevel(2) * 50 + spell->powers[caster->getSpellSchoolLevel(spell)];
  3113. return std::min<ui32>(healedHealth, stack->MaxHealth() - stack->firstHPleft + stack->baseAmount * stack->MaxHealth());
  3114. break;
  3115. }
  3116. case 39: //animate dead
  3117. {
  3118. int healedHealth = caster->getPrimSkillLevel(2) * 50 + spell->powers[caster->getSpellSchoolLevel(spell)];
  3119. return std::min<ui32>(healedHealth, stack->MaxHealth() - stack->firstHPleft + stack->baseAmount * stack->MaxHealth());
  3120. break;
  3121. }
  3122. }
  3123. //we shouldn't be here
  3124. tlog1 << "calculateHealedHP called for non-healing spell: " << spell->name << std::endl;
  3125. return 0;
  3126. }
  3127. static std::vector<ui32> calculateResistedStacks(const CSpell * sp, const CGHeroInstance * caster, const CGHeroInstance * hero2, const std::set<CStack*> affectedCreatures)
  3128. {
  3129. std::vector<ui32> ret;
  3130. for(std::set<CStack*>::const_iterator it = affectedCreatures.begin(); it != affectedCreatures.end(); ++it)
  3131. {
  3132. if ((*it)->hasBonusOfType(Bonus::SPELL_IMMUNITY, sp->id) //100% sure spell immunity
  3133. || ( (*it)->hasBonusOfType(Bonus::LEVEL_SPELL_IMMUNITY) &&
  3134. (*it)->valOfBonuses(Bonus::LEVEL_SPELL_IMMUNITY) >= sp->level) ) //some creature abilities have level 0
  3135. {
  3136. ret.push_back((*it)->ID);
  3137. continue;
  3138. }
  3139. //non-negative spells on friendly stacks should always succeed, unless immune
  3140. if(sp->positiveness >= 0 && (*it)->owner == caster->tempOwner)
  3141. continue;
  3142. const CGHeroInstance * bonusHero; //hero we should take bonuses from
  3143. if(caster && (*it)->owner == caster->tempOwner)
  3144. bonusHero = caster;
  3145. else
  3146. bonusHero = hero2;
  3147. int prob = (*it)->valOfBonuses(Bonus::MAGIC_RESISTANCE); //probability of resistance in %
  3148. if(bonusHero)
  3149. {
  3150. //bonusHero's resistance support (secondary skils and artifacts)
  3151. prob += bonusHero->valOfBonuses(Bonus::MAGIC_RESISTANCE);
  3152. switch(bonusHero->getSecSkillLevel(26)) //resistance
  3153. {
  3154. case 1: //basic
  3155. prob += 5;
  3156. break;
  3157. case 2: //advanced
  3158. prob += 10;
  3159. break;
  3160. case 3: //expert
  3161. prob += 20;
  3162. break;
  3163. }
  3164. }
  3165. if(prob > 100) prob = 100;
  3166. if(rand()%100 < prob) //immunity from resistance
  3167. ret.push_back((*it)->ID);
  3168. }
  3169. if(sp->id == 60) //hypnotize
  3170. {
  3171. for(std::set<CStack*>::const_iterator it = affectedCreatures.begin(); it != affectedCreatures.end(); ++it)
  3172. {
  3173. if( (*it)->hasBonusOfType(Bonus::SPELL_IMMUNITY, sp->id) //100% sure spell immunity
  3174. || ( (*it)->count - 1 ) * (*it)->MaxHealth() + (*it)->firstHPleft
  3175. >
  3176. caster->getPrimSkillLevel(2) * 25 + sp->powers[caster->getSpellSchoolLevel(sp)]
  3177. )
  3178. {
  3179. ret.push_back((*it)->ID);
  3180. }
  3181. }
  3182. }
  3183. return ret;
  3184. }
  3185. void CGameHandler::handleSpellCasting( int spellID, int spellLvl, int destination, ui8 casterSide, ui8 casterColor,
  3186. const CGHeroInstance * caster, const CGHeroInstance * secHero, int usedSpellPower )
  3187. {
  3188. CSpell *spell = &VLC->spellh->spells[spellID];
  3189. SpellCast sc;
  3190. sc.side = casterSide;
  3191. sc.id = spellID;
  3192. sc.skill = spellLvl;
  3193. sc.tile = destination;
  3194. sc.dmgToDisplay = 0;
  3195. sc.castedByHero = (bool)caster;
  3196. //calculating affected creatures for all spells
  3197. std::set<CStack*> attackedCres = gs->curB->getAttackedCreatures(spell, spellLvl, casterColor, destination);
  3198. for(std::set<CStack*>::const_iterator it = attackedCres.begin(); it != attackedCres.end(); ++it)
  3199. {
  3200. sc.affectedCres.insert((*it)->ID);
  3201. }
  3202. //checking if creatures resist
  3203. sc.resisted = calculateResistedStacks(spell, caster, secHero, attackedCres);
  3204. //calculating dmg to display
  3205. for(std::set<CStack*>::iterator it = attackedCres.begin(); it != attackedCres.end(); ++it)
  3206. {
  3207. if(vstd::contains(sc.resisted, (*it)->ID)) //this creature resisted the spell
  3208. continue;
  3209. sc.dmgToDisplay += gs->curB->calculateSpellDmg(spell, caster, *it, spellLvl, usedSpellPower);
  3210. }
  3211. sendAndApply(&sc);
  3212. //applying effects
  3213. switch(spellID)
  3214. {
  3215. case 15: //magic arrow
  3216. case 16: //ice bolt
  3217. case 17: //lightning bolt
  3218. case 18: //implosion
  3219. case 20: //frost ring
  3220. case 21: //fireball
  3221. case 22: //inferno
  3222. case 23: //meteor shower
  3223. case 24: //death ripple
  3224. case 25: //destroy undead
  3225. case 26: //armageddon
  3226. case 77: //Thunderbolt (thunderbirds)
  3227. {
  3228. StacksInjured si;
  3229. for(std::set<CStack*>::iterator it = attackedCres.begin(); it != attackedCres.end(); ++it)
  3230. {
  3231. if(vstd::contains(sc.resisted, (*it)->ID)) //this creature resisted the spell
  3232. continue;
  3233. BattleStackAttacked bsa;
  3234. bsa.flags |= 2;
  3235. bsa.effect = spell->mainEffectAnim;
  3236. bsa.damageAmount = gs->curB->calculateSpellDmg(spell, caster, *it, spellLvl, usedSpellPower);
  3237. bsa.stackAttacked = (*it)->ID;
  3238. bsa.attackerID = -1;
  3239. prepareAttacked(bsa,*it);
  3240. si.stacks.push_back(bsa);
  3241. }
  3242. if(!si.stacks.empty())
  3243. sendAndApply(&si);
  3244. break;
  3245. }
  3246. case 27: //shield
  3247. case 28: //air shield
  3248. case 29: //fire shield
  3249. case 30: //protection from air
  3250. case 31: //protection from fire
  3251. case 32: //protection from water
  3252. case 33: //protection from earth
  3253. case 34: //anti-magic
  3254. case 41: //bless
  3255. case 42: //curse
  3256. case 43: //bloodlust
  3257. case 44: //precision
  3258. case 45: //weakness
  3259. case 46: //stone skin
  3260. case 47: //disrupting ray
  3261. case 48: //prayer
  3262. case 49: //mirth
  3263. case 50: //sorrow
  3264. case 51: //fortune
  3265. case 52: //misfortune
  3266. case 53: //haste
  3267. case 54: //slow
  3268. case 55: //slayer
  3269. case 56: //frenzy
  3270. case 58: //counterstrike
  3271. case 59: //berserk
  3272. case 60: //hypnotize
  3273. case 61: //forgetfulness
  3274. case 62: //blind
  3275. {
  3276. SetStackEffect sse;
  3277. for(std::set<CStack*>::iterator it = attackedCres.begin(); it != attackedCres.end(); ++it)
  3278. {
  3279. if(vstd::contains(sc.resisted, (*it)->ID)) //this creature resisted the spell
  3280. continue;
  3281. sse.stacks.push_back((*it)->ID);
  3282. }
  3283. sse.effect.id = spellID;
  3284. sse.effect.level = spellLvl;
  3285. sse.effect.turnsRemain = BattleInfo::calculateSpellDuration(spell, caster);
  3286. if(!sse.stacks.empty())
  3287. sendAndApply(&sse);
  3288. break;
  3289. }
  3290. case 63: //teleport
  3291. {
  3292. BattleStackMoved bsm;
  3293. bsm.distance = -1;
  3294. bsm.stack = gs->curB->activeStack;
  3295. bsm.ending = true;
  3296. bsm.tile = destination;
  3297. bsm.teleporting = true;
  3298. sendAndApply(&bsm);
  3299. break;
  3300. }
  3301. case 37: //cure
  3302. case 38: //resurrection
  3303. case 39: //animate dead
  3304. {
  3305. StacksHealedOrResurrected shr;
  3306. shr.lifeDrain = false;
  3307. for(std::set<CStack*>::iterator it = attackedCres.begin(); it != attackedCres.end(); ++it)
  3308. {
  3309. if(vstd::contains(sc.resisted, (*it)->ID) //this creature resisted the spell
  3310. || (spellID == 39 && !(*it)->hasBonusOfType(Bonus::UNDEAD)) //we try to cast animate dead on living stack
  3311. )
  3312. continue;
  3313. StacksHealedOrResurrected::HealInfo hi;
  3314. hi.stackID = (*it)->ID;
  3315. hi.healedHP = calculateHealedHP(caster, spell, *it);
  3316. hi.lowLevelResurrection = spellLvl <= 1;
  3317. shr.healedStacks.push_back(hi);
  3318. }
  3319. if(!shr.healedStacks.empty())
  3320. sendAndApply(&shr);
  3321. break;
  3322. }
  3323. case 64: //remove obstacle
  3324. {
  3325. ObstaclesRemoved obr;
  3326. for(int g=0; g<gs->curB->obstacles.size(); ++g)
  3327. {
  3328. std::vector<int> blockedHexes = VLC->heroh->obstacles[gs->curB->obstacles[g].ID].getBlocked(gs->curB->obstacles[g].pos);
  3329. if(vstd::contains(blockedHexes, destination)) //this obstacle covers given hex
  3330. {
  3331. obr.obstacles.insert(gs->curB->obstacles[g].uniqueID);
  3332. }
  3333. }
  3334. if(!obr.obstacles.empty())
  3335. sendAndApply(&obr);
  3336. break;
  3337. }
  3338. }
  3339. }
  3340. bool CGameHandler::makeCustomAction( BattleAction &ba )
  3341. {
  3342. switch(ba.actionType)
  3343. {
  3344. case 1: //hero casts spell
  3345. {
  3346. const CGHeroInstance *h = gs->curB->heroes[ba.side];
  3347. const CGHeroInstance *secondHero = gs->curB->heroes[!ba.side];
  3348. if(!h)
  3349. {
  3350. tlog2 << "Wrong caster!\n";
  3351. return false;
  3352. }
  3353. if(ba.additionalInfo >= VLC->spellh->spells.size())
  3354. {
  3355. tlog2 << "Wrong spell id (" << ba.additionalInfo << ")!\n";
  3356. return false;
  3357. }
  3358. const CSpell *s = &VLC->spellh->spells[ba.additionalInfo];
  3359. ui8 skill = h->getSpellSchoolLevel(s); //skill level
  3360. if( !(h->canCastThisSpell(s)) //hero cannot cast this spell at all
  3361. || (h->mana < gs->curB->getSpellCost(s, h)) //not enough mana
  3362. || (ba.additionalInfo < 10) //it's adventure spell (not combat)
  3363. || (gs->curB->castSpells[ba.side]) //spell has been cast
  3364. || (NBonus::hasOfType(secondHero, Bonus::SPELL_IMMUNITY, s->id)) //non - casting hero provides immunity for this spell
  3365. || (gs->battleMaxSpellLevel() < s->level) //non - casting hero stops caster from casting this spell
  3366. )
  3367. {
  3368. tlog2 << "Spell cannot be cast!\n";
  3369. return false;
  3370. }
  3371. sendAndApply(&StartAction(ba)); //start spell casting
  3372. handleSpellCasting(ba.additionalInfo, skill, ba.destinationTile, ba.side, h->tempOwner, h, secondHero, h->getPrimSkillLevel(2));
  3373. sendAndApply(&EndAction());
  3374. if( !gs->curB->getStack(gs->curB->activeStack, false)->alive() )
  3375. {
  3376. battleMadeAction.setn(true);
  3377. }
  3378. checkForBattleEnd(gs->curB->stacks);
  3379. if(battleResult.get())
  3380. {
  3381. endBattle(gs->curB->tile, gs->curB->heroes[0], gs->curB->heroes[1]);
  3382. }
  3383. return true;
  3384. }
  3385. }
  3386. return false;
  3387. }
  3388. void CGameHandler::handleTimeEvents()
  3389. {
  3390. gs->map->events.sort(evntCmp);
  3391. while(gs->map->events.size() && gs->map->events.front()->firstOccurence+1 == gs->day)
  3392. {
  3393. CMapEvent *ev = gs->map->events.front();
  3394. for(int player = 0; player < PLAYER_LIMIT; player++)
  3395. {
  3396. PlayerState *pinfo = gs->getPlayer(player);
  3397. if( pinfo //player exists
  3398. && (ev->players & 1<<player) //event is enabled to this player
  3399. && ((ev->computerAffected && !pinfo->human)
  3400. || (ev->humanAffected && pinfo->human)
  3401. )
  3402. )
  3403. {
  3404. //give resources
  3405. SetResources sr;
  3406. sr.player = player;
  3407. sr.res = pinfo->resources;
  3408. //prepare dialog
  3409. InfoWindow iw;
  3410. iw.player = player;
  3411. iw.text << ev->message;
  3412. for (int i=0; i<ev->resources.size(); i++)
  3413. {
  3414. if(ev->resources[i]) //if resource is changed, we add it to the dialog
  3415. {
  3416. // If removing too much resources, adjust the
  3417. // amount so the total doesn't become negative.
  3418. if (sr.res[i] + ev->resources[i] < 0)
  3419. ev->resources[i] = -sr.res[i];
  3420. if(ev->resources[i]) //if non-zero res change
  3421. {
  3422. iw.components.push_back(Component(Component::RESOURCE,i,ev->resources[i],0));
  3423. sr.res[i] += ev->resources[i];
  3424. }
  3425. }
  3426. }
  3427. if (iw.components.size())
  3428. {
  3429. sendAndApply(&sr); //update player resources if changed
  3430. }
  3431. sendAndApply(&iw); //show dialog
  3432. }
  3433. } //PLAYERS LOOP
  3434. if(ev->nextOccurence)
  3435. {
  3436. ev->firstOccurence += ev->nextOccurence;
  3437. gs->map->events.sort(evntCmp);
  3438. }
  3439. else
  3440. {
  3441. delete ev;
  3442. gs->map->events.pop_front();
  3443. }
  3444. }
  3445. }
  3446. bool CGameHandler::complain( const std::string &problem )
  3447. {
  3448. sendMessageToAll("Server encountered a problem: " + problem);
  3449. tlog1 << problem << std::endl;
  3450. return true;
  3451. }
  3452. ui32 CGameHandler::getQueryResult( ui8 player, int queryID )
  3453. {
  3454. //TODO: write
  3455. return 0;
  3456. }
  3457. void CGameHandler::showGarrisonDialog( int upobj, int hid, bool removableUnits, const boost::function<void()> &cb )
  3458. {
  3459. ui8 player = getOwner(hid);
  3460. GarrisonDialog gd;
  3461. gd.hid = hid;
  3462. gd.objid = upobj;
  3463. {
  3464. boost::unique_lock<boost::recursive_mutex> lock(gsm);
  3465. gd.id = QID;
  3466. garrisonCallbacks[QID] = cb;
  3467. allowedExchanges[QID] = std::pair<si32,si32>(upobj,hid);
  3468. states.addQuery(player,QID);
  3469. QID++;
  3470. gd.removableUnits = removableUnits;
  3471. sendAndApply(&gd);
  3472. }
  3473. }
  3474. void CGameHandler::showThievesGuildWindow(int requestingObjId)
  3475. {
  3476. OpenWindow ow;
  3477. ow.window = OpenWindow::THIEVES_GUILD;
  3478. ow.id1 = requestingObjId;
  3479. sendAndApply(&ow);
  3480. }
  3481. bool CGameHandler::isAllowedExchange( int id1, int id2 )
  3482. {
  3483. if(id1 == id2)
  3484. return true;
  3485. {
  3486. boost::unique_lock<boost::recursive_mutex> lock(gsm);
  3487. for(std::map<ui32, std::pair<si32,si32> >::const_iterator i = allowedExchanges.begin(); i!=allowedExchanges.end(); i++)
  3488. if(id1 == i->second.first && id2 == i->second.second || id2 == i->second.first && id1 == i->second.second)
  3489. return true;
  3490. }
  3491. const CGObjectInstance *o1 = getObj(id1), *o2 = getObj(id2);
  3492. if(o1->ID == TOWNI_TYPE)
  3493. {
  3494. const CGTownInstance *t = static_cast<const CGTownInstance*>(o1);
  3495. if(t->visitingHero == o2 || t->garrisonHero == o2)
  3496. return true;
  3497. }
  3498. if(o2->ID == TOWNI_TYPE)
  3499. {
  3500. const CGTownInstance *t = static_cast<const CGTownInstance*>(o2);
  3501. if(t->visitingHero == o1 || t->garrisonHero == o1)
  3502. return true;
  3503. }
  3504. if(o1->ID == HEROI_TYPE && o2->ID == HEROI_TYPE
  3505. && distance(o1->pos, o2->pos) < 2) //hero stands on the same tile or on the neighbouring tiles
  3506. {
  3507. //TODO: it's workaround, we should check if first hero visited second and player hasn't closed exchange window
  3508. //(to block moving stacks for free [without visiting] beteen heroes)
  3509. return true;
  3510. }
  3511. return false;
  3512. }
  3513. void CGameHandler::objectVisited( const CGObjectInstance * obj, const CGHeroInstance * h )
  3514. {
  3515. obj->onHeroVisit(h);
  3516. }
  3517. bool CGameHandler::buildBoat( ui32 objid )
  3518. {
  3519. const IShipyard *obj = IShipyard::castFrom(getObj(objid));
  3520. int boatType = 1;
  3521. if(obj->state())
  3522. {
  3523. complain("Cannot build boat in this shipyard!");
  3524. return false;
  3525. }
  3526. else if(obj->o->ID == TOWNI_TYPE
  3527. && !vstd::contains((static_cast<const CGTownInstance*>(obj))->builtBuildings,6))
  3528. {
  3529. complain("Cannot build boat in the town - no shipyard!");
  3530. return false;
  3531. }
  3532. //TODO use "real" cost via obj->getBoatCost
  3533. if(getResource(obj->o->tempOwner, 6) < 1000 || getResource(obj->o->tempOwner, 0) < 10)
  3534. {
  3535. complain("Not enough resources to build a boat!");
  3536. return false;
  3537. }
  3538. int3 tile = obj->bestLocation();
  3539. if(!gs->map->isInTheMap(tile))
  3540. {
  3541. complain("Cannot find appropriate tile for a boat!");
  3542. return false;
  3543. }
  3544. //take boat cost
  3545. SetResources sr;
  3546. sr.player = obj->o->tempOwner;
  3547. sr.res = gs->getPlayer(obj->o->tempOwner)->resources;
  3548. sr.res[0] -= 10;
  3549. sr.res[6] -= 1000;
  3550. sendAndApply(&sr);
  3551. //create boat
  3552. NewObject no;
  3553. no.ID = 8;
  3554. no.subID = obj->getBoatType();
  3555. no.pos = tile + int3(1,0,0);
  3556. sendAndApply(&no);
  3557. return true;
  3558. }
  3559. void CGameHandler::engageIntoBattle( ui8 player )
  3560. {
  3561. if(vstd::contains(states.players, player))
  3562. states.setFlag(player,&PlayerStatus::engagedIntoBattle,true);
  3563. //notify interfaces
  3564. PlayerBlocked pb;
  3565. pb.player = player;
  3566. pb.reason = PlayerBlocked::UPCOMING_BATTLE;
  3567. sendAndApply(&pb);
  3568. }
  3569. void CGameHandler::winLoseHandle(ui8 players )
  3570. {
  3571. for(size_t i = 0; i < PLAYER_LIMIT; i++)
  3572. {
  3573. if(players & 1<<i && gs->getPlayer(i))
  3574. {
  3575. checkLossVictory(i);
  3576. }
  3577. }
  3578. }
  3579. void CGameHandler::checkLossVictory( ui8 player )
  3580. {
  3581. const PlayerState *p = gs->getPlayer(player);
  3582. if(p->status) //player already won / lost
  3583. return;
  3584. int loss = gs->lossCheck(player);
  3585. int vic = gs->victoryCheck(player);
  3586. if(!loss && !vic)
  3587. return;
  3588. InfoWindow iw;
  3589. getLossVicMessage(player, vic ? vic : loss , vic, iw);
  3590. sendAndApply(&iw);
  3591. PlayerEndsGame peg;
  3592. peg.player = player;
  3593. peg.victory = vic;
  3594. sendAndApply(&peg);
  3595. if(vic > 0) //one player won -> all enemies lost //TODO: allies
  3596. {
  3597. iw.text.localStrings.front().second++; //message about losing because enemy won first is just after victory message
  3598. for (std::map<ui8,PlayerState>::const_iterator i = gs->players.begin(); i!=gs->players.end(); i++)
  3599. {
  3600. if(i->first < PLAYER_LIMIT && i->first != player)
  3601. {
  3602. iw.player = i->first;
  3603. sendAndApply(&iw);
  3604. peg.player = i->first;
  3605. peg.victory = false;
  3606. sendAndApply(&peg);
  3607. }
  3608. }
  3609. }
  3610. else //player lost -> all his objects become unflagged (neutral)
  3611. {
  3612. std::vector<CGHeroInstance*> hlp = p->heroes;
  3613. for (std::vector<CGHeroInstance*>::const_iterator i = hlp.begin(); i != hlp.end(); i++) //eliminate heroes
  3614. removeObject((*i)->id);
  3615. for (std::vector<CGObjectInstance*>::const_iterator i = gs->map->objects.begin(); i != gs->map->objects.end(); i++) //unflag objs
  3616. {
  3617. if(*i && (*i)->tempOwner == player)
  3618. setOwner((**i).id,NEUTRAL_PLAYER);
  3619. }
  3620. //eliminating one player may cause victory of another:
  3621. winLoseHandle(ALL_PLAYERS & ~(1<<player));
  3622. }
  3623. if(vic)
  3624. end2 = true;
  3625. }
  3626. void CGameHandler::getLossVicMessage( ui8 player, ui8 standard, bool victory, InfoWindow &out ) const
  3627. {
  3628. const PlayerState *p = gs->getPlayer(player);
  3629. // if(!p->human)
  3630. // return; //AI doesn't need text info of loss
  3631. out.player = player;
  3632. if(victory)
  3633. {
  3634. if(standard < 0) //not std loss
  3635. {
  3636. switch(gs->map->victoryCondition.condition)
  3637. {
  3638. case artifact:
  3639. out.text.addTxt(MetaString::GENERAL_TXT, 280); //Congratulations! You have found the %s, and can claim victory!
  3640. out.text.addReplacement(MetaString::ART_NAMES,gs->map->victoryCondition.ID); //artifact name
  3641. break;
  3642. case gatherTroop:
  3643. out.text.addTxt(MetaString::GENERAL_TXT, 276); //Congratulations! You have over %d %s in your armies. Your enemies have no choice but to bow down before your power!
  3644. out.text.addReplacement(gs->map->victoryCondition.count);
  3645. out.text.addReplacement(MetaString::CRE_PL_NAMES, gs->map->victoryCondition.ID);
  3646. break;
  3647. case gatherResource:
  3648. out.text.addTxt(MetaString::GENERAL_TXT, 278); //Congratulations! You have collected over %d %s in your treasury. Victory is yours!
  3649. out.text.addReplacement(gs->map->victoryCondition.count);
  3650. out.text.addReplacement(MetaString::RES_NAMES, gs->map->victoryCondition.ID);
  3651. break;
  3652. case buildCity:
  3653. out.text.addTxt(MetaString::GENERAL_TXT, 282); //Congratulations! You have successfully upgraded your town, and can claim victory!
  3654. break;
  3655. case buildGrail:
  3656. out.text.addTxt(MetaString::GENERAL_TXT, 284); //Congratulations! You have constructed a permanent home for the Grail, and can claim victory!
  3657. break;
  3658. case beatHero:
  3659. {
  3660. out.text.addTxt(MetaString::GENERAL_TXT, 252); //Congratulations! You have completed your quest to defeat the enemy hero %s. Victory is yours!
  3661. const CGHeroInstance *h = dynamic_cast<const CGHeroInstance*>(gs->map->victoryCondition.obj);
  3662. assert(h);
  3663. out.text.addReplacement(h->name);
  3664. }
  3665. break;
  3666. case captureCity:
  3667. {
  3668. out.text.addTxt(MetaString::GENERAL_TXT, 249); //Congratulations! You captured %s, and are victorious!
  3669. const CGTownInstance *t = dynamic_cast<const CGTownInstance*>(gs->map->victoryCondition.obj);
  3670. assert(t);
  3671. out.text.addReplacement(t->name);
  3672. }
  3673. break;
  3674. case beatMonster:
  3675. out.text.addTxt(MetaString::GENERAL_TXT, 286); //Congratulations! You have completed your quest to kill the fearsome beast, and can claim victory!
  3676. break;
  3677. case takeDwellings:
  3678. out.text.addTxt(MetaString::GENERAL_TXT, 288); //Congratulations! Your flag flies on the dwelling of every creature. Victory is yours!
  3679. break;
  3680. case takeMines:
  3681. out.text.addTxt(MetaString::GENERAL_TXT, 290); //Congratulations! Your flag flies on every mine. Victory is yours!
  3682. break;
  3683. case transportItem:
  3684. out.text.addTxt(MetaString::GENERAL_TXT, 292); //Congratulations! You have reached your destination, precious cargo intact, and can claim victory!
  3685. break;
  3686. }
  3687. }
  3688. else
  3689. {
  3690. out.text.addTxt(MetaString::GENERAL_TXT, 659); //Congratulations! You have reached your destination, precious cargo intact, and can claim victory!
  3691. }
  3692. }
  3693. else
  3694. {
  3695. if(standard < 0) //not std loss
  3696. {
  3697. switch(gs->map->lossCondition.typeOfLossCon)
  3698. {
  3699. case lossCastle:
  3700. {
  3701. out.text.addTxt(MetaString::GENERAL_TXT, 251); //The town of %s has fallen - all is lost!
  3702. const CGTownInstance *t = dynamic_cast<const CGTownInstance*>(gs->map->lossCondition.obj);
  3703. assert(t);
  3704. out.text.addReplacement(t->name);
  3705. }
  3706. break;
  3707. case lossHero:
  3708. {
  3709. out.text.addTxt(MetaString::GENERAL_TXT, 253); //The hero, %s, has suffered defeat - your quest is over!
  3710. const CGHeroInstance *h = dynamic_cast<const CGHeroInstance*>(gs->map->lossCondition.obj);
  3711. assert(h);
  3712. out.text.addReplacement(h->name);
  3713. }
  3714. break;
  3715. case timeExpires:
  3716. out.text.addTxt(MetaString::GENERAL_TXT, 254); //Alas, time has run out on your quest. All is lost.
  3717. break;
  3718. }
  3719. }
  3720. else if(standard == 2)
  3721. {
  3722. out.text.addTxt(MetaString::GENERAL_TXT, 7);//%s, your heroes abandon you, and you are banished from this land.
  3723. out.text.addReplacement(MetaString::COLOR, player);
  3724. out.components.push_back(Component(Component::FLAG,player,0,0));
  3725. }
  3726. else //lost all towns and heroes
  3727. {
  3728. out.text.addTxt(MetaString::GENERAL_TXT, 660); //All your forces have been defeated, and you are banished from this land!
  3729. }
  3730. }
  3731. }
  3732. bool CGameHandler::dig( const CGHeroInstance *h )
  3733. {
  3734. for (std::vector<CGObjectInstance*>::const_iterator i = gs->map->objects.begin(); i != gs->map->objects.end(); i++) //unflag objs
  3735. {
  3736. if(*i && (*i)->ID == 124 && (*i)->pos == h->getPosition())
  3737. {
  3738. complain("Cannot dig - there is already a hole under the hero!");
  3739. return false;
  3740. }
  3741. }
  3742. NewObject no;
  3743. no.ID = 124;
  3744. no.pos = h->getPosition();
  3745. no.subID = getTile(no.pos)->tertype;
  3746. if(no.subID >= 8) //no digging on water / rock
  3747. {
  3748. complain("Cannot dig - wrong terrain type!");
  3749. return false;
  3750. }
  3751. sendAndApply(&no);
  3752. SetMovePoints smp;
  3753. smp.hid = h->id;
  3754. smp.val = 0;
  3755. sendAndApply(&smp);
  3756. InfoWindow iw;
  3757. iw.player = h->tempOwner;
  3758. if(gs->map->grailPos == h->getPosition())
  3759. {
  3760. iw.text.addTxt(MetaString::GENERAL_TXT, 58); //"Congratulations! After spending many hours digging here, your hero has uncovered the "
  3761. iw.text.addTxt(MetaString::ART_NAMES, 2);
  3762. iw.soundID = soundBase::ULTIMATEARTIFACT;
  3763. giveHeroArtifact(2, h->id, -1); //give grail
  3764. sendAndApply(&iw);
  3765. iw.text.clear();
  3766. iw.text.addTxt(MetaString::ART_DESCR, 2);
  3767. sendAndApply(&iw);
  3768. }
  3769. else
  3770. {
  3771. iw.text.addTxt(MetaString::GENERAL_TXT, 59); //"Nothing here. \n Where could it be?"
  3772. iw.soundID = soundBase::Dig;
  3773. sendAndApply(&iw);
  3774. }
  3775. return true;
  3776. }
  3777. void CGameHandler::handleAfterAttackCasting( const BattleAttack & bat )
  3778. {
  3779. const CStack * attacker = gs->curB->getStack(bat.stackAttacking);
  3780. if( attacker->hasBonusOfType(Bonus::SPELL_AFTER_ATTACK) )
  3781. {
  3782. BOOST_FOREACH(const Bonus & sf, attacker->bonuses)
  3783. {
  3784. if (sf.type == Bonus::SPELL_AFTER_ATTACK)
  3785. {
  3786. const CStack * oneOfAttacked = NULL;
  3787. for(int g=0; g<bat.bsa.size(); ++g)
  3788. {
  3789. if (bat.bsa[g].newAmount > 0)
  3790. {
  3791. oneOfAttacked = gs->curB->getStack(bat.bsa[g].stackAttacked);
  3792. break;
  3793. }
  3794. }
  3795. if(oneOfAttacked == NULL) //all attacked creatures have been killed
  3796. return;
  3797. int spellID = sf.subtype;
  3798. int spellLevel = sf.val;
  3799. int chance = sf.additionalInfo % 1000;
  3800. int meleeRanged = sf.additionalInfo / 1000;
  3801. int destination = oneOfAttacked->position;
  3802. //check if spell should be casted (probability handling)
  3803. if( rand()%100 >= chance )
  3804. continue;
  3805. //casting
  3806. handleSpellCasting(spellID, spellLevel, destination, !attacker->attackerOwned, attacker->owner, NULL, NULL, attacker->count);
  3807. }
  3808. }
  3809. }
  3810. }
  3811. bool CGameHandler::castSpell(const CGHeroInstance *h, int spellID, const int3 &pos)
  3812. {
  3813. const CSpell *s = &VLC->spellh->spells[spellID];
  3814. int cost = h->getSpellCost(s);
  3815. int schoolLevel = h->getSpellSchoolLevel(s);
  3816. if(!h->canCastThisSpell(s))
  3817. COMPLAIN_RET("Hero cannot cast this spell!");
  3818. if(h->mana < cost)
  3819. COMPLAIN_RET("Hero doesn't have enough spell points to cast this spell!");
  3820. if(s->combatSpell)
  3821. COMPLAIN_RET("This function can be used only for adventure map spells!");
  3822. using namespace Spells;
  3823. switch(spellID)
  3824. {
  3825. case SUMMON_BOAT: //Summon Boat
  3826. {
  3827. //check if spell works at all
  3828. if(rand() % 100 >= s->powers[schoolLevel]) //power is % chance of success
  3829. {
  3830. InfoWindow iw;
  3831. iw.player = h->tempOwner;
  3832. iw.text.addTxt(MetaString::GENERAL_TXT, 336); //%s tried to summon a boat, but failed.
  3833. iw.text.addReplacement(h->name);
  3834. sendAndApply(&iw);
  3835. return true; //TODO? or should it be false? request was correct and realized, but spell failed...
  3836. }
  3837. //try to find unoccupied boat to summon
  3838. const CGBoat *nearest = NULL;
  3839. double dist = 0;
  3840. int3 summonPos = h->bestLocation();
  3841. if(summonPos.x < 0)
  3842. COMPLAIN_RET("There is no water tile available!");
  3843. BOOST_FOREACH(const CGObjectInstance *obj, gs->map->objects)
  3844. {
  3845. if(obj && obj->ID == 8)
  3846. {
  3847. const CGBoat *b = static_cast<const CGBoat*>(obj);
  3848. if(b->hero) continue; //we're looking for unoccupied boat
  3849. double nDist = distance(b->pos, h->getPosition());
  3850. if(!nearest || nDist < dist) //it's first boat or closer than previous
  3851. {
  3852. nearest = b;
  3853. dist = nDist;
  3854. }
  3855. }
  3856. }
  3857. if(nearest) //we found boat to summon
  3858. {
  3859. ChangeObjPos cop;
  3860. cop.objid = nearest->id;
  3861. cop.nPos = summonPos + int3(1,0,0);;
  3862. cop.flags = 1;
  3863. sendAndApply(&cop);
  3864. }
  3865. else if(schoolLevel < 2) //none or basic level -> cannot create boat :(
  3866. {
  3867. InfoWindow iw;
  3868. iw.player = h->tempOwner;
  3869. iw.text.addTxt(MetaString::GENERAL_TXT, 335); //There are no boats to summon.
  3870. sendAndApply(&iw);
  3871. }
  3872. else //create boat
  3873. {
  3874. NewObject no;
  3875. no.ID = 8;
  3876. no.subID = h->getBoatType();
  3877. no.pos = summonPos + int3(1,0,0);;
  3878. sendAndApply(&no);
  3879. }
  3880. break;
  3881. }
  3882. case SCUTTLE_BOAT: //Scuttle Boat
  3883. {
  3884. //check if spell works at all
  3885. if(rand() % 100 >= s->powers[schoolLevel]) //power is % chance of success
  3886. {
  3887. InfoWindow iw;
  3888. iw.player = h->tempOwner;
  3889. iw.text.addTxt(MetaString::GENERAL_TXT, 337); //%s tried to scuttle the boat, but failed
  3890. iw.text.addReplacement(h->name);
  3891. sendAndApply(&iw);
  3892. return true; //TODO? or should it be false? request was correct and realized, but spell failed...
  3893. }
  3894. //TODO: test range, visibility
  3895. const TerrainTile *t = &gs->map->getTile(pos);
  3896. if(!t->visitableObjects.size() || t->visitableObjects.back()->ID != 8)
  3897. COMPLAIN_RET("There is no boat to scuttle!");
  3898. RemoveObject ro;
  3899. ro.id = t->visitableObjects.back()->id;
  3900. sendAndApply(&ro);
  3901. break;
  3902. }
  3903. case DIMENSION_DOOR: //Dimension Door
  3904. {
  3905. const TerrainTile *dest = getTile(pos);
  3906. const TerrainTile *curr = getTile(h->getSightCenter());
  3907. if(!dest)
  3908. COMPLAIN_RET("Destination tile doesn't exist!");
  3909. if(!h->movement)
  3910. COMPLAIN_RET("Hero needs movement points to cast Dimension Door!");
  3911. if(h->getBonusesCount(Bonus::CASTED_SPELL, Spells::DIMENSION_DOOR) >= s->powers[schoolLevel]) //limit casts per turn
  3912. {
  3913. InfoWindow iw;
  3914. iw.player = h->tempOwner;
  3915. iw.text.addTxt(MetaString::GENERAL_TXT, 338); //%s is not skilled enough to cast this spell again today.
  3916. iw.text.addReplacement(h->name);
  3917. sendAndApply(&iw);
  3918. break;
  3919. }
  3920. GiveBonus gb;
  3921. gb.id = h->id;
  3922. gb.bonus = Bonus(Bonus::ONE_DAY, Bonus::NONE, Bonus::CASTED_SPELL, 0, Spells::DIMENSION_DOOR);
  3923. sendAndApply(&gb);
  3924. if(!dest->isClear(curr)) //wrong dest tile
  3925. {
  3926. InfoWindow iw;
  3927. iw.player = h->tempOwner;
  3928. iw.text.addTxt(MetaString::GENERAL_TXT, 70); //Dimension Door failed!
  3929. sendAndApply(&iw);
  3930. break;
  3931. }
  3932. TryMoveHero tmh;
  3933. tmh.id = h->id;
  3934. tmh.movePoints = std::max<int>(0, h->movement - 300);
  3935. tmh.result = TryMoveHero::TELEPORTATION;
  3936. tmh.start = h->pos;
  3937. tmh.end = pos;
  3938. getTilesInRange(tmh.fowRevealed, pos, h->getSightRadious(), h->tempOwner,1);
  3939. sendAndApply(&tmh);
  3940. }
  3941. break;
  3942. case VISIONS: //Visions
  3943. case VIEW_EARTH: //View Earth
  3944. case DISGUISE: //Disguise
  3945. case VIEW_AIR: //View Air
  3946. case FLY: //Fly
  3947. case WATER_WALK: //Water Walk
  3948. case TOWN_PORTAL: //Town Portal
  3949. default:
  3950. COMPLAIN_RET("This spell is not implemented yet!");
  3951. }
  3952. SetMana sm;
  3953. sm.hid = h->id;
  3954. sm.val = h->mana - cost;
  3955. sendAndApply(&sm);
  3956. return true;
  3957. }