CGameHandler.cpp 132 KB

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