CGameHandler.cpp 138 KB

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