CObjectHandler.cpp 196 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275
  1. /*
  2. * CObjectHandler.cpp, part of VCMI engine
  3. *
  4. * Authors: listed in file AUTHORS in main folder
  5. *
  6. * License: GNU General Public License v2.0 or later
  7. * Full text of license available in license.txt file, in main folder
  8. *
  9. */
  10. #include "StdInc.h"
  11. #include "CObjectHandler.h"
  12. #include "CDefObjInfoHandler.h"
  13. #include "CGeneralTextHandler.h"
  14. #include "CDefObjInfoHandler.h"
  15. #include "CHeroHandler.h"
  16. #include "CSpellHandler.h"
  17. #include "CModHandler.h"
  18. #include "../client/CSoundBase.h"
  19. #include <boost/random/linear_congruential.hpp>
  20. #include "CTownHandler.h"
  21. #include "CCreatureHandler.h"
  22. #include "VCMI_Lib.h"
  23. #include "IGameCallback.h"
  24. #include "CGameState.h"
  25. #include "NetPacks.h"
  26. #include "StartInfo.h"
  27. #include "Mapping/CMap.h"
  28. #include <SDL_stdinc.h>
  29. #include "CBuildingHandler.h"
  30. #include "JsonNode.h"
  31. #include "Filesystem/CResourceLoader.h"
  32. using namespace boost::assign;
  33. // It looks that we can't rely on shadowCoverage correctness (Mantis #866). This may result
  34. // in notable performance decrease (SDL blit with custom alpha blit) not notable on my system (Ivan)
  35. #define USE_COVERAGE_MAP 0
  36. std::map<Obj, std::map<int, std::vector<ObjectInstanceID> > > CGTeleport::objs;
  37. std::vector<std::pair<ObjectInstanceID, ObjectInstanceID> > CGTeleport::gates;
  38. IGameCallback * IObjectInterface::cb = NULL;
  39. extern boost::rand48 ran;
  40. std::map <PlayerColor, std::set <ui8> > CGKeys::playerKeyMap;
  41. std::map <si32, std::vector<ObjectInstanceID> > CGMagi::eyelist;
  42. ui8 CGObelisk::obeliskCount; //how many obelisks are on map
  43. std::map<TeamID, ui8> CGObelisk::visited; //map: team_id => how many obelisks has been visited
  44. std::vector<const CArtifact *> CGTownInstance::merchantArtifacts;
  45. std::vector<int> CGTownInstance::universitySkills;
  46. ///helpers
  47. static void openWindow(const OpenWindow::EWindow type, const int id1, const int id2 = -1)
  48. {
  49. OpenWindow ow;
  50. ow.window = type;
  51. ow.id1 = id1;
  52. ow.id2 = id2;
  53. IObjectInterface::cb->sendAndApply(&ow);
  54. }
  55. static void showInfoDialog(const PlayerColor playerID, const ui32 txtID, const ui16 soundID)
  56. {
  57. InfoWindow iw;
  58. iw.soundID = soundID;
  59. iw.player = playerID;
  60. iw.text.addTxt(MetaString::ADVOB_TXT,txtID);
  61. IObjectInterface::cb->sendAndApply(&iw);
  62. }
  63. static void showInfoDialog(const ObjectInstanceID heroID, const ui32 txtID, const ui16 soundID)
  64. {
  65. const PlayerColor playerID = IObjectInterface::cb->getOwner(heroID);
  66. showInfoDialog(playerID,txtID,soundID);
  67. }
  68. static void showInfoDialog(const CGHeroInstance* h, const ui32 txtID, const ui16 soundID)
  69. {
  70. const PlayerColor playerID = h->getOwner();
  71. showInfoDialog(playerID,txtID,soundID);
  72. }
  73. static std::string & visitedTxt(const bool visited)
  74. {
  75. int id = visited ? 352 : 353;
  76. return VLC->generaltexth->allTexts[id];
  77. }
  78. ///IObjectInterface
  79. void IObjectInterface::onHeroVisit(const CGHeroInstance * h) const
  80. {}
  81. void IObjectInterface::onHeroLeave(const CGHeroInstance * h) const
  82. {}
  83. void IObjectInterface::newTurn () const
  84. {}
  85. IObjectInterface::~IObjectInterface()
  86. {}
  87. IObjectInterface::IObjectInterface()
  88. {}
  89. void IObjectInterface::initObj()
  90. {}
  91. void IObjectInterface::setProperty( ui8 what, ui32 val )
  92. {}
  93. bool IObjectInterface::wasVisited (PlayerColor player) const
  94. {
  95. return false;
  96. }
  97. bool IObjectInterface::wasVisited (const CGHeroInstance * h) const
  98. {
  99. return false;
  100. }
  101. void IObjectInterface::postInit()
  102. {}
  103. void IObjectInterface::preInit()
  104. {}
  105. void CPlayersVisited::setPropertyDer( ui8 what, ui32 val )
  106. {
  107. if(what == 10)
  108. players.insert(PlayerColor(val));
  109. }
  110. bool CPlayersVisited::wasVisited( PlayerColor player ) const
  111. {
  112. return vstd::contains(players,player);
  113. }
  114. bool CPlayersVisited::wasVisited( TeamID team ) const
  115. {
  116. BOOST_FOREACH(auto i, players)
  117. {
  118. if(cb->getPlayer(i)->team == team)
  119. return true;
  120. }
  121. return false;
  122. }
  123. // Bank helper. Find the creature ID and their number, and store the
  124. // result in storage (either guards or reward creatures).
  125. static void readCreatures(const JsonNode &creature, std::vector< std::pair <CreatureID, ui32> > &storage)
  126. {
  127. std::pair<CreatureID, si32> creInfo = std::make_pair(CreatureID::NONE, 0);
  128. creInfo.second = creature["number"].Float();
  129. creInfo.first = CreatureID((si32)creature["id"].Float());
  130. storage.push_back(creInfo);
  131. }
  132. // Bank helper. Process a bank level.
  133. static void readBankLevel(const JsonNode &level, BankConfig &bc)
  134. {
  135. int idx;
  136. bc.chance = level["chance"].Float();
  137. BOOST_FOREACH(const JsonNode &creature, level["guards"].Vector())
  138. {
  139. readCreatures(creature, bc.guards);
  140. }
  141. bc.upgradeChance = level["upgrade_chance"].Float();
  142. bc.combatValue = level["combat_value"].Float();
  143. bc.resources.resize(GameConstants::RESOURCE_QUANTITY);
  144. idx = 0;
  145. BOOST_FOREACH(const JsonNode &resource, level["reward_resources"].Vector())
  146. {
  147. bc.resources[idx] = resource.Float();
  148. idx ++;
  149. }
  150. BOOST_FOREACH(const JsonNode &creature, level["reward_creatures"].Vector())
  151. {
  152. readCreatures(creature, bc.creatures);
  153. }
  154. bc.artifacts.resize(4);
  155. idx = 0;
  156. BOOST_FOREACH(const JsonNode &artifact, level["reward_artifacts"].Vector())
  157. {
  158. bc.artifacts[idx] = artifact.Float();
  159. idx ++;
  160. }
  161. bc.value = level["value"].Float();
  162. bc.rewardDifficulty = level["profitability"].Float();
  163. bc.easiest = level["easiest"].Float();
  164. }
  165. void CObjectHandler::load()
  166. {
  167. tlog5 << "\t\tReading cregens \n";
  168. const JsonNode config(ResourceID("config/dwellings.json"));
  169. BOOST_FOREACH(const JsonNode &dwelling, config["dwellings"].Vector())
  170. {
  171. cregens[dwelling["dwelling"].Float()] = CreatureID((si32)dwelling["creature"].Float());
  172. }
  173. tlog5 << "\t\tDone loading cregens!\n";
  174. tlog5 << "\t\tReading resources prices \n";
  175. const JsonNode config2(ResourceID("config/resources.json"));
  176. BOOST_FOREACH(const JsonNode &price, config2["resources_prices"].Vector())
  177. {
  178. resVals.push_back(price.Float());
  179. }
  180. tlog5 << "\t\tDone loading resource prices!\n";
  181. tlog5 << "\t\tReading banks configs \n";
  182. const JsonNode config3(ResourceID("config/bankconfig.json"));
  183. int bank_num = 0;
  184. BOOST_FOREACH(const JsonNode &bank, config3["banks"].Vector())
  185. {
  186. creBanksNames[bank_num] = bank["name"].String();
  187. int level_num = 0;
  188. BOOST_FOREACH(const JsonNode &level, bank["levels"].Vector())
  189. {
  190. banksInfo[bank_num].push_back(new BankConfig);
  191. BankConfig &bc = *banksInfo[bank_num].back();
  192. bc.level = level_num;
  193. readBankLevel(level, bc);
  194. level_num ++;
  195. }
  196. bank_num ++;
  197. }
  198. tlog5 << "\t\tDone loading banks configs \n";
  199. }
  200. int CObjectHandler::bankObjToIndex (const CGObjectInstance * obj)
  201. {
  202. switch (obj->ID) //find appriopriate key
  203. {
  204. case Obj::CREATURE_BANK:
  205. return obj->subID;
  206. case Obj::DERELICT_SHIP:
  207. return 8;
  208. case Obj::DRAGON_UTOPIA:
  209. return 10;
  210. case Obj::CRYPT:
  211. return 9;
  212. case Obj::SHIPWRECK:
  213. return 7;
  214. default:
  215. tlog2 << "Unrecognized Bank indetifier!\n";
  216. return 0;
  217. }
  218. }
  219. PlayerColor CGObjectInstance::getOwner() const
  220. {
  221. //if (state)
  222. // return state->owner;
  223. //else
  224. return tempOwner; //won't have owner
  225. }
  226. CGObjectInstance::CGObjectInstance()
  227. {
  228. pos = int3(-1,-1,-1);
  229. //std::cout << "Tworze obiekt "<<this<<std::endl;
  230. //state = new CLuaObjectScript();
  231. ID = Obj::NO_OBJ;
  232. subID = -1;
  233. defInfo = NULL;
  234. tempOwner = PlayerColor::UNFLAGGABLE;
  235. blockVisit = false;
  236. }
  237. CGObjectInstance::~CGObjectInstance()
  238. {
  239. //std::cout << "Usuwam obiekt "<<this<<std::endl;
  240. //if (state)
  241. // delete state;
  242. //state=NULL;
  243. }
  244. const std::string & CGObjectInstance::getHoverText() const
  245. {
  246. return hoverName;
  247. }
  248. void CGObjectInstance::setOwner(PlayerColor ow)
  249. {
  250. //if (state)
  251. // state->owner = ow;
  252. //else
  253. tempOwner = ow;
  254. }
  255. int CGObjectInstance::getWidth() const//returns width of object graphic in tiles
  256. {
  257. return defInfo->width;
  258. }
  259. int CGObjectInstance::getHeight() const //returns height of object graphic in tiles
  260. {
  261. return defInfo->height;
  262. }
  263. bool CGObjectInstance::visitableAt(int x, int y) const //returns true if object is visitable at location (x, y) form left top tile of image (x, y in tiles)
  264. {
  265. if(defInfo==NULL)
  266. {
  267. tlog2 << "Warning: VisitableAt for obj "<< id.getNum() <<": NULL defInfo!\n";
  268. return false;
  269. }
  270. if((defInfo->visitMap[y] >> (7-x) ) & 1)
  271. {
  272. return true;
  273. }
  274. return false;
  275. }
  276. bool CGObjectInstance::blockingAt(int x, int y) const
  277. {
  278. if(x<0 || y<0 || x>=getWidth() || y>=getHeight() || defInfo==NULL)
  279. return false;
  280. if((defInfo->blockMap[y+6-getHeight()] >> (7-(8-getWidth()+x) )) & 1)
  281. return false;
  282. return true;
  283. }
  284. bool CGObjectInstance::coveringAt(int x, int y) const
  285. {
  286. //input coordinates are always negative
  287. x = -x;
  288. y = -y;
  289. #if USE_COVERAGE_MAP
  290. //NOTE: this code may be broken
  291. if((defInfo->coverageMap[y] >> (7-(x) )) & 1
  292. || (defInfo->shadowCoverage[y] >> (7-(x) )) & 1)
  293. return true;
  294. return false;
  295. #else
  296. return x >= 0 && y >= 0 && x < getWidth() && y < getHeight();
  297. #endif
  298. }
  299. bool CGObjectInstance::hasShadowAt( int x, int y ) const
  300. {
  301. #if USE_COVERAGE_MAP
  302. //NOTE: this code may be broken
  303. if( (defInfo->shadowCoverage[y] >> (7-(x) )) & 1 )
  304. return true;
  305. return false;
  306. #else
  307. return coveringAt(x,y);// ignore unreliable shadowCoverage map
  308. #endif
  309. }
  310. std::set<int3> CGObjectInstance::getBlockedPos() const
  311. {
  312. std::set<int3> ret;
  313. for(int w=0; w<getWidth(); ++w)
  314. {
  315. for(int h=0; h<getHeight(); ++h)
  316. {
  317. if(blockingAt(w, h))
  318. ret.insert(int3(pos.x - getWidth() + w + 1, pos.y - getHeight() + h + 1, pos.z));
  319. }
  320. }
  321. return ret;
  322. }
  323. bool CGObjectInstance::operator<(const CGObjectInstance & cmp) const //screen printing priority comparing
  324. {
  325. if(defInfo->printPriority==1 && cmp.defInfo->printPriority==0)
  326. return true;
  327. if(cmp.defInfo->printPriority==1 && defInfo->printPriority==0)
  328. return false;
  329. if(this->pos.y<cmp.pos.y)
  330. return true;
  331. if(this->pos.y>cmp.pos.y)
  332. return false;
  333. if(cmp.ID==Obj::HERO && ID!=Obj::HERO)
  334. return true;
  335. if(cmp.ID!=Obj::HERO && ID==Obj::HERO)
  336. return false;
  337. if(!defInfo->isVisitable() && cmp.defInfo->isVisitable())
  338. return true;
  339. if(!cmp.defInfo->isVisitable() && defInfo->isVisitable())
  340. return false;
  341. if(this->pos.x<cmp.pos.x)
  342. return true;
  343. return false;
  344. }
  345. void CGObjectInstance::initObj()
  346. {
  347. switch(ID)
  348. {
  349. case Obj::TAVERN:
  350. blockVisit = true;
  351. break;
  352. }
  353. }
  354. void CGObjectInstance::setProperty( ui8 what, ui32 val )
  355. {
  356. switch(what)
  357. {
  358. case ObjProperty::OWNER:
  359. tempOwner = PlayerColor(val);
  360. break;
  361. case ObjProperty::BLOCKVIS:
  362. blockVisit = val;
  363. break;
  364. case ObjProperty::ID:
  365. ID = Obj(val);
  366. break;
  367. case ObjProperty::SUBID:
  368. subID = val;
  369. break;
  370. }
  371. setPropertyDer(what, val);
  372. }
  373. void CGObjectInstance::setPropertyDer( ui8 what, ui32 val )
  374. {}
  375. int3 CGObjectInstance::getSightCenter() const
  376. {
  377. //return vistiable tile if possible
  378. for(int i=0; i < 8; i++)
  379. for(int j=0; j < 6; j++)
  380. if(visitableAt(i,j))
  381. return(pos + int3(i-7, j-5, 0));
  382. return pos;
  383. }
  384. int CGObjectInstance::getSightRadious() const
  385. {
  386. return 3;
  387. }
  388. void CGObjectInstance::getSightTiles(boost::unordered_set<int3, ShashInt3> &tiles) const //returns reference to the set
  389. {
  390. cb->getTilesInRange(tiles, getSightCenter(), getSightRadious(), tempOwner, 1);
  391. }
  392. void CGObjectInstance::hideTiles(PlayerColor ourplayer, int radius) const
  393. {
  394. for (auto i = cb->gameState()->teams.begin(); i != cb->gameState()->teams.end(); i++)
  395. {
  396. if ( !vstd::contains(i->second.players, ourplayer ))//another team
  397. {
  398. for (auto j = i->second.players.begin(); j != i->second.players.end(); j++)
  399. if ( cb->getPlayer(*j)->status == EPlayerStatus::INGAME )//seek for living player (if any)
  400. {
  401. FoWChange fw;
  402. fw.mode = 0;
  403. fw.player = *j;
  404. cb->getTilesInRange (fw.tiles, pos, radius, (*j), -1);
  405. cb->sendAndApply (&fw);
  406. break;
  407. }
  408. }
  409. }
  410. }
  411. int3 CGObjectInstance::getVisitableOffset() const
  412. {
  413. for(int y = 0; y < 6; y++)
  414. for (int x = 0; x < 8; x++)
  415. if((defInfo->visitMap[5-y] >> x) & 1)
  416. return int3(x,y,0);
  417. tlog2 << "Warning: getVisitableOffset called on non-visitable obj!\n";
  418. return int3(-1,-1,-1);
  419. }
  420. void CGObjectInstance::getNameVis( std::string &hname ) const
  421. {
  422. const CGHeroInstance *h = cb->getSelectedHero(cb->getCurrentPlayer());
  423. hname = VLC->generaltexth->names[ID];
  424. if(h)
  425. {
  426. const bool visited = h->hasBonusFrom(Bonus::OBJECT,ID);
  427. hname + " " + visitedTxt(visited);
  428. }
  429. }
  430. void CGObjectInstance::giveDummyBonus(ObjectInstanceID heroID, ui8 duration) const
  431. {
  432. GiveBonus gbonus;
  433. gbonus.bonus.type = Bonus::NONE;
  434. gbonus.id = heroID.getNum();
  435. gbonus.bonus.duration = duration;
  436. gbonus.bonus.source = Bonus::OBJECT;
  437. gbonus.bonus.sid = ID;
  438. cb->giveHeroBonus(&gbonus);
  439. }
  440. void CGObjectInstance::onHeroVisit( const CGHeroInstance * h ) const
  441. {
  442. switch(ID)
  443. {
  444. case Obj::HILL_FORT:
  445. {
  446. openWindow(OpenWindow::HILL_FORT_WINDOW,id.getNum(),h->id.getNum());
  447. }
  448. break;
  449. case Obj::SANCTUARY:
  450. {
  451. //You enter the sanctuary and immediately feel as if a great weight has been lifted off your shoulders. You feel safe here.
  452. showInfoDialog(h,114,soundBase::GETPROTECTION);
  453. }
  454. break;
  455. case Obj::TAVERN:
  456. {
  457. openWindow(OpenWindow::TAVERN_WINDOW,h->id.getNum(),id.getNum());
  458. }
  459. break;
  460. }
  461. }
  462. ui8 CGObjectInstance::getPassableness() const
  463. {
  464. return 0;
  465. }
  466. int3 CGObjectInstance::visitablePos() const
  467. {
  468. return pos - getVisitableOffset();
  469. }
  470. bool CGObjectInstance::isVisitable() const
  471. {
  472. for(int g=0; g<ARRAY_COUNT(defInfo->visitMap); ++g)
  473. {
  474. if(defInfo->visitMap[g] != 0)
  475. {
  476. return true;
  477. }
  478. }
  479. return false;
  480. }
  481. static int lowestSpeed(const CGHeroInstance * chi)
  482. {
  483. if(!chi->Slots().size())
  484. {
  485. tlog1 << "Error! Hero " << chi->id.getNum() << " ("<<chi->name<<") has no army!\n";
  486. return 20;
  487. }
  488. TSlots::const_iterator i = chi->Slots().begin();
  489. //TODO? should speed modifiers (eg from artifacts) affect hero movement?
  490. int ret = (i++)->second->valOfBonuses(Bonus::STACKS_SPEED);
  491. for (;i!=chi->Slots().end();i++)
  492. {
  493. ret = std::min(ret, i->second->valOfBonuses(Bonus::STACKS_SPEED));
  494. }
  495. return ret;
  496. }
  497. ui32 CGHeroInstance::getTileCost(const TerrainTile &dest, const TerrainTile &from) const
  498. {
  499. //base move cost
  500. unsigned ret = 100;
  501. //if there is road both on dest and src tiles - use road movement cost
  502. if(dest.roadType != ERoadType::NO_ROAD && from.roadType != ERoadType::NO_ROAD)
  503. {
  504. int road = std::min(dest.roadType,from.roadType); //used road ID
  505. switch(road)
  506. {
  507. case ERoadType::DIRT_ROAD:
  508. ret = 75;
  509. break;
  510. case ERoadType::GRAVEL_ROAD:
  511. ret = 65;
  512. break;
  513. case ERoadType::COBBLESTONE_ROAD:
  514. ret = 50;
  515. break;
  516. default:
  517. tlog1 << "Unknown road type: " << road << "... Something wrong!\n";
  518. break;
  519. }
  520. }
  521. else
  522. {
  523. //FIXME: in H3 presence of Nomad in army will remove terrain penalty for sand. Bonus not implemented in VCMI
  524. // NOTE: in H3 neutral stacks will ignore terrain penalty only if placed as topmost stack(s) in hero army.
  525. // This is clearly bug in H3 however intended behaviour is not clear.
  526. // Current VCMI behaviour will ignore neutrals in calculations so army in VCMI
  527. // will always have best penalty without any influence from player-defined stacks order
  528. bool nativeArmy = true;
  529. BOOST_FOREACH(auto stack, stacks)
  530. {
  531. int nativeTerrain = VLC->townh->factions[stack.second->type->faction].nativeTerrain;
  532. if (nativeTerrain != -1 && nativeTerrain != from.terType)
  533. {
  534. nativeArmy = false;
  535. break;
  536. }
  537. }
  538. if (!nativeArmy)
  539. ret = VLC->heroh->terrCosts[from.terType];
  540. }
  541. return ret;
  542. }
  543. int3 CGHeroInstance::convertPosition(int3 src, bool toh3m) //toh3m=true: manifest->h3m; toh3m=false: h3m->manifest
  544. {
  545. if (toh3m)
  546. {
  547. src.x+=1;
  548. return src;
  549. }
  550. else
  551. {
  552. src.x-=1;
  553. return src;
  554. }
  555. }
  556. int3 CGHeroInstance::getPosition(bool h3m) const //h3m=true - returns position of hero object; h3m=false - returns position of hero 'manifestation'
  557. {
  558. if (h3m)
  559. {
  560. return pos;
  561. }
  562. else
  563. {
  564. return convertPosition(pos,false);
  565. }
  566. }
  567. bool CGHeroInstance::canWalkOnSea() const
  568. {
  569. return hasBonusOfType(Bonus::FLYING_MOVEMENT) || hasBonusOfType(Bonus::WATER_WALKING);
  570. }
  571. ui8 CGHeroInstance::getSecSkillLevel(SecondarySkill skill) const
  572. {
  573. for(size_t i=0; i < secSkills.size(); ++i)
  574. if(secSkills[i].first == skill)
  575. return secSkills[i].second;
  576. return 0;
  577. }
  578. void CGHeroInstance::setSecSkillLevel(SecondarySkill which, int val, bool abs)
  579. {
  580. if(getSecSkillLevel(which) == 0)
  581. {
  582. secSkills.push_back(std::pair<SecondarySkill,ui8>(which, val));
  583. updateSkill(which, val);
  584. }
  585. else
  586. {
  587. for (unsigned i=0; i<secSkills.size(); i++)
  588. {
  589. if(secSkills[i].first == which)
  590. {
  591. if(abs)
  592. secSkills[i].second = val;
  593. else
  594. secSkills[i].second += val;
  595. if(secSkills[i].second > 3) //workaround to avoid crashes when same sec skill is given more than once
  596. {
  597. tlog1 << "Warning: Skill " << which << " increased over limit! Decreasing to Expert.\n";
  598. secSkills[i].second = 3;
  599. }
  600. updateSkill(which, secSkills[i].second); //when we know final value
  601. }
  602. }
  603. }
  604. }
  605. bool CGHeroInstance::canLearnSkill() const
  606. {
  607. return secSkills.size() < GameConstants::SKILL_PER_HERO;
  608. }
  609. int CGHeroInstance::maxMovePoints(bool onLand) const
  610. {
  611. int base;
  612. if(onLand)
  613. {
  614. // used function is f(x) = 66.6x + 1300, rounded to second digit, where x is lowest speed in army
  615. static const int baseSpeed = 1300; // base speed from creature with 0 speed
  616. int armySpeed = lowestSpeed(this) * 20 / 3;
  617. base = armySpeed * 10 + baseSpeed; // separate *10 is intentional to receive same rounding as in h3
  618. vstd::abetween(base, 1500, 2000); // base speed is limited by these values
  619. }
  620. else
  621. {
  622. base = 1500; //on water base movement is always 1500 (speed of army doesn't matter)
  623. }
  624. const Bonus::BonusType bt = onLand ? Bonus::LAND_MOVEMENT : Bonus::SEA_MOVEMENT;
  625. const int bonus = valOfBonuses(Bonus::MOVEMENT) + valOfBonuses(bt);
  626. const int subtype = onLand ? SecondarySkill::LOGISTICS : SecondarySkill::NAVIGATION;
  627. const double modifier = valOfBonuses(Bonus::SECONDARY_SKILL_PREMY, subtype) / 100.0;
  628. return int(base* (1+modifier)) + bonus;
  629. }
  630. CGHeroInstance::CGHeroInstance()
  631. : IBoatGenerator(this)
  632. {
  633. setNodeType(HERO);
  634. ID = Obj::HERO;
  635. tacticFormationEnabled = inTownGarrison = false;
  636. mana = movement = portrait = level = -1;
  637. isStanding = true;
  638. moveDir = 4;
  639. exp = 0xffffffff;
  640. visitedTown = NULL;
  641. type = NULL;
  642. boat = NULL;
  643. commander = NULL;
  644. sex = 0xff;
  645. secSkills.push_back(std::make_pair(SecondarySkill::DEFAULT, -1));
  646. }
  647. void CGHeroInstance::initHero(int SUBID)
  648. {
  649. subID = SUBID;
  650. initHero();
  651. }
  652. void CGHeroInstance::initHero()
  653. {
  654. assert(validTypes(true));
  655. if(ID == Obj::HERO)
  656. initHeroDefInfo();
  657. if(!type)
  658. type = VLC->heroh->heroes[subID];
  659. if(!vstd::contains(spells, SpellID::PRESET)) //hero starts with a spell
  660. {
  661. BOOST_FOREACH(auto spellID, type->spells)
  662. spells.insert(spellID);
  663. }
  664. else //remove placeholder
  665. spells -= SpellID::PRESET;
  666. if(!getArt(ArtifactPosition::MACH4) && !getArt(ArtifactPosition::SPELLBOOK) && type->haveSpellBook) //no catapult means we haven't read pre-existent set -> use default rules for spellbook
  667. putArtifact(ArtifactPosition::SPELLBOOK, CArtifactInstance::createNewArtifactInstance(0));
  668. if(!getArt(ArtifactPosition::MACH4))
  669. putArtifact(ArtifactPosition::MACH4, CArtifactInstance::createNewArtifactInstance(3)); //everyone has a catapult
  670. if(portrait < 0 || portrait == 255)
  671. portrait = type->imageIndex;
  672. if(!hasBonus(Selector::sourceType(Bonus::HERO_BASE_SKILL)))
  673. {
  674. for(int g=0; g<GameConstants::PRIMARY_SKILLS; ++g)
  675. {
  676. pushPrimSkill(static_cast<PrimarySkill::PrimarySkill>(g), type->heroClass->primarySkillInitial[g]);
  677. }
  678. }
  679. if(secSkills.size() == 1 && secSkills[0] == std::pair<SecondarySkill,ui8>(SecondarySkill::DEFAULT, -1)) //set secondary skills to default
  680. secSkills = type->secSkillsInit;
  681. if (!name.length())
  682. name = type->name;
  683. if (sex == 0xFF)//sex is default
  684. sex = type->sex;
  685. setFormation(false);
  686. if (!stacksCount()) //standard army//initial army
  687. {
  688. initArmy();
  689. }
  690. assert(validTypes());
  691. if (exp == 0xffffffff)
  692. {
  693. initExp();
  694. }
  695. else if (ID != Obj::PRISON)
  696. {
  697. level = VLC->heroh->level(exp);
  698. }
  699. else //warp hero at the beginning of next turn
  700. {
  701. level = 1;
  702. }
  703. if (VLC->modh->modules.COMMANDERS && !commander)
  704. {
  705. commander = new CCommanderInstance (VLC->townh->factions[type->heroClass->faction].commander);
  706. commander->setArmyObj (castToArmyObj()); //TODO: separate function for setting commanders
  707. commander->giveStackExp (exp); //after our exp is set
  708. }
  709. hoverName = VLC->generaltexth->allTexts[15];
  710. boost::algorithm::replace_first(hoverName,"%s",name);
  711. boost::algorithm::replace_first(hoverName,"%s", type->heroClass->name);
  712. if (mana < 0)
  713. mana = manaLimit();
  714. }
  715. void CGHeroInstance::initArmy(IArmyDescriptor *dst /*= NULL*/)
  716. {
  717. if(!dst)
  718. dst = this;
  719. int howManyStacks = 0; //how many stacks will hero receives <1 - 3>
  720. int pom = ran()%100;
  721. int warMachinesGiven = 0;
  722. if(pom < 9)
  723. howManyStacks = 1;
  724. else if(pom < 79)
  725. howManyStacks = 2;
  726. else
  727. howManyStacks = 3;
  728. vstd::amin(howManyStacks, type->initialArmy.size());
  729. for(int stackNo=0; stackNo < howManyStacks; stackNo++)
  730. {
  731. auto & stack = type->initialArmy[stackNo];
  732. int range = stack.maxAmount - stack.minAmount;
  733. int count = ran()%(range+1) + stack.minAmount;
  734. if(stack.creature >= CreatureID::CATAPULT &&
  735. stack.creature <= CreatureID::ARROW_TOWERS) //war machine
  736. {
  737. warMachinesGiven++;
  738. if(dst != this)
  739. continue;
  740. int slot = -1;
  741. ArtifactID aid = ArtifactID::NONE;
  742. switch (stack.creature)
  743. {
  744. case CreatureID::CATAPULT:
  745. slot = ArtifactPosition::MACH4;
  746. aid = ArtifactID::CATAPULT;
  747. break;
  748. default:
  749. aid = CArtHandler::creatureToMachineID(stack.creature);
  750. slot = 9 + aid;
  751. break;
  752. }
  753. auto convSlot = ArtifactPosition(slot);
  754. if(!getArt(convSlot))
  755. putArtifact(convSlot, CArtifactInstance::createNewArtifactInstance(aid));
  756. else
  757. tlog3 << "Hero " << name << " already has artifact at " << slot << ", omitting giving " << aid << std::endl;
  758. }
  759. else
  760. dst->setCreature(SlotID(stackNo-warMachinesGiven), stack.creature, count);
  761. }
  762. }
  763. void CGHeroInstance::initHeroDefInfo()
  764. {
  765. if(!defInfo || defInfo->id != Obj::HERO)
  766. {
  767. defInfo = new CGDefInfo();
  768. defInfo->id = Obj::HERO;
  769. defInfo->subid = subID;
  770. defInfo->printPriority = 0;
  771. defInfo->visitDir = 0xff;
  772. }
  773. for(int i=0;i<6;i++)
  774. {
  775. defInfo->blockMap[i] = 255;
  776. defInfo->visitMap[i] = 0;
  777. defInfo->coverageMap[i] = 0;
  778. defInfo->shadowCoverage[i] = 0;
  779. }
  780. defInfo->blockMap[5] = 253;
  781. defInfo->visitMap[5] = 2;
  782. defInfo->coverageMap[4] = defInfo->coverageMap[5] = 224;
  783. }
  784. CGHeroInstance::~CGHeroInstance()
  785. {
  786. }
  787. bool CGHeroInstance::needsLastStack() const
  788. {
  789. return true;
  790. }
  791. void CGHeroInstance::onHeroVisit(const CGHeroInstance * h) const
  792. {
  793. if(h == this) return; //exclude potential self-visiting
  794. if (ID == Obj::HERO)
  795. {
  796. if( cb->gameState()->getPlayerRelations(tempOwner, h->tempOwner)) //our or ally hero
  797. {
  798. //exchange
  799. cb->heroExchange(h->id, id);
  800. }
  801. else //battle
  802. {
  803. if(visitedTown) //we're in town
  804. visitedTown->onHeroVisit(h); //town will handle attacking
  805. else
  806. cb->startBattleI(h, this);
  807. }
  808. }
  809. else if(ID == Obj::PRISON)
  810. {
  811. int txt_id;
  812. if(cb->getHeroCount(h->tempOwner,false) < GameConstants::MAX_HEROES_PER_PLAYER) //free hero slot
  813. {
  814. cb->changeObjPos(id,pos+int3(1,0,0),0);
  815. //update hero parameters
  816. SetMovePoints smp;
  817. smp.hid = id;
  818. smp.val = maxMovePoints (true); //TODO: hota prison on water?
  819. cb->setMovePoints (&smp);
  820. cb->setManaPoints (id, manaLimit());
  821. cb->setObjProperty(id, ObjProperty::ID, Obj::HERO); //set ID to 34
  822. cb->giveHero(id,h->tempOwner); //recreates def and adds hero to player
  823. txt_id = 102;
  824. }
  825. else //already 8 wandering heroes
  826. {
  827. txt_id = 103;
  828. }
  829. showInfoDialog(h,txt_id,soundBase::ROGUE);
  830. }
  831. }
  832. const std::string & CGHeroInstance::getBiography() const
  833. {
  834. if (biography.length())
  835. return biography;
  836. return type->biography;
  837. }
  838. void CGHeroInstance::initObj() //TODO: use bonus system
  839. {
  840. blockVisit = true;
  841. HeroSpecial * hs = new HeroSpecial();
  842. hs->setNodeType(CBonusSystemNode::specialty);
  843. attachTo(hs); //do we ever need to detach it?
  844. if(!type)
  845. initHero(); //TODO: set up everything for prison before specialties are configured
  846. BOOST_FOREACH(const auto &spec, type->spec) //TODO: unfity with bonus system
  847. {
  848. Bonus *bonus = new Bonus();
  849. bonus->val = spec.val;
  850. bonus->sid = id.getNum(); //from the hero, specialty has no unique id
  851. bonus->duration = Bonus::PERMANENT;
  852. bonus->source = Bonus::HERO_SPECIAL;
  853. switch (spec.type)
  854. {
  855. case 1:// creature specialty
  856. {
  857. hs->growsWithLevel = true;
  858. const CCreature &specCreature = *VLC->creh->creatures[spec.additionalinfo]; //creature in which we have specialty
  859. int creLevel = specCreature.level;
  860. if(!creLevel)
  861. {
  862. if(spec.additionalinfo == 146)
  863. creLevel = 5; //treat ballista as 5-level
  864. else
  865. {
  866. tlog2 << "Warning: unknown level of " << specCreature.namePl << std::endl;
  867. continue;
  868. }
  869. }
  870. //bonus->additionalInfo = spec.additionalinfo; //creature id, should not be used again - this works only with limiter
  871. bonus->limiter.reset(new CCreatureTypeLimiter (specCreature, true)); //with upgrades
  872. bonus->type = Bonus::PRIMARY_SKILL;
  873. bonus->valType = Bonus::ADDITIVE_VALUE;
  874. bonus->subtype = PrimarySkill::ATTACK;
  875. hs->addNewBonus(bonus);
  876. bonus = new Bonus(*bonus);
  877. bonus->subtype = PrimarySkill::DEFENSE;
  878. hs->addNewBonus(bonus);
  879. //values will be calculated later
  880. bonus = new Bonus(*bonus);
  881. bonus->type = Bonus::STACKS_SPEED;
  882. bonus->val = 1; //+1 speed
  883. hs->addNewBonus(bonus);
  884. }
  885. break;
  886. case 2://secondary skill
  887. hs->growsWithLevel = true;
  888. bonus->type = Bonus::SPECIAL_SECONDARY_SKILL; //needs to be recalculated with level, based on this value
  889. bonus->valType = Bonus::BASE_NUMBER; // to receive nonzero value
  890. bonus->subtype = spec.subtype; //skill id
  891. bonus->val = spec.val; //value per level, in percent
  892. hs->addNewBonus(bonus);
  893. bonus = new Bonus(*bonus);
  894. switch (spec.additionalinfo)
  895. {
  896. case 0: //normal
  897. bonus->valType = Bonus::PERCENT_TO_BASE;
  898. break;
  899. case 1: //when it's navigation or there's no 'base' at all
  900. bonus->valType = Bonus::PERCENT_TO_ALL;
  901. break;
  902. }
  903. bonus->type = Bonus::SECONDARY_SKILL_PREMY; //value will be calculated later
  904. hs->addNewBonus(bonus);
  905. break;
  906. case 3://spell damage bonus, level dependent but calculated elsewhere
  907. bonus->type = Bonus::SPECIAL_SPELL_LEV;
  908. bonus->subtype = spec.subtype;
  909. hs->addNewBonus(bonus);
  910. break;
  911. case 4://creature stat boost
  912. switch (spec.subtype)
  913. {
  914. case 1://attack
  915. bonus->type = Bonus::PRIMARY_SKILL;
  916. bonus->subtype = PrimarySkill::ATTACK;
  917. break;
  918. case 2://defense
  919. bonus->type = Bonus::PRIMARY_SKILL;
  920. bonus->subtype = PrimarySkill::DEFENSE;
  921. break;
  922. case 3:
  923. bonus->type = Bonus::CREATURE_DAMAGE;
  924. bonus->subtype = 0; //both min and max
  925. break;
  926. case 4://hp
  927. bonus->type = Bonus::STACK_HEALTH;
  928. break;
  929. case 5:
  930. bonus->type = Bonus::STACKS_SPEED;
  931. break;
  932. default:
  933. continue;
  934. }
  935. bonus->additionalInfo = spec.additionalinfo; //creature id
  936. bonus->valType = Bonus::ADDITIVE_VALUE;
  937. bonus->limiter.reset(new CCreatureTypeLimiter (*VLC->creh->creatures[spec.additionalinfo], true));
  938. hs->addNewBonus(bonus);
  939. break;
  940. case 5://spell damage bonus in percent
  941. bonus->type = Bonus::SPECIFIC_SPELL_DAMAGE;
  942. bonus->valType = Bonus::BASE_NUMBER; // current spell system is screwed
  943. bonus->subtype = spec.subtype; //spell id
  944. hs->addNewBonus(bonus);
  945. break;
  946. case 6://damage bonus for bless (Adela)
  947. bonus->type = Bonus::SPECIAL_BLESS_DAMAGE;
  948. bonus->subtype = spec.subtype; //spell id if you ever wanted to use it otherwise
  949. bonus->additionalInfo = spec.additionalinfo; //damage factor
  950. hs->addNewBonus(bonus);
  951. break;
  952. case 7://maxed mastery for spell
  953. bonus->type = Bonus::MAXED_SPELL;
  954. bonus->subtype = spec.subtype; //spell i
  955. hs->addNewBonus(bonus);
  956. break;
  957. case 8://peculiar spells - enchantments
  958. bonus->type = Bonus::SPECIAL_PECULIAR_ENCHANT;
  959. bonus->subtype = spec.subtype; //spell id
  960. bonus->additionalInfo = spec.additionalinfo;//0, 1 for Coronius
  961. hs->addNewBonus(bonus);
  962. break;
  963. case 9://upgrade creatures
  964. {
  965. const auto &creatures = VLC->creh->creatures;
  966. bonus->type = Bonus::SPECIAL_UPGRADE;
  967. bonus->subtype = spec.subtype; //base id
  968. bonus->additionalInfo = spec.additionalinfo; //target id
  969. hs->addNewBonus(bonus);
  970. bonus = new Bonus(*bonus);
  971. BOOST_FOREACH(auto cre_id, creatures[spec.subtype]->upgrades)
  972. {
  973. bonus->subtype = cre_id; //propagate for regular upgrades of base creature
  974. hs->addNewBonus(bonus);
  975. bonus = new Bonus(*bonus);
  976. }
  977. vstd::clear_pointer(bonus);
  978. break;
  979. }
  980. case 10://resource generation
  981. bonus->type = Bonus::GENERATE_RESOURCE;
  982. bonus->subtype = spec.subtype;
  983. hs->addNewBonus(bonus);
  984. break;
  985. case 11://starting skill with mastery (Adrienne)
  986. cb->changeSecSkill(this, SecondarySkill(spec.val), spec.additionalinfo); //simply give it and forget
  987. break;
  988. case 12://army speed
  989. bonus->type = Bonus::STACKS_SPEED;
  990. hs->addNewBonus(bonus);
  991. break;
  992. case 13://Dragon bonuses (Mutare)
  993. bonus->type = Bonus::PRIMARY_SKILL;
  994. bonus->valType = Bonus::ADDITIVE_VALUE;
  995. switch (spec.subtype)
  996. {
  997. case 1:
  998. bonus->subtype = PrimarySkill::ATTACK;
  999. break;
  1000. case 2:
  1001. bonus->subtype = PrimarySkill::DEFENSE;
  1002. break;
  1003. }
  1004. bonus->limiter.reset(new HasAnotherBonusLimiter(Bonus::DRAGON_NATURE));
  1005. hs->addNewBonus(bonus);
  1006. break;
  1007. default:
  1008. tlog2 << "Unexpected hero specialty " << type <<'\n';
  1009. }
  1010. }
  1011. specialty.push_back(hs); //will it work?
  1012. BOOST_FOREACH (auto hs2, type->specialty) //copy active (probably growing) bonuses from hero prootype to hero object
  1013. {
  1014. HeroSpecial * hs = new HeroSpecial();
  1015. attachTo(hs); //do we ever need to detach it?
  1016. hs->setNodeType(CBonusSystemNode::specialty);
  1017. BOOST_FOREACH (auto bonus, hs2.bonuses)
  1018. {
  1019. hs->addNewBonus (bonus);
  1020. }
  1021. hs->growsWithLevel = hs2.growsWithLevel;
  1022. specialty.push_back(hs); //will it work?
  1023. }
  1024. //initialize bonuses
  1025. BOOST_FOREACH(auto skill_info, secSkills)
  1026. updateSkill(SecondarySkill(skill_info.first), skill_info.second);
  1027. Updatespecialty();
  1028. mana = manaLimit(); //after all bonuses are taken into account, make sure this line is the last one
  1029. type->name = name;
  1030. }
  1031. void CGHeroInstance::Updatespecialty() //TODO: calculate special value of bonuses on-the-fly?
  1032. {
  1033. BOOST_FOREACH (auto hs, specialty)
  1034. {
  1035. if (hs->growsWithLevel)
  1036. {
  1037. //const auto &creatures = VLC->creh->creatures;
  1038. BOOST_FOREACH(Bonus * b, hs->getBonusList())
  1039. {
  1040. switch (b->type)
  1041. {
  1042. case Bonus::SECONDARY_SKILL_PREMY:
  1043. b->val = (hs->valOfBonuses(Bonus::SPECIAL_SECONDARY_SKILL, b->subtype) * level);
  1044. break; //use only hero skills as bonuses to avoid feedback loop
  1045. case Bonus::PRIMARY_SKILL: //for creatures, that is
  1046. {
  1047. const CCreature * cre = NULL;
  1048. int creLevel = 0;
  1049. if (auto creatureLimiter = std::dynamic_pointer_cast<CCreatureTypeLimiter>(b->limiter)) //TODO: more general eveluation of bonuses?
  1050. {
  1051. cre = creatureLimiter->creature;
  1052. creLevel = cre->level;
  1053. if (!creLevel)
  1054. {
  1055. creLevel = 5; //treat ballista as tier 5
  1056. }
  1057. }
  1058. else //no creature found, can't calculate value
  1059. {
  1060. tlog2 << "Primary skill specialty growth supported only with creature type limiters\n";
  1061. break;
  1062. }
  1063. double primSkillModifier = (int)(level / creLevel) / 20.0;
  1064. int param;
  1065. switch (b->subtype)
  1066. {
  1067. case PrimarySkill::ATTACK:
  1068. param = cre->Attack();
  1069. break;
  1070. case PrimarySkill::DEFENSE:
  1071. param = cre->Defense();
  1072. break;
  1073. default:
  1074. continue;
  1075. }
  1076. b->val = ceil(param * (1 + primSkillModifier)) - param; //yep, overcomplicated but matches original
  1077. break;
  1078. }
  1079. }
  1080. }
  1081. }
  1082. }
  1083. }
  1084. void CGHeroInstance::updateSkill(SecondarySkill which, int val)
  1085. {
  1086. if(which == SecondarySkill::LEADERSHIP || which == SecondarySkill::LUCK)
  1087. { //luck-> VLC->generaltexth->arraytxt[73+luckSkill]; VLC->generaltexth->arraytxt[104+moraleSkill]
  1088. bool luck = which == SecondarySkill::LUCK;
  1089. Bonus::BonusType type[] = {Bonus::MORALE, Bonus::LUCK};
  1090. Bonus *b = getBonusLocalFirst(Selector::type(type[luck]) && Selector::sourceType(Bonus::SECONDARY_SKILL));
  1091. if(!b)
  1092. {
  1093. b = new Bonus(Bonus::PERMANENT, type[luck], Bonus::SECONDARY_SKILL, +val, which, which, Bonus::BASE_NUMBER);
  1094. addNewBonus(b);
  1095. }
  1096. else
  1097. b->val = +val;
  1098. }
  1099. else if(which == SecondarySkill::DIPLOMACY) //surrender discount: 20% per level
  1100. {
  1101. if(Bonus *b = getBonusLocalFirst(Selector::type(Bonus::SURRENDER_DISCOUNT) && Selector::sourceType(Bonus::SECONDARY_SKILL)))
  1102. b->val = +val;
  1103. else
  1104. addNewBonus(new Bonus(Bonus::PERMANENT, Bonus::SURRENDER_DISCOUNT, Bonus::SECONDARY_SKILL, val * 20, which));
  1105. }
  1106. int skillVal = 0;
  1107. switch (which)
  1108. {
  1109. case SecondarySkill::ARCHERY:
  1110. switch (val)
  1111. {
  1112. case 1:
  1113. skillVal = 10; break;
  1114. case 2:
  1115. skillVal = 25; break;
  1116. case 3:
  1117. skillVal = 50; break;
  1118. }
  1119. break;
  1120. case SecondarySkill::LOGISTICS:
  1121. skillVal = 10 * val; break;
  1122. case SecondarySkill::NAVIGATION:
  1123. skillVal = 50 * val; break;
  1124. case SecondarySkill::MYSTICISM:
  1125. skillVal = val; break;
  1126. case SecondarySkill::EAGLE_EYE:
  1127. skillVal = 30 + 10 * val; break;
  1128. case SecondarySkill::NECROMANCY:
  1129. skillVal = 10 * val; break;
  1130. case SecondarySkill::LEARNING:
  1131. skillVal = 5 * val; break;
  1132. case SecondarySkill::OFFENCE:
  1133. skillVal = 10 * val; break;
  1134. case SecondarySkill::ARMORER:
  1135. skillVal = 5 * val; break;
  1136. case SecondarySkill::INTELLIGENCE:
  1137. skillVal = 25 << (val-1); break;
  1138. case SecondarySkill::SORCERY:
  1139. skillVal = 5 * val; break;
  1140. case SecondarySkill::RESISTANCE:
  1141. skillVal = 5 << (val-1); break;
  1142. case SecondarySkill::FIRST_AID:
  1143. skillVal = 25 + 25*val; break;
  1144. case SecondarySkill::ESTATES:
  1145. skillVal = 125 << (val-1); break;
  1146. }
  1147. Bonus::ValueType skillValType = skillVal ? Bonus::BASE_NUMBER : Bonus::INDEPENDENT_MIN;
  1148. if(Bonus * b = getBonusList().getFirst(Selector::typeSubtype(Bonus::SECONDARY_SKILL_PREMY, which) && Selector::sourceType(Bonus::SECONDARY_SKILL))) //only local hero bonus
  1149. {
  1150. b->val = skillVal;
  1151. b->valType = skillValType;
  1152. }
  1153. else
  1154. {
  1155. Bonus *bonus = new Bonus(Bonus::PERMANENT, Bonus::SECONDARY_SKILL_PREMY, Bonus::SECONDARY_SKILL, skillVal, id.getNum(), which, skillValType);
  1156. bonus->source = Bonus::SECONDARY_SKILL;
  1157. addNewBonus(bonus);
  1158. }
  1159. }
  1160. void CGHeroInstance::setPropertyDer( ui8 what, ui32 val )
  1161. {
  1162. if(what == ObjProperty::PRIMARY_STACK_COUNT)
  1163. setStackCount(SlotID(0), val);
  1164. }
  1165. double CGHeroInstance::getHeroStrength() const
  1166. {
  1167. return sqrt((1.0 + 0.05*getPrimSkillLevel(PrimarySkill::ATTACK)) * (1.0 + 0.05*getPrimSkillLevel(PrimarySkill::DEFENSE)));
  1168. }
  1169. ui64 CGHeroInstance::getTotalStrength() const
  1170. {
  1171. double ret = getHeroStrength() * getArmyStrength();
  1172. return (ui64) ret;
  1173. }
  1174. TExpType CGHeroInstance::calculateXp(TExpType exp) const
  1175. {
  1176. return exp * (100 + valOfBonuses(Bonus::SECONDARY_SKILL_PREMY, SecondarySkill::LEARNING))/100.0;
  1177. }
  1178. ui8 CGHeroInstance::getSpellSchoolLevel(const CSpell * spell, int *outSelectedSchool) const
  1179. {
  1180. si16 skill = -1; //skill level
  1181. #define TRY_SCHOOL(schoolName, schoolMechanicsId, schoolOutId) \
  1182. if(spell-> schoolName) \
  1183. { \
  1184. int thisSchool = std::max<int>(getSecSkillLevel( \
  1185. SecondarySkill(14 + (schoolMechanicsId))), \
  1186. valOfBonuses(Bonus::MAGIC_SCHOOL_SKILL, 1 << (schoolMechanicsId))); \
  1187. if(thisSchool > skill) \
  1188. { \
  1189. skill = thisSchool; \
  1190. if(outSelectedSchool) \
  1191. *outSelectedSchool = schoolOutId; \
  1192. } \
  1193. }
  1194. TRY_SCHOOL(fire, 0, 1)
  1195. TRY_SCHOOL(air, 1, 0)
  1196. TRY_SCHOOL(water, 2, 2)
  1197. TRY_SCHOOL(earth, 3, 3)
  1198. #undef TRY_SCHOOL
  1199. vstd::amax(skill, valOfBonuses(Bonus::MAGIC_SCHOOL_SKILL, 0)); //any school bonus
  1200. vstd::amax(skill, valOfBonuses(Bonus::SPELL, spell->id.toEnum())); //given by artifact or other effect
  1201. if (hasBonusOfType(Bonus::MAXED_SPELL, spell->id))//hero specialty (Daremyth, Melodia)
  1202. skill = 3;
  1203. assert(skill >= 0 && skill <= 3);
  1204. return skill;
  1205. }
  1206. bool CGHeroInstance::canCastThisSpell(const CSpell * spell) const
  1207. {
  1208. if(!getArt(ArtifactPosition::SPELLBOOK)) //if hero has no spellbook
  1209. return false;
  1210. if(vstd::contains(spells, spell->id) //hero has this spell in spellbook
  1211. || (spell->air && hasBonusOfType(Bonus::AIR_SPELLS)) // this is air spell and hero can cast all air spells
  1212. || (spell->fire && hasBonusOfType(Bonus::FIRE_SPELLS)) // this is fire spell and hero can cast all fire spells
  1213. || (spell->water && hasBonusOfType(Bonus::WATER_SPELLS)) // this is water spell and hero can cast all water spells
  1214. || (spell->earth && hasBonusOfType(Bonus::EARTH_SPELLS)) // this is earth spell and hero can cast all earth spells
  1215. || hasBonusOfType(Bonus::SPELL, spell->id)
  1216. || hasBonusOfType(Bonus::SPELLS_OF_LEVEL, spell->level)
  1217. )
  1218. return true;
  1219. return false;
  1220. }
  1221. /**
  1222. * Calculates what creatures and how many to be raised from a battle.
  1223. * @param battleResult The results of the battle.
  1224. * @return Returns a pair with the first value indicating the ID of the creature
  1225. * type and second value the amount. Both values are returned as -1 if necromancy
  1226. * could not be applied.
  1227. */
  1228. CStackBasicDescriptor CGHeroInstance::calculateNecromancy (const BattleResult &battleResult) const
  1229. {
  1230. const ui8 necromancyLevel = getSecSkillLevel(SecondarySkill::NECROMANCY);
  1231. // Hero knows necromancy.
  1232. if (necromancyLevel > 0)
  1233. {
  1234. double necromancySkill = valOfBonuses(Bonus::SECONDARY_SKILL_PREMY, SecondarySkill::NECROMANCY)/100.0;
  1235. vstd::amin(necromancySkill, 1.0); //it's impossible to raise more creatures than all...
  1236. const std::map<ui32,si32> &casualties = battleResult.casualties[!battleResult.winner];
  1237. ui32 raisedUnits = 0;
  1238. // Figure out what to raise and how many.
  1239. const CreatureID creatureTypes[] = {CreatureID::SKELETON, CreatureID::WALKING_DEAD, CreatureID::WIGHTS, CreatureID::LICHES};
  1240. const bool improvedNecromancy = hasBonusOfType(Bonus::IMPROVED_NECROMANCY);
  1241. const CCreature *raisedUnitType = VLC->creh->creatures[creatureTypes[improvedNecromancy ? necromancyLevel : 0]];
  1242. const ui32 raisedUnitHP = raisedUnitType->valOfBonuses(Bonus::STACK_HEALTH);
  1243. //calculate creatures raised from each defeated stack
  1244. for (std::map<ui32,si32>::const_iterator it = casualties.begin(); it != casualties.end(); it++)
  1245. {
  1246. // Get lost enemy hit points convertible to units.
  1247. CCreature * c = VLC->creh->creatures[it->first];
  1248. if (c->isLiving())
  1249. {
  1250. const ui32 raisedHP = c->valOfBonuses(Bonus::STACK_HEALTH) * it->second * necromancySkill;
  1251. raisedUnits += std::min<ui32>(raisedHP / raisedUnitHP, it->second * necromancySkill); //limit to % of HP and % of original stack count
  1252. }
  1253. }
  1254. // Make room for new units.
  1255. SlotID slot = getSlotFor(raisedUnitType->idNumber);
  1256. if (slot == SlotID())
  1257. {
  1258. // If there's no room for unit, try it's upgraded version 2/3rds the size.
  1259. raisedUnitType = VLC->creh->creatures[*raisedUnitType->upgrades.begin()];
  1260. raisedUnits = (raisedUnits*2)/3;
  1261. slot = getSlotFor(raisedUnitType->idNumber);
  1262. }
  1263. if (raisedUnits <= 0)
  1264. raisedUnits = 1;
  1265. return CStackBasicDescriptor(raisedUnitType->idNumber, raisedUnits);
  1266. }
  1267. return CStackBasicDescriptor();
  1268. }
  1269. /**
  1270. * Show the necromancy dialog with information about units raised.
  1271. * @param raisedStack Pair where the first element represents ID of the raised creature
  1272. * and the second element the amount.
  1273. */
  1274. void CGHeroInstance::showNecromancyDialog(const CStackBasicDescriptor &raisedStack) const
  1275. {
  1276. InfoWindow iw;
  1277. iw.soundID = soundBase::pickup01 + ran() % 7;
  1278. iw.player = tempOwner;
  1279. iw.components.push_back(Component(raisedStack));
  1280. if (raisedStack.count > 1) // Practicing the dark arts of necromancy, ... (plural)
  1281. {
  1282. iw.text.addTxt(MetaString::GENERAL_TXT, 145);
  1283. iw.text.addReplacement(raisedStack.count);
  1284. }
  1285. else // Practicing the dark arts of necromancy, ... (singular)
  1286. {
  1287. iw.text.addTxt(MetaString::GENERAL_TXT, 146);
  1288. }
  1289. iw.text.addReplacement(raisedStack);
  1290. cb->showInfoDialog(&iw);
  1291. }
  1292. int3 CGHeroInstance::getSightCenter() const
  1293. {
  1294. return getPosition(false);
  1295. }
  1296. int CGHeroInstance::getSightRadious() const
  1297. {
  1298. return 5 + getSecSkillLevel(SecondarySkill::SCOUTING) + valOfBonuses(Bonus::SIGHT_RADIOUS); //default + scouting
  1299. }
  1300. si32 CGHeroInstance::manaRegain() const
  1301. {
  1302. if (hasBonusOfType(Bonus::FULL_MANA_REGENERATION))
  1303. return manaLimit();
  1304. return 1 + valOfBonuses(Bonus::SECONDARY_SKILL_PREMY, 8) + valOfBonuses(Bonus::MANA_REGENERATION); //1 + Mysticism level
  1305. }
  1306. // /**
  1307. // * Places an artifact in hero's backpack. If it's a big artifact equips it
  1308. // * or discards it if it cannot be equipped.
  1309. // */
  1310. // void CGHeroInstance::giveArtifact (ui32 aid) //use only for fixed artifacts
  1311. // {
  1312. // CArtifact * const artifact = VLC->arth->artifacts[aid]; //pointer to constant object
  1313. // CArtifactInstance *ai = CArtifactInstance::createNewArtifactInstance(artifact);
  1314. // ai->putAt(this, ai->firstAvailableSlot(this));
  1315. // }
  1316. int CGHeroInstance::getBoatType() const
  1317. {
  1318. switch(type->heroClass->getAlignment())
  1319. {
  1320. case EAlignment::GOOD:
  1321. return 1;
  1322. case EAlignment::EVIL:
  1323. return 0;
  1324. case EAlignment::NEUTRAL:
  1325. return 2;
  1326. default:
  1327. throw std::runtime_error("Wrong alignment!");
  1328. }
  1329. }
  1330. void CGHeroInstance::getOutOffsets(std::vector<int3> &offsets) const
  1331. {
  1332. static int3 dirs[] = { int3(0,1,0),int3(0,-1,0),int3(-1,0,0),int3(+1,0,0), int3(1,1,0),int3(-1,1,0),int3(1,-1,0),int3(-1,-1,0) };
  1333. for (size_t i = 0; i < ARRAY_COUNT(dirs); i++)
  1334. offsets += dirs[i];
  1335. }
  1336. int CGHeroInstance::getSpellCost(const CSpell *sp) const
  1337. {
  1338. return sp->costs[getSpellSchoolLevel(sp)];
  1339. }
  1340. void CGHeroInstance::pushPrimSkill( PrimarySkill::PrimarySkill which, int val )
  1341. {
  1342. addNewBonus(new Bonus(Bonus::PERMANENT, Bonus::PRIMARY_SKILL, Bonus::HERO_BASE_SKILL, val, id.getNum(), which));
  1343. }
  1344. EAlignment::EAlignment CGHeroInstance::getAlignment() const
  1345. {
  1346. return type->heroClass->getAlignment();
  1347. }
  1348. void CGHeroInstance::initExp()
  1349. {
  1350. exp=40+ (ran()) % 50;
  1351. level = 1;
  1352. }
  1353. std::string CGHeroInstance::nodeName() const
  1354. {
  1355. return "Hero " + name;
  1356. }
  1357. void CGHeroInstance::putArtifact(ArtifactPosition pos, CArtifactInstance *art)
  1358. {
  1359. assert(!getArt(pos));
  1360. art->putAt(ArtifactLocation(this, pos));
  1361. }
  1362. void CGHeroInstance::putInBackpack(CArtifactInstance *art)
  1363. {
  1364. putArtifact(art->firstBackpackSlot(this), art);
  1365. }
  1366. bool CGHeroInstance::hasSpellbook() const
  1367. {
  1368. return getArt(ArtifactPosition::SPELLBOOK);
  1369. }
  1370. void CGHeroInstance::deserializationFix()
  1371. {
  1372. artDeserializationFix(this);
  1373. //BOOST_FOREACH (auto hs, specialty)
  1374. //{
  1375. // attachTo (hs);
  1376. //}
  1377. }
  1378. CBonusSystemNode * CGHeroInstance::whereShouldBeAttached(CGameState *gs)
  1379. {
  1380. if(visitedTown)
  1381. {
  1382. if(inTownGarrison)
  1383. return visitedTown;
  1384. else
  1385. return &visitedTown->townAndVis;
  1386. }
  1387. else
  1388. return CArmedInstance::whereShouldBeAttached(gs);
  1389. }
  1390. int CGHeroInstance::movementPointsAfterEmbark(int MPsBefore, int basicCost, bool disembark /*= false*/) const
  1391. {
  1392. if(hasBonusOfType(Bonus::FREE_SHIP_BOARDING))
  1393. return (MPsBefore - basicCost) * static_cast<double>(maxMovePoints(disembark)) / maxMovePoints(!disembark);
  1394. return 0; //take all MPs otherwise
  1395. }
  1396. CGHeroInstance::ECanDig CGHeroInstance::diggingStatus() const
  1397. {
  1398. if(movement < maxMovePoints(true))
  1399. return LACK_OF_MOVEMENT;
  1400. else if(cb->getTile(getPosition(false))->terType == ETerrainType::WATER)
  1401. return WRONG_TERRAIN;
  1402. else
  1403. {
  1404. const TerrainTile *t = cb->getTile(getPosition());
  1405. //TODO look for hole
  1406. //CGI->mh->getTerrainDescr(h->getPosition(false), hlp, false);
  1407. if(/*hlp.length() || */t->blockingObjects.size() > 1)
  1408. return TILE_OCCUPIED;
  1409. else
  1410. return CAN_DIG;
  1411. }
  1412. }
  1413. ArtBearer::ArtBearer CGHeroInstance::bearerType() const
  1414. {
  1415. return ArtBearer::HERO;
  1416. }
  1417. void CGDwelling::initObj()
  1418. {
  1419. switch(ID)
  1420. {
  1421. case Obj::CREATURE_GENERATOR1:
  1422. {
  1423. CreatureID crid = VLC->objh->cregens[subID];
  1424. const CCreature *crs = VLC->creh->creatures[crid];
  1425. creatures.resize(1);
  1426. creatures[0].second.push_back(crid);
  1427. if (subID >= VLC->generaltexth->creGens.size()) //very messy workaround
  1428. {
  1429. TFaction faction = VLC->creh->creatures[subID]->faction;
  1430. assert (VLC->townh->towns[faction].dwellingNames.size());
  1431. hoverName = VLC->townh->towns[faction].dwellingNames[VLC->creh->creatures[subID]->level - 1];
  1432. }
  1433. else
  1434. hoverName = VLC->generaltexth->creGens[subID];
  1435. if(crs->level > 4)
  1436. putStack(SlotID(0), new CStackInstance(crs, (crs->growth) * 3));
  1437. if (getOwner() != PlayerColor::NEUTRAL)
  1438. cb->gameState()->players[getOwner()].dwellings.push_back (this);
  1439. }
  1440. break;
  1441. case Obj::CREATURE_GENERATOR4:
  1442. creatures.resize(4);
  1443. if(subID == 1) //Golem Factory
  1444. {
  1445. creatures[0].second.push_back(CreatureID::STONE_GOLEM);
  1446. creatures[1].second.push_back(CreatureID::IRON_GOLEM);
  1447. creatures[2].second.push_back(CreatureID::GOLD_GOLEM);
  1448. creatures[3].second.push_back(CreatureID::DIAMOND_GOLEM);
  1449. //guards
  1450. putStack(SlotID(0), new CStackInstance(CreatureID::GOLD_GOLEM, 9));
  1451. putStack(SlotID(1), new CStackInstance(CreatureID::DIAMOND_GOLEM, 6));
  1452. }
  1453. else if(subID == 0) // Elemental Conflux
  1454. {
  1455. creatures[0].second.push_back(CreatureID::AIR_ELEMENTAL);
  1456. creatures[1].second.push_back(CreatureID::FIRE_ELEMENTAL);
  1457. creatures[2].second.push_back(CreatureID::EARTH_ELEMENTAL);
  1458. creatures[3].second.push_back(CreatureID::WATER_ELEMENTAL);
  1459. //guards
  1460. putStack(SlotID(0), new CStackInstance(CreatureID::EARTH_ELEMENTAL, 12));
  1461. }
  1462. else
  1463. {
  1464. assert(0);
  1465. }
  1466. hoverName = VLC->generaltexth->creGens4[subID];
  1467. break;
  1468. case Obj::REFUGEE_CAMP:
  1469. //is handled within newturn func
  1470. break;
  1471. case Obj::WAR_MACHINE_FACTORY:
  1472. creatures.resize(3);
  1473. creatures[0].second.push_back(CreatureID::BALLISTA);
  1474. creatures[1].second.push_back(CreatureID::FIRST_AID_TENT);
  1475. creatures[2].second.push_back(CreatureID::AMMO_CART);
  1476. break;
  1477. default:
  1478. assert(0);
  1479. break;
  1480. }
  1481. }
  1482. void CGDwelling::setProperty(ui8 what, ui32 val)
  1483. {
  1484. switch (what)
  1485. {
  1486. case ObjProperty::OWNER: //change owner
  1487. if (ID == Obj::CREATURE_GENERATOR1) //single generators
  1488. {
  1489. if (tempOwner != PlayerColor::NEUTRAL)
  1490. {
  1491. std::vector<ConstTransitivePtr<CGDwelling> >* dwellings = &cb->gameState()->players[tempOwner].dwellings;
  1492. dwellings->erase (std::find(dwellings->begin(), dwellings->end(), this));
  1493. }
  1494. if (PlayerColor(val) != PlayerColor::NEUTRAL) //can new owner be neutral?
  1495. cb->gameState()->players[PlayerColor(val)].dwellings.push_back (this);
  1496. }
  1497. break;
  1498. case ObjProperty::AVAILABLE_CREATURE:
  1499. creatures.resize(1);
  1500. creatures[0].second.resize(1);
  1501. creatures[0].second[0] = CreatureID(val);
  1502. break;
  1503. }
  1504. CGObjectInstance::setProperty(what,val);
  1505. }
  1506. void CGDwelling::onHeroVisit( const CGHeroInstance * h ) const
  1507. {
  1508. if(ID == Obj::REFUGEE_CAMP && !creatures[0].first) //Refugee Camp, no available cres
  1509. {
  1510. InfoWindow iw;
  1511. iw.player = h->tempOwner;
  1512. iw.text.addTxt(MetaString::ADVOB_TXT, 44); //{%s} \n\n The camp is deserted. Perhaps you should try next week.
  1513. iw.text.addReplacement(MetaString::OBJ_NAMES, ID);
  1514. cb->sendAndApply(&iw);
  1515. return;
  1516. }
  1517. PlayerRelations::PlayerRelations relations = cb->gameState()->getPlayerRelations( h->tempOwner, tempOwner );
  1518. if ( relations == PlayerRelations::ALLIES )
  1519. return;//do not allow recruiting or capturing
  1520. if( !relations && stacksCount() > 0) //object is guarded, owned by enemy
  1521. {
  1522. BlockingDialog bd(true,false);
  1523. bd.player = h->tempOwner;
  1524. bd.text.addTxt(MetaString::GENERAL_TXT, 421); //Much to your dismay, the %s is guarded by %s %s. Do you wish to fight the guards?
  1525. bd.text.addReplacement(ID == Obj::CREATURE_GENERATOR1 ? MetaString::CREGENS : MetaString::CREGENS4, subID);
  1526. bd.text.addReplacement(MetaString::ARRAY_TXT, 176 + Slots().begin()->second->getQuantityID()*3);
  1527. bd.text.addReplacement(*Slots().begin()->second);
  1528. cb->showBlockingDialog(&bd, boost::bind(&CGDwelling::wantsFight, this, h, _1));
  1529. return;
  1530. }
  1531. if(!relations && ID != Obj::WAR_MACHINE_FACTORY)
  1532. {
  1533. cb->setOwner(this, h->tempOwner);
  1534. }
  1535. BlockingDialog bd (true,false);
  1536. bd.player = h->tempOwner;
  1537. if(ID == Obj::CREATURE_GENERATOR1 || ID == Obj::CREATURE_GENERATOR4)
  1538. {
  1539. bd.text.addTxt(MetaString::ADVOB_TXT, ID == Obj::CREATURE_GENERATOR1 ? 35 : 36); //{%s} Would you like to recruit %s? / {%s} Would you like to recruit %s, %s, %s, or %s?
  1540. bd.text.addReplacement(ID == Obj::CREATURE_GENERATOR1 ? MetaString::CREGENS : MetaString::CREGENS4, subID);
  1541. for(size_t i = 0; i < creatures.size(); i++)
  1542. bd.text.addReplacement(MetaString::CRE_PL_NAMES, creatures[i].second[0]);
  1543. }
  1544. else if(ID == Obj::REFUGEE_CAMP)
  1545. {
  1546. bd.text.addTxt(MetaString::ADVOB_TXT, 35); //{%s} Would you like to recruit %s?
  1547. bd.text.addReplacement(MetaString::OBJ_NAMES, ID);
  1548. for(size_t i = 0; i < creatures.size(); i++)
  1549. bd.text.addReplacement(MetaString::CRE_PL_NAMES, creatures[i].second[0]);
  1550. }
  1551. else if(ID == Obj::WAR_MACHINE_FACTORY)
  1552. bd.text.addTxt(MetaString::ADVOB_TXT, 157); //{War Machine Factory} Would you like to purchase War Machines?
  1553. else
  1554. throw std::runtime_error("Illegal dwelling!");
  1555. cb->showBlockingDialog(&bd, boost::bind(&CGDwelling::heroAcceptsCreatures, this, h, _1));
  1556. }
  1557. void CGDwelling::newTurn() const
  1558. {
  1559. if(cb->getDate(Date::DAY_OF_WEEK) != 1) //not first day of week
  1560. return;
  1561. //town growths and War Machines Factories are handled separately
  1562. if(ID == Obj::TOWN || ID == Obj::WAR_MACHINE_FACTORY)
  1563. return;
  1564. if(ID == Obj::REFUGEE_CAMP) //if it's a refugee camp, we need to pick an available creature
  1565. {
  1566. cb->setObjProperty(id, ObjProperty::AVAILABLE_CREATURE, VLC->creh->pickRandomMonster());
  1567. }
  1568. bool change = false;
  1569. SetAvailableCreatures sac;
  1570. sac.creatures = creatures;
  1571. sac.tid = id;
  1572. for (size_t i = 0; i < creatures.size(); i++)
  1573. {
  1574. if(creatures[i].second.size())
  1575. {
  1576. CCreature *cre = VLC->creh->creatures[creatures[i].second[0]];
  1577. TQuantity amount = cre->growth * (1 + cre->valOfBonuses(Bonus::CREATURE_GROWTH_PERCENT)/100) + cre->valOfBonuses(Bonus::CREATURE_GROWTH);
  1578. if (VLC->modh->settings.DWELLINGS_ACCUMULATE_CREATURES && ID != Obj::REFUGEE_CAMP) //camp should not try to accumulate different kinds of creatures
  1579. sac.creatures[i].first += amount;
  1580. else
  1581. sac.creatures[i].first = amount;
  1582. change = true;
  1583. }
  1584. }
  1585. if(change)
  1586. cb->sendAndApply(&sac);
  1587. }
  1588. void CGDwelling::heroAcceptsCreatures( const CGHeroInstance *h, ui32 answer ) const
  1589. {
  1590. if(!answer)
  1591. return;
  1592. CreatureID crid = creatures[0].second[0];
  1593. CCreature *crs = VLC->creh->creatures[crid];
  1594. TQuantity count = creatures[0].first;
  1595. if(crs->level == 1 && ID != Obj::REFUGEE_CAMP) //first level - creatures are for free
  1596. {
  1597. if(count) //there are available creatures
  1598. {
  1599. SlotID slot = h->getSlotFor(crid);
  1600. if(!slot.validSlot()) //no available slot
  1601. {
  1602. InfoWindow iw;
  1603. iw.player = h->tempOwner;
  1604. iw.text.addTxt(MetaString::GENERAL_TXT, 425);//The %s would join your hero, but there aren't enough provisions to support them.
  1605. iw.text.addReplacement(MetaString::CRE_PL_NAMES, crid);
  1606. cb->showInfoDialog(&iw);
  1607. }
  1608. else //give creatures
  1609. {
  1610. SetAvailableCreatures sac;
  1611. sac.tid = id;
  1612. sac.creatures = creatures;
  1613. sac.creatures[0].first = 0;
  1614. InfoWindow iw;
  1615. iw.player = h->tempOwner;
  1616. iw.text.addTxt(MetaString::GENERAL_TXT, 423); //%d %s join your army.
  1617. iw.text.addReplacement(count);
  1618. iw.text.addReplacement(MetaString::CRE_PL_NAMES, crid);
  1619. cb->showInfoDialog(&iw);
  1620. cb->sendAndApply(&sac);
  1621. cb->addToSlot(StackLocation(h, slot), crs, count);
  1622. }
  1623. }
  1624. else //there no creatures
  1625. {
  1626. InfoWindow iw;
  1627. iw.text.addTxt(MetaString::GENERAL_TXT, 422); //There are no %s here to recruit.
  1628. iw.text.addReplacement(MetaString::CRE_PL_NAMES, crid);
  1629. iw.player = h->tempOwner;
  1630. cb->sendAndApply(&iw);
  1631. }
  1632. }
  1633. else
  1634. {
  1635. if(ID == Obj::WAR_MACHINE_FACTORY) //pick available War Machines
  1636. {
  1637. //there is 1 war machine available to recruit if hero doesn't have one
  1638. SetAvailableCreatures sac;
  1639. sac.tid = id;
  1640. sac.creatures = creatures;
  1641. sac.creatures[0].first = !h->getArt(ArtifactPosition::MACH1); //ballista
  1642. sac.creatures[1].first = !h->getArt(ArtifactPosition::MACH3); //first aid tent
  1643. sac.creatures[2].first = !h->getArt(ArtifactPosition::MACH2); //ammo cart
  1644. cb->sendAndApply(&sac);
  1645. }
  1646. OpenWindow ow;
  1647. ow.id1 = id.getNum();
  1648. ow.id2 = h->id.getNum();
  1649. ow.window = (ID == Obj::CREATURE_GENERATOR1 || ID == Obj::REFUGEE_CAMP)
  1650. ? OpenWindow::RECRUITMENT_FIRST
  1651. : OpenWindow::RECRUITMENT_ALL;
  1652. cb->sendAndApply(&ow);
  1653. }
  1654. }
  1655. void CGDwelling::wantsFight( const CGHeroInstance *h, ui32 answer ) const
  1656. {
  1657. if(answer)
  1658. cb->startBattleI(h, this, boost::bind(&CGDwelling::fightOver, this, h, _1));
  1659. }
  1660. void CGDwelling::fightOver(const CGHeroInstance *h, BattleResult *result) const
  1661. {
  1662. if (result->winner == 0)
  1663. {
  1664. onHeroVisit(h);
  1665. }
  1666. }
  1667. int CGTownInstance::getSightRadious() const //returns sight distance
  1668. {
  1669. if (subID == ETownType::TOWER)
  1670. {
  1671. if (hasBuilt(BuildingID::GRAIL)) //skyship
  1672. return -1; //entire map
  1673. else if (hasBuilt(BuildingID::LOOKOUT_TOWER)) //lookout tower
  1674. return 20;
  1675. }
  1676. return 5;
  1677. }
  1678. void CGTownInstance::setPropertyDer(ui8 what, ui32 val)
  1679. {
  1680. ///this is freakin' overcomplicated solution
  1681. switch (what)
  1682. {
  1683. case ObjProperty::STRUCTURE_ADD_VISITING_HERO:
  1684. bonusingBuildings[val]->setProperty (ObjProperty::VISITORS, visitingHero->id.getNum());
  1685. break;
  1686. case ObjProperty::STRUCTURE_CLEAR_VISITORS:
  1687. bonusingBuildings[val]->setProperty (ObjProperty::STRUCTURE_CLEAR_VISITORS, 0);
  1688. break;
  1689. case ObjProperty::STRUCTURE_ADD_GARRISONED_HERO: //add garrisoned hero to visitors
  1690. bonusingBuildings[val]->setProperty (ObjProperty::VISITORS, garrisonHero->id.getNum());
  1691. break;
  1692. case ObjProperty::BONUS_VALUE_FIRST:
  1693. bonusValue.first = val;
  1694. break;
  1695. case ObjProperty::BONUS_VALUE_SECOND:
  1696. bonusValue.second = val;
  1697. break;
  1698. }
  1699. }
  1700. CGTownInstance::EFortLevel CGTownInstance::fortLevel() const //0 - none, 1 - fort, 2 - citadel, 3 - castle
  1701. {
  1702. if (hasBuilt(BuildingID::CASTLE))
  1703. return CASTLE;
  1704. if (hasBuilt(BuildingID::CITADEL))
  1705. return CITADEL;
  1706. if (hasBuilt(BuildingID::FORT))
  1707. return FORT;
  1708. return NONE;
  1709. }
  1710. int CGTownInstance::hallLevel() const // -1 - none, 0 - village, 1 - town, 2 - city, 3 - capitol
  1711. {
  1712. if (hasBuilt(BuildingID::CAPITOL))
  1713. return 3;
  1714. if (hasBuilt(BuildingID::CITY_HALL))
  1715. return 2;
  1716. if (hasBuilt(BuildingID::TOWN_HALL))
  1717. return 1;
  1718. if (hasBuilt(BuildingID::VILLAGE_HALL))
  1719. return 0;
  1720. return -1;
  1721. }
  1722. int CGTownInstance::mageGuildLevel() const
  1723. {
  1724. if (hasBuilt(BuildingID::MAGES_GUILD_5))
  1725. return 5;
  1726. if (hasBuilt(BuildingID::MAGES_GUILD_4))
  1727. return 4;
  1728. if (hasBuilt(BuildingID::MAGES_GUILD_3))
  1729. return 3;
  1730. if (hasBuilt(BuildingID::MAGES_GUILD_2))
  1731. return 2;
  1732. if (hasBuilt(BuildingID::MAGES_GUILD_1))
  1733. return 1;
  1734. return 0;
  1735. }
  1736. int CGTownInstance::creatureDwellingLevel(int dwelling) const
  1737. {
  1738. if ( dwelling<0 || dwelling >= GameConstants::CREATURES_PER_TOWN )
  1739. return -1;
  1740. for (int i=0; ; i++)
  1741. {
  1742. if (!hasBuilt(BuildingID(BuildingID::DWELL_FIRST+dwelling+i*GameConstants::CREATURES_PER_TOWN)))
  1743. return i-1;
  1744. }
  1745. }
  1746. int CGTownInstance::getHordeLevel(const int & HID) const//HID - 0 or 1; returns creature level or -1 if that horde structure is not present
  1747. {
  1748. return town->hordeLvl[HID];
  1749. }
  1750. int CGTownInstance::creatureGrowth(const int & level) const
  1751. {
  1752. return getGrowthInfo(level).totalGrowth();
  1753. }
  1754. GrowthInfo CGTownInstance::getGrowthInfo(int level) const
  1755. {
  1756. GrowthInfo ret;
  1757. if (level<0 || level >=GameConstants::CREATURES_PER_TOWN)
  1758. return ret;
  1759. if (!hasBuilt(BuildingID(BuildingID::DWELL_FIRST+level)))
  1760. return ret; //no dwelling
  1761. const CCreature *creature = VLC->creh->creatures[creatures[level].second.back()];
  1762. const int base = creature->growth;
  1763. int castleBonus = 0;
  1764. ret.entries.push_back(GrowthInfo::Entry(VLC->generaltexth->allTexts[590], base));// \n\nBasic growth %d"
  1765. if (hasBuilt(BuildingID::CASTLE))
  1766. ret.entries.push_back(GrowthInfo::Entry(subID, BuildingID::CASTLE, castleBonus = base));
  1767. else if (hasBuilt(BuildingID::CITADEL))
  1768. ret.entries.push_back(GrowthInfo::Entry(subID, BuildingID::CITADEL, castleBonus = base / 2));
  1769. if(town->hordeLvl[0] == level)//horde 1
  1770. if(hasBuilt(BuildingID::HORDE_1))
  1771. ret.entries.push_back(GrowthInfo::Entry(subID, BuildingID::HORDE_1, creature->hordeGrowth));
  1772. if(town->hordeLvl[1] == level)//horde 2
  1773. if(hasBuilt(BuildingID::HORDE_2))
  1774. ret.entries.push_back(GrowthInfo::Entry(subID, BuildingID::HORDE_2, creature->hordeGrowth));
  1775. int dwellingBonus = 0;
  1776. if(const PlayerState *p = cb->getPlayer(tempOwner, false))
  1777. {
  1778. BOOST_FOREACH(const CGDwelling *dwelling, p->dwellings)
  1779. if(vstd::contains(creatures[level].second, dwelling->creatures[0].second[0]))
  1780. dwellingBonus++;
  1781. }
  1782. if(dwellingBonus)
  1783. ret.entries.push_back(GrowthInfo::Entry(VLC->generaltexth->allTexts[591], dwellingBonus));// \nExternal dwellings %+d
  1784. //other *-of-legion-like bonuses (%d to growth cumulative with grail)
  1785. TBonusListPtr bonuses = getBonuses(Selector::type(Bonus::CREATURE_GROWTH) && Selector::subtype(level));
  1786. BOOST_FOREACH(const Bonus *b, *bonuses)
  1787. ret.entries.push_back(GrowthInfo::Entry(b->Description() + " %+d", b->val));
  1788. //statue-of-legion-like bonus: % to base+castle
  1789. TBonusListPtr bonuses2 = getBonuses(Selector::type(Bonus::CREATURE_GROWTH_PERCENT));
  1790. BOOST_FOREACH(const Bonus *b, *bonuses2)
  1791. ret.entries.push_back(GrowthInfo::Entry(b->Description() + " %+d", b->val * (base + castleBonus) / 100));
  1792. if(hasBuilt(BuildingID::GRAIL)) //grail - +50% to ALL (so far added) growth
  1793. ret.entries.push_back(GrowthInfo::Entry(subID, BuildingID::GRAIL, ret.totalGrowth() / 2));
  1794. return ret;
  1795. }
  1796. int CGTownInstance::dailyIncome() const
  1797. {
  1798. int ret = 0;
  1799. if (hasBuilt(BuildingID::GRAIL))
  1800. ret+=5000;
  1801. if (hasBuilt(BuildingID::CAPITOL))
  1802. ret+=4000;
  1803. else if (hasBuilt(BuildingID::CITY_HALL))
  1804. ret+=2000;
  1805. else if (hasBuilt(BuildingID::TOWN_HALL))
  1806. ret+=1000;
  1807. else if (hasBuilt(BuildingID::VILLAGE_HALL))
  1808. ret+=500;
  1809. return ret;
  1810. }
  1811. bool CGTownInstance::hasFort() const
  1812. {
  1813. return hasBuilt(BuildingID::FORT);
  1814. }
  1815. bool CGTownInstance::hasCapitol() const
  1816. {
  1817. return hasBuilt(BuildingID::CAPITOL);
  1818. }
  1819. CGTownInstance::CGTownInstance()
  1820. :IShipyard(this), IMarket(this), town(nullptr), builded(0), destroyed(0), identifier(0), alignment(0xff)
  1821. {
  1822. }
  1823. CGTownInstance::~CGTownInstance()
  1824. {
  1825. for (std::vector<CGTownBuilding*>::const_iterator i = bonusingBuildings.begin(); i != bonusingBuildings.end(); i++)
  1826. delete *i;
  1827. }
  1828. int CGTownInstance::spellsAtLevel(int level, bool checkGuild) const
  1829. {
  1830. if(checkGuild && mageGuildLevel() < level)
  1831. return 0;
  1832. int ret = 6 - level; //how many spells are available at this level
  1833. if (hasBuilt(BuildingID::LIBRARY, ETownType::TOWER))
  1834. ret++;
  1835. return ret;
  1836. }
  1837. bool CGTownInstance::needsLastStack() const
  1838. {
  1839. if(garrisonHero)
  1840. return true;
  1841. else return false;
  1842. }
  1843. void CGTownInstance::onHeroVisit(const CGHeroInstance * h) const
  1844. {
  1845. if( !cb->gameState()->getPlayerRelations( getOwner(), h->getOwner() ))//if this is enemy
  1846. {
  1847. if(armedGarrison() || visitingHero)
  1848. {
  1849. const CGHeroInstance *defendingHero = NULL;
  1850. const CArmedInstance *defendingArmy = this;
  1851. if(visitingHero)
  1852. defendingHero = visitingHero;
  1853. else if(garrisonHero)
  1854. defendingHero = garrisonHero;
  1855. if(defendingHero)
  1856. defendingArmy = defendingHero;
  1857. bool outsideTown = (defendingHero == visitingHero && garrisonHero);
  1858. //TODO
  1859. //"borrowing" army from garrison to visiting hero
  1860. cb->startBattleI(h, defendingArmy, getSightCenter(), h, defendingHero, false, boost::bind(&CGTownInstance::fightOver, this, h, _1), (outsideTown ? NULL : this));
  1861. }
  1862. else
  1863. {
  1864. cb->setOwner(this, h->tempOwner);
  1865. removeCapitols(h->getOwner());
  1866. cb->heroVisitCastle(this, h);
  1867. }
  1868. }
  1869. else
  1870. {
  1871. if (h->commander && !h->commander->alive) //rise commander. TODO: interactive script
  1872. {
  1873. SetCommanderProperty scp;
  1874. scp.heroid = h->id;
  1875. scp.which = SetCommanderProperty::ALIVE;
  1876. scp.amount = 1;
  1877. cb->sendAndApply (&scp);
  1878. }
  1879. cb->heroVisitCastle(this, h);
  1880. }
  1881. }
  1882. void CGTownInstance::onHeroLeave(const CGHeroInstance * h) const
  1883. {
  1884. cb->stopHeroVisitCastle(this, h);
  1885. }
  1886. void CGTownInstance::initObj()
  1887. ///initialize town structures
  1888. {
  1889. blockVisit = true;
  1890. hoverName = name + ", " + VLC->townh->factions[town->typeID].name;
  1891. if (subID == ETownType::DUNGEON)
  1892. creatures.resize(GameConstants::CREATURES_PER_TOWN+1);//extra dwelling for Dungeon
  1893. else
  1894. creatures.resize(GameConstants::CREATURES_PER_TOWN);
  1895. for (int i = 0; i < GameConstants::CREATURES_PER_TOWN; i++)
  1896. {
  1897. int dwellingLevel = creatureDwellingLevel(i);
  1898. int creaturesTotal = town->creatures[i].size();
  1899. for (int j=0; j< std::min(dwellingLevel + 1, creaturesTotal); j++)
  1900. creatures[i].second.push_back(town->creatures[i][j]);
  1901. }
  1902. switch (subID)
  1903. { //add new visitable objects
  1904. case 0:
  1905. bonusingBuildings.push_back (new COPWBonus(BuildingID::STABLES, this));
  1906. break;
  1907. case 5:
  1908. bonusingBuildings.push_back (new COPWBonus(BuildingID::MANA_VORTEX, this));
  1909. case 2: case 3: case 6:
  1910. bonusingBuildings.push_back (new CTownBonus(BuildingID::SPECIAL_4, this));
  1911. break;
  1912. case 7:
  1913. bonusingBuildings.push_back (new CTownBonus(BuildingID::SPECIAL_1, this));
  1914. break;
  1915. }
  1916. //add special bonuses from buildings
  1917. recreateBuildingsBonuses();
  1918. }
  1919. void CGTownInstance::newTurn() const
  1920. {
  1921. if (cb->getDate(Date::DAY_OF_WEEK) == 1) //reset on new week
  1922. {
  1923. //give resources for Rampart, Mystic Pond
  1924. if (hasBuilt(BuildingID::MYSTIC_POND, ETownType::RAMPART)
  1925. && cb->getDate(Date::DAY) != 1 && (tempOwner < PlayerColor::PLAYER_LIMIT))
  1926. {
  1927. int resID = rand()%4+2;//bonus to random rare resource
  1928. resID = (resID==2)?1:resID;
  1929. int resVal = rand()%4+1;//with size 1..4
  1930. cb->giveResource(tempOwner, static_cast<Res::ERes>(resID), resVal);
  1931. cb->setObjProperty (id, ObjProperty::BONUS_VALUE_FIRST, resID);
  1932. cb->setObjProperty (id, ObjProperty::BONUS_VALUE_SECOND, resVal);
  1933. }
  1934. if ( subID == ETownType::DUNGEON )
  1935. for (std::vector<CGTownBuilding*>::const_iterator i = bonusingBuildings.begin(); i!=bonusingBuildings.end(); i++)
  1936. {
  1937. if ((*i)->ID == BuildingID::MANA_VORTEX)
  1938. cb->setObjProperty (id, ObjProperty::STRUCTURE_CLEAR_VISITORS, (*i)->id); //reset visitors for Mana Vortex
  1939. }
  1940. if (tempOwner == PlayerColor::NEUTRAL) //garrison growth for neutral towns
  1941. {
  1942. std::vector<SlotID> nativeCrits; //slots
  1943. for (TSlots::const_iterator it = Slots().begin(); it != Slots().end(); it++)
  1944. {
  1945. if (it->second->type->faction == subID) //native
  1946. {
  1947. nativeCrits.push_back(it->first); //collect matching slots
  1948. }
  1949. }
  1950. if (nativeCrits.size())
  1951. {
  1952. SlotID pos = nativeCrits[rand() % nativeCrits.size()];
  1953. StackLocation sl(this, pos);
  1954. const CCreature *c = getCreature(pos);
  1955. if (rand()%100 < 90 || c->upgrades.empty()) //increase number if no upgrade available
  1956. {
  1957. cb->changeStackCount(sl, c->growth);
  1958. }
  1959. else //upgrade
  1960. {
  1961. cb->changeStackType(sl, VLC->creh->creatures[*c->upgrades.begin()]);
  1962. }
  1963. }
  1964. if ((stacksCount() < GameConstants::ARMY_SIZE && rand()%100 < 25) || Slots().empty()) //add new stack
  1965. {
  1966. int i = rand() % std::min (GameConstants::ARMY_SIZE, cb->getDate(Date::MONTH)<<1);
  1967. CreatureID c = town->creatures[i][0];
  1968. SlotID n;
  1969. TQuantity count = creatureGrowth(i);
  1970. if (!count) // no dwelling
  1971. count = VLC->creh->creatures[c]->growth;
  1972. {//no lower tiers or above current month
  1973. if ((n = getSlotFor(c)).validSlot())
  1974. {
  1975. StackLocation sl(this, n);
  1976. if (slotEmpty(n))
  1977. cb->insertNewStack(sl, VLC->creh->creatures[c], count);
  1978. else //add to existing
  1979. cb->changeStackCount(sl, count);
  1980. }
  1981. }
  1982. }
  1983. }
  1984. }
  1985. }
  1986. int3 CGTownInstance::getSightCenter() const
  1987. {
  1988. return pos - int3(2,0,0);
  1989. }
  1990. ui8 CGTownInstance::getPassableness() const
  1991. {
  1992. if (!armedGarrison())//empty castle - anyone can visit
  1993. return GameConstants::ALL_PLAYERS;
  1994. if ( tempOwner == PlayerColor::NEUTRAL )//neutral guarded - no one can visit
  1995. return 0;
  1996. ui8 mask = 0;
  1997. TeamState * ts = cb->gameState()->getPlayerTeam(tempOwner);
  1998. BOOST_FOREACH(PlayerColor it, ts->players)
  1999. mask |= 1<<it.getNum();//allies - add to possible visitors
  2000. return mask;
  2001. }
  2002. void CGTownInstance::getOutOffsets( std::vector<int3> &offsets ) const
  2003. {
  2004. offsets += int3(-1,2,0), int3(-3,2,0);
  2005. }
  2006. void CGTownInstance::fightOver( const CGHeroInstance *h, BattleResult *result ) const
  2007. {
  2008. if(result->winner == 0)
  2009. {
  2010. removeCapitols (h->getOwner());
  2011. cb->setOwner (this, h->tempOwner); //give control after checkout is done
  2012. FoWChange fw;
  2013. fw.player = h->tempOwner;
  2014. fw.mode = 1;
  2015. getSightTiles (fw.tiles); //update visibility for castle structures
  2016. cb->sendAndApply (&fw);
  2017. }
  2018. }
  2019. void CGTownInstance::removeCapitols (PlayerColor owner) const
  2020. {
  2021. if (hasCapitol()) // search if there's an older capitol
  2022. {
  2023. PlayerState* state = cb->gameState()->getPlayer (owner); //get all towns owned by player
  2024. for (auto i = state->towns.cbegin(); i < state->towns.cend(); ++i)
  2025. {
  2026. if (*i != this && (*i)->hasCapitol())
  2027. {
  2028. RazeStructures rs;
  2029. rs.tid = id;
  2030. rs.bid.insert(BuildingID::CAPITOL);
  2031. rs.destroyed = destroyed;
  2032. cb->sendAndApply(&rs);
  2033. return;
  2034. }
  2035. }
  2036. }
  2037. }
  2038. int CGTownInstance::getBoatType() const
  2039. {
  2040. switch (VLC->townh->factions[town->typeID].alignment)
  2041. {
  2042. case EAlignment::EVIL : return 0;
  2043. case EAlignment::GOOD : return 1;
  2044. case EAlignment::NEUTRAL : return 2;
  2045. }
  2046. }
  2047. int CGTownInstance::getMarketEfficiency() const
  2048. {
  2049. if (!hasBuilt(BuildingID::MARKETPLACE))
  2050. return 0;
  2051. const PlayerState *p = cb->getPlayer(tempOwner);
  2052. assert(p);
  2053. int marketCount = 0;
  2054. BOOST_FOREACH(const CGTownInstance *t, p->towns)
  2055. if(t->hasBuilt(BuildingID::MARKETPLACE))
  2056. marketCount++;
  2057. return marketCount;
  2058. }
  2059. bool CGTownInstance::allowsTrade(EMarketMode::EMarketMode mode) const
  2060. {
  2061. switch(mode)
  2062. {
  2063. case EMarketMode::RESOURCE_RESOURCE:
  2064. case EMarketMode::RESOURCE_PLAYER:
  2065. return hasBuilt(BuildingID::MARKETPLACE);
  2066. case EMarketMode::ARTIFACT_RESOURCE:
  2067. case EMarketMode::RESOURCE_ARTIFACT:
  2068. return hasBuilt(BuildingID::ARTIFACT_MERCHANT, ETownType::TOWER)
  2069. || hasBuilt(BuildingID::ARTIFACT_MERCHANT, ETownType::DUNGEON)
  2070. || hasBuilt(BuildingID::ARTIFACT_MERCHANT, ETownType::CONFLUX);
  2071. case EMarketMode::CREATURE_RESOURCE:
  2072. return hasBuilt(BuildingID::FREELANCERS_GUILD, ETownType::STRONGHOLD);
  2073. case EMarketMode::CREATURE_UNDEAD:
  2074. return hasBuilt(BuildingID::SKELETON_TRANSFORMER, ETownType::NECROPOLIS);
  2075. case EMarketMode::RESOURCE_SKILL:
  2076. return hasBuilt(BuildingID::MAGIC_UNIVERSITY, ETownType::CONFLUX);
  2077. default:
  2078. assert(0);
  2079. return false;
  2080. }
  2081. }
  2082. std::vector<int> CGTownInstance::availableItemsIds(EMarketMode::EMarketMode mode) const
  2083. {
  2084. if(mode == EMarketMode::RESOURCE_ARTIFACT)
  2085. {
  2086. std::vector<int> ret;
  2087. BOOST_FOREACH(const CArtifact *a, merchantArtifacts)
  2088. if(a)
  2089. ret.push_back(a->id);
  2090. else
  2091. ret.push_back(-1);
  2092. return ret;
  2093. }
  2094. else if ( mode == EMarketMode::RESOURCE_SKILL )
  2095. {
  2096. return universitySkills;
  2097. }
  2098. else
  2099. return IMarket::availableItemsIds(mode);
  2100. }
  2101. std::string CGTownInstance::nodeName() const
  2102. {
  2103. return "Town (" + (town ? VLC->townh->factions[town->typeID].name : "unknown") + ") of " + name;
  2104. }
  2105. void CGTownInstance::deserializationFix()
  2106. {
  2107. attachTo(&townAndVis);
  2108. if(visitingHero)
  2109. visitingHero->attachTo(&townAndVis);
  2110. if(garrisonHero)
  2111. garrisonHero->attachTo(this);
  2112. }
  2113. void CGTownInstance::recreateBuildingsBonuses()
  2114. {
  2115. BonusList bl;
  2116. getExportedBonusList().getBonuses(bl, Selector::sourceType(Bonus::TOWN_STRUCTURE));
  2117. BOOST_FOREACH(Bonus *b, bl)
  2118. removeBonus(b);
  2119. //tricky! -> checks tavern only if no bratherhood of sword or not a castle
  2120. if(subID != ETownType::CASTLE || !addBonusIfBuilt(BuildingID::BROTHERHOOD, Bonus::MORALE, +2))
  2121. addBonusIfBuilt(BuildingID::TAVERN, Bonus::MORALE, +1);
  2122. if(subID == ETownType::CASTLE) //castle
  2123. {
  2124. addBonusIfBuilt(BuildingID::LIGHTHOUSE, Bonus::SEA_MOVEMENT, +500, make_shared<CPropagatorNodeType>(PLAYER));
  2125. addBonusIfBuilt(BuildingID::GRAIL, Bonus::MORALE, +2, make_shared<CPropagatorNodeType>(PLAYER)); //colossus
  2126. }
  2127. else if(subID == ETownType::RAMPART) //rampart
  2128. {
  2129. addBonusIfBuilt(BuildingID::FOUNTAIN_OF_FORTUNE, Bonus::LUCK, +2); //fountain of fortune
  2130. addBonusIfBuilt(BuildingID::GRAIL, Bonus::LUCK, +2, make_shared<CPropagatorNodeType>(PLAYER)); //guardian spirit
  2131. }
  2132. else if(subID == ETownType::TOWER) //tower
  2133. {
  2134. addBonusIfBuilt(BuildingID::GRAIL, Bonus::PRIMARY_SKILL, +15, PrimarySkill::KNOWLEDGE); //grail
  2135. }
  2136. else if(subID == ETownType::INFERNO) //Inferno
  2137. {
  2138. addBonusIfBuilt(BuildingID::STORMCLOUDS, Bonus::PRIMARY_SKILL, +2, PrimarySkill::SPELL_POWER); //Brimstone Clouds
  2139. }
  2140. else if(subID == ETownType::NECROPOLIS) //necropolis
  2141. {
  2142. addBonusIfBuilt(BuildingID::COVER_OF_DARKNESS, Bonus::DARKNESS, +20);
  2143. addBonusIfBuilt(BuildingID::NECROMANCY_AMPLIFIER, Bonus::SECONDARY_SKILL_PREMY, +10, make_shared<CPropagatorNodeType>(PLAYER), SecondarySkill::NECROMANCY); //necromancy amplifier
  2144. addBonusIfBuilt(BuildingID::GRAIL, Bonus::SECONDARY_SKILL_PREMY, +20, make_shared<CPropagatorNodeType>(PLAYER), SecondarySkill::NECROMANCY); //Soul prison
  2145. }
  2146. else if(subID == ETownType::DUNGEON) //Dungeon
  2147. {
  2148. addBonusIfBuilt(BuildingID::GRAIL, Bonus::PRIMARY_SKILL, +12, PrimarySkill::SPELL_POWER); //grail
  2149. }
  2150. else if(subID == ETownType::STRONGHOLD) //Stronghold
  2151. {
  2152. addBonusIfBuilt(BuildingID::GRAIL, Bonus::PRIMARY_SKILL, +20, PrimarySkill::ATTACK); //grail
  2153. }
  2154. else if(subID == ETownType::FORTRESS) //Fortress
  2155. {
  2156. addBonusIfBuilt(BuildingID::GLYPHS_OF_FEAR, Bonus::PRIMARY_SKILL, +2, PrimarySkill::DEFENSE); //Glyphs of Fear
  2157. addBonusIfBuilt(BuildingID::BLOOD_OBELISK, Bonus::PRIMARY_SKILL, +2, PrimarySkill::ATTACK); //Blood Obelisk
  2158. addBonusIfBuilt(BuildingID::GRAIL, Bonus::PRIMARY_SKILL, +10, PrimarySkill::ATTACK); //grail
  2159. addBonusIfBuilt(BuildingID::GRAIL, Bonus::PRIMARY_SKILL, +10, PrimarySkill::DEFENSE); //grail
  2160. }
  2161. else if(subID == ETownType::CONFLUX)
  2162. {
  2163. }
  2164. }
  2165. bool CGTownInstance::addBonusIfBuilt(BuildingID building, Bonus::BonusType type, int val, int subtype /*= -1*/)
  2166. {
  2167. return addBonusIfBuilt(building, type, val, TPropagatorPtr(), subtype);
  2168. }
  2169. bool CGTownInstance::addBonusIfBuilt(BuildingID building, Bonus::BonusType type, int val, TPropagatorPtr prop, int subtype /*= -1*/)
  2170. {
  2171. if(hasBuilt(building))
  2172. {
  2173. std::ostringstream descr;
  2174. descr << town->buildings[building]->Name() << " ";
  2175. if(val > 0)
  2176. descr << "+";
  2177. else if(val < 0)
  2178. descr << "-";
  2179. descr << val;
  2180. Bonus *b = new Bonus(Bonus::PERMANENT, type, Bonus::TOWN_STRUCTURE, val, building, descr.str(), subtype);
  2181. if(prop)
  2182. b->addPropagator(prop);
  2183. addNewBonus(b);
  2184. return true;
  2185. }
  2186. return false;
  2187. }
  2188. void CGTownInstance::setVisitingHero(CGHeroInstance *h)
  2189. {
  2190. assert(!!visitingHero == !h);
  2191. if(h)
  2192. {
  2193. PlayerState *p = cb->gameState()->getPlayer(h->tempOwner);
  2194. assert(p);
  2195. h->detachFrom(p);
  2196. h->attachTo(&townAndVis);
  2197. visitingHero = h;
  2198. h->visitedTown = this;
  2199. h->inTownGarrison = false;
  2200. }
  2201. else
  2202. {
  2203. PlayerState *p = cb->gameState()->getPlayer(visitingHero->tempOwner);
  2204. visitingHero->visitedTown = NULL;
  2205. visitingHero->detachFrom(&townAndVis);
  2206. visitingHero->attachTo(p);
  2207. visitingHero = NULL;
  2208. }
  2209. }
  2210. void CGTownInstance::setGarrisonedHero(CGHeroInstance *h)
  2211. {
  2212. assert(!!garrisonHero == !h);
  2213. if(h)
  2214. {
  2215. PlayerState *p = cb->gameState()->getPlayer(h->tempOwner);
  2216. assert(p);
  2217. h->detachFrom(p);
  2218. h->attachTo(this);
  2219. garrisonHero = h;
  2220. h->visitedTown = this;
  2221. h->inTownGarrison = true;
  2222. }
  2223. else
  2224. {
  2225. PlayerState *p = cb->gameState()->getPlayer(garrisonHero->tempOwner);
  2226. garrisonHero->visitedTown = NULL;
  2227. garrisonHero->inTownGarrison = false;
  2228. garrisonHero->detachFrom(this);
  2229. garrisonHero->attachTo(p);
  2230. garrisonHero = NULL;
  2231. }
  2232. }
  2233. bool CGTownInstance::armedGarrison() const
  2234. {
  2235. return stacksCount() || garrisonHero;
  2236. }
  2237. CBonusSystemNode * CGTownInstance::whatShouldBeAttached()
  2238. {
  2239. return &townAndVis;
  2240. }
  2241. const CArmedInstance * CGTownInstance::getUpperArmy() const
  2242. {
  2243. if(garrisonHero)
  2244. return garrisonHero;
  2245. return this;
  2246. }
  2247. bool CGTownInstance::hasBuilt(BuildingID buildingID, int townID) const
  2248. {
  2249. if (townID == town->typeID || townID == ETownType::ANY)
  2250. return hasBuilt(buildingID);
  2251. return false;
  2252. }
  2253. bool CGTownInstance::hasBuilt(BuildingID buildingID) const
  2254. {
  2255. return vstd::contains(builtBuildings, buildingID);
  2256. }
  2257. void CGTownInstance::addHeroToStructureVisitors( const CGHeroInstance *h, si32 structureInstanceID ) const
  2258. {
  2259. if(visitingHero == h)
  2260. cb->setObjProperty(id, ObjProperty::STRUCTURE_ADD_VISITING_HERO, structureInstanceID); //add to visitors
  2261. else if(garrisonHero == h)
  2262. cb->setObjProperty(id, ObjProperty::STRUCTURE_ADD_GARRISONED_HERO, structureInstanceID); //then it must be garrisoned hero
  2263. else
  2264. {
  2265. //should never ever happen
  2266. tlog1 << "Cannot add hero " << h->name << " to visitors of structure #" << structureInstanceID << std::endl;
  2267. assert(0);
  2268. }
  2269. }
  2270. bool CGVisitableOPH::wasVisited (const CGHeroInstance * h) const
  2271. {
  2272. return vstd::contains(visitors, h->id);
  2273. }
  2274. void CGVisitableOPH::onHeroVisit( const CGHeroInstance * h ) const
  2275. {
  2276. if(!vstd::contains(visitors, h->id))
  2277. {
  2278. onNAHeroVisit(h->id, false);
  2279. switch(ID)
  2280. {
  2281. case Obj::TREE_OF_KNOWLEDGE:
  2282. case Obj::ARENA:
  2283. case Obj::LIBRARY_OF_ENLIGHTENMENT:
  2284. case Obj::SCHOOL_OF_MAGIC:
  2285. case Obj::SCHOOL_OF_WAR:
  2286. break;
  2287. default:
  2288. cb->setObjProperty(id, ObjProperty::VISITORS, h->id.getNum()); //add to the visitors
  2289. break;
  2290. }
  2291. }
  2292. else
  2293. {
  2294. onNAHeroVisit(h->id, true);
  2295. }
  2296. }
  2297. void CGVisitableOPH::initObj()
  2298. {
  2299. if(ID==Obj::TREE_OF_KNOWLEDGE)
  2300. ttype = ran()%3;
  2301. else
  2302. ttype = -1;
  2303. }
  2304. void CGVisitableOPH::treeSelected( ObjectInstanceID heroID, int resType, int resVal, TExpType expVal, ui32 result ) const
  2305. {
  2306. if(result) //player agreed to give res for exp
  2307. {
  2308. cb->giveResource(cb->getOwner(heroID), static_cast<Res::ERes>(resType), -resVal); //take resource
  2309. cb->changePrimSkill(cb->getHero(heroID), PrimarySkill::EXPERIENCE, expVal);
  2310. cb->setObjProperty(id, ObjProperty::VISITORS, heroID.getNum()); //add to the visitors
  2311. }
  2312. }
  2313. void CGVisitableOPH::onNAHeroVisit(ObjectInstanceID heroID, bool alreadyVisited) const
  2314. {
  2315. Component::EComponentType c_id = Component::PRIM_SKILL; //most used here
  2316. int subid=0, ot=0, sound = 0;
  2317. TExpType val=1;
  2318. switch(ID)
  2319. {
  2320. case Obj::ARENA:
  2321. sound = soundBase::NOMAD;
  2322. ot = 0;
  2323. break;
  2324. case Obj::MERCENARY_CAMP:
  2325. sound = soundBase::NOMAD;
  2326. subid=PrimarySkill::ATTACK;
  2327. ot=80;
  2328. break;
  2329. case Obj::MARLETTO_TOWER:
  2330. sound = soundBase::NOMAD;
  2331. subid=PrimarySkill::DEFENSE;
  2332. ot=39;
  2333. break;
  2334. case Obj::STAR_AXIS:
  2335. sound = soundBase::gazebo;
  2336. subid=PrimarySkill::SPELL_POWER;
  2337. ot=100;
  2338. break;
  2339. case Obj::GARDEN_OF_REVELATION:
  2340. sound = soundBase::GETPROTECTION;
  2341. subid=PrimarySkill::KNOWLEDGE;
  2342. ot=59;
  2343. break;
  2344. case Obj::LEARNING_STONE:
  2345. sound = soundBase::gazebo;
  2346. c_id=Component::EXPERIENCE;
  2347. ot=143;
  2348. val=1000;
  2349. break;
  2350. case Obj::TREE_OF_KNOWLEDGE:
  2351. sound = soundBase::gazebo;
  2352. c_id = Component::EXPERIENCE;
  2353. subid = 1;
  2354. ot = 147;
  2355. val = 1;
  2356. break;
  2357. case Obj::LIBRARY_OF_ENLIGHTENMENT:
  2358. sound = soundBase::gazebo;
  2359. ot = 66;
  2360. break;
  2361. case Obj::SCHOOL_OF_MAGIC:
  2362. sound = soundBase::faerie;
  2363. ot = 71;
  2364. break;
  2365. case Obj::SCHOOL_OF_WAR:
  2366. c_id=Component::PRIM_SKILL;
  2367. sound = soundBase::MILITARY;
  2368. ot = 158;
  2369. break;
  2370. }
  2371. if (!alreadyVisited)
  2372. {
  2373. switch (ID)
  2374. {
  2375. case Obj::ARENA:
  2376. {
  2377. BlockingDialog sd(false,true);
  2378. sd.soundID = sound;
  2379. sd.text.addTxt(MetaString::ADVOB_TXT,ot);
  2380. sd.components.push_back(Component(c_id, PrimarySkill::ATTACK, 2, 0));
  2381. sd.components.push_back(Component(c_id, PrimarySkill::DEFENSE, 2, 0));
  2382. sd.player = cb->getOwner(heroID);
  2383. cb->showBlockingDialog(&sd,boost::bind(&CGVisitableOPH::arenaSelected,this,heroID,_1));
  2384. return;
  2385. }
  2386. case Obj::MERCENARY_CAMP:
  2387. case Obj::MARLETTO_TOWER:
  2388. case Obj::STAR_AXIS:
  2389. case Obj::GARDEN_OF_REVELATION:
  2390. {
  2391. cb->changePrimSkill(cb->getHero(heroID), static_cast<PrimarySkill::PrimarySkill>(subid), val);
  2392. InfoWindow iw;
  2393. iw.soundID = sound;
  2394. iw.components.push_back(Component(c_id, subid, val, 0));
  2395. iw.text.addTxt(MetaString::ADVOB_TXT,ot);
  2396. iw.player = cb->getOwner(heroID);
  2397. cb->showInfoDialog(&iw);
  2398. break;
  2399. }
  2400. case Obj::LEARNING_STONE: //give exp
  2401. {
  2402. const CGHeroInstance *h = cb->getHero(heroID);
  2403. val = h->calculateXp(val);
  2404. InfoWindow iw;
  2405. iw.soundID = sound;
  2406. iw.components.push_back(Component(c_id,subid,val,0));
  2407. iw.player = cb->getOwner(heroID);
  2408. iw.text.addTxt(MetaString::ADVOB_TXT,ot);
  2409. cb->showInfoDialog(&iw);
  2410. cb->changePrimSkill(h, PrimarySkill::EXPERIENCE, val);
  2411. break;
  2412. }
  2413. case Obj::TREE_OF_KNOWLEDGE:
  2414. {
  2415. const CGHeroInstance *h = cb->getHero(heroID);
  2416. val = VLC->heroh->reqExp(h->level+val) - VLC->heroh->reqExp(h->level);
  2417. if(!ttype)
  2418. {
  2419. cb->setObjProperty(id, ObjProperty::VISITORS, heroID.getNum()); //add to the visitors
  2420. InfoWindow iw;
  2421. iw.soundID = sound;
  2422. iw.components.push_back(Component(c_id,subid,1,0));
  2423. iw.player = cb->getOwner(heroID);
  2424. iw.text.addTxt(MetaString::ADVOB_TXT,148);
  2425. cb->showInfoDialog(&iw);
  2426. cb->changePrimSkill(h, PrimarySkill::EXPERIENCE, val);
  2427. break;
  2428. }
  2429. else
  2430. {
  2431. Res::ERes res;
  2432. si32 resval;
  2433. if(ttype==1)
  2434. {
  2435. res = Res::GOLD;
  2436. resval = 2000;
  2437. ot = 149;
  2438. }
  2439. else
  2440. {
  2441. res = Res::GEMS;
  2442. resval = 10;
  2443. ot = 151;
  2444. }
  2445. if(cb->getResource(h->tempOwner,res) < resval) //not enough resources
  2446. {
  2447. ot++;
  2448. showInfoDialog(h,ot,sound);
  2449. return;
  2450. }
  2451. BlockingDialog sd (true, false);
  2452. sd.soundID = sound;
  2453. sd.player = cb->getOwner(heroID);
  2454. sd.text.addTxt(MetaString::ADVOB_TXT,ot);
  2455. sd.components.push_back (Component (Component::RESOURCE, res, resval, 0));
  2456. cb->showBlockingDialog(&sd,boost::bind(&CGVisitableOPH::treeSelected,this,heroID,res,resval,val,_1));
  2457. }
  2458. break;
  2459. }
  2460. case Obj::LIBRARY_OF_ENLIGHTENMENT:
  2461. {
  2462. const CGHeroInstance *h = cb->getHero(heroID);
  2463. int txt_id = 66;
  2464. if(h->level < 10 - 2*h->getSecSkillLevel(SecondarySkill::DIPLOMACY)) //not enough level
  2465. {
  2466. txt_id += 2;
  2467. }
  2468. else
  2469. {
  2470. cb->setObjProperty(id, ObjProperty::VISITORS, heroID.getNum()); //add to the visitors
  2471. cb->changePrimSkill(h,PrimarySkill::ATTACK,2);
  2472. cb->changePrimSkill(h,PrimarySkill::DEFENSE,2);
  2473. cb->changePrimSkill(h,PrimarySkill::KNOWLEDGE,2);
  2474. cb->changePrimSkill(h,PrimarySkill::SPELL_POWER,2);
  2475. }
  2476. showInfoDialog(h,txt_id,sound);
  2477. break;
  2478. }
  2479. case Obj::SCHOOL_OF_MAGIC:
  2480. case Obj::SCHOOL_OF_WAR:
  2481. {
  2482. int skill = (ID==Obj::SCHOOL_OF_MAGIC ? 2 : 0);
  2483. if(cb->getResource(cb->getOwner(heroID), Res::GOLD) < 1000) //not enough resources
  2484. {
  2485. showInfoDialog(heroID,ot+2,sound);
  2486. }
  2487. else
  2488. {
  2489. BlockingDialog sd(true,true);
  2490. sd.soundID = sound;
  2491. sd.player = cb->getOwner(heroID);
  2492. sd.text.addTxt(MetaString::ADVOB_TXT,ot);
  2493. sd.components.push_back(Component(c_id, skill, +1, 0));
  2494. sd.components.push_back(Component(c_id, skill+1, +1, 0));
  2495. cb->showBlockingDialog(&sd,boost::bind(&CGVisitableOPH::schoolSelected,this,heroID,_1));
  2496. }
  2497. }
  2498. break;
  2499. }
  2500. }
  2501. else
  2502. {
  2503. ot++;
  2504. showInfoDialog(heroID,ot,sound);
  2505. }
  2506. }
  2507. const std::string & CGVisitableOPH::getHoverText() const
  2508. {
  2509. int pom = -1;
  2510. switch(ID)
  2511. {
  2512. case Obj::ARENA:
  2513. pom = -1;
  2514. break;
  2515. case Obj::MERCENARY_CAMP:
  2516. pom = 8;
  2517. break;
  2518. case Obj::MARLETTO_TOWER:
  2519. pom = 7;
  2520. break;
  2521. case Obj::STAR_AXIS:
  2522. pom = 11;
  2523. break;
  2524. case Obj::GARDEN_OF_REVELATION:
  2525. pom = 4;
  2526. break;
  2527. case Obj::LEARNING_STONE:
  2528. pom = 5;
  2529. break;
  2530. case Obj::TREE_OF_KNOWLEDGE:
  2531. pom = 18;
  2532. break;
  2533. case Obj::LIBRARY_OF_ENLIGHTENMENT:
  2534. break;
  2535. case Obj::SCHOOL_OF_MAGIC:
  2536. pom = 9;
  2537. break;
  2538. case Obj::SCHOOL_OF_WAR:
  2539. pom = 10;
  2540. break;
  2541. default:
  2542. throw std::runtime_error("Wrong CGVisitableOPH object ID!\n");
  2543. }
  2544. hoverName = VLC->generaltexth->names[ID];
  2545. if(pom >= 0)
  2546. hoverName += ("\n" + VLC->generaltexth->xtrainfo[pom]);
  2547. const CGHeroInstance *h = cb->getSelectedHero(cb->getCurrentPlayer());
  2548. if(h)
  2549. {
  2550. hoverName += "\n\n";
  2551. bool visited = vstd::contains(visitors,h->id);
  2552. hoverName += visitedTxt(visited);
  2553. }
  2554. return hoverName;
  2555. }
  2556. void CGVisitableOPH::arenaSelected( ObjectInstanceID heroID, int primSkill ) const
  2557. {
  2558. cb->setObjProperty(id, ObjProperty::VISITORS, heroID.getNum()); //add to the visitors
  2559. cb->changePrimSkill(cb->getHero(heroID), static_cast<PrimarySkill::PrimarySkill>(primSkill-1), 2);
  2560. }
  2561. void CGVisitableOPH::setPropertyDer( ui8 what, ui32 val )
  2562. {
  2563. if(what == ObjProperty::VISITORS)
  2564. visitors.insert(ObjectInstanceID(val));
  2565. }
  2566. void CGVisitableOPH::schoolSelected(ObjectInstanceID heroID, ui32 which) const
  2567. {
  2568. if(!which) //player refused to pay
  2569. return;
  2570. int base = (ID == Obj::SCHOOL_OF_MAGIC ? 2 : 0);
  2571. cb->setObjProperty(id, ObjProperty::VISITORS, heroID.getNum()); //add to the visitors
  2572. cb->giveResource(cb->getOwner(heroID),Res::GOLD,-1000); //take 1000 gold
  2573. cb->changePrimSkill(cb->getHero(heroID), static_cast<PrimarySkill::PrimarySkill>(base + which-1), +1); //give appropriate skill
  2574. }
  2575. COPWBonus::COPWBonus (BuildingID index, CGTownInstance *TOWN)
  2576. {
  2577. ID = index;
  2578. town = TOWN;
  2579. id = town->bonusingBuildings.size();
  2580. }
  2581. void COPWBonus::setProperty(ui8 what, ui32 val)
  2582. {
  2583. switch (what)
  2584. {
  2585. case ObjProperty::VISITORS:
  2586. visitors.insert(val);
  2587. break;
  2588. case ObjProperty::STRUCTURE_CLEAR_VISITORS:
  2589. visitors.clear();
  2590. break;
  2591. }
  2592. }
  2593. void COPWBonus::onHeroVisit (const CGHeroInstance * h) const
  2594. {
  2595. ObjectInstanceID heroID = h->id;
  2596. if (town->hasBuilt(ID))
  2597. {
  2598. InfoWindow iw;
  2599. iw.player = h->tempOwner;
  2600. switch (town->subID)
  2601. {
  2602. case ETownType::CASTLE: //Stables
  2603. if (!h->hasBonusFrom(Bonus::OBJECT, Obj::STABLES)) //does not stack with advMap Stables
  2604. {
  2605. GiveBonus gb;
  2606. gb.bonus = Bonus(Bonus::ONE_WEEK, Bonus::LAND_MOVEMENT, Bonus::OBJECT, 600, 94, VLC->generaltexth->arraytxt[100]);
  2607. gb.id = heroID.getNum();
  2608. cb->giveHeroBonus(&gb);
  2609. iw.text << VLC->generaltexth->allTexts[580];
  2610. cb->showInfoDialog(&iw);
  2611. }
  2612. break;
  2613. case ETownType::DUNGEON: //Mana Vortex
  2614. if (visitors.empty() && h->mana <= h->manaLimit() * 2)
  2615. {
  2616. cb->setManaPoints (heroID, 2 * h->manaLimit());
  2617. //TODO: investigate line below
  2618. //cb->setObjProperty (town->id, ObjProperty::VISITED, true);
  2619. iw.text << VLC->generaltexth->allTexts[579];
  2620. cb->showInfoDialog(&iw);
  2621. town->addHeroToStructureVisitors(h, id);
  2622. }
  2623. break;
  2624. }
  2625. }
  2626. }
  2627. CTownBonus::CTownBonus (BuildingID index, CGTownInstance *TOWN)
  2628. {
  2629. ID = index;
  2630. town = TOWN;
  2631. id = town->bonusingBuildings.size();
  2632. }
  2633. void CTownBonus::setProperty (ui8 what, ui32 val)
  2634. {
  2635. if(what == ObjProperty::VISITORS)
  2636. visitors.insert(ObjectInstanceID(val));
  2637. }
  2638. void CTownBonus::onHeroVisit (const CGHeroInstance * h) const
  2639. {
  2640. ObjectInstanceID heroID = h->id;
  2641. if (town->hasBuilt(ID) && visitors.find(heroID) == visitors.end())
  2642. {
  2643. InfoWindow iw;
  2644. PrimarySkill::PrimarySkill what = PrimarySkill::ATTACK;
  2645. int val=0, mid=0;
  2646. switch (ID)
  2647. {
  2648. case BuildingID::SPECIAL_4:
  2649. switch(town->subID)
  2650. {
  2651. case ETownType::TOWER: //wall
  2652. what = PrimarySkill::KNOWLEDGE;
  2653. val = 1;
  2654. mid = 581;
  2655. iw.components.push_back (Component(Component::PRIM_SKILL, 3, 1, 0));
  2656. break;
  2657. case ETownType::INFERNO: //order of fire
  2658. what = PrimarySkill::SPELL_POWER;
  2659. val = 1;
  2660. mid = 582;
  2661. iw.components.push_back (Component(Component::PRIM_SKILL, 2, 1, 0));
  2662. break;
  2663. case ETownType::STRONGHOLD://hall of valhalla
  2664. what = PrimarySkill::ATTACK;
  2665. val = 1;
  2666. mid = 584;
  2667. iw.components.push_back (Component(Component::PRIM_SKILL, 0, 1, 0));
  2668. break;
  2669. case ETownType::DUNGEON://academy of battle scholars
  2670. what = PrimarySkill::EXPERIENCE;
  2671. val = h->calculateXp(1000);
  2672. mid = 583;
  2673. iw.components.push_back (Component(Component::EXPERIENCE, 0, val, 0));
  2674. break;
  2675. }
  2676. break;
  2677. case BuildingID::SPECIAL_1:
  2678. switch(town->subID)
  2679. {
  2680. case ETownType::FORTRESS: //cage of warlords
  2681. what = PrimarySkill::DEFENSE;
  2682. val = 1;
  2683. mid = 585;
  2684. iw.components.push_back (Component(Component::PRIM_SKILL, 1, 1, 0));
  2685. break;
  2686. }
  2687. break;
  2688. }
  2689. assert(mid);
  2690. iw.player = cb->getOwner(heroID);
  2691. iw.text << VLC->generaltexth->allTexts[mid];
  2692. cb->showInfoDialog(&iw);
  2693. cb->changePrimSkill (cb->getHero(heroID), what, val);
  2694. town->addHeroToStructureVisitors(h, id);
  2695. }
  2696. }
  2697. const std::string & CGCreature::getHoverText() const
  2698. {
  2699. MetaString ms;
  2700. int pom = stacks.begin()->second->getQuantityID();
  2701. pom = 172 + 3*pom;
  2702. ms.addTxt(MetaString::ARRAY_TXT,pom);
  2703. ms << " " ;
  2704. ms.addTxt(MetaString::CRE_PL_NAMES,subID);
  2705. ms.toString(hoverName);
  2706. if(const CGHeroInstance *selHero = cb->getSelectedHero(cb->getCurrentPlayer()))
  2707. {
  2708. std::vector<std::string> * texts = &VLC->generaltexth->threat;
  2709. hoverName += "\n\n ";
  2710. hoverName += (*texts)[0];
  2711. int choice;
  2712. double ratio = ((double)getArmyStrength() / selHero->getTotalStrength());
  2713. if (ratio < 0.1) choice = 1;
  2714. else if (ratio < 0.25) choice = 2;
  2715. else if (ratio < 0.6) choice = 3;
  2716. else if (ratio < 0.9) choice = 4;
  2717. else if (ratio < 1.1) choice = 5;
  2718. else if (ratio < 1.3) choice = 6;
  2719. else if (ratio < 1.8) choice = 7;
  2720. else if (ratio < 2.5) choice = 8;
  2721. else if (ratio < 4) choice = 9;
  2722. else if (ratio < 8) choice = 10;
  2723. else if (ratio < 20) choice = 11;
  2724. else choice = 12;
  2725. hoverName += (*texts)[choice];
  2726. }
  2727. return hoverName;
  2728. }
  2729. void CGCreature::onHeroVisit( const CGHeroInstance * h ) const
  2730. {
  2731. int action = takenAction(h);
  2732. switch( action ) //decide what we do...
  2733. {
  2734. case -2: //fight
  2735. fight(h);
  2736. break;
  2737. case -1: //flee
  2738. {
  2739. flee(h);
  2740. break;
  2741. }
  2742. case 0: //join for free
  2743. {
  2744. BlockingDialog ynd(true,false);
  2745. ynd.player = h->tempOwner;
  2746. ynd.text.addTxt(MetaString::ADVOB_TXT, 86);
  2747. ynd.text.addReplacement(MetaString::CRE_PL_NAMES, subID);
  2748. cb->showBlockingDialog(&ynd,boost::bind(&CGCreature::joinDecision,this,h,0,_1));
  2749. break;
  2750. }
  2751. default: //join for gold
  2752. {
  2753. assert(action > 0);
  2754. //ask if player agrees to pay gold
  2755. BlockingDialog ynd(true,false);
  2756. ynd.player = h->tempOwner;
  2757. std::string tmp = VLC->generaltexth->advobtxt[90];
  2758. boost::algorithm::replace_first(tmp,"%d",boost::lexical_cast<std::string>(getStackCount(SlotID(0))));
  2759. boost::algorithm::replace_first(tmp,"%d",boost::lexical_cast<std::string>(action));
  2760. boost::algorithm::replace_first(tmp,"%s",VLC->creh->creatures[subID]->namePl);
  2761. ynd.text << tmp;
  2762. cb->showBlockingDialog(&ynd,boost::bind(&CGCreature::joinDecision,this,h,action,_1));
  2763. break;
  2764. }
  2765. }
  2766. }
  2767. void CGCreature::endBattle( BattleResult *result ) const
  2768. {
  2769. if(result->winner==0)
  2770. {
  2771. cb->removeObject(this);
  2772. }
  2773. else
  2774. {
  2775. //int killedAmount=0;
  2776. //for(std::set<std::pair<ui32,si32> >::iterator i=result->casualties[1].begin(); i!=result->casualties[1].end(); i++)
  2777. // if(i->first == subID)
  2778. // killedAmount += i->second;
  2779. //cb->setAmount(id, slots.find(0)->second.second - killedAmount);
  2780. /*
  2781. MetaString ms;
  2782. int pom = slots.find(0)->second.getQuantityID();
  2783. pom = 174 + 3*pom + 1;
  2784. ms << std::pair<ui8,ui32>(6,pom) << " " << std::pair<ui8,ui32>(7,subID);
  2785. cb->setHoverName(id,&ms);
  2786. cb->setObjProperty(id, 11, slots.begin()->second.count * 1000);
  2787. */
  2788. //merge stacks into one
  2789. TSlots::const_iterator i;
  2790. CCreature * cre = VLC->creh->creatures[restore.basicType];
  2791. for (i = stacks.begin(); i != stacks.end(); i++)
  2792. {
  2793. if (cre->isMyUpgrade(i->second->type))
  2794. {
  2795. cb->changeStackType (StackLocation(this, i->first), cre); //un-upgrade creatures
  2796. }
  2797. }
  2798. //first stack has to be at slot 0 -> if original one got killed, move there first remaining stack
  2799. if(!hasStackAtSlot(SlotID(0)))
  2800. cb->moveStack(StackLocation(this, stacks.begin()->first), StackLocation(this, SlotID(0)), stacks.begin()->second->count);
  2801. while (stacks.size() > 1) //hopefully that's enough
  2802. {
  2803. // TODO it's either overcomplicated (if we assume there'll be only one stack) or buggy (if we allow multiple stacks... but that'll also cause troubles elsewhere)
  2804. i = stacks.end();
  2805. i--;
  2806. SlotID slot = getSlotFor(i->second->type);
  2807. if (slot == i->first) //no reason to move stack to its own slot
  2808. break;
  2809. else
  2810. cb->moveStack (StackLocation(this, i->first), StackLocation(this, slot), i->second->count);
  2811. }
  2812. cb->setObjProperty(id, ObjProperty::MONSTER_POWER, stacks.begin()->second->count * 1000); //remember casualties
  2813. }
  2814. }
  2815. void CGCreature::initObj()
  2816. {
  2817. blockVisit = true;
  2818. switch(character)
  2819. {
  2820. case 0:
  2821. character = -4;
  2822. break;
  2823. case 1:
  2824. character = 1 + ran()%7;
  2825. break;
  2826. case 2:
  2827. character = 1 + ran()%10;
  2828. break;
  2829. case 3:
  2830. character = 4 + ran()%7;
  2831. break;
  2832. case 4:
  2833. character = 10;
  2834. break;
  2835. }
  2836. stacks[SlotID(0)]->setType(CreatureID(subID));
  2837. TQuantity &amount = stacks[SlotID(0)]->count;
  2838. CCreature &c = *VLC->creh->creatures[subID];
  2839. if(!amount)
  2840. {
  2841. if(c.ammMax == c.ammMin)
  2842. amount = c.ammMax;
  2843. else
  2844. amount = c.ammMin + (ran() % (c.ammMax - c.ammMin));
  2845. if(!amount) //armies with 0 creatures are illegal
  2846. {
  2847. tlog2 << "Problem: stack " << nodeName() << " cannot have 0 creatures. Check properties of " << c.nodeName() << std::endl;
  2848. amount = 1;
  2849. }
  2850. }
  2851. temppower = stacks[SlotID(0)]->count * 1000;
  2852. }
  2853. void CGCreature::newTurn() const
  2854. {//Works only for stacks of single type of size up to 2 millions
  2855. if (stacks.begin()->second->count < VLC->modh->settings.CREEP_SIZE && cb->getDate(Date::DAY_OF_WEEK) == 1 && cb->getDate(Date::DAY) > 1)
  2856. {
  2857. ui32 power = temppower * (100 + VLC->modh->settings.WEEKLY_GROWTH)/100;
  2858. cb->setObjProperty(id, ObjProperty::MONSTER_COUNT, std::min (power/1000 , (ui32)VLC->modh->settings.CREEP_SIZE)); //set new amount
  2859. cb->setObjProperty(id, ObjProperty::MONSTER_POWER, power); //increase temppower
  2860. }
  2861. if (VLC->modh->modules.STACK_EXP)
  2862. cb->setObjProperty(id, ObjProperty::MONSTER_EXP, VLC->modh->settings.NEUTRAL_STACK_EXP); //for testing purpose
  2863. }
  2864. void CGCreature::setPropertyDer(ui8 what, ui32 val)
  2865. {
  2866. switch (what)
  2867. {
  2868. case ObjProperty::MONSTER_COUNT:
  2869. stacks[SlotID(0)]->count = val;
  2870. break;
  2871. case ObjProperty::MONSTER_POWER:
  2872. temppower = val;
  2873. break;
  2874. case ObjProperty::MONSTER_EXP:
  2875. giveStackExp(val);
  2876. break;
  2877. case ObjProperty::MONSTER_RESTORE_TYPE:
  2878. restore.basicType = val;
  2879. break;
  2880. }
  2881. }
  2882. int CGCreature::takenAction(const CGHeroInstance *h, bool allowJoin) const
  2883. {
  2884. //calculate relative strength of hero and creatures armies
  2885. double relStrength = double(h->getTotalStrength()) / getArmyStrength();
  2886. int powerFactor;
  2887. if(relStrength >= 7)
  2888. powerFactor = 11;
  2889. else if(relStrength >= 1)
  2890. powerFactor = (int)(2*(relStrength-1));
  2891. else if(relStrength >= 0.5)
  2892. powerFactor = -1;
  2893. else if(relStrength >= 0.333)
  2894. powerFactor = -2;
  2895. else
  2896. powerFactor = -3;
  2897. std::set<CreatureID> myKindCres; //what creatures are the same kind as we
  2898. const CCreature * myCreature = VLC->creh->creatures[subID];
  2899. myKindCres.insert(myCreature->idNumber); //we
  2900. myKindCres.insert(myCreature->upgrades.begin(), myCreature->upgrades.end()); //our upgrades
  2901. BOOST_FOREACH(ConstTransitivePtr<CCreature> &crea, VLC->creh->creatures)
  2902. {
  2903. if(vstd::contains(crea->upgrades, myCreature->idNumber)) //it's our base creatures
  2904. myKindCres.insert(crea->idNumber);
  2905. }
  2906. int count = 0, //how many creatures of similar kind has hero
  2907. totalCount = 0;
  2908. for (TSlots::const_iterator i = h->Slots().begin(); i != h->Slots().end(); i++)
  2909. {
  2910. if(vstd::contains(myKindCres,i->second->type->idNumber))
  2911. count += i->second->count;
  2912. totalCount += i->second->count;
  2913. }
  2914. int sympathy = 0; // 0 if hero have no similar creatures
  2915. if(count)
  2916. sympathy++; // 1 - if hero have at least 1 similar creature
  2917. if(count*2 > totalCount)
  2918. sympathy++; // 2 - hero have similar creatures more that 50%
  2919. int charisma = powerFactor + h->getSecSkillLevel(SecondarySkill::DIPLOMACY) + sympathy;
  2920. if(charisma < character) //creatures will fight
  2921. return -2;
  2922. if (allowJoin)
  2923. {
  2924. if(h->getSecSkillLevel(SecondarySkill::DIPLOMACY) + sympathy + 1 >= character)
  2925. return 0; //join for free
  2926. else if(h->getSecSkillLevel(SecondarySkill::DIPLOMACY) * 2 + sympathy + 1 >= character)
  2927. return VLC->creh->creatures[subID]->cost[6] * getStackCount(SlotID(0)); //join for gold
  2928. }
  2929. //we are still here - creatures have not joined hero, flee or fight
  2930. if (charisma > character)
  2931. return -1; //flee
  2932. else
  2933. return -2; //fight
  2934. }
  2935. void CGCreature::fleeDecision(const CGHeroInstance *h, ui32 pursue) const
  2936. {
  2937. if(pursue)
  2938. {
  2939. fight(h);
  2940. }
  2941. else
  2942. {
  2943. cb->removeObject(this);
  2944. }
  2945. }
  2946. void CGCreature::joinDecision(const CGHeroInstance *h, int cost, ui32 accept) const
  2947. {
  2948. if(!accept)
  2949. {
  2950. if(takenAction(h,false) == -1) //they flee
  2951. {
  2952. flee(h);
  2953. }
  2954. else //they fight
  2955. {
  2956. showInfoDialog(h,87,0);//Insulted by your refusal of their offer, the monsters attack!
  2957. fight(h);
  2958. }
  2959. }
  2960. else //accepted
  2961. {
  2962. if (cb->getResource(h->tempOwner, Res::GOLD) < cost) //player don't have enough gold!
  2963. {
  2964. InfoWindow iw;
  2965. iw.player = h->tempOwner;
  2966. iw.text << std::pair<ui8,ui32>(1,29); //You don't have enough gold
  2967. cb->showInfoDialog(&iw);
  2968. //act as if player refused
  2969. joinDecision(h,cost,false);
  2970. return;
  2971. }
  2972. //take gold
  2973. if(cost)
  2974. cb->giveResource(h->tempOwner,Res::GOLD,-cost);
  2975. cb->tryJoiningArmy(this, h, true, true);
  2976. }
  2977. }
  2978. void CGCreature::fight( const CGHeroInstance *h ) const
  2979. {
  2980. //split stacks
  2981. //TODO: multiple creature types in a stack?
  2982. int basicType = stacks.begin()->second->type->idNumber;
  2983. cb->setObjProperty(id, ObjProperty::MONSTER_RESTORE_TYPE, basicType); //store info about creature stack
  2984. double relativePower = static_cast<double>(h->getTotalStrength()) / getArmyStrength();
  2985. int stacksCount;
  2986. //TODO: number depends on tile type
  2987. if (relativePower < 0.5)
  2988. {
  2989. stacksCount = 7;
  2990. }
  2991. else if (relativePower < 0.67)
  2992. {
  2993. stacksCount = 7;
  2994. }
  2995. else if (relativePower < 1)
  2996. {
  2997. stacksCount = 6;
  2998. }
  2999. else if (relativePower < 1.5)
  3000. {
  3001. stacksCount = 5;
  3002. }
  3003. else if (relativePower < 2)
  3004. {
  3005. stacksCount = 4;
  3006. }
  3007. else
  3008. {
  3009. stacksCount = 3;
  3010. }
  3011. int stackSize;
  3012. SlotID sourceSlot = stacks.begin()->first;
  3013. SlotID destSlot;
  3014. for (int stacksLeft = stacksCount; stacksLeft > 1; --stacksLeft)
  3015. {
  3016. stackSize = stacks.begin()->second->count / stacksLeft;
  3017. if (stackSize)
  3018. {
  3019. if ((destSlot = getFreeSlot()).validSlot())
  3020. cb->moveStack(StackLocation(this, sourceSlot), StackLocation(this, destSlot), stackSize);
  3021. else
  3022. {
  3023. tlog2 <<"Warning! Not enough empty slots to split stack!";
  3024. break;
  3025. }
  3026. }
  3027. else break;
  3028. }
  3029. if (stacksCount > 1)
  3030. {
  3031. if (rand()%100 < 50) //upgrade
  3032. {
  3033. SlotID slotId = SlotID(stacks.size() / 2);
  3034. if(ui32 upgradesSize = getStack(slotId).type->upgrades.size())
  3035. {
  3036. auto it = getStack(slotId).type->upgrades.cbegin(); //pick random in case there are more
  3037. std::advance (it, rand() % upgradesSize);
  3038. cb->changeStackType(StackLocation(this, slotId), VLC->creh->creatures[*it]);
  3039. }
  3040. }
  3041. }
  3042. cb->startBattleI(h, this, boost::bind(&CGCreature::endBattle,this,_1));
  3043. }
  3044. void CGCreature::flee( const CGHeroInstance * h ) const
  3045. {
  3046. BlockingDialog ynd(true,false);
  3047. ynd.player = h->tempOwner;
  3048. ynd.text.addTxt(MetaString::ADVOB_TXT,91);
  3049. ynd.text.addReplacement(MetaString::CRE_PL_NAMES, subID);
  3050. cb->showBlockingDialog(&ynd,boost::bind(&CGCreature::fleeDecision,this,h,_1));
  3051. }
  3052. void CGMine::onHeroVisit( const CGHeroInstance * h ) const
  3053. {
  3054. int relations = cb->gameState()->getPlayerRelations(h->tempOwner, tempOwner);
  3055. if(relations == 2) //we're visiting our mine
  3056. {
  3057. cb->showGarrisonDialog(id,h->id,true,0);
  3058. return;
  3059. }
  3060. else if (relations == 1)//ally
  3061. return;
  3062. if(stacksCount()) //Mine is guarded
  3063. {
  3064. BlockingDialog ynd(true,false);
  3065. ynd.player = h->tempOwner;
  3066. ynd.text.addTxt(MetaString::ADVOB_TXT, subID == 7 ? 84 : 187);
  3067. cb->showBlockingDialog(&ynd,boost::bind(&CGMine::fight, this, _1, h));
  3068. return;
  3069. }
  3070. flagMine(h->tempOwner);
  3071. }
  3072. void CGMine::newTurn() const
  3073. {
  3074. if(cb->getDate() == 1)
  3075. return;
  3076. if (tempOwner == PlayerColor::NEUTRAL)
  3077. return;
  3078. cb->giveResource(tempOwner, producedResource, producedQuantity);
  3079. }
  3080. void CGMine::initObj()
  3081. {
  3082. if(subID >= 7) //Abandoned Mine
  3083. {
  3084. //set guardians
  3085. int howManyTroglodytes = 100 + ran()%100;
  3086. CStackInstance *troglodytes = new CStackInstance(CreatureID::TROGLODYTES, howManyTroglodytes);
  3087. putStack(SlotID(0), troglodytes);
  3088. //after map reading tempOwner placeholds bitmask for allowed resources
  3089. std::vector<Res::ERes> possibleResources;
  3090. for (int i = 0; i < PlayerColor::PLAYER_LIMIT_I; i++)
  3091. if(tempOwner.getNum() & 1<<i) //NOTE: reuse of tempOwner
  3092. possibleResources.push_back(static_cast<Res::ERes>(i));
  3093. assert(possibleResources.size());
  3094. producedResource = possibleResources[ran()%possibleResources.size()];
  3095. tempOwner = PlayerColor::NEUTRAL;
  3096. hoverName = VLC->generaltexth->mines[7].first + "\n" + VLC->generaltexth->allTexts[202] + " " + troglodytes->getQuantityTXT(false) + " " + troglodytes->type->namePl;
  3097. }
  3098. else
  3099. {
  3100. producedResource = static_cast<Res::ERes>(subID);
  3101. MetaString ms;
  3102. ms << std::pair<ui8,ui32>(9,producedResource);
  3103. if(tempOwner >= PlayerColor::PLAYER_LIMIT)
  3104. tempOwner = PlayerColor::NEUTRAL;
  3105. else
  3106. ms << " (" << std::pair<ui8,ui32>(6,23+tempOwner.getNum()) << ")";
  3107. ms.toString(hoverName);
  3108. }
  3109. producedQuantity = defaultResProduction();
  3110. }
  3111. void CGMine::fight(ui32 agreed, const CGHeroInstance *h) const
  3112. {
  3113. cb->startBattleI(h, this, boost::bind(&CGMine::endBattle, this, _1, h->tempOwner));
  3114. }
  3115. void CGMine::endBattle(BattleResult *result, PlayerColor attackingPlayer) const
  3116. {
  3117. if(result->winner == 0) //attacker won
  3118. {
  3119. if(subID == 7)
  3120. {
  3121. showInfoDialog(attackingPlayer,85,0);
  3122. }
  3123. flagMine(attackingPlayer);
  3124. }
  3125. }
  3126. void CGMine::flagMine(PlayerColor player) const
  3127. {
  3128. assert(tempOwner != player);
  3129. cb->setOwner(this, player); //not ours? flag it!
  3130. MetaString ms;
  3131. ms << std::pair<ui8,ui32>(9,subID) << "\n(" << std::pair<ui8,ui32>(6,23+player.getNum()) << ")";
  3132. if(subID == 7)
  3133. {
  3134. ms << "(%s)";
  3135. ms.addReplacement(MetaString::RES_NAMES, producedResource);
  3136. }
  3137. cb->setHoverName(this,&ms);
  3138. InfoWindow iw;
  3139. iw.soundID = soundBase::FLAGMINE;
  3140. iw.text.addTxt(MetaString::MINE_EVNTS,producedResource); //not use subID, abandoned mines uses default mine texts
  3141. iw.player = player;
  3142. iw.components.push_back(Component(Component::RESOURCE,producedResource,producedQuantity,-1));
  3143. cb->showInfoDialog(&iw);
  3144. }
  3145. ui32 CGMine::defaultResProduction()
  3146. {
  3147. switch(producedResource)
  3148. {
  3149. case Res::WOOD:
  3150. case Res::ORE:
  3151. return 2;
  3152. case Res::GOLD:
  3153. return 1000;
  3154. default:
  3155. return 1;
  3156. }
  3157. }
  3158. void CGResource::initObj()
  3159. {
  3160. blockVisit = true;
  3161. hoverName = VLC->generaltexth->restypes[subID];
  3162. if(!amount)
  3163. {
  3164. switch(subID)
  3165. {
  3166. case 6:
  3167. amount = 500 + (ran()%6)*100;
  3168. break;
  3169. case 0: case 2:
  3170. amount = 6 + (ran()%5);
  3171. break;
  3172. default:
  3173. amount = 3 + (ran()%3);
  3174. break;
  3175. }
  3176. }
  3177. }
  3178. void CGResource::onHeroVisit( const CGHeroInstance * h ) const
  3179. {
  3180. if(stacksCount())
  3181. {
  3182. if(message.size())
  3183. {
  3184. BlockingDialog ynd(true,false);
  3185. ynd.player = h->getOwner();
  3186. ynd.text << message;
  3187. cb->showBlockingDialog(&ynd,boost::bind(&CGResource::fightForRes,this,_1,h));
  3188. }
  3189. else
  3190. {
  3191. fightForRes(1,h);
  3192. }
  3193. }
  3194. else
  3195. {
  3196. if(message.length())
  3197. {
  3198. InfoWindow iw;
  3199. iw.player = h->tempOwner;
  3200. iw.text << message;
  3201. cb->showInfoDialog(&iw);
  3202. }
  3203. collectRes(h->getOwner());
  3204. }
  3205. }
  3206. void CGResource::collectRes( PlayerColor player ) const
  3207. {
  3208. cb->giveResource(player, static_cast<Res::ERes>(subID), amount);
  3209. ShowInInfobox sii;
  3210. sii.player = player;
  3211. sii.c = Component(Component::RESOURCE,subID,amount,0);
  3212. sii.text.addTxt(MetaString::ADVOB_TXT,113);
  3213. sii.text.addReplacement(MetaString::RES_NAMES, subID);
  3214. cb->showCompInfo(&sii);
  3215. cb->removeObject(this);
  3216. }
  3217. void CGResource::fightForRes(ui32 agreed, const CGHeroInstance *h) const
  3218. {
  3219. if(agreed)
  3220. cb->startBattleI(h, this, boost::bind(&CGResource::endBattle,this,_1,h));
  3221. }
  3222. void CGResource::endBattle( BattleResult *result, const CGHeroInstance *h ) const
  3223. {
  3224. if(result->winner == 0) //attacker won
  3225. collectRes(h->getOwner());
  3226. }
  3227. void CGVisitableOPW::newTurn() const
  3228. {
  3229. if (cb->getDate(Date::DAY_OF_WEEK) == 1) //first day of week = 1
  3230. {
  3231. cb->setObjProperty(id, ObjProperty::VISITED, false);
  3232. MetaString ms; //set text to "not visited"
  3233. ms << std::pair<ui8,ui32>(3,ID) << " " << std::pair<ui8,ui32>(1,353);
  3234. cb->setHoverName(this,&ms);
  3235. }
  3236. }
  3237. bool CGVisitableOPW::wasVisited(PlayerColor player) const
  3238. {
  3239. return visited; //TODO: other players should see object as unvisited
  3240. }
  3241. void CGVisitableOPW::onHeroVisit( const CGHeroInstance * h ) const
  3242. {
  3243. int mid=0, sound = 0;
  3244. switch (ID)
  3245. {
  3246. case Obj::MYSTICAL_GARDEN:
  3247. sound = soundBase::experience;
  3248. mid = 92;
  3249. break;
  3250. case Obj::WINDMILL:
  3251. sound = soundBase::GENIE;
  3252. mid = 170;
  3253. break;
  3254. case Obj::WATER_WHEEL:
  3255. sound = soundBase::GENIE;
  3256. mid = 164;
  3257. break;
  3258. default:
  3259. assert(0);
  3260. }
  3261. if (visited)
  3262. {
  3263. if (ID!=Obj::WINDMILL)
  3264. mid++;
  3265. else
  3266. mid--;
  3267. showInfoDialog(h,mid,sound);
  3268. }
  3269. else
  3270. {
  3271. Component::EComponentType type = Component::RESOURCE;
  3272. Res::ERes sub=Res::WOOD;
  3273. int val=0;
  3274. switch (ID)
  3275. {
  3276. case Obj::MYSTICAL_GARDEN:
  3277. if (rand()%2)
  3278. {
  3279. sub = Res::GEMS;
  3280. val = 5;
  3281. }
  3282. else
  3283. {
  3284. sub = Res::GOLD;
  3285. val = 500;
  3286. }
  3287. break;
  3288. case Obj::WINDMILL:
  3289. mid = 170;
  3290. sub = static_cast<Res::ERes>((rand() % 5) + 1);
  3291. val = (rand() % 4) + 3;
  3292. break;
  3293. case Obj::WATER_WHEEL:
  3294. mid = 164;
  3295. sub = Res::GOLD;
  3296. if(cb->getDate(Date::DAY)<8)
  3297. val = 500;
  3298. else
  3299. val = 1000;
  3300. }
  3301. cb->giveResource(h->tempOwner, sub, val);
  3302. InfoWindow iw;
  3303. iw.soundID = sound;
  3304. iw.player = h->tempOwner;
  3305. iw.components.push_back(Component(type,sub,val,0));
  3306. iw.text.addTxt(MetaString::ADVOB_TXT,mid);
  3307. cb->showInfoDialog(&iw);
  3308. cb->setObjProperty(id, ObjProperty::VISITED, true);
  3309. MetaString ms; //set text to "visited"
  3310. ms.addTxt(MetaString::OBJ_NAMES,ID); ms << " "; ms.addTxt(MetaString::GENERAL_TXT,352);
  3311. cb->setHoverName(this,&ms);
  3312. }
  3313. }
  3314. void CGVisitableOPW::setPropertyDer( ui8 what, ui32 val )
  3315. {
  3316. if(what == ObjProperty::VISITED)
  3317. visited = val;
  3318. }
  3319. void CGTeleport::onHeroVisit( const CGHeroInstance * h ) const
  3320. {
  3321. ObjectInstanceID destinationid;
  3322. switch(ID)
  3323. {
  3324. case Obj::MONOLITH1: //one way - find corresponding exit monolith
  3325. if(vstd::contains(objs,Obj::MONOLITH2) && vstd::contains(objs[Obj::MONOLITH2],subID) && objs[Obj::MONOLITH2][subID].size())
  3326. destinationid = objs[Obj::MONOLITH2][subID][rand()%objs[Obj::MONOLITH2][subID].size()];
  3327. else
  3328. tlog2 << "Cannot find corresponding exit monolith for "<< id << std::endl;
  3329. break;
  3330. case Obj::MONOLITH3://two way monolith - pick any other one
  3331. case Obj::WHIRLPOOL: //Whirlpool
  3332. if(vstd::contains(objs,ID) && vstd::contains(objs[ID],subID) && objs[ID][subID].size()>1)
  3333. {
  3334. while ((destinationid = objs[ID][subID][rand()%objs[ID][subID].size()]) == id); //choose another exit
  3335. if (ID == Obj::WHIRLPOOL)
  3336. {
  3337. if (!h->hasBonusOfType(Bonus::WHIRLPOOL_PROTECTION))
  3338. {
  3339. if (h->Slots().size() > 1 || h->Slots().begin()->second->count > 1)
  3340. { //we can't remove last unit
  3341. SlotID targetstack = h->Slots().begin()->first; //slot numbers may vary
  3342. for(TSlots::const_reverse_iterator i = h->Slots().rbegin(); i != h->Slots().rend(); i++)
  3343. {
  3344. if (h->getPower(targetstack) > h->getPower(i->first))
  3345. {
  3346. targetstack = (i->first);
  3347. }
  3348. }
  3349. TQuantity countToTake = h->getStackCount(targetstack) * 0.5;
  3350. vstd::amax(countToTake, 1);
  3351. InfoWindow iw;
  3352. iw.player = h->tempOwner;
  3353. iw.text.addTxt (MetaString::ADVOB_TXT, 168);
  3354. iw.components.push_back (Component(CStackBasicDescriptor(h->getCreature(targetstack), countToTake)));
  3355. cb->showInfoDialog(&iw);
  3356. cb->changeStackCount(StackLocation(h, targetstack), -countToTake);
  3357. }
  3358. }
  3359. }
  3360. }
  3361. else
  3362. tlog2 << "Cannot find corresponding exit monolith for "<< id << std::endl;
  3363. break;
  3364. case Obj::SUBTERRANEAN_GATE: //find nearest subterranean gate on the other level
  3365. {
  3366. destinationid = getMatchingGate(id);
  3367. if(destinationid == ObjectInstanceID()) //no exit
  3368. {
  3369. showInfoDialog(h,153,0);//Just inside the entrance you find a large pile of rubble blocking the tunnel. You leave discouraged.
  3370. }
  3371. break;
  3372. }
  3373. }
  3374. if(destinationid == ObjectInstanceID())
  3375. {
  3376. tlog2 << "Cannot find exit... (obj at " << pos << ") :( \n";
  3377. return;
  3378. }
  3379. if (ID == Obj::WHIRLPOOL)
  3380. {
  3381. std::set<int3> tiles = cb->getObj(destinationid)->getBlockedPos();
  3382. std::set<int3>::iterator it = tiles.begin();
  3383. std::advance (it, rand() % tiles.size()); //picking random element of set is tiring
  3384. cb->moveHero (h->id, *it + int3(1,0,0), true);
  3385. }
  3386. else
  3387. cb->moveHero (h->id,CGHeroInstance::convertPosition(cb->getObj(destinationid)->pos,true) - getVisitableOffset(), true);
  3388. }
  3389. void CGTeleport::initObj()
  3390. {
  3391. int si = subID;
  3392. switch (ID)
  3393. {
  3394. case Obj::SUBTERRANEAN_GATE://ignore subterranean gates subid
  3395. case Obj::WHIRLPOOL:
  3396. {
  3397. si = 0;
  3398. break;
  3399. }
  3400. default:
  3401. break;
  3402. }
  3403. objs[ID][si].push_back(id);
  3404. }
  3405. void CGTeleport::postInit() //matches subterranean gates into pairs
  3406. {
  3407. //split on underground and surface gates
  3408. std::vector<const CGObjectInstance *> gatesSplit[2]; //surface and underground gates
  3409. for(size_t i = 0; i < objs[Obj::SUBTERRANEAN_GATE][0].size(); i++)
  3410. {
  3411. const CGObjectInstance *hlp = cb->getObj(objs[Obj::SUBTERRANEAN_GATE][0][i]);
  3412. gatesSplit[hlp->pos.z].push_back(hlp);
  3413. }
  3414. //sort by position
  3415. std::sort(gatesSplit[0].begin(), gatesSplit[0].end(), boost::bind(&CGObjectInstance::pos, _1) < boost::bind(&CGObjectInstance::pos, _2));
  3416. for(size_t i = 0; i < gatesSplit[0].size(); i++)
  3417. {
  3418. const CGObjectInstance *cur = gatesSplit[0][i];
  3419. //find nearest underground exit
  3420. std::pair<int,double> best(-1,150000); //pair<pos_in_vector, distance>
  3421. for(int j = 0; j < gatesSplit[1].size(); j++)
  3422. {
  3423. const CGObjectInstance *checked = gatesSplit[1][j];
  3424. if(!checked)
  3425. continue;
  3426. double hlp = checked->pos.dist2d(cur->pos);
  3427. if(hlp < best.second)
  3428. {
  3429. best.first = j;
  3430. best.second = hlp;
  3431. }
  3432. }
  3433. if(best.first >= 0) //found pair
  3434. {
  3435. gates.push_back(std::make_pair(cur->id, gatesSplit[1][best.first]->id));
  3436. gatesSplit[1][best.first] = NULL;
  3437. }
  3438. else
  3439. {
  3440. gates.push_back(std::make_pair(cur->id, ObjectInstanceID()));
  3441. }
  3442. }
  3443. objs.erase(Obj::SUBTERRANEAN_GATE);
  3444. }
  3445. ObjectInstanceID CGTeleport::getMatchingGate(ObjectInstanceID id)
  3446. {
  3447. for(int i=0; i < gates.size(); i++)
  3448. {
  3449. if(gates[i].first == id)
  3450. return gates[i].second;
  3451. if(gates[i].second == id)
  3452. return gates[i].first;
  3453. }
  3454. return ObjectInstanceID();
  3455. }
  3456. void CGArtifact::initObj()
  3457. {
  3458. blockVisit = true;
  3459. if(ID == Obj::ARTIFACT)
  3460. {
  3461. hoverName = VLC->arth->artifacts[subID]->Name();
  3462. if(!storedArtifact->artType)
  3463. storedArtifact->setType(VLC->arth->artifacts[subID]);
  3464. }
  3465. if(ID == Obj::SPELL_SCROLL)
  3466. subID = 1;
  3467. assert(storedArtifact->artType);
  3468. assert(storedArtifact->getParentNodes().size());
  3469. //assert(storedArtifact->artType->id == subID); //this does not stop desync
  3470. }
  3471. void CGArtifact::onHeroVisit( const CGHeroInstance * h ) const
  3472. {
  3473. if(!stacksCount())
  3474. {
  3475. InfoWindow iw;
  3476. iw.player = h->tempOwner;
  3477. switch(ID)
  3478. {
  3479. case Obj::ARTIFACT:
  3480. {
  3481. iw.soundID = soundBase::treasure; //play sound only for non-scroll arts
  3482. iw.components.push_back(Component(Component::ARTIFACT,subID,0,0));
  3483. if(message.length())
  3484. iw.text << message;
  3485. else
  3486. {
  3487. if (VLC->arth->artifacts[subID]->EventText().size())
  3488. iw.text << std::pair<ui8, ui32> (MetaString::ART_EVNTS, subID);
  3489. else //fix for mod artifacts with no event text
  3490. {
  3491. iw.text.addTxt (MetaString::ADVOB_TXT, 183); //% has found treasure
  3492. iw.text.addReplacement (h->name);
  3493. }
  3494. }
  3495. }
  3496. break;
  3497. case Obj::SPELL_SCROLL:
  3498. {
  3499. int spellID = storedArtifact->getGivenSpellID();
  3500. iw.components.push_back (Component(Component::SPELL, spellID,0,0));
  3501. iw.text.addTxt (MetaString::ADVOB_TXT,135);
  3502. iw.text.addReplacement(MetaString::SPELL_NAME, spellID);
  3503. }
  3504. break;
  3505. }
  3506. cb->showInfoDialog(&iw);
  3507. pick(h);
  3508. }
  3509. else
  3510. {
  3511. if(message.size())
  3512. {
  3513. BlockingDialog ynd(true,false);
  3514. ynd.player = h->getOwner();
  3515. ynd.text << message;
  3516. cb->showBlockingDialog(&ynd,boost::bind(&CGArtifact::fightForArt,this,_1,h));
  3517. }
  3518. else
  3519. {
  3520. fightForArt(0,h);
  3521. }
  3522. }
  3523. }
  3524. void CGArtifact::pick(const CGHeroInstance * h) const
  3525. {
  3526. cb->giveHeroArtifact(h, storedArtifact, ArtifactPosition::FIRST_AVAILABLE);
  3527. cb->removeObject(this);
  3528. }
  3529. void CGArtifact::fightForArt( ui32 agreed, const CGHeroInstance *h ) const
  3530. {
  3531. if(agreed)
  3532. cb->startBattleI(h, this, boost::bind(&CGArtifact::endBattle,this,_1,h));
  3533. }
  3534. void CGArtifact::endBattle( BattleResult *result, const CGHeroInstance *h ) const
  3535. {
  3536. if(result->winner == 0) //attacker won
  3537. pick(h);
  3538. }
  3539. void CGPickable::initObj()
  3540. {
  3541. blockVisit = true;
  3542. switch(ID)
  3543. {
  3544. case Obj::CAMPFIRE:
  3545. val2 = (ran()%3) + 4; //4 - 6
  3546. val1 = val2 * 100;
  3547. type = ran()%6; //given resource
  3548. break;
  3549. case Obj::FLOTSAM:
  3550. switch(type = ran()%4)
  3551. {
  3552. case 0:
  3553. val1 = val2 = 0;
  3554. break;
  3555. case 1:
  3556. val1 = 5;
  3557. val2 = 0;
  3558. break;
  3559. case 2:
  3560. val1 = 5;
  3561. val2 = 200;
  3562. break;
  3563. case 3:
  3564. val1 = 10;
  3565. val2 = 500;
  3566. break;
  3567. }
  3568. break;
  3569. case Obj::SEA_CHEST:
  3570. {
  3571. int hlp = ran()%100;
  3572. if(hlp < 20)
  3573. {
  3574. val1 = 0;
  3575. type = 0;
  3576. }
  3577. else if(hlp < 90)
  3578. {
  3579. val1 = 1500;
  3580. type = 2;
  3581. }
  3582. else
  3583. {
  3584. val1 = 1000;
  3585. val2 = cb->getRandomArt (CArtifact::ART_TREASURE);
  3586. type = 1;
  3587. }
  3588. }
  3589. break;
  3590. case Obj::SHIPWRECK_SURVIVOR:
  3591. {
  3592. int hlp = ran()%100;
  3593. if(hlp < 55)
  3594. val1 = cb->getRandomArt (CArtifact::ART_TREASURE);
  3595. else if(hlp < 75)
  3596. val1 = cb->getRandomArt (CArtifact::ART_MINOR);
  3597. else if(hlp < 95)
  3598. val1 = cb->getRandomArt (CArtifact::ART_MAJOR);
  3599. else
  3600. val1 = cb->getRandomArt (CArtifact::ART_RELIC);
  3601. }
  3602. break;
  3603. case Obj::TREASURE_CHEST:
  3604. {
  3605. int hlp = ran()%100;
  3606. if(hlp >= 95)
  3607. {
  3608. type = 1;
  3609. val1 = cb->getRandomArt (CArtifact::ART_TREASURE);
  3610. return;
  3611. }
  3612. else if (hlp >= 65)
  3613. {
  3614. val1 = 2000;
  3615. }
  3616. else if(hlp >= 33)
  3617. {
  3618. val1 = 1500;
  3619. }
  3620. else
  3621. {
  3622. val1 = 1000;
  3623. }
  3624. val2 = val1 - 500;
  3625. type = 0;
  3626. break;
  3627. }
  3628. }
  3629. }
  3630. void CGPickable::onHeroVisit( const CGHeroInstance * h ) const
  3631. {
  3632. switch(ID)
  3633. {
  3634. case Obj::CAMPFIRE:
  3635. {
  3636. cb->giveResource(h->tempOwner,static_cast<Res::ERes>(type),val2); //non-gold resource
  3637. cb->giveResource(h->tempOwner,Res::GOLD,val1);//gold
  3638. InfoWindow iw;
  3639. iw.soundID = soundBase::experience;
  3640. iw.player = h->tempOwner;
  3641. iw.components.push_back(Component(Component::RESOURCE,Res::GOLD,val1,0));
  3642. iw.components.push_back(Component(Component::RESOURCE,type,val2,0));
  3643. iw.text.addTxt(MetaString::ADVOB_TXT,23);
  3644. cb->showInfoDialog(&iw);
  3645. break;
  3646. }
  3647. case Obj::FLOTSAM:
  3648. {
  3649. cb->giveResource(h->tempOwner,Res::WOOD,val1); //wood
  3650. cb->giveResource(h->tempOwner,Res::GOLD,val2);//gold
  3651. InfoWindow iw;
  3652. iw.soundID = soundBase::GENIE;
  3653. iw.player = h->tempOwner;
  3654. if(val1)
  3655. iw.components.push_back(Component(Component::RESOURCE,Res::WOOD,val1,0));
  3656. if(val2)
  3657. iw.components.push_back(Component(Component::RESOURCE,Res::GOLD,val2,0));
  3658. iw.text.addTxt(MetaString::ADVOB_TXT, 51+type);
  3659. cb->showInfoDialog(&iw);
  3660. break;
  3661. }
  3662. case Obj::SEA_CHEST:
  3663. {
  3664. InfoWindow iw;
  3665. iw.soundID = soundBase::chest;
  3666. iw.player = h->tempOwner;
  3667. iw.text.addTxt(MetaString::ADVOB_TXT, 116 + type);
  3668. if(val1) //there is gold
  3669. {
  3670. iw.components.push_back(Component(Component::RESOURCE,Res::GOLD,val1,0));
  3671. cb->giveResource(h->tempOwner,Res::GOLD,val1);
  3672. }
  3673. if(type == 1) //art
  3674. {
  3675. //TODO: what if no space in backpack?
  3676. iw.components.push_back(Component(Component::ARTIFACT, val2, 1, 0));
  3677. iw.text.addReplacement(MetaString::ART_NAMES, val2);
  3678. cb->giveHeroNewArtifact(h, VLC->arth->artifacts[val2],ArtifactPosition::FIRST_AVAILABLE);
  3679. }
  3680. cb->showInfoDialog(&iw);
  3681. break;
  3682. }
  3683. case Obj::SHIPWRECK_SURVIVOR:
  3684. {
  3685. InfoWindow iw;
  3686. iw.soundID = soundBase::experience;
  3687. iw.player = h->tempOwner;
  3688. iw.components.push_back(Component(Component::ARTIFACT,val1,1,0));
  3689. iw.text.addTxt(MetaString::ADVOB_TXT, 125);
  3690. iw.text.addReplacement(MetaString::ART_NAMES, val1);
  3691. cb->giveHeroNewArtifact(h, VLC->arth->artifacts[val1],ArtifactPosition::FIRST_AVAILABLE);
  3692. cb->showInfoDialog(&iw);
  3693. break;
  3694. }
  3695. case Obj::TREASURE_CHEST:
  3696. {
  3697. if (subID) //not OH3 treasure chest
  3698. {
  3699. tlog2 << "Not supported WoG treasure chest!\n";
  3700. return;
  3701. }
  3702. if(type) //there is an artifact
  3703. {
  3704. cb->giveHeroNewArtifact(h, VLC->arth->artifacts[val1],ArtifactPosition::FIRST_AVAILABLE);
  3705. InfoWindow iw;
  3706. iw.soundID = soundBase::treasure;
  3707. iw.player = h->tempOwner;
  3708. iw.components.push_back(Component(Component::ARTIFACT,val1,1,0));
  3709. iw.text.addTxt(MetaString::ADVOB_TXT,145);
  3710. iw.text.addReplacement(MetaString::ART_NAMES, val1);
  3711. cb->showInfoDialog(&iw);
  3712. break;
  3713. }
  3714. else
  3715. {
  3716. BlockingDialog sd(false,true);
  3717. sd.player = h->tempOwner;
  3718. sd.text.addTxt(MetaString::ADVOB_TXT,146);
  3719. sd.components.push_back(Component(Component::RESOURCE,Res::GOLD,val1,0));
  3720. TExpType expVal = h->calculateXp(val2);
  3721. sd.components.push_back(Component(Component::EXPERIENCE,0,expVal, 0));
  3722. sd.soundID = soundBase::chest;
  3723. boost::function<void(ui32)> fun = boost::bind(&CGPickable::chosen,this,_1,h->id);
  3724. cb->showBlockingDialog(&sd,fun);
  3725. return;
  3726. }
  3727. }
  3728. }
  3729. cb->removeObject(this);
  3730. }
  3731. void CGPickable::chosen( int which, ObjectInstanceID heroID ) const
  3732. {
  3733. const CGHeroInstance *h = cb->getHero(heroID);
  3734. switch(which)
  3735. {
  3736. case 1: //player pick gold
  3737. cb->giveResource(cb->getOwner(heroID), Res::GOLD, val1);
  3738. break;
  3739. case 2: //player pick exp
  3740. cb->changePrimSkill(cb->getHero(heroID), PrimarySkill::EXPERIENCE, h->calculateXp(val2));
  3741. break;
  3742. default:
  3743. throw std::runtime_error("Unhandled treasure choice");
  3744. }
  3745. cb->removeObject(this);
  3746. }
  3747. bool CQuest::checkQuest (const CGHeroInstance * h) const
  3748. {
  3749. switch (missionType)
  3750. {
  3751. case MISSION_NONE:
  3752. return true;
  3753. case MISSION_LEVEL:
  3754. if (m13489val <= h->level)
  3755. return true;
  3756. return false;
  3757. case MISSION_PRIMARY_STAT:
  3758. for (int i = 0; i < GameConstants::PRIMARY_SKILLS; ++i)
  3759. {
  3760. if (h->getPrimSkillLevel(static_cast<PrimarySkill::PrimarySkill>(i)) < m2stats[i])
  3761. return false;
  3762. }
  3763. return true;
  3764. case MISSION_KILL_HERO:
  3765. case MISSION_KILL_CREATURE:
  3766. if (!h->cb->getObjByQuestIdentifier(m13489val))
  3767. return true;
  3768. return false;
  3769. case MISSION_ART:
  3770. for (int i = 0; i < m5arts.size(); ++i)
  3771. {
  3772. if (h->hasArt(m5arts[i]))
  3773. continue;
  3774. return false; //if the artifact was not found
  3775. }
  3776. return true;
  3777. case MISSION_ARMY:
  3778. {
  3779. std::vector<CStackBasicDescriptor>::const_iterator cre;
  3780. TSlots::const_iterator it;
  3781. ui32 count;
  3782. for (cre = m6creatures.begin(); cre != m6creatures.end(); ++cre)
  3783. {
  3784. for (count = 0, it = h->Slots().begin(); it != h->Slots().end(); ++it)
  3785. {
  3786. if (it->second->type == cre->type)
  3787. count += it->second->count;
  3788. }
  3789. if (count < cre->count) //not enough creatures of this kind
  3790. return false;
  3791. }
  3792. }
  3793. return true;
  3794. case MISSION_RESOURCES:
  3795. for (Res::ERes i = Res::WOOD; i <= Res::GOLD; vstd::advance(i, +1)) //including Mithril ?
  3796. { //Quest has no direct access to callback
  3797. if (h->cb->getResource (h->tempOwner, i) < m7resources[i])
  3798. return false;
  3799. }
  3800. return true;
  3801. case MISSION_HERO:
  3802. if (m13489val == h->type->ID)
  3803. return true;
  3804. return false;
  3805. case MISSION_PLAYER:
  3806. if (m13489val == h->getOwner().getNum())
  3807. return true;
  3808. return false;
  3809. default:
  3810. return false;
  3811. }
  3812. }
  3813. void CQuest::getVisitText (MetaString &iwText, std::vector<Component> &components, bool isCustom, bool firstVisit, const CGHeroInstance * h) const
  3814. {
  3815. std::string text;
  3816. bool failRequirements = (h ? !checkQuest(h) : true);
  3817. if (firstVisit)
  3818. {
  3819. isCustom = isCustomFirst;
  3820. iwText << firstVisitText;
  3821. }
  3822. else if (failRequirements)
  3823. {
  3824. isCustom = isCustomNext;
  3825. iwText << nextVisitText;
  3826. }
  3827. switch (missionType)
  3828. {
  3829. case MISSION_LEVEL:
  3830. components.push_back(Component (Component::EXPERIENCE, 1, m13489val, 0));
  3831. if (!isCustom)
  3832. iwText.addReplacement(m13489val);
  3833. break;
  3834. case MISSION_PRIMARY_STAT:
  3835. {
  3836. MetaString loot;
  3837. for (int i = 0; i < 4; ++i)
  3838. {
  3839. if (m2stats[i])
  3840. {
  3841. components.push_back(Component (Component::PRIM_SKILL, i, m2stats[i], 0));
  3842. loot << "%d %s";
  3843. loot.addReplacement(m2stats[i]);
  3844. loot.addReplacement(VLC->generaltexth->primarySkillNames[i]);
  3845. }
  3846. }
  3847. if (!isCustom)
  3848. iwText.addReplacement(loot.buildList());
  3849. }
  3850. break;
  3851. case MISSION_KILL_HERO:
  3852. components.push_back(Component(Component::HERO, heroPortrait, 0, 0));
  3853. if (!isCustom)
  3854. addReplacements(iwText, text);
  3855. break;
  3856. case MISSION_HERO:
  3857. components.push_back(Component (Component::HERO, m13489val, 0, 0));
  3858. if (!isCustom)
  3859. iwText.addReplacement(VLC->heroh->heroes[m13489val]->name);
  3860. break;
  3861. case MISSION_KILL_CREATURE:
  3862. {
  3863. components.push_back(Component(stackToKill));
  3864. if (!isCustom)
  3865. addReplacements(iwText, text);
  3866. }
  3867. break;
  3868. case MISSION_ART:
  3869. {
  3870. MetaString loot;
  3871. for (std::vector<ui16>::const_iterator it = m5arts.begin(); it != m5arts.end(); ++it)
  3872. {
  3873. components.push_back(Component (Component::ARTIFACT, *it, 0, 0));
  3874. loot << "%s";
  3875. loot.addReplacement(MetaString::ART_NAMES, *it);
  3876. }
  3877. if (!isCustom)
  3878. iwText.addReplacement(loot.buildList());
  3879. }
  3880. break;
  3881. case MISSION_ARMY:
  3882. {
  3883. MetaString loot;
  3884. for (std::vector<CStackBasicDescriptor>::const_iterator it = m6creatures.begin(); it != m6creatures.end(); ++it)
  3885. {
  3886. components.push_back(Component(*it));
  3887. loot << "%s";
  3888. loot.addReplacement(*it);
  3889. }
  3890. if (!isCustom)
  3891. iwText.addReplacement(loot.buildList());
  3892. }
  3893. break;
  3894. case MISSION_RESOURCES:
  3895. {
  3896. MetaString loot;
  3897. for (int i = 0; i < 7; ++i)
  3898. {
  3899. if (m7resources[i])
  3900. {
  3901. components.push_back(Component (Component::RESOURCE, i, m7resources[i], 0));
  3902. loot << "%d %s";
  3903. loot.addReplacement(m7resources[i]);
  3904. loot.addReplacement(MetaString::RES_NAMES, i);
  3905. }
  3906. }
  3907. if (!isCustom)
  3908. iwText.addReplacement(loot.buildList());
  3909. }
  3910. break;
  3911. case MISSION_PLAYER:
  3912. components.push_back(Component (Component::FLAG, m13489val, 0, 0));
  3913. if (!isCustom)
  3914. iwText.addReplacement(VLC->generaltexth->colors[m13489val]);
  3915. break;
  3916. }
  3917. }
  3918. void CQuest::getRolloverText (MetaString &ms, bool onHover) const
  3919. {
  3920. if (onHover)
  3921. ms << "\n\n";
  3922. ms << VLC->generaltexth->quests[missionType-1][onHover ? 3 : 4][textOption];
  3923. switch (missionType)
  3924. {
  3925. case MISSION_LEVEL:
  3926. ms.addReplacement(m13489val);
  3927. break;
  3928. case MISSION_PRIMARY_STAT:
  3929. {
  3930. MetaString loot;
  3931. for (int i = 0; i < 4; ++i)
  3932. {
  3933. if (m2stats[i])
  3934. {
  3935. loot << "%d %s";
  3936. loot.addReplacement(m2stats[i]);
  3937. loot.addReplacement(VLC->generaltexth->primarySkillNames[i]);
  3938. }
  3939. }
  3940. ms.addReplacement(loot.buildList());
  3941. }
  3942. break;
  3943. case MISSION_KILL_HERO:
  3944. ms.addReplacement(heroName);
  3945. break;
  3946. case MISSION_KILL_CREATURE:
  3947. ms.addReplacement(stackToKill);
  3948. break;
  3949. case MISSION_ART:
  3950. {
  3951. MetaString loot;
  3952. for (std::vector<ui16>::const_iterator it = m5arts.begin(); it != m5arts.end(); ++it)
  3953. {
  3954. loot << "%s";
  3955. loot.addReplacement(MetaString::ART_NAMES, *it);
  3956. }
  3957. ms.addReplacement(loot.buildList());
  3958. }
  3959. break;
  3960. case MISSION_ARMY:
  3961. {
  3962. MetaString loot;
  3963. for (std::vector<CStackBasicDescriptor>::const_iterator it = m6creatures.begin(); it != m6creatures.end(); ++it)
  3964. {
  3965. loot << "%s";
  3966. loot.addReplacement(*it);
  3967. }
  3968. ms.addReplacement(loot.buildList());
  3969. }
  3970. break;
  3971. case MISSION_RESOURCES:
  3972. {
  3973. MetaString loot;
  3974. for (int i = 0; i < 7; ++i)
  3975. {
  3976. if (m7resources[i])
  3977. {
  3978. loot << "%d %s";
  3979. loot.addReplacement(m7resources[i]);
  3980. loot.addReplacement(MetaString::RES_NAMES, i);
  3981. }
  3982. }
  3983. ms.addReplacement(loot.buildList());
  3984. }
  3985. break;
  3986. case MISSION_HERO:
  3987. ms.addReplacement(VLC->heroh->heroes[m13489val]->name);
  3988. break;
  3989. case MISSION_PLAYER:
  3990. ms.addReplacement(VLC->generaltexth->colors[m13489val]);
  3991. break;
  3992. default:
  3993. break;
  3994. }
  3995. }
  3996. void CQuest::getCompletionText (MetaString &iwText, std::vector<Component> &components, bool isCustom, const CGHeroInstance * h) const
  3997. {
  3998. iwText << completedText;
  3999. switch (missionType)
  4000. {
  4001. case CQuest::MISSION_LEVEL:
  4002. if (!isCustomComplete)
  4003. iwText.addReplacement(m13489val);
  4004. break;
  4005. case CQuest::MISSION_PRIMARY_STAT:
  4006. if (vstd::contains (completedText,'%')) //there's one case when there's nothing to replace
  4007. {
  4008. MetaString loot;
  4009. for (int i = 0; i < 4; ++i)
  4010. {
  4011. if (m2stats[i])
  4012. {
  4013. loot << "%d %s";
  4014. loot.addReplacement(m2stats[i]);
  4015. loot.addReplacement(VLC->generaltexth->primarySkillNames[i]);
  4016. }
  4017. }
  4018. if (!isCustomComplete)
  4019. iwText.addReplacement(loot.buildList());
  4020. }
  4021. break;
  4022. case CQuest::MISSION_ART:
  4023. {
  4024. MetaString loot;
  4025. for (std::vector<ui16>::const_iterator it = m5arts.begin(); it != m5arts.end(); ++it)
  4026. {
  4027. loot << "%s";
  4028. loot.addReplacement(MetaString::ART_NAMES, *it);
  4029. }
  4030. if (!isCustomComplete)
  4031. iwText.addReplacement(loot.buildList());
  4032. }
  4033. break;
  4034. case CQuest::MISSION_ARMY:
  4035. {
  4036. MetaString loot;
  4037. for (std::vector<CStackBasicDescriptor>::const_iterator it = m6creatures.begin(); it != m6creatures.end(); ++it)
  4038. {
  4039. loot << "%s";
  4040. loot.addReplacement(*it);
  4041. }
  4042. if (!isCustomComplete)
  4043. iwText.addReplacement(loot.buildList());
  4044. }
  4045. break;
  4046. case CQuest::MISSION_RESOURCES:
  4047. {
  4048. MetaString loot;
  4049. for (int i = 0; i < 7; ++i)
  4050. {
  4051. if (m7resources[i])
  4052. {
  4053. loot << "%d %s";
  4054. loot.addReplacement(m7resources[i]);
  4055. loot.addReplacement(MetaString::RES_NAMES, i);
  4056. }
  4057. }
  4058. if (!isCustomComplete)
  4059. iwText.addReplacement(loot.buildList());
  4060. }
  4061. break;
  4062. case MISSION_KILL_HERO:
  4063. case MISSION_KILL_CREATURE:
  4064. if (!isCustomComplete)
  4065. addReplacements(iwText, completedText);
  4066. break;
  4067. case MISSION_HERO:
  4068. if (!isCustomComplete)
  4069. iwText.addReplacement(VLC->heroh->heroes[m13489val]->name);
  4070. break;
  4071. case MISSION_PLAYER:
  4072. if (!isCustomComplete)
  4073. iwText.addReplacement(VLC->generaltexth->colors[m13489val]);
  4074. break;
  4075. }
  4076. }
  4077. void CGSeerHut::setObjToKill()
  4078. {
  4079. if (quest->missionType == CQuest::MISSION_KILL_CREATURE)
  4080. {
  4081. quest->stackToKill = getCreatureToKill(false)->getStack(SlotID(0)); //FIXME: stacks tend to dissapear (desync?) on server :?
  4082. assert(quest->stackToKill.type);
  4083. quest->stackToKill.count = 0; //no count in info window
  4084. quest->stackDirection = checkDirection();
  4085. }
  4086. else if (quest->missionType == CQuest::MISSION_KILL_HERO)
  4087. {
  4088. quest->heroName = getHeroToKill(false)->name;
  4089. quest->heroPortrait = getHeroToKill(false)->portrait;
  4090. }
  4091. }
  4092. void CGSeerHut::initObj()
  4093. {
  4094. seerName = VLC->generaltexth->seerNames[ran()%VLC->generaltexth->seerNames.size()];
  4095. quest->textOption = ran()%3;
  4096. quest->progress = CQuest::NOT_ACTIVE;
  4097. if (quest->missionType)
  4098. {
  4099. if (!quest->isCustomFirst)
  4100. quest->firstVisitText = VLC->generaltexth->quests[quest->missionType-1][0][quest->textOption];
  4101. if (!quest->isCustomNext)
  4102. quest->nextVisitText = VLC->generaltexth->quests[quest->missionType-1][1][quest->textOption];
  4103. if (!quest->isCustomComplete)
  4104. quest->completedText = VLC->generaltexth->quests[quest->missionType-1][2][quest->textOption];
  4105. }
  4106. else
  4107. quest->firstVisitText = VLC->generaltexth->seerEmpty[quest->textOption];
  4108. }
  4109. void CGSeerHut::getRolloverText (MetaString &text, bool onHover) const
  4110. {
  4111. quest->getRolloverText (text, onHover);//TODO: simplify?
  4112. if (!onHover)
  4113. text.addReplacement(seerName);
  4114. }
  4115. const std::string & CGSeerHut::getHoverText() const
  4116. {
  4117. switch (ID)
  4118. {
  4119. case Obj::SEER_HUT:
  4120. if (quest->progress != CQuest::NOT_ACTIVE)
  4121. {
  4122. hoverName = VLC->generaltexth->allTexts[347];
  4123. boost::algorithm::replace_first(hoverName,"%s", seerName);
  4124. }
  4125. else //just seer hut
  4126. hoverName = VLC->generaltexth->names[ID];
  4127. break;
  4128. case Obj::QUEST_GUARD:
  4129. hoverName = VLC->generaltexth->names[ID];
  4130. break;
  4131. default:
  4132. tlog5 << "unrecognized quest object\n";
  4133. }
  4134. if (quest->progress & quest->missionType) //rollover when the quest is active
  4135. {
  4136. MetaString ms;
  4137. getRolloverText (ms, true);
  4138. hoverName += ms.toString();
  4139. }
  4140. return hoverName;
  4141. }
  4142. void CQuest::addReplacements(MetaString &out, const std::string &base) const
  4143. {
  4144. switch(missionType)
  4145. {
  4146. case MISSION_KILL_CREATURE:
  4147. out.addReplacement(stackToKill);
  4148. if (std::count(base.begin(), base.end(), '%') == 2) //say where is placed monster
  4149. {
  4150. out.addReplacement(VLC->generaltexth->arraytxt[147+stackDirection]);
  4151. }
  4152. break;
  4153. case MISSION_KILL_HERO:
  4154. out.addReplacement(heroName);
  4155. break;
  4156. }
  4157. }
  4158. bool IQuestObject::checkQuest(const CGHeroInstance* h) const
  4159. {
  4160. return quest->checkQuest(h);
  4161. }
  4162. void IQuestObject::getVisitText (MetaString &text, std::vector<Component> &components, bool isCustom, bool FirstVisit, const CGHeroInstance * h) const
  4163. {
  4164. quest->getVisitText (text,components, isCustom, FirstVisit, h);
  4165. }
  4166. void CGSeerHut::getCompletionText(MetaString &text, std::vector<Component> &components, bool isCustom, const CGHeroInstance * h) const
  4167. {
  4168. quest->getCompletionText (text, components, isCustom, h);
  4169. switch (rewardType)
  4170. {
  4171. case EXPERIENCE: components.push_back(Component (Component::EXPERIENCE, 0, h->calculateXp(rVal), 0));
  4172. break;
  4173. case MANA_POINTS: components.push_back(Component (Component::PRIM_SKILL, 5, rVal, 0));
  4174. break;
  4175. case MORALE_BONUS: components.push_back(Component (Component::MORALE, 0, rVal, 0));
  4176. break;
  4177. case LUCK_BONUS: components.push_back(Component (Component::LUCK, 0, rVal, 0));
  4178. break;
  4179. case RESOURCES: components.push_back(Component (Component::RESOURCE, rID, rVal, 0));
  4180. break;
  4181. case PRIMARY_SKILL: components.push_back(Component (Component::PRIM_SKILL, rID, rVal, 0));
  4182. break;
  4183. case SECONDARY_SKILL: components.push_back(Component (Component::SEC_SKILL, rID, rVal, 0));
  4184. break;
  4185. case ARTIFACT: components.push_back(Component (Component::ARTIFACT, rID, 0, 0));
  4186. break;
  4187. case SPELL: components.push_back(Component (Component::SPELL, rID, 0, 0));
  4188. break;
  4189. case CREATURE: components.push_back(Component (Component::CREATURE, rID, rVal, 0));
  4190. break;
  4191. }
  4192. }
  4193. void CGSeerHut::setPropertyDer (ui8 what, ui32 val)
  4194. {
  4195. switch (what)
  4196. {
  4197. case 10:
  4198. quest->progress = static_cast<CQuest::Eprogress>(val);
  4199. break;
  4200. case 11:
  4201. quest->missionType = CQuest::MISSION_NONE;
  4202. break;
  4203. }
  4204. }
  4205. void CGSeerHut::newTurn() const
  4206. {
  4207. if (quest->lastDay >= 0 && quest->lastDay < cb->getDate()) //time is up
  4208. {
  4209. cb->setObjProperty (id, 11, 0);
  4210. cb->setObjProperty (id, 10, 0);
  4211. }
  4212. }
  4213. void CGSeerHut::onHeroVisit( const CGHeroInstance * h ) const
  4214. {
  4215. InfoWindow iw;
  4216. iw.player = h->getOwner();
  4217. if (quest->missionType)
  4218. {
  4219. bool firstVisit = !quest->progress;
  4220. bool failRequirements = !checkQuest(h);
  4221. bool isCustom=false;
  4222. if (firstVisit)
  4223. {
  4224. isCustom = quest->isCustomFirst;
  4225. cb->setObjProperty (id, 10, CQuest::IN_PROGRESS);
  4226. AddQuest aq;
  4227. aq.quest = QuestInfo (quest, this, visitablePos());
  4228. aq.player = h->tempOwner;
  4229. cb->sendAndApply (&aq); //TODO: merge with setObjProperty?
  4230. }
  4231. else if (failRequirements)
  4232. {
  4233. isCustom = quest->isCustomNext;
  4234. }
  4235. if (firstVisit || failRequirements)
  4236. {
  4237. getVisitText (iw.text, iw.components, isCustom, firstVisit, h);
  4238. cb->showInfoDialog(&iw);
  4239. }
  4240. if (!failRequirements) // propose completion, also on first visit
  4241. {
  4242. BlockingDialog bd (true, false);
  4243. bd.player = h->getOwner();
  4244. bd.soundID = soundBase::QUEST;
  4245. getCompletionText (bd.text, bd.components, isCustom, h);
  4246. cb->showBlockingDialog (&bd, boost::bind (&CGSeerHut::finishQuest, this, h, _1));
  4247. return;
  4248. }
  4249. }
  4250. else
  4251. {
  4252. iw.text << VLC->generaltexth->seerEmpty[quest->textOption];
  4253. if (ID == Obj::SEER_HUT)
  4254. iw.text.addReplacement(seerName);
  4255. cb->showInfoDialog(&iw);
  4256. }
  4257. }
  4258. int CGSeerHut::checkDirection() const
  4259. {
  4260. int3 cord = getCreatureToKill()->pos;
  4261. if ((double)cord.x/(double)cb->getMapSize().x < 0.34) //north
  4262. {
  4263. if ((double)cord.y/(double)cb->getMapSize().y < 0.34) //northwest
  4264. return 8;
  4265. else if ((double)cord.y/(double)cb->getMapSize().y < 0.67) //north
  4266. return 1;
  4267. else //northeast
  4268. return 2;
  4269. }
  4270. else if ((double)cord.x/(double)cb->getMapSize().x < 0.67) //horizontal
  4271. {
  4272. if ((double)cord.y/(double)cb->getMapSize().y < 0.34) //west
  4273. return 7;
  4274. else if ((double)cord.y/(double)cb->getMapSize().y < 0.67) //central
  4275. return 9;
  4276. else //east
  4277. return 3;
  4278. }
  4279. else //south
  4280. {
  4281. if ((double)cord.y/(double)cb->getMapSize().y < 0.34) //southwest
  4282. return 6;
  4283. else if ((double)cord.y/(double)cb->getMapSize().y < 0.67) //south
  4284. return 5;
  4285. else //southeast
  4286. return 4;
  4287. }
  4288. }
  4289. void CGSeerHut::finishQuest(const CGHeroInstance * h, ui32 accept) const
  4290. {
  4291. if (accept)
  4292. {
  4293. switch (quest->missionType)
  4294. {
  4295. case CQuest::MISSION_ART:
  4296. for (std::vector<ui16>::const_iterator it = quest->m5arts.begin(); it != quest->m5arts.end(); ++it)
  4297. {
  4298. cb->removeArtifact(ArtifactLocation(h, h->getArtPos(*it, false)));
  4299. }
  4300. break;
  4301. case CQuest::MISSION_ARMY:
  4302. cb->takeCreatures(h->id, quest->m6creatures);
  4303. break;
  4304. case CQuest::MISSION_RESOURCES:
  4305. for (int i = 0; i < 7; ++i)
  4306. {
  4307. cb->giveResource(h->getOwner(), static_cast<Res::ERes>(i), -quest->m7resources[i]);
  4308. }
  4309. break;
  4310. default:
  4311. break;
  4312. }
  4313. cb->setObjProperty (id, 10, CQuest::COMPLETE); //mission complete - for AI
  4314. cb->setObjProperty (id, 11, 0); //no more mission available - redundant?
  4315. completeQuest(h); //make sure to remove QuestQuard at the very end
  4316. }
  4317. }
  4318. void CGSeerHut::completeQuest (const CGHeroInstance * h) const //reward
  4319. {
  4320. switch (rewardType)
  4321. {
  4322. case EXPERIENCE:
  4323. {
  4324. TExpType expVal = h->calculateXp(rVal);
  4325. cb->changePrimSkill(h, PrimarySkill::EXPERIENCE, expVal, false);
  4326. break;
  4327. }
  4328. case MANA_POINTS:
  4329. {
  4330. cb->setManaPoints(h->id, h->mana+rVal);
  4331. break;
  4332. }
  4333. case MORALE_BONUS: case LUCK_BONUS:
  4334. {
  4335. Bonus hb(Bonus::ONE_WEEK, (rewardType == 3 ? Bonus::MORALE : Bonus::LUCK),
  4336. Bonus::OBJECT, rVal, h->id.getNum(), "", -1);
  4337. GiveBonus gb;
  4338. gb.id = h->id.getNum();
  4339. gb.bonus = hb;
  4340. cb->giveHeroBonus(&gb);
  4341. }
  4342. break;
  4343. case RESOURCES:
  4344. cb->giveResource(h->getOwner(), static_cast<Res::ERes>(rID), rVal);
  4345. break;
  4346. case PRIMARY_SKILL:
  4347. cb->changePrimSkill(h, static_cast<PrimarySkill::PrimarySkill>(rID), rVal, false);
  4348. break;
  4349. case SECONDARY_SKILL:
  4350. cb->changeSecSkill(h, SecondarySkill(rID), rVal, false);
  4351. break;
  4352. case ARTIFACT:
  4353. cb->giveHeroNewArtifact(h, VLC->arth->artifacts[rID],ArtifactPosition::FIRST_AVAILABLE);
  4354. break;
  4355. case SPELL:
  4356. {
  4357. std::set<SpellID> spell;
  4358. spell.insert (SpellID(rID));
  4359. cb->changeSpells(h, true, spell);
  4360. }
  4361. break;
  4362. case CREATURE:
  4363. {
  4364. CCreatureSet creatures;
  4365. creatures.setCreature(SlotID(0), CreatureID(rID), rVal);
  4366. cb->giveCreatures(this, h, creatures, false);
  4367. }
  4368. break;
  4369. default:
  4370. break;
  4371. }
  4372. }
  4373. const CGHeroInstance * CGSeerHut::getHeroToKill(bool allowNull) const
  4374. {
  4375. const CGObjectInstance *o = cb->getObjByQuestIdentifier(quest->m13489val);
  4376. if(allowNull && !o)
  4377. return NULL;
  4378. assert(o && o->ID == Obj::HERO);
  4379. return static_cast<const CGHeroInstance*>(o);
  4380. }
  4381. const CGCreature * CGSeerHut::getCreatureToKill(bool allowNull) const
  4382. {
  4383. const CGObjectInstance *o = cb->getObjByQuestIdentifier(quest->m13489val);
  4384. if(allowNull && !o)
  4385. return NULL;
  4386. assert(o && o->ID == Obj::MONSTER);
  4387. return static_cast<const CGCreature*>(o);
  4388. }
  4389. void CGQuestGuard::initObj()
  4390. {
  4391. blockVisit = true;
  4392. quest->progress = CQuest::NOT_ACTIVE;
  4393. quest->textOption = ran()%3 + 3; //3-5
  4394. if (quest->missionType)
  4395. {
  4396. if (!quest->isCustomFirst)
  4397. quest->firstVisitText = VLC->generaltexth->quests[quest->missionType-1][0][quest->textOption];
  4398. if (!quest->isCustomNext)
  4399. quest->nextVisitText = VLC->generaltexth->quests[quest->missionType-1][1][quest->textOption];
  4400. if (!quest->isCustomComplete)
  4401. quest->completedText = VLC->generaltexth->quests[quest->missionType-1][2][quest->textOption];
  4402. }
  4403. else
  4404. quest->firstVisitText = VLC->generaltexth->seerEmpty[quest->textOption];
  4405. }
  4406. void CGQuestGuard::completeQuest(const CGHeroInstance *h) const
  4407. {
  4408. cb->removeObject(this);
  4409. }
  4410. void CGWitchHut::initObj()
  4411. {
  4412. ability = allowedAbilities[ran()%allowedAbilities.size()];
  4413. }
  4414. void CGWitchHut::onHeroVisit( const CGHeroInstance * h ) const
  4415. {
  4416. InfoWindow iw;
  4417. iw.soundID = soundBase::gazebo;
  4418. iw.player = h->getOwner();
  4419. if(!wasVisited(h->tempOwner))
  4420. cb->setObjProperty(id, 10, h->tempOwner.getNum());
  4421. ui32 txt_id;
  4422. if(h->getSecSkillLevel(SecondarySkill(ability))) //you already know this skill
  4423. {
  4424. txt_id =172;
  4425. }
  4426. else if(!h->canLearnSkill()) //already all skills slots used
  4427. {
  4428. txt_id = 173;
  4429. }
  4430. else //give sec skill
  4431. {
  4432. iw.components.push_back(Component(Component::SEC_SKILL, ability, 1, 0));
  4433. txt_id = 171;
  4434. cb->changeSecSkill(h, SecondarySkill(ability), 1, true);
  4435. }
  4436. iw.text.addTxt(MetaString::ADVOB_TXT,txt_id);
  4437. iw.text.addReplacement(MetaString::SEC_SKILL_NAME, ability);
  4438. cb->showInfoDialog(&iw);
  4439. }
  4440. const std::string & CGWitchHut::getHoverText() const
  4441. {
  4442. hoverName = VLC->generaltexth->names[ID];
  4443. if(wasVisited(cb->getLocalPlayer()))
  4444. {
  4445. hoverName += "\n" + VLC->generaltexth->allTexts[356]; // + (learn %s)
  4446. boost::algorithm::replace_first(hoverName,"%s",VLC->generaltexth->skillName[ability]);
  4447. const CGHeroInstance *h = cb->getSelectedHero(cb->getCurrentPlayer());
  4448. if(h && h->getSecSkillLevel(SecondarySkill(ability))) //hero knows that ability
  4449. hoverName += "\n\n" + VLC->generaltexth->allTexts[357]; // (Already learned)
  4450. }
  4451. return hoverName;
  4452. }
  4453. bool CGBonusingObject::wasVisited (const CGHeroInstance * h) const
  4454. {
  4455. return h->hasBonusFrom(Bonus::OBJECT, ID);
  4456. }
  4457. void CGBonusingObject::onHeroVisit( const CGHeroInstance * h ) const
  4458. {
  4459. bool visited = h->hasBonusFrom(Bonus::OBJECT,ID);
  4460. int messageID=0;
  4461. int bonusMove = 0;
  4462. ui32 descr_id = 0;
  4463. InfoWindow iw;
  4464. iw.player = h->tempOwner;
  4465. GiveBonus gbonus;
  4466. gbonus.id = h->id.getNum();
  4467. gbonus.bonus.duration = Bonus::ONE_BATTLE;
  4468. gbonus.bonus.source = Bonus::OBJECT;
  4469. gbonus.bonus.sid = ID;
  4470. bool second = false;
  4471. Bonus secondBonus;
  4472. switch(ID)
  4473. {
  4474. case Obj::BUOY:
  4475. messageID = 21;
  4476. iw.soundID = soundBase::MORALE;
  4477. gbonus.bonus.type = Bonus::MORALE;
  4478. gbonus.bonus.val = +1;
  4479. descr_id = 94;
  4480. break;
  4481. case Obj::SWAN_POND:
  4482. messageID = 29;
  4483. iw.soundID = soundBase::LUCK;
  4484. gbonus.bonus.type = Bonus::LUCK;
  4485. gbonus.bonus.val = 2;
  4486. descr_id = 67;
  4487. bonusMove = -h->movement;
  4488. break;
  4489. case Obj::FAERIE_RING:
  4490. messageID = 49;
  4491. iw.soundID = soundBase::LUCK;
  4492. gbonus.bonus.type = Bonus::LUCK;
  4493. gbonus.bonus.val = 1;
  4494. descr_id = 71;
  4495. break;
  4496. case Obj::FOUNTAIN_OF_FORTUNE:
  4497. messageID = 55;
  4498. iw.soundID = soundBase::LUCK;
  4499. gbonus.bonus.type = Bonus::LUCK;
  4500. gbonus.bonus.val = rand()%5 - 1;
  4501. descr_id = 69;
  4502. gbonus.bdescr.addReplacement((gbonus.bonus.val<0 ? "-" : "+") + boost::lexical_cast<std::string>(gbonus.bonus.val));
  4503. break;
  4504. case Obj::IDOL_OF_FORTUNE:
  4505. messageID = 62;
  4506. iw.soundID = soundBase::experience;
  4507. gbonus.bonus.val = 1;
  4508. descr_id = 68;
  4509. if(cb->getDate(Date::DAY_OF_WEEK) == 7) //7th day of week
  4510. {
  4511. gbonus.bonus.type = Bonus::MORALE;
  4512. second = true;
  4513. secondBonus = gbonus.bonus;
  4514. secondBonus.type = Bonus::LUCK;
  4515. }
  4516. else
  4517. {
  4518. gbonus.bonus.type = (cb->getDate(Date::DAY_OF_WEEK)%2) ? Bonus::LUCK : Bonus::MORALE;
  4519. }
  4520. break;
  4521. case Obj::MERMAID:
  4522. messageID = 83;
  4523. iw.soundID = soundBase::LUCK;
  4524. gbonus.bonus.type = Bonus::LUCK;
  4525. gbonus.bonus.val = 1;
  4526. descr_id = 72;
  4527. break;
  4528. case Obj::RALLY_FLAG:
  4529. iw.soundID = soundBase::MORALE;
  4530. messageID = 111;
  4531. gbonus.bonus.type = Bonus::MORALE;
  4532. gbonus.bonus.val = 1;
  4533. descr_id = 102;
  4534. second = true;
  4535. secondBonus = gbonus.bonus;
  4536. secondBonus.type = Bonus::LUCK;
  4537. bonusMove = 400;
  4538. break;
  4539. case Obj::OASIS:
  4540. iw.soundID = soundBase::MORALE;
  4541. messageID = 95;
  4542. gbonus.bonus.type = Bonus::MORALE;
  4543. gbonus.bonus.val = 1;
  4544. descr_id = 95;
  4545. bonusMove = 800;
  4546. break;
  4547. case Obj::TEMPLE:
  4548. messageID = 140;
  4549. iw.soundID = soundBase::temple;
  4550. gbonus.bonus.type = Bonus::MORALE;
  4551. if(cb->getDate(Date::DAY_OF_WEEK)==7) //sunday
  4552. {
  4553. gbonus.bonus.val = 2;
  4554. descr_id = 97;
  4555. }
  4556. else
  4557. {
  4558. gbonus.bonus.val = 1;
  4559. descr_id = 96;
  4560. }
  4561. break;
  4562. case Obj::WATERING_HOLE:
  4563. iw.soundID = soundBase::MORALE;
  4564. messageID = 166;
  4565. gbonus.bonus.type = Bonus::MORALE;
  4566. gbonus.bonus.val = 1;
  4567. descr_id = 100;
  4568. bonusMove = 400;
  4569. break;
  4570. case Obj::FOUNTAIN_OF_YOUTH:
  4571. iw.soundID = soundBase::MORALE;
  4572. messageID = 57;
  4573. gbonus.bonus.type = Bonus::MORALE;
  4574. gbonus.bonus.val = 1;
  4575. descr_id = 103;
  4576. bonusMove = 400;
  4577. break;
  4578. case Obj::STABLES:
  4579. iw.soundID = soundBase::STORE;
  4580. bool someUpgradeDone = false;
  4581. for (TSlots::const_iterator i = h->Slots().begin(); i != h->Slots().end(); ++i)
  4582. {
  4583. if(i->second->type->idNumber == CreatureID::CAVALIER)
  4584. {
  4585. cb->changeStackType(StackLocation(h, i->first), VLC->creh->creatures[CreatureID::CHAMPION]);
  4586. someUpgradeDone = true;
  4587. }
  4588. }
  4589. if (someUpgradeDone)
  4590. {
  4591. messageID = 138;
  4592. iw.components.push_back(Component(Component::CREATURE,11,0,1));
  4593. }
  4594. else
  4595. messageID = 137;
  4596. gbonus.bonus.type = Bonus::LAND_MOVEMENT;
  4597. gbonus.bonus.val = 600;
  4598. bonusMove = 600;
  4599. gbonus.bonus.duration = Bonus::ONE_WEEK;
  4600. //gbonus.bdescr << std::pair<ui8,ui32>(6, 100);
  4601. break;
  4602. }
  4603. if (descr_id != 0)
  4604. gbonus.bdescr.addTxt(MetaString::ARRAY_TXT,descr_id);
  4605. assert(messageID);
  4606. if(visited)
  4607. {
  4608. if(ID==Obj::RALLY_FLAG || ID==Obj::OASIS || ID==Obj::MERMAID || ID==Obj::STABLES)
  4609. messageID--;
  4610. else
  4611. messageID++;
  4612. }
  4613. else
  4614. {
  4615. //TODO: fix if second bonus val != main bonus val
  4616. if(gbonus.bonus.type == Bonus::MORALE || secondBonus.type == Bonus::MORALE)
  4617. iw.components.push_back(Component(Component::MORALE,0,gbonus.bonus.val,0));
  4618. if(gbonus.bonus.type == Bonus::LUCK || secondBonus.type == Bonus::LUCK)
  4619. iw.components.push_back(Component(Component::LUCK,0,gbonus.bonus.val,0));
  4620. cb->giveHeroBonus(&gbonus);
  4621. if(second)
  4622. {
  4623. gbonus.bonus = secondBonus;
  4624. cb->giveHeroBonus(&gbonus);
  4625. }
  4626. if(bonusMove) //swan pond - take all move points, stables - give move point this day
  4627. {
  4628. SetMovePoints smp;
  4629. smp.hid = h->id;
  4630. smp.val = h->movement + bonusMove;
  4631. cb->setMovePoints(&smp);
  4632. }
  4633. }
  4634. iw.text.addTxt(MetaString::ADVOB_TXT,messageID);
  4635. cb->showInfoDialog(&iw);
  4636. }
  4637. const std::string & CGBonusingObject::getHoverText() const
  4638. {
  4639. const CGHeroInstance *h = cb->getSelectedHero(cb->getCurrentPlayer());
  4640. hoverName = VLC->generaltexth->names[ID];
  4641. if(h)
  4642. {
  4643. bool visited = h->hasBonusFrom(Bonus::OBJECT,ID);
  4644. hoverName += " " + visitedTxt(visited);
  4645. }
  4646. return hoverName;
  4647. }
  4648. void CGBonusingObject::initObj()
  4649. {
  4650. if(ID == Obj::BUOY || ID == Obj::MERMAID)
  4651. {
  4652. blockVisit = true;
  4653. }
  4654. }
  4655. void CGMagicSpring::onHeroVisit(const CGHeroInstance * h) const
  4656. {
  4657. int messageID;
  4658. if (!visited)
  4659. {
  4660. if (h->mana > h->manaLimit())
  4661. messageID = 76;
  4662. else
  4663. {
  4664. messageID = 74;
  4665. cb->setManaPoints (h->id, 2 * h->manaLimit());
  4666. cb->setObjProperty (id, ObjProperty::VISITED, true);
  4667. }
  4668. }
  4669. else
  4670. messageID = 75;
  4671. showInfoDialog(h,messageID,soundBase::GENIE);
  4672. }
  4673. const std::string & CGMagicSpring::getHoverText() const
  4674. {
  4675. hoverName = VLC->generaltexth->names[ID] + " " + visitedTxt(visited);
  4676. return hoverName;
  4677. }
  4678. void CGMagicWell::onHeroVisit( const CGHeroInstance * h ) const
  4679. {
  4680. int message;
  4681. if(h->hasBonusFrom(Bonus::OBJECT,ID)) //has already visited Well today
  4682. {
  4683. message = 78;//"A second drink at the well in one day will not help you."
  4684. }
  4685. else if(h->mana < h->manaLimit())
  4686. {
  4687. giveDummyBonus(h->id);
  4688. cb->setManaPoints(h->id,h->manaLimit());
  4689. message = 77;
  4690. }
  4691. else
  4692. {
  4693. message = 79;
  4694. }
  4695. showInfoDialog(h,message,soundBase::faerie);
  4696. }
  4697. const std::string & CGMagicWell::getHoverText() const
  4698. {
  4699. getNameVis(hoverName);
  4700. return hoverName;
  4701. }
  4702. void CGPandoraBox::initObj()
  4703. {
  4704. blockVisit = (ID==Obj::PANDORAS_BOX); //block only if it's really pandora's box (events also derive from that class)
  4705. }
  4706. void CGPandoraBox::onHeroVisit(const CGHeroInstance * h) const
  4707. {
  4708. BlockingDialog bd (true, false);
  4709. bd.player = h->getOwner();
  4710. bd.soundID = soundBase::QUEST;
  4711. bd.text.addTxt (MetaString::ADVOB_TXT, 14);
  4712. cb->showBlockingDialog (&bd, boost::bind (&CGPandoraBox::open, this, h, _1));
  4713. }
  4714. void CGPandoraBox::open( const CGHeroInstance * h, ui32 accept ) const
  4715. {
  4716. if (accept)
  4717. {
  4718. if (stacksCount() > 0) //if pandora's box is protected by army
  4719. {
  4720. showInfoDialog(h,16,0);
  4721. cb->startBattleI(h, this, boost::bind(&CGPandoraBox::endBattle, this, h, _1)); //grants things after battle
  4722. }
  4723. else if (message.size() == 0 && resources.size() == 0
  4724. && primskills.size() == 0 && abilities.size() == 0
  4725. && abilityLevels.size() == 0 && artifacts.size() == 0
  4726. && spells.size() == 0 && creatures.Slots().size() > 0
  4727. && gainedExp == 0 && manaDiff == 0 && moraleDiff == 0 && luckDiff == 0) //if it gives nothing without battle
  4728. {
  4729. showInfoDialog(h,15,0);
  4730. cb->removeObject(this);
  4731. }
  4732. else //if it gives something without battle
  4733. {
  4734. giveContents (h, false);
  4735. }
  4736. }
  4737. }
  4738. void CGPandoraBox::endBattle( const CGHeroInstance *h, BattleResult *result ) const
  4739. {
  4740. if(result->winner)
  4741. return;
  4742. giveContents(h,true);
  4743. }
  4744. void CGPandoraBox::giveContents( const CGHeroInstance *h, bool afterBattle ) const
  4745. {
  4746. InfoWindow iw;
  4747. iw.player = h->getOwner();
  4748. std::string msg = message; //in case box is removed in the meantime
  4749. bool changesPrimSkill = false;
  4750. for (int i = 0; i < primskills.size(); i++)
  4751. {
  4752. if(primskills[i])
  4753. {
  4754. changesPrimSkill = true;
  4755. break;
  4756. }
  4757. }
  4758. if(gainedExp || changesPrimSkill || abilities.size())
  4759. {
  4760. TExpType expVal = h->calculateXp(gainedExp);
  4761. //getText(iw,afterBattle,175,h); //wtf?
  4762. iw.text.addTxt(MetaString::ADVOB_TXT, 175); //%s learns something
  4763. iw.text.addReplacement(h->name);
  4764. if(expVal)
  4765. iw.components.push_back(Component(Component::EXPERIENCE,0,expVal,0));
  4766. for(int i=0; i<primskills.size(); i++)
  4767. if(primskills[i])
  4768. iw.components.push_back(Component(Component::PRIM_SKILL,i,primskills[i],0));
  4769. for(int i=0; i<abilities.size(); i++)
  4770. iw.components.push_back(Component(Component::SEC_SKILL,abilities[i],abilityLevels[i],0));
  4771. cb->showInfoDialog(&iw);
  4772. //give exp
  4773. if(expVal)
  4774. cb->changePrimSkill(h, PrimarySkill::EXPERIENCE, expVal, false);
  4775. //give prim skills
  4776. for(int i=0; i<primskills.size(); i++)
  4777. if(primskills[i])
  4778. cb->changePrimSkill(h,static_cast<PrimarySkill::PrimarySkill>(i),primskills[i],false);
  4779. //give sec skills
  4780. for(int i=0; i<abilities.size(); i++)
  4781. {
  4782. int curLev = h->getSecSkillLevel(abilities[i]);
  4783. if( (curLev && curLev < abilityLevels[i]) || (h->canLearnSkill() ))
  4784. {
  4785. cb->changeSecSkill(h,abilities[i],abilityLevels[i],true);
  4786. }
  4787. }
  4788. }
  4789. if(spells.size())
  4790. {
  4791. std::set<SpellID> spellsToGive;
  4792. iw.components.clear();
  4793. if (spells.size() > 1)
  4794. {
  4795. iw.text.addTxt(MetaString::ADVOB_TXT, 188); //%s learns spells
  4796. }
  4797. else
  4798. {
  4799. iw.text.addTxt(MetaString::ADVOB_TXT, 184); //%s learns a spell
  4800. }
  4801. iw.text.addReplacement(h->name);
  4802. std::vector<ConstTransitivePtr<CSpell> > * sp = &VLC->spellh->spells;
  4803. for(auto i=spells.cbegin(); i != spells.cend(); i++)
  4804. {
  4805. if ((*sp)[*i]->level <= h->getSecSkillLevel(SecondarySkill::WISDOM) + 2) //enough wisdom
  4806. {
  4807. iw.components.push_back(Component(Component::SPELL,*i,0,0));
  4808. spellsToGive.insert(*i);
  4809. }
  4810. }
  4811. if(spellsToGive.size())
  4812. {
  4813. cb->changeSpells(h,true,spellsToGive);
  4814. cb->showInfoDialog(&iw);
  4815. }
  4816. }
  4817. if(manaDiff)
  4818. {
  4819. getText(iw,afterBattle,manaDiff,176,177,h);
  4820. iw.components.push_back(Component(Component::PRIM_SKILL,5,manaDiff,0));
  4821. cb->showInfoDialog(&iw);
  4822. cb->setManaPoints(h->id, h->mana + manaDiff);
  4823. }
  4824. if(moraleDiff)
  4825. {
  4826. getText(iw,afterBattle,moraleDiff,178,179,h);
  4827. iw.components.push_back(Component(Component::MORALE,0,moraleDiff,0));
  4828. cb->showInfoDialog(&iw);
  4829. GiveBonus gb;
  4830. gb.bonus = Bonus(Bonus::ONE_BATTLE,Bonus::MORALE,Bonus::OBJECT,moraleDiff,id.getNum(),"");
  4831. gb.id = h->id.getNum();
  4832. cb->giveHeroBonus(&gb);
  4833. }
  4834. if(luckDiff)
  4835. {
  4836. getText(iw,afterBattle,luckDiff,180,181,h);
  4837. iw.components.push_back(Component(Component::LUCK,0,luckDiff,0));
  4838. cb->showInfoDialog(&iw);
  4839. GiveBonus gb;
  4840. gb.bonus = Bonus(Bonus::ONE_BATTLE,Bonus::LUCK,Bonus::OBJECT,luckDiff,id.getNum(),"");
  4841. gb.id = h->id.getNum();
  4842. cb->giveHeroBonus(&gb);
  4843. }
  4844. iw.components.clear();
  4845. iw.text.clear();
  4846. for(int i=0; i<resources.size(); i++)
  4847. {
  4848. if(resources[i] < 0)
  4849. iw.components.push_back(Component(Component::RESOURCE,i,resources[i],0));
  4850. }
  4851. if(iw.components.size())
  4852. {
  4853. getText(iw,afterBattle,182,h);
  4854. cb->showInfoDialog(&iw);
  4855. }
  4856. iw.components.clear();
  4857. iw.text.clear();
  4858. for(int i=0; i<resources.size(); i++)
  4859. {
  4860. if(resources[i] > 0)
  4861. iw.components.push_back(Component(Component::RESOURCE,i,resources[i],0));
  4862. }
  4863. if(iw.components.size())
  4864. {
  4865. getText(iw,afterBattle,183,h);
  4866. cb->showInfoDialog(&iw);
  4867. }
  4868. iw.components.clear();
  4869. // getText(iw,afterBattle,183,h);
  4870. iw.text.addTxt(MetaString::ADVOB_TXT, 183); //% has found treasure
  4871. iw.text.addReplacement(h->name);
  4872. for(int i=0; i<artifacts.size(); i++)
  4873. {
  4874. iw.components.push_back(Component(Component::ARTIFACT,artifacts[i],0,0));
  4875. if(iw.components.size() >= 14)
  4876. {
  4877. cb->showInfoDialog(&iw);
  4878. iw.components.clear();
  4879. iw.text.addTxt(MetaString::ADVOB_TXT, 183); //% has found treasure - once more?
  4880. iw.text.addReplacement(h->name);
  4881. }
  4882. }
  4883. if(iw.components.size())
  4884. {
  4885. cb->showInfoDialog(&iw);
  4886. }
  4887. for(int i=0; i<resources.size(); i++)
  4888. if(resources[i])
  4889. cb->giveResource(h->getOwner(),static_cast<Res::ERes>(i),resources[i]);
  4890. for(int i=0; i<artifacts.size(); i++)
  4891. cb->giveHeroNewArtifact(h, VLC->arth->artifacts[artifacts[i]],ArtifactPosition::FIRST_AVAILABLE);
  4892. iw.components.clear();
  4893. iw.text.clear();
  4894. if (creatures.Slots().size())
  4895. { //this part is taken straight from creature bank
  4896. MetaString loot;
  4897. for(TSlots::const_iterator i = creatures.Slots().begin(); i != creatures.Slots().end(); i++)
  4898. { //build list of joined creatures
  4899. iw.components.push_back(Component(*i->second));
  4900. loot << "%s";
  4901. loot.addReplacement(*i->second);
  4902. }
  4903. if (creatures.Slots().size() == 1 && creatures.Slots().begin()->second->count == 1)
  4904. iw.text.addTxt(MetaString::ADVOB_TXT, 185);
  4905. else
  4906. iw.text.addTxt(MetaString::ADVOB_TXT, 186);
  4907. iw.text.addReplacement(loot.buildList());
  4908. iw.text.addReplacement(h->name);
  4909. cb->showInfoDialog(&iw);
  4910. cb->giveCreatures(this, h, creatures, true);
  4911. }
  4912. if(!afterBattle && msg.size())
  4913. {
  4914. iw.text << msg;
  4915. cb->showInfoDialog(&iw);
  4916. }
  4917. if (!creatures.Slots().size())
  4918. cb->removeObject(this); //only when we don't need to display garrison window
  4919. }
  4920. void CGPandoraBox::getText( InfoWindow &iw, bool &afterBattle, int text, const CGHeroInstance * h ) const
  4921. {
  4922. if(afterBattle || !message.size())
  4923. {
  4924. iw.text.addTxt(MetaString::ADVOB_TXT,text);//%s has lost treasure.
  4925. iw.text.addReplacement(h->name);
  4926. }
  4927. else
  4928. {
  4929. iw.text << message;
  4930. afterBattle = true;
  4931. }
  4932. }
  4933. void CGPandoraBox::getText( InfoWindow &iw, bool &afterBattle, int val, int negative, int positive, const CGHeroInstance * h ) const
  4934. {
  4935. iw.components.clear();
  4936. iw.text.clear();
  4937. if(afterBattle || !message.size())
  4938. {
  4939. iw.text.addTxt(MetaString::ADVOB_TXT,val < 0 ? negative : positive); //%s's luck takes a turn for the worse / %s's luck increases
  4940. iw.text.addReplacement(h->name);
  4941. }
  4942. else
  4943. {
  4944. iw.text << message;
  4945. afterBattle = true;
  4946. }
  4947. }
  4948. void CGEvent::onHeroVisit( const CGHeroInstance * h ) const
  4949. {
  4950. if(!(availableFor & (1 << h->tempOwner.getNum())))
  4951. return;
  4952. if(cb->getPlayerSettings(h->tempOwner)->playerID)
  4953. {
  4954. if(humanActivate)
  4955. activated(h);
  4956. }
  4957. else if(computerActivate)
  4958. activated(h);
  4959. }
  4960. void CGEvent::activated( const CGHeroInstance * h ) const
  4961. {
  4962. if(stacksCount() > 0)
  4963. {
  4964. InfoWindow iw;
  4965. iw.player = h->tempOwner;
  4966. if(message.size())
  4967. iw.text << message;
  4968. else
  4969. iw.text.addTxt(MetaString::ADVOB_TXT, 16);
  4970. cb->showInfoDialog(&iw);
  4971. cb->startBattleI(h, this, boost::bind(&CGEvent::endBattle,this,h,_1));
  4972. }
  4973. else
  4974. {
  4975. giveContents(h,false);
  4976. }
  4977. }
  4978. void CGObservatory::onHeroVisit( const CGHeroInstance * h ) const
  4979. {
  4980. InfoWindow iw;
  4981. iw.player = h->tempOwner;
  4982. switch (ID)
  4983. {
  4984. case Obj::REDWOOD_OBSERVATORY:
  4985. case Obj::PILLAR_OF_FIRE:
  4986. {
  4987. iw.soundID = soundBase::LIGHTHOUSE;
  4988. iw.text.addTxt(MetaString::ADVOB_TXT,98 + (ID==Obj::PILLAR_OF_FIRE));
  4989. FoWChange fw;
  4990. fw.player = h->tempOwner;
  4991. fw.mode = 1;
  4992. cb->getTilesInRange (fw.tiles, pos, 20, h->tempOwner, 1);
  4993. cb->sendAndApply (&fw);
  4994. break;
  4995. }
  4996. case Obj::COVER_OF_DARKNESS:
  4997. {
  4998. iw.text.addTxt (MetaString::ADVOB_TXT, 31);
  4999. hideTiles(h->tempOwner, 20);
  5000. break;
  5001. }
  5002. }
  5003. cb->showInfoDialog(&iw);
  5004. }
  5005. void CGShrine::onHeroVisit( const CGHeroInstance * h ) const
  5006. {
  5007. if(spell == SpellID::NONE)
  5008. {
  5009. tlog1 << "Not initialized shrine visited!\n";
  5010. return;
  5011. }
  5012. if(!wasVisited(h->tempOwner))
  5013. cb->setObjProperty(id, 10, h->tempOwner.getNum());
  5014. InfoWindow iw;
  5015. iw.soundID = soundBase::temple;
  5016. iw.player = h->getOwner();
  5017. iw.text.addTxt(MetaString::ADVOB_TXT,127 + ID - 88);
  5018. iw.text.addTxt(MetaString::SPELL_NAME,spell);
  5019. iw.text << ".";
  5020. if(!h->getArt(ArtifactPosition::SPELLBOOK))
  5021. {
  5022. iw.text.addTxt(MetaString::ADVOB_TXT,131);
  5023. }
  5024. else if(ID == Obj::SHRINE_OF_MAGIC_THOUGHT && !h->getSecSkillLevel(SecondarySkill::WISDOM)) //it's third level spell and hero doesn't have wisdom
  5025. {
  5026. iw.text.addTxt(MetaString::ADVOB_TXT,130);
  5027. }
  5028. else if(vstd::contains(h->spells,spell))//hero already knows the spell
  5029. {
  5030. iw.text.addTxt(MetaString::ADVOB_TXT,174);
  5031. }
  5032. else //give spell
  5033. {
  5034. std::set<SpellID> spells;
  5035. spells.insert(spell);
  5036. cb->changeSpells(h, true, spells);
  5037. iw.components.push_back(Component(Component::SPELL,spell,0,0));
  5038. }
  5039. cb->showInfoDialog(&iw);
  5040. }
  5041. void CGShrine::initObj()
  5042. {
  5043. if(spell == SpellID::NONE) //spell not set
  5044. {
  5045. int level = ID-87;
  5046. std::vector<SpellID> possibilities;
  5047. cb->getAllowedSpells (possibilities, level);
  5048. if(!possibilities.size())
  5049. {
  5050. tlog1 << "Error: cannot init shrine, no allowed spells!\n";
  5051. return;
  5052. }
  5053. spell = possibilities[ran() % possibilities.size()];
  5054. }
  5055. }
  5056. const std::string & CGShrine::getHoverText() const
  5057. {
  5058. hoverName = VLC->generaltexth->names[ID];
  5059. if(wasVisited(cb->getCurrentPlayer())) //TODO: use local player, not current
  5060. {
  5061. hoverName += "\n" + VLC->generaltexth->allTexts[355]; // + (learn %s)
  5062. boost::algorithm::replace_first(hoverName,"%s", spell.toSpell()->name);
  5063. const CGHeroInstance *h = cb->getSelectedHero(cb->getCurrentPlayer());
  5064. if(h && vstd::contains(h->spells,spell)) //hero knows that ability
  5065. hoverName += "\n\n" + VLC->generaltexth->allTexts[354]; // (Already learned)
  5066. }
  5067. return hoverName;
  5068. }
  5069. void CGSignBottle::initObj()
  5070. {
  5071. //if no text is set than we pick random from the predefined ones
  5072. if(!message.size())
  5073. message = VLC->generaltexth->randsign[ran()%VLC->generaltexth->randsign.size()];
  5074. if(ID == Obj::OCEAN_BOTTLE)
  5075. {
  5076. blockVisit = true;
  5077. }
  5078. }
  5079. void CGSignBottle::onHeroVisit( const CGHeroInstance * h ) const
  5080. {
  5081. InfoWindow iw;
  5082. iw.soundID = soundBase::STORE;
  5083. iw.player = h->getOwner();
  5084. iw.text << message;
  5085. cb->showInfoDialog(&iw);
  5086. if(ID == Obj::OCEAN_BOTTLE)
  5087. cb->removeObject(this);
  5088. }
  5089. //TODO: remove
  5090. //void CGScholar::giveAnyBonus( const CGHeroInstance * h ) const
  5091. //{
  5092. //
  5093. //}
  5094. void CGScholar::onHeroVisit( const CGHeroInstance * h ) const
  5095. {
  5096. EBonusType type = bonusType;
  5097. int bid = bonusID;
  5098. //check if the bonus if applicable, if not - give primary skill (always possible)
  5099. int ssl = h->getSecSkillLevel(SecondarySkill(bid)); //current sec skill level, used if bonusType == 1
  5100. if((type == SECONDARY_SKILL
  5101. && ((ssl == 3) || (!ssl && !h->canLearnSkill()))) ////hero already has expert level in the skill or (don't know skill and doesn't have free slot)
  5102. || (type == SPELL && (!h->getArt(ArtifactPosition::SPELLBOOK) || vstd::contains(h->spells, (ui32) bid)
  5103. || ( SpellID(bid).toSpell()->level > h->getSecSkillLevel(SecondarySkill::WISDOM) + 2)
  5104. ))) //hero doesn't have a spellbook or already knows the spell or doesn't have Wisdom
  5105. {
  5106. type = PRIM_SKILL;
  5107. bid = ran() % GameConstants::PRIMARY_SKILLS;
  5108. }
  5109. InfoWindow iw;
  5110. iw.soundID = soundBase::gazebo;
  5111. iw.player = h->getOwner();
  5112. iw.text.addTxt(MetaString::ADVOB_TXT,115);
  5113. switch (type)
  5114. {
  5115. case PRIM_SKILL:
  5116. cb->changePrimSkill(h,static_cast<PrimarySkill::PrimarySkill>(bid),+1);
  5117. iw.components.push_back(Component(Component::PRIM_SKILL,bid,+1,0));
  5118. break;
  5119. case SECONDARY_SKILL:
  5120. cb->changeSecSkill(h,SecondarySkill(bid),+1);
  5121. iw.components.push_back(Component(Component::SEC_SKILL,bid,ssl+1,0));
  5122. break;
  5123. case SPELL:
  5124. {
  5125. std::set<SpellID> hlp;
  5126. hlp.insert(SpellID(bid));
  5127. cb->changeSpells(h,true,hlp);
  5128. iw.components.push_back(Component(Component::SPELL,bid,0,0));
  5129. }
  5130. break;
  5131. default:
  5132. tlog1 << "Error: wrong bonustype (" << (int)type << ") for Scholar!\n";
  5133. return;
  5134. }
  5135. cb->showInfoDialog(&iw);
  5136. cb->removeObject(this);
  5137. }
  5138. void CGScholar::initObj()
  5139. {
  5140. blockVisit = true;
  5141. if(bonusType == RANDOM)
  5142. {
  5143. bonusType = static_cast<EBonusType>(ran()%3);
  5144. switch(bonusType)
  5145. {
  5146. case PRIM_SKILL:
  5147. bonusID = ran() % GameConstants::PRIMARY_SKILLS;
  5148. break;
  5149. case SECONDARY_SKILL:
  5150. bonusID = ran() % GameConstants::SKILL_QUANTITY;
  5151. break;
  5152. case SPELL:
  5153. std::vector<SpellID> possibilities;
  5154. for (int i = 1; i < 6; ++i)
  5155. cb->getAllowedSpells (possibilities, i);
  5156. bonusID = possibilities[ran() % possibilities.size()];
  5157. break;
  5158. }
  5159. }
  5160. }
  5161. void CGGarrison::onHeroVisit (const CGHeroInstance *h) const
  5162. {
  5163. int ally = cb->gameState()->getPlayerRelations(h->tempOwner, tempOwner);
  5164. if (!ally && stacksCount() > 0) {
  5165. //TODO: Find a way to apply magic garrison effects in battle.
  5166. cb->startBattleI(h, this, boost::bind(&CGGarrison::fightOver, this, h, _1));
  5167. return;
  5168. }
  5169. //New owner.
  5170. if (!ally)
  5171. cb->setOwner(this, h->tempOwner);
  5172. cb->showGarrisonDialog(id, h->id, removableUnits, 0);
  5173. }
  5174. void CGGarrison::fightOver (const CGHeroInstance *h, BattleResult *result) const
  5175. {
  5176. if (result->winner == 0)
  5177. onHeroVisit(h);
  5178. }
  5179. ui8 CGGarrison::getPassableness() const
  5180. {
  5181. if ( !stacksCount() )//empty - anyone can visit
  5182. return GameConstants::ALL_PLAYERS;
  5183. if ( tempOwner == PlayerColor::NEUTRAL )//neutral guarded - no one can visit
  5184. return 0;
  5185. ui8 mask = 0;
  5186. TeamState * ts = cb->gameState()->getPlayerTeam(tempOwner);
  5187. BOOST_FOREACH(PlayerColor it, ts->players)
  5188. mask |= 1<<it.getNum(); //allies - add to possible visitors
  5189. return mask;
  5190. }
  5191. void CGOnceVisitable::onHeroVisit( const CGHeroInstance * h ) const
  5192. {
  5193. int sound = soundBase::sound_todo;
  5194. int txtid;
  5195. switch(ID)
  5196. {
  5197. case Obj::CORPSE:
  5198. txtid = 37;
  5199. sound = soundBase::MYSTERY;
  5200. break;
  5201. case Obj::LEAN_TO:
  5202. sound = soundBase::GENIE;
  5203. txtid = 64;
  5204. break;
  5205. case Obj::WAGON:
  5206. sound = soundBase::GENIE;
  5207. txtid = 154;
  5208. break;
  5209. case Obj::WARRIORS_TOMB:
  5210. {
  5211. //ask if player wants to search the Tomb
  5212. BlockingDialog bd(true, false);
  5213. bd.soundID = soundBase::GRAVEYARD;
  5214. bd.player = h->getOwner();
  5215. bd.text.addTxt(MetaString::ADVOB_TXT,161);
  5216. cb->showBlockingDialog(&bd,boost::bind(&CGOnceVisitable::searchTomb,this,h,_1));
  5217. return;
  5218. }
  5219. break;
  5220. default:
  5221. tlog1 << "Error: Unknown object (" << ID <<") treated as CGOnceVisitable!\n";
  5222. return;
  5223. }
  5224. InfoWindow iw;
  5225. iw.soundID = sound;
  5226. iw.player = h->getOwner();
  5227. if(players.size()) //we have been already visited...
  5228. {
  5229. txtid++;
  5230. if(ID == Obj::WAGON) //wagon has extra text (for finding art) we need to omit
  5231. txtid++;
  5232. iw.text.addTxt(MetaString::ADVOB_TXT, txtid);
  5233. }
  5234. else //first visit - give bonus!
  5235. {
  5236. switch(artOrRes)
  5237. {
  5238. case 0: // first visit but empty
  5239. if (ID == Obj::CORPSE)
  5240. ++txtid;
  5241. else
  5242. txtid+=2;
  5243. iw.text.addTxt(MetaString::ADVOB_TXT, txtid);
  5244. break;
  5245. case 1: //art
  5246. iw.components.push_back(Component(Component::ARTIFACT,bonusType,0,0));
  5247. cb->giveHeroNewArtifact(h, VLC->arth->artifacts[bonusType],ArtifactPosition::FIRST_AVAILABLE);
  5248. iw.text.addTxt(MetaString::ADVOB_TXT, txtid);
  5249. if (ID == Obj::CORPSE)
  5250. {
  5251. iw.text << "%s";
  5252. iw.text.addReplacement(MetaString::ART_NAMES, bonusType);
  5253. }
  5254. break;
  5255. case 2: //res
  5256. iw.text.addTxt(MetaString::ADVOB_TXT, txtid);
  5257. iw.components.push_back (Component(Component::RESOURCE, bonusType, bonusVal, 0));
  5258. cb->giveResource(h->getOwner(), static_cast<Res::ERes>(bonusType), bonusVal);
  5259. break;
  5260. }
  5261. if(ID == Obj::WAGON && artOrRes == 1)
  5262. {
  5263. iw.text.localStrings.back().second++;
  5264. iw.text.addReplacement(MetaString::ART_NAMES, bonusType);
  5265. }
  5266. }
  5267. cb->showInfoDialog(&iw);
  5268. cb->setObjProperty(id, 10, h->getOwner().getNum());
  5269. }
  5270. const std::string & CGOnceVisitable::getHoverText() const
  5271. {
  5272. const bool visited = wasVisited(cb->getCurrentPlayer());
  5273. hoverName = VLC->generaltexth->names[ID] + " " + visitedTxt(visited);
  5274. return hoverName;
  5275. }
  5276. void CGOnceVisitable::initObj()
  5277. {
  5278. switch(ID)
  5279. {
  5280. case Obj::CORPSE:
  5281. {
  5282. blockVisit = true;
  5283. int hlp = ran()%100;
  5284. if(hlp < 20)
  5285. {
  5286. artOrRes = 1;
  5287. bonusType = cb->getRandomArt (CArtifact::ART_TREASURE | CArtifact::ART_MINOR | CArtifact::ART_MAJOR);
  5288. }
  5289. else
  5290. {
  5291. artOrRes = 0;
  5292. }
  5293. }
  5294. break;
  5295. case Obj::LEAN_TO:
  5296. {
  5297. artOrRes = 2;
  5298. bonusType = ran()%6; //any basic resource without gold
  5299. bonusVal = ran()%4 + 1;
  5300. }
  5301. break;
  5302. case Obj::WARRIORS_TOMB:
  5303. {
  5304. artOrRes = 1;
  5305. int hlp = ran()%100;
  5306. if(hlp < 30)
  5307. bonusType = cb->getRandomArt (CArtifact::ART_TREASURE);
  5308. else if(hlp < 80)
  5309. bonusType = cb->getRandomArt (CArtifact::ART_MINOR);
  5310. else if(hlp < 95)
  5311. bonusType = cb->getRandomArt (CArtifact::ART_MAJOR);
  5312. else
  5313. bonusType = cb->getRandomArt (CArtifact::ART_RELIC);
  5314. }
  5315. break;
  5316. case Obj::WAGON:
  5317. {
  5318. int hlp = ran()%100;
  5319. if(hlp < 10)
  5320. {
  5321. artOrRes = 0; // nothing... :(
  5322. }
  5323. else if(hlp < 50) //minor or treasure art
  5324. {
  5325. artOrRes = 1;
  5326. bonusType = cb->getRandomArt (CArtifact::ART_TREASURE | CArtifact::ART_MINOR);
  5327. }
  5328. else //2 - 5 of non-gold resource
  5329. {
  5330. artOrRes = 2;
  5331. bonusType = ran()%6;
  5332. bonusVal = ran()%4 + 2;
  5333. }
  5334. }
  5335. break;
  5336. }
  5337. }
  5338. void CGOnceVisitable::searchTomb(const CGHeroInstance *h, ui32 accept) const
  5339. {
  5340. if(accept)
  5341. {
  5342. InfoWindow iw;
  5343. iw.player = h->getOwner();
  5344. iw.components.push_back(Component(Component::MORALE,0,-3,0));
  5345. if(players.size()) //we've been already visited, player found nothing
  5346. {
  5347. iw.text.addTxt(MetaString::ADVOB_TXT,163);
  5348. }
  5349. else //first visit - give artifact
  5350. {
  5351. iw.text.addTxt(MetaString::ADVOB_TXT,162);
  5352. iw.components.push_back(Component(Component::ARTIFACT,bonusType,0,0));
  5353. iw.text.addReplacement(MetaString::ART_NAMES, bonusType);
  5354. cb->giveHeroNewArtifact(h, VLC->arth->artifacts[bonusType],ArtifactPosition::FIRST_AVAILABLE);
  5355. }
  5356. if(!h->hasBonusFrom(Bonus::OBJECT,ID)) //we don't have modifier from this object yet
  5357. {
  5358. //ruin morale
  5359. GiveBonus gb;
  5360. gb.id = h->id.getNum();
  5361. gb.bonus = Bonus(Bonus::ONE_BATTLE,Bonus::MORALE,Bonus::OBJECT,-3,id.getNum(),"");
  5362. gb.bdescr.addTxt(MetaString::ARRAY_TXT,104); //Warrior Tomb Visited -3
  5363. cb->giveHeroBonus(&gb);
  5364. }
  5365. cb->showInfoDialog(&iw);
  5366. cb->setObjProperty(id, 10, h->getOwner().getNum());
  5367. }
  5368. }
  5369. void CBank::initObj()
  5370. {
  5371. index = VLC->objh->bankObjToIndex(this);
  5372. bc = NULL;
  5373. daycounter = 0;
  5374. multiplier = 1;
  5375. }
  5376. const std::string & CBank::getHoverText() const
  5377. {
  5378. bool visited = (bc == nullptr);
  5379. hoverName = VLC->objh->creBanksNames[index] + " " + visitedTxt(visited);
  5380. return hoverName;
  5381. }
  5382. void CBank::reset(ui16 var1) //prevents desync
  5383. {
  5384. ui8 chance = 0;
  5385. for (ui8 i = 0; i < VLC->objh->banksInfo[index].size(); i++)
  5386. {
  5387. if (var1 < (chance += VLC->objh->banksInfo[index][i]->chance))
  5388. {
  5389. bc = VLC->objh->banksInfo[index][i];
  5390. break;
  5391. }
  5392. }
  5393. artifacts.clear();
  5394. }
  5395. void CBank::initialize() const
  5396. {
  5397. cb->setObjProperty (id, ObjProperty::BANK_RESET, ran()); //synchronous reset
  5398. for (ui8 i = 0; i <= 3; i++)
  5399. {
  5400. for (ui8 n = 0; n < bc->artifacts[i]; n++)
  5401. {
  5402. CArtifact::EartClass artClass;
  5403. switch(i)
  5404. {
  5405. case 0: artClass = CArtifact::ART_TREASURE; break;
  5406. case 1: artClass = CArtifact::ART_MINOR; break;
  5407. case 2: artClass = CArtifact::ART_MAJOR; break;
  5408. case 3: artClass = CArtifact::ART_RELIC; break;
  5409. default: assert(0); continue;
  5410. }
  5411. int artID = cb->getArtSync(ran(), artClass, true);
  5412. cb->setObjProperty(id, ObjProperty::BANK_ADD_ARTIFACT, artID);
  5413. }
  5414. }
  5415. cb->setObjProperty (id, ObjProperty::BANK_INIT_ARMY, ran()); //get army
  5416. }
  5417. void CBank::setPropertyDer (ui8 what, ui32 val)
  5418. /// random values are passed as arguments and processed identically on all clients
  5419. {
  5420. switch (what)
  5421. {
  5422. case ObjProperty::BANK_DAYCOUNTER: //daycounter
  5423. if (val == 0)
  5424. daycounter = 1; //yes, 1
  5425. else
  5426. daycounter++;
  5427. break;
  5428. case ObjProperty::BANK_MULTIPLIER: //multiplier, in percent
  5429. multiplier = val / 100.0;
  5430. break;
  5431. case 13: //bank preset
  5432. bc = VLC->objh->banksInfo[index][val];
  5433. break;
  5434. case ObjProperty::BANK_RESET:
  5435. reset (val%100);
  5436. break;
  5437. case ObjProperty::BANK_CLEAR_CONFIG:
  5438. bc = NULL;
  5439. break;
  5440. case ObjProperty::BANK_CLEAR_ARTIFACTS: //remove rewards from Derelict Ship
  5441. artifacts.clear();
  5442. break;
  5443. case ObjProperty::BANK_INIT_ARMY: //set ArmedInstance army
  5444. {
  5445. int upgraded = 0;
  5446. if (val%100 < bc->upgradeChance) //once again anti-desync
  5447. upgraded = 1;
  5448. switch (bc->guards.size())
  5449. {
  5450. case 1:
  5451. for (int i = 0; i < 4; ++i)
  5452. setCreature (SlotID(i), bc->guards[0].first, bc->guards[0].second / 5 );
  5453. setCreature (SlotID(4), CreatureID(bc->guards[0].first + upgraded), bc->guards[0].second / 5 );
  5454. break;
  5455. case 4:
  5456. {
  5457. if (bc->guards.back().second) //all stacks are present
  5458. {
  5459. for (auto it = bc->guards.begin(); it != bc->guards.end(); it++)
  5460. {
  5461. setCreature (SlotID(stacksCount()), it->first, it->second);
  5462. }
  5463. }
  5464. else if (bc->guards[2].second)//Wraiths are present, split two stacks in Crypt
  5465. {
  5466. setCreature (SlotID(0), bc->guards[0].first, bc->guards[0].second / 2 );
  5467. setCreature (SlotID(1), bc->guards[1].first, bc->guards[1].second / 2);
  5468. setCreature (SlotID(2), CreatureID(bc->guards[2].first + upgraded), bc->guards[2].second);
  5469. setCreature (SlotID(3), bc->guards[1].first, bc->guards[1].second / 2 );
  5470. setCreature (SlotID(4), bc->guards[0].first, bc->guards[0].second - (bc->guards[0].second / 2) );
  5471. }
  5472. else //split both stacks
  5473. {
  5474. for (int i = 0; i < 3; ++i) //skellies
  5475. setCreature (SlotID(2*i), bc->guards[0].first, bc->guards[0].second / 3);
  5476. for (int i = 0; i < 2; ++i) //zombies
  5477. setCreature (SlotID(2*i+1), bc->guards[1].first, bc->guards[1].second / 2);
  5478. }
  5479. }
  5480. break;
  5481. default:
  5482. tlog2 << "Error: Unexpected army data: " << bc->guards.size() <<" items found";
  5483. return;
  5484. }
  5485. }
  5486. break;
  5487. case ObjProperty::BANK_ADD_ARTIFACT: //add Artifact
  5488. {
  5489. artifacts.push_back (val);
  5490. break;
  5491. }
  5492. }
  5493. }
  5494. void CBank::newTurn() const
  5495. {
  5496. if (bc == NULL)
  5497. {
  5498. if (cb->getDate() == 1)
  5499. initialize(); //initialize on first day
  5500. else if (daycounter >= 28 && (subID < 13 || subID > 16)) //no reset for Emissaries
  5501. {
  5502. initialize();
  5503. cb->setObjProperty (id, ObjProperty::BANK_DAYCOUNTER, 0); //daycounter 0
  5504. if (ID == Obj::DERELICT_SHIP && cb->getDate() > 1)
  5505. {
  5506. cb->setObjProperty (id, ObjProperty::BANK_MULTIPLIER, 0);//ugly hack to make derelict ships usable only once
  5507. cb->setObjProperty (id, ObjProperty::BANK_CLEAR_ARTIFACTS, 0);
  5508. }
  5509. }
  5510. else
  5511. cb->setObjProperty (id, ObjProperty::BANK_DAYCOUNTER, 1); //daycounter++
  5512. }
  5513. }
  5514. bool CBank::wasVisited (PlayerColor player) const
  5515. {
  5516. return !bc;
  5517. }
  5518. void CBank::onHeroVisit (const CGHeroInstance * h) const
  5519. {
  5520. if (bc)
  5521. {
  5522. int banktext = 0;
  5523. switch (ID)
  5524. {
  5525. case Obj::CREATURE_BANK:
  5526. banktext = 32;
  5527. break;
  5528. case Obj::DERELICT_SHIP:
  5529. banktext = 41;
  5530. break;
  5531. case Obj::DRAGON_UTOPIA:
  5532. banktext = 47;
  5533. break;
  5534. case Obj::CRYPT:
  5535. banktext = 119;
  5536. break;
  5537. case Obj::SHIPWRECK:
  5538. banktext = 122;
  5539. break;
  5540. }
  5541. BlockingDialog bd (true, false);
  5542. bd.player = h->getOwner();
  5543. bd.soundID = soundBase::ROGUE;
  5544. bd.text.addTxt(MetaString::ADVOB_TXT,banktext);
  5545. if (ID == Obj::CREATURE_BANK)
  5546. bd.text.addReplacement(VLC->objh->creBanksNames[index]);
  5547. cb->showBlockingDialog (&bd, boost::bind (&CBank::fightGuards, this, h, _1));
  5548. }
  5549. else
  5550. {
  5551. InfoWindow iw;
  5552. iw.soundID = soundBase::GRAVEYARD;
  5553. iw.player = h->getOwner();
  5554. if (ID == Obj::CRYPT) //morale penalty for empty Crypt
  5555. {
  5556. GiveBonus gbonus;
  5557. gbonus.id = h->id.getNum();
  5558. gbonus.bonus.duration = Bonus::ONE_BATTLE;
  5559. gbonus.bonus.source = Bonus::OBJECT;
  5560. gbonus.bonus.sid = ID;
  5561. gbonus.bdescr << "\n" << VLC->generaltexth->arraytxt[98];
  5562. gbonus.bonus.type = Bonus::MORALE;
  5563. gbonus.bonus.val = -1;
  5564. cb->giveHeroBonus(&gbonus);
  5565. iw.text << VLC->generaltexth->advobtxt[120];
  5566. iw.components.push_back (Component (Component::MORALE, 0 , -1, 0));
  5567. }
  5568. else
  5569. {
  5570. iw.text << VLC->generaltexth->advobtxt[33];
  5571. iw.text.addReplacement(VLC->objh->creBanksNames[index]);
  5572. }
  5573. cb->showInfoDialog(&iw);
  5574. }
  5575. }
  5576. void CBank::fightGuards (const CGHeroInstance * h, ui32 accept) const
  5577. {
  5578. if (accept)
  5579. {
  5580. cb->startBattleI (h, this, boost::bind (&CBank::endBattle, this, h, _1), true);
  5581. }
  5582. }
  5583. void CBank::endBattle (const CGHeroInstance *h, const BattleResult *result) const
  5584. {
  5585. if (result->winner == 0)
  5586. {
  5587. int textID = -1;
  5588. InfoWindow iw;
  5589. iw.player = h->getOwner();
  5590. MetaString loot;
  5591. switch (ID)
  5592. {
  5593. case Obj::CREATURE_BANK: case Obj::DRAGON_UTOPIA:
  5594. textID = 34;
  5595. break;
  5596. case Obj::DERELICT_SHIP:
  5597. if (multiplier)
  5598. textID = 43;
  5599. else
  5600. {
  5601. GiveBonus gbonus;
  5602. gbonus.id = h->id.getNum();
  5603. gbonus.bonus.duration = Bonus::ONE_BATTLE;
  5604. gbonus.bonus.source = Bonus::OBJECT;
  5605. gbonus.bonus.sid = ID;
  5606. gbonus.bdescr << "\n" << VLC->generaltexth->arraytxt[101];
  5607. gbonus.bonus.type = Bonus::MORALE;
  5608. gbonus.bonus.val = -1;
  5609. cb->giveHeroBonus(&gbonus);
  5610. textID = 42;
  5611. iw.components.push_back (Component (Component::MORALE, 0 , -1, 0));
  5612. }
  5613. break;
  5614. case Obj::CRYPT:
  5615. if (bc->resources.size() != 0)
  5616. textID = 121;
  5617. else
  5618. {
  5619. iw.components.push_back (Component (Component::MORALE, 0 , -1, 0));
  5620. GiveBonus gbonus;
  5621. gbonus.id = h->id.getNum();
  5622. gbonus.bonus.duration = Bonus::ONE_BATTLE;
  5623. gbonus.bonus.source = Bonus::OBJECT;
  5624. gbonus.bonus.sid = ID;
  5625. gbonus.bdescr << "\n" << VLC->generaltexth->arraytxt[ID];
  5626. gbonus.bonus.type = Bonus::MORALE;
  5627. gbonus.bonus.val = -1;
  5628. cb->giveHeroBonus(&gbonus);
  5629. textID = 120;
  5630. iw.components.push_back (Component (Component::MORALE, 0 , -1, 0));
  5631. }
  5632. break;
  5633. case Obj::SHIPWRECK:
  5634. if (bc->resources.size())
  5635. textID = 124;
  5636. else
  5637. textID = 123;
  5638. break;
  5639. }
  5640. //grant resources
  5641. if (textID != 42) //empty derelict ship gives no cash
  5642. {
  5643. for (int it = 0; it < bc->resources.size(); it++)
  5644. {
  5645. if (bc->resources[it] != 0)
  5646. {
  5647. iw.components.push_back (Component (Component::RESOURCE, it, bc->resources[it], 0));
  5648. loot << "%d %s";
  5649. loot.addReplacement(iw.components.back().val);
  5650. loot.addReplacement(MetaString::RES_NAMES, iw.components.back().subtype);
  5651. cb->giveResource (h->getOwner(), static_cast<Res::ERes>(it), bc->resources[it]);
  5652. }
  5653. }
  5654. }
  5655. //grant artifacts
  5656. for (std::vector<ui32>::const_iterator it = artifacts.begin(); it != artifacts.end(); it++)
  5657. {
  5658. iw.components.push_back (Component (Component::ARTIFACT, *it, 0, 0));
  5659. loot << "%s";
  5660. loot.addReplacement(MetaString::ART_NAMES, *it);
  5661. cb->giveHeroNewArtifact (h, VLC->arth->artifacts[*it], ArtifactPosition::FIRST_AVAILABLE);
  5662. }
  5663. //display loot
  5664. if (!iw.components.empty())
  5665. {
  5666. iw.text.addTxt (MetaString::ADVOB_TXT, textID);
  5667. if (textID == 34)
  5668. {
  5669. iw.text.addReplacement(MetaString::CRE_PL_NAMES, result->casualties[1].begin()->first);
  5670. iw.text.addReplacement(loot.buildList());
  5671. }
  5672. cb->showInfoDialog(&iw);
  5673. }
  5674. loot.clear();
  5675. iw.components.clear();
  5676. iw.text.clear();
  5677. //grant creatures
  5678. CCreatureSet ourArmy;
  5679. for (auto it = bc->creatures.cbegin(); it != bc->creatures.cend(); it++)
  5680. {
  5681. SlotID slot = ourArmy.getSlotFor(it->first);
  5682. ourArmy.addToSlot(slot, it->first, it->second);
  5683. }
  5684. for (TSlots::const_iterator i = ourArmy.Slots().begin(); i != ourArmy.Slots().end(); i++)
  5685. {
  5686. iw.components.push_back(Component(*i->second));
  5687. loot << "%s";
  5688. loot.addReplacement(*i->second);
  5689. }
  5690. if (ourArmy.Slots().size())
  5691. {
  5692. if (ourArmy.Slots().size() == 1 && ourArmy.Slots().begin()->second->count == 1)
  5693. iw.text.addTxt (MetaString::ADVOB_TXT, 185);
  5694. else
  5695. iw.text.addTxt (MetaString::ADVOB_TXT, 186);
  5696. iw.text.addReplacement(loot.buildList());
  5697. iw.text.addReplacement(h->name);
  5698. cb->showInfoDialog(&iw);
  5699. cb->giveCreatures(this, h, ourArmy, false);
  5700. }
  5701. cb->setObjProperty (id, ObjProperty::BANK_CLEAR_CONFIG, 0); //bc = NULL
  5702. }
  5703. }
  5704. void CGPyramid::initObj()
  5705. {
  5706. std::vector<SpellID> available;
  5707. cb->getAllowedSpells (available, 5);
  5708. if (available.size())
  5709. {
  5710. bc = VLC->objh->banksInfo[21].front(); //TODO: remove hardcoded value?
  5711. spell = (available[ran()%available.size()]);
  5712. }
  5713. else
  5714. {
  5715. tlog1 <<"No spells available for Pyramid! Object set to empty.\n";
  5716. }
  5717. setPropertyDer (ObjProperty::BANK_INIT_ARMY,ran()); //set guards at game start
  5718. }
  5719. const std::string & CGPyramid::getHoverText() const
  5720. {
  5721. hoverName = VLC->objh->creBanksNames[21]+ " " + visitedTxt((bc==nullptr));
  5722. return hoverName;
  5723. }
  5724. void CGPyramid::onHeroVisit (const CGHeroInstance * h) const
  5725. {
  5726. if (bc)
  5727. {
  5728. BlockingDialog bd (true, false);
  5729. bd.player = h->getOwner();
  5730. bd.soundID = soundBase::MYSTERY;
  5731. bd.text << VLC->generaltexth->advobtxt[105];
  5732. cb->showBlockingDialog (&bd, boost::bind (&CBank::fightGuards, this, h, _1));
  5733. }
  5734. else
  5735. {
  5736. InfoWindow iw;
  5737. iw.player = h->getOwner();
  5738. iw.text << VLC->generaltexth->advobtxt[107];
  5739. iw.components.push_back (Component (Component::LUCK, 0 , -2, 0));
  5740. GiveBonus gb;
  5741. gb.bonus = Bonus(Bonus::ONE_BATTLE,Bonus::LUCK,Bonus::OBJECT,-2,id.getNum(),VLC->generaltexth->arraytxt[70]);
  5742. gb.id = h->id.getNum();
  5743. cb->giveHeroBonus(&gb);
  5744. cb->showInfoDialog(&iw);
  5745. }
  5746. }
  5747. void CGPyramid::endBattle (const CGHeroInstance *h, const BattleResult *result) const
  5748. {
  5749. if (result->winner == 0)
  5750. {
  5751. InfoWindow iw;
  5752. iw.player = h->getOwner();
  5753. iw.text.addTxt (MetaString::ADVOB_TXT, 106);
  5754. iw.text.addTxt (MetaString::SPELL_NAME, spell);
  5755. if (!h->getArt(ArtifactPosition::SPELLBOOK))
  5756. iw.text.addTxt (MetaString::ADVOB_TXT, 109); //no spellbook
  5757. else if (h->getSecSkillLevel(SecondarySkill::WISDOM) < 3)
  5758. iw.text.addTxt (MetaString::ADVOB_TXT, 108); //no expert Wisdom
  5759. else
  5760. {
  5761. std::set<SpellID> spells;
  5762. spells.insert (SpellID(spell));
  5763. cb->changeSpells (h, true, spells);
  5764. iw.components.push_back(Component (Component::SPELL, spell, 0, 0));
  5765. }
  5766. cb->showInfoDialog(&iw);
  5767. cb->setObjProperty (id, ObjProperty::BANK_CLEAR_CONFIG, 0);
  5768. }
  5769. }
  5770. void CGKeys::setPropertyDer (ui8 what, ui32 val) //101-108 - enable key for player 1-8
  5771. {
  5772. if (what >= 101 && what <= (100 + PlayerColor::PLAYER_LIMIT_I))
  5773. playerKeyMap.find(PlayerColor(what-101))->second.insert((ui8)val);
  5774. }
  5775. bool CGKeys::wasMyColorVisited (PlayerColor player) const
  5776. {
  5777. if (vstd::contains(playerKeyMap[player], subID)) //creates set if it's not there
  5778. return true;
  5779. else
  5780. return false;
  5781. }
  5782. const std::string& CGKeys::getHoverText() const
  5783. {
  5784. bool visited = wasMyColorVisited (cb->getLocalPlayer());
  5785. hoverName = getName() + "\n" + visitedTxt(visited);
  5786. return hoverName;
  5787. }
  5788. const std::string CGKeys::getName() const
  5789. {
  5790. std::string name;
  5791. name = VLC->generaltexth->tentColors[subID] + " " + VLC->generaltexth->names[ID];
  5792. return name;
  5793. }
  5794. bool CGKeymasterTent::wasVisited (PlayerColor player) const
  5795. {
  5796. return wasMyColorVisited (player);
  5797. }
  5798. void CGKeymasterTent::onHeroVisit( const CGHeroInstance * h ) const
  5799. {
  5800. int txt_id;
  5801. if (!wasMyColorVisited (h->getOwner()) )
  5802. {
  5803. cb->setObjProperty(id, h->tempOwner.getNum()+101, subID);
  5804. txt_id=19;
  5805. }
  5806. else
  5807. txt_id=20;
  5808. showInfoDialog(h,txt_id,soundBase::CAVEHEAD);
  5809. }
  5810. void CGBorderGuard::initObj()
  5811. {
  5812. //ui32 m13489val = subID; //store color as quest info
  5813. blockVisit = true;
  5814. }
  5815. void CGBorderGuard::getVisitText (MetaString &text, std::vector<Component> &components, bool isCustom, bool FirstVisit, const CGHeroInstance * h) const
  5816. {
  5817. text << std::pair<ui8,ui32>(11,18);
  5818. }
  5819. void CGBorderGuard::getRolloverText (MetaString &text, bool onHover) const
  5820. {
  5821. if (!onHover)
  5822. text << VLC->generaltexth->tentColors[subID] << " " << VLC->generaltexth->names[Obj::KEYMASTER];
  5823. }
  5824. bool CGBorderGuard::checkQuest (const CGHeroInstance * h) const
  5825. {
  5826. return wasMyColorVisited (h->tempOwner);
  5827. }
  5828. void CGBorderGuard::onHeroVisit( const CGHeroInstance * h ) const
  5829. {
  5830. if (wasMyColorVisited (h->getOwner()) )
  5831. {
  5832. BlockingDialog bd (true, false);
  5833. bd.player = h->getOwner();
  5834. bd.soundID = soundBase::QUEST;
  5835. bd.text.addTxt (MetaString::ADVOB_TXT, 17);
  5836. cb->showBlockingDialog (&bd, boost::bind (&CGBorderGuard::openGate, this, h, _1));
  5837. }
  5838. else
  5839. {
  5840. showInfoDialog(h,18,soundBase::CAVEHEAD);
  5841. AddQuest aq;
  5842. aq.quest = QuestInfo (quest, this, visitablePos());
  5843. aq.player = h->tempOwner;
  5844. cb->sendAndApply (&aq);
  5845. //TODO: add this quest only once OR check for multiple instances later
  5846. }
  5847. }
  5848. void CGBorderGuard::openGate(const CGHeroInstance *h, ui32 accept) const
  5849. {
  5850. if (accept)
  5851. cb->removeObject(this);
  5852. }
  5853. void CGBorderGate::onHeroVisit( const CGHeroInstance * h ) const //TODO: passability
  5854. {
  5855. if (!wasMyColorVisited (h->getOwner()) )
  5856. {
  5857. showInfoDialog(h,18,0);
  5858. AddQuest aq;
  5859. aq.quest = QuestInfo (quest, this, visitablePos());
  5860. aq.player = h->tempOwner;
  5861. cb->sendAndApply (&aq);
  5862. }
  5863. }
  5864. ui8 CGBorderGate::getPassableness() const
  5865. {
  5866. ui8 ret = 0;
  5867. for (int i = 0; i < PlayerColor::PLAYER_LIMIT_I; i++)
  5868. ret |= wasMyColorVisited(PlayerColor(i))<<i;
  5869. return ret;
  5870. }
  5871. void CGMagi::initObj()
  5872. {
  5873. if (ID == Obj::EYE_OF_MAGI)
  5874. {
  5875. blockVisit = true;
  5876. eyelist[subID].push_back(id);
  5877. }
  5878. }
  5879. void CGMagi::onHeroVisit(const CGHeroInstance * h) const
  5880. {
  5881. if (ID == Obj::HUT_OF_MAGI)
  5882. {
  5883. showInfoDialog(h, 61, soundBase::LIGHTHOUSE);
  5884. if (!eyelist[subID].empty())
  5885. {
  5886. CenterView cv;
  5887. cv.player = h->tempOwner;
  5888. cv.focusTime = 2000;
  5889. FoWChange fw;
  5890. fw.player = h->tempOwner;
  5891. fw.mode = 1;
  5892. BOOST_FOREACH(auto it, eyelist[subID])
  5893. {
  5894. const CGObjectInstance *eye = cb->getObj(it);
  5895. cb->getTilesInRange (fw.tiles, eye->pos, 10, h->tempOwner, 1);
  5896. cb->sendAndApply(&fw);
  5897. cv.pos = eye->pos;
  5898. cb->sendAndApply(&cv);
  5899. }
  5900. cv.pos = h->getPosition(false);
  5901. cb->sendAndApply(&cv);
  5902. }
  5903. }
  5904. else if (ID == Obj::EYE_OF_MAGI)
  5905. {
  5906. showInfoDialog(h,48,soundBase::invalid);
  5907. }
  5908. }
  5909. void CGBoat::initObj()
  5910. {
  5911. hero = NULL;
  5912. }
  5913. void CGSirens::initObj()
  5914. {
  5915. blockVisit = true;
  5916. }
  5917. const std::string & CGSirens::getHoverText() const
  5918. {
  5919. getNameVis(hoverName);
  5920. return hoverName;
  5921. }
  5922. void CGSirens::onHeroVisit( const CGHeroInstance * h ) const
  5923. {
  5924. InfoWindow iw;
  5925. iw.soundID = soundBase::DANGER;
  5926. iw.player = h->tempOwner;
  5927. if(h->hasBonusFrom(Bonus::OBJECT,ID)) //has already visited Sirens
  5928. {
  5929. iw.text.addTxt(MetaString::ADVOB_TXT,133);
  5930. }
  5931. else
  5932. {
  5933. giveDummyBonus(h->id, Bonus::ONE_BATTLE);
  5934. TExpType xp = 0;
  5935. for (TSlots::const_iterator i = h->Slots().begin(); i != h->Slots().end(); i++)
  5936. {
  5937. TQuantity drown = i->second->count * 0.3;
  5938. if(drown)
  5939. {
  5940. cb->changeStackCount(StackLocation(h, i->first), -drown);
  5941. xp += drown * i->second->type->valOfBonuses(Bonus::STACK_HEALTH);
  5942. }
  5943. }
  5944. if(xp)
  5945. {
  5946. xp = h->calculateXp(xp);
  5947. iw.text.addTxt(MetaString::ADVOB_TXT,132);
  5948. iw.text.addReplacement(xp);
  5949. cb->changePrimSkill(h, PrimarySkill::EXPERIENCE, xp, false);
  5950. }
  5951. else
  5952. {
  5953. iw.text.addTxt(MetaString::ADVOB_TXT,134);
  5954. }
  5955. }
  5956. cb->showInfoDialog(&iw);
  5957. }
  5958. //bool IShipyard::validLocation() const
  5959. //{
  5960. // std::vector<int3> offsets;
  5961. // getOutOffsets(offsets);
  5962. //
  5963. // TerrainTile *tile;
  5964. // for(int i = 0; i < offsets.size(); i++)
  5965. // if((tile = IObjectInterface::cb->getTile(o->pos + offsets[i])) && tile->terType == TerrainTile::water) //tile is in the map and is water
  5966. // return true;
  5967. // return false;
  5968. //}
  5969. int3 IBoatGenerator::bestLocation() const
  5970. {
  5971. std::vector<int3> offsets;
  5972. getOutOffsets(offsets);
  5973. for (int i = 0; i < offsets.size(); ++i)
  5974. {
  5975. if (const TerrainTile *tile = IObjectInterface::cb->getTile(o->pos + offsets[i], false)) //tile is in the map
  5976. {
  5977. if (tile->terType == ETerrainType::WATER && (!tile->blocked || tile->blockingObjects.front()->ID == 8)) //and is water and is not blocked or is blocked by boat
  5978. return o->pos + offsets[i];
  5979. }
  5980. }
  5981. return int3 (-1,-1,-1);
  5982. }
  5983. IBoatGenerator::EGeneratorState IBoatGenerator::state() const
  5984. {
  5985. int3 tile = bestLocation();
  5986. const TerrainTile *t = IObjectInterface::cb->getTile(tile);
  5987. if(!t)
  5988. return TILE_BLOCKED; //no available water
  5989. else if(!t->blockingObjects.size())
  5990. return GOOD; //OK
  5991. else if(t->blockingObjects.front()->ID == Obj::BOAT)
  5992. return BOAT_ALREADY_BUILT; //blocked with boat
  5993. else
  5994. return TILE_BLOCKED; //blocked
  5995. }
  5996. int IBoatGenerator::getBoatType() const
  5997. {
  5998. //We make good ships by default
  5999. return 1;
  6000. }
  6001. IBoatGenerator::IBoatGenerator(const CGObjectInstance *O)
  6002. : o(O)
  6003. {
  6004. }
  6005. void IBoatGenerator::getProblemText(MetaString &out, const CGHeroInstance *visitor) const
  6006. {
  6007. switch(state())
  6008. {
  6009. case BOAT_ALREADY_BUILT:
  6010. out.addTxt(MetaString::GENERAL_TXT, 51);
  6011. break;
  6012. case TILE_BLOCKED:
  6013. if(visitor)
  6014. {
  6015. out.addTxt(MetaString::GENERAL_TXT, 134);
  6016. out.addReplacement(visitor->name);
  6017. }
  6018. else
  6019. out.addTxt(MetaString::ADVOB_TXT, 189);
  6020. break;
  6021. case NO_WATER:
  6022. tlog1 << "Shipyard without water!!! " << o->pos << "\t" << o->id << std::endl;
  6023. return;
  6024. }
  6025. }
  6026. void IShipyard::getBoatCost( std::vector<si32> &cost ) const
  6027. {
  6028. cost.resize(GameConstants::RESOURCE_QUANTITY);
  6029. cost[Res::WOOD] = 10;
  6030. cost[Res::GOLD] = 1000;
  6031. }
  6032. IShipyard::IShipyard(const CGObjectInstance *O)
  6033. : IBoatGenerator(O)
  6034. {
  6035. }
  6036. IShipyard * IShipyard::castFrom( CGObjectInstance *obj )
  6037. {
  6038. if(!obj)
  6039. return NULL;
  6040. if(obj->ID == Obj::TOWN)
  6041. {
  6042. return static_cast<CGTownInstance*>(obj);
  6043. }
  6044. else if(obj->ID == Obj::SHIPYARD)
  6045. {
  6046. return static_cast<CGShipyard*>(obj);
  6047. }
  6048. else
  6049. {
  6050. //tlog1 << "Cannot cast to IShipyard object with ID " << obj->ID << std::endl;
  6051. return NULL;
  6052. }
  6053. }
  6054. const IShipyard * IShipyard::castFrom( const CGObjectInstance *obj )
  6055. {
  6056. return castFrom(const_cast<CGObjectInstance*>(obj));
  6057. }
  6058. CGShipyard::CGShipyard()
  6059. :IShipyard(this)
  6060. {
  6061. }
  6062. void CGShipyard::getOutOffsets( std::vector<int3> &offsets ) const
  6063. {
  6064. // H J L K I
  6065. // A x S x B
  6066. // C E G F D
  6067. offsets += int3(-3,0,0), int3(1,0,0), //AB
  6068. int3(-3,1,0), int3(1,1,0), int3(-2,1,0), int3(0,1,0), int3(-1,1,0), //CDEFG
  6069. int3(-3,-1,0), int3(1,-1,0), int3(-2,-1,0), int3(0,-1,0), int3(-1,-1,0); //HIJKL
  6070. }
  6071. void CGShipyard::onHeroVisit( const CGHeroInstance * h ) const
  6072. {
  6073. if(!cb->gameState()->getPlayerRelations(tempOwner, h->tempOwner))
  6074. cb->setOwner(this, h->tempOwner);
  6075. auto s = state();
  6076. if(s != IBoatGenerator::GOOD)
  6077. {
  6078. InfoWindow iw;
  6079. iw.player = tempOwner;
  6080. getProblemText(iw.text, h);
  6081. cb->showInfoDialog(&iw);
  6082. }
  6083. else
  6084. {
  6085. openWindow(OpenWindow::SHIPYARD_WINDOW,id.getNum(),h->id.getNum());
  6086. }
  6087. }
  6088. void CCartographer::onHeroVisit( const CGHeroInstance * h ) const
  6089. {
  6090. if (!wasVisited (h->getOwner()) ) //if hero has not visited yet this cartographer
  6091. {
  6092. if (cb->getResource(h->tempOwner, Res::GOLD) >= 1000) //if he can afford a map
  6093. {
  6094. //ask if he wants to buy one
  6095. int text=0;
  6096. switch (subID)
  6097. {
  6098. case 0:
  6099. text = 25;
  6100. break;
  6101. case 1:
  6102. text = 26;
  6103. break;
  6104. case 2:
  6105. text = 27;
  6106. break;
  6107. default:
  6108. tlog2 << "Unrecognized subtype of cartographer" << std::endl;
  6109. }
  6110. assert(text);
  6111. BlockingDialog bd (true, false);
  6112. bd.player = h->getOwner();
  6113. bd.soundID = soundBase::LIGHTHOUSE;
  6114. bd.text.addTxt (MetaString::ADVOB_TXT, text);
  6115. cb->showBlockingDialog (&bd, boost::bind (&CCartographer::buyMap, this, h, _1));
  6116. }
  6117. else //if he cannot afford
  6118. {
  6119. showInfoDialog(h,28,soundBase::CAVEHEAD);
  6120. }
  6121. }
  6122. else //if he already visited carographer
  6123. {
  6124. showInfoDialog(h,24,soundBase::CAVEHEAD);
  6125. }
  6126. }
  6127. void CCartographer::buyMap (const CGHeroInstance *h, ui32 accept) const
  6128. {
  6129. if (accept) //if hero wants to buy map
  6130. {
  6131. cb->giveResource (h->tempOwner, Res::GOLD, -1000);
  6132. FoWChange fw;
  6133. fw.mode = 1;
  6134. fw.player = h->tempOwner;
  6135. //subIDs of different types of cartographers:
  6136. //water = 0; land = 1; underground = 2;
  6137. cb->getAllTiles (fw.tiles, h->tempOwner, subID - 1, !subID + 1); //reveal appropriate tiles
  6138. cb->sendAndApply (&fw);
  6139. cb->setObjProperty (id, 10, h->tempOwner.getNum());
  6140. }
  6141. }
  6142. void CGDenOfthieves::onHeroVisit (const CGHeroInstance * h) const
  6143. {
  6144. cb->showThievesGuildWindow(h->tempOwner, id);
  6145. }
  6146. void CGObelisk::onHeroVisit( const CGHeroInstance * h ) const
  6147. {
  6148. InfoWindow iw;
  6149. iw.player = h->tempOwner;
  6150. TeamState *ts = cb->gameState()->getPlayerTeam(h->tempOwner);
  6151. assert(ts);
  6152. TeamID team = ts->id;
  6153. if(!wasVisited(team))
  6154. {
  6155. iw.text.addTxt(MetaString::ADVOB_TXT, 96);
  6156. cb->sendAndApply(&iw);
  6157. cb->setObjProperty(id, 20, h->tempOwner.getNum()); //increment general visited obelisks counter
  6158. openWindow(OpenWindow::PUZZLE_MAP, h->tempOwner.getNum());
  6159. cb->setObjProperty(id, 10, h->tempOwner.getNum()); //mark that particular obelisk as visited
  6160. }
  6161. else
  6162. {
  6163. iw.text.addTxt(MetaString::ADVOB_TXT, 97);
  6164. cb->sendAndApply(&iw);
  6165. }
  6166. }
  6167. void CGObelisk::initObj()
  6168. {
  6169. obeliskCount++;
  6170. }
  6171. const std::string & CGObelisk::getHoverText() const
  6172. {
  6173. bool visited = wasVisited(cb->getLocalPlayer());
  6174. hoverName = VLC->generaltexth->names[ID] + " " + visitedTxt(visited);
  6175. return hoverName;
  6176. }
  6177. void CGObelisk::setPropertyDer( ui8 what, ui32 val )
  6178. {
  6179. CPlayersVisited::setPropertyDer(what, val);
  6180. switch(what)
  6181. {
  6182. case 20:
  6183. assert(val < PlayerColor::PLAYER_LIMIT_I);
  6184. visited[TeamID(val)]++;
  6185. if(visited[TeamID(val)] > obeliskCount)
  6186. {
  6187. tlog0 << "Error: Visited " << visited[TeamID(val)] << "\t\t" << obeliskCount << std::endl;
  6188. assert(0);
  6189. }
  6190. break;
  6191. }
  6192. }
  6193. void CGLighthouse::onHeroVisit( const CGHeroInstance * h ) const
  6194. {
  6195. if(h->tempOwner != tempOwner)
  6196. {
  6197. PlayerColor oldOwner = tempOwner;
  6198. cb->setOwner(this,h->tempOwner); //not ours? flag it!
  6199. showInfoDialog(h,69,soundBase::LIGHTHOUSE);
  6200. giveBonusTo(h->tempOwner);
  6201. if(oldOwner < PlayerColor::PLAYER_LIMIT) //remove bonus from old owner
  6202. {
  6203. RemoveBonus rb(RemoveBonus::PLAYER);
  6204. rb.whoID = oldOwner.getNum();
  6205. rb.source = Bonus::OBJECT;
  6206. rb.id = id.getNum();
  6207. cb->sendAndApply(&rb);
  6208. }
  6209. }
  6210. }
  6211. void CGLighthouse::initObj()
  6212. {
  6213. if(tempOwner < PlayerColor::PLAYER_LIMIT)
  6214. {
  6215. giveBonusTo(tempOwner);
  6216. }
  6217. }
  6218. const std::string & CGLighthouse::getHoverText() const
  6219. {
  6220. hoverName = VLC->generaltexth->names[ID];
  6221. //TODO: owned by %s player
  6222. return hoverName;
  6223. }
  6224. void CGLighthouse::giveBonusTo( PlayerColor player ) const
  6225. {
  6226. GiveBonus gb(GiveBonus::PLAYER);
  6227. gb.bonus.type = Bonus::SEA_MOVEMENT;
  6228. gb.bonus.val = 500;
  6229. gb.id = player.getNum();
  6230. gb.bonus.duration = Bonus::PERMANENT;
  6231. gb.bonus.source = Bonus::OBJECT;
  6232. gb.bonus.sid = id.getNum();
  6233. cb->sendAndApply(&gb);
  6234. }
  6235. void CArmedInstance::randomizeArmy(int type)
  6236. {
  6237. int max = VLC->creh->creatures.size();
  6238. for (TSlots::iterator j = stacks.begin(); j != stacks.end();j++)
  6239. {
  6240. int randID = j->second->idRand;
  6241. if(randID > max)
  6242. {
  6243. int level = (randID-VLC->creh->creatures.size()) / 2 -1;
  6244. bool upgrade = !(randID % 2);
  6245. j->second->setType(VLC->townh->towns[type].creatures[level][upgrade]);
  6246. randID = -1;
  6247. }
  6248. assert(j->second->armyObj == this);
  6249. }
  6250. return;
  6251. }
  6252. CArmedInstance::CArmedInstance()
  6253. {
  6254. battle = NULL;
  6255. }
  6256. //int CArmedInstance::valOfGlobalBonuses(CSelector selector) const
  6257. //{
  6258. //// if (tempOwner != NEUTRAL_PLAYER)
  6259. // return cb->gameState()->players[tempOwner].valOfBonuses(selector);
  6260. //}
  6261. void CArmedInstance::updateMoraleBonusFromArmy()
  6262. {
  6263. if(!validTypes(false)) //object not randomized, don't bother
  6264. return;
  6265. Bonus *b = getBonusList().getFirst(Selector::sourceType(Bonus::ARMY) && Selector::type(Bonus::MORALE));
  6266. if(!b)
  6267. {
  6268. b = new Bonus(Bonus::PERMANENT, Bonus::MORALE, Bonus::ARMY, 0, -1);
  6269. addNewBonus(b);
  6270. }
  6271. //number of alignments and presence of undead
  6272. std::set<TFaction> factions;
  6273. bool hasUndead = false;
  6274. BOOST_FOREACH(auto slot, Slots())
  6275. {
  6276. const CStackInstance * inst = slot.second;
  6277. const CCreature * creature = VLC->creh->creatures[inst->getCreatureID()];
  6278. factions.insert(creature->faction);
  6279. // Check for undead flag instead of faction (undead mummies are neutral)
  6280. hasUndead |= inst->hasBonusOfType(Bonus::UNDEAD);
  6281. }
  6282. size_t factionsInArmy = factions.size();
  6283. // Take Angelic Alliance troop-mixing freedom of non-evil units into account.
  6284. if (hasBonusOfType(Bonus::NONEVIL_ALIGNMENT_MIX))
  6285. {
  6286. size_t mixableFactions = 0;
  6287. BOOST_FOREACH(TFaction f, factions)
  6288. {
  6289. if (VLC->townh->factions[f].alignment != EAlignment::EVIL)
  6290. mixableFactions++;
  6291. }
  6292. if (mixableFactions > 0)
  6293. factionsInArmy -= mixableFactions - 1;
  6294. }
  6295. if(factionsInArmy == 1)
  6296. {
  6297. b->val = +1;
  6298. b->description = VLC->generaltexth->arraytxt[115]; //All troops of one alignment +1
  6299. }
  6300. else
  6301. {
  6302. b->val = 2 - factionsInArmy;
  6303. b->description = boost::str(boost::format(VLC->generaltexth->arraytxt[114]) % factionsInArmy % b->val); //Troops of %d alignments %d
  6304. }
  6305. boost::algorithm::trim(b->description);
  6306. //-1 modifier for any Undead unit in army
  6307. const ui8 UNDEAD_MODIFIER_ID = -2;
  6308. Bonus *undeadModifier = getBonusList().getFirst(Selector::source(Bonus::ARMY, UNDEAD_MODIFIER_ID));
  6309. if(hasUndead)
  6310. {
  6311. if(!undeadModifier)
  6312. addNewBonus(new Bonus(Bonus::PERMANENT, Bonus::MORALE, Bonus::ARMY, -1, UNDEAD_MODIFIER_ID, VLC->generaltexth->arraytxt[116]));
  6313. }
  6314. else if(undeadModifier)
  6315. removeBonus(undeadModifier);
  6316. }
  6317. void CArmedInstance::armyChanged()
  6318. {
  6319. updateMoraleBonusFromArmy();
  6320. }
  6321. CBonusSystemNode * CArmedInstance::whereShouldBeAttached(CGameState *gs)
  6322. {
  6323. if(tempOwner < PlayerColor::PLAYER_LIMIT)
  6324. return gs->getPlayer(tempOwner);
  6325. else
  6326. return &gs->globalEffects;
  6327. }
  6328. CBonusSystemNode * CArmedInstance::whatShouldBeAttached()
  6329. {
  6330. return this;
  6331. }
  6332. bool IMarket::getOffer(int id1, int id2, int &val1, int &val2, EMarketMode::EMarketMode mode) const
  6333. {
  6334. switch(mode)
  6335. {
  6336. case EMarketMode::RESOURCE_RESOURCE:
  6337. {
  6338. double effectiveness = std::min((getMarketEfficiency() + 1.0) / 20.0, 0.5);
  6339. double r = VLC->objh->resVals[id1], //value of given resource
  6340. g = VLC->objh->resVals[id2] / effectiveness; //value of wanted resource
  6341. if(r>g) //if given resource is more expensive than wanted
  6342. {
  6343. val2 = ceil(r / g);
  6344. val1 = 1;
  6345. }
  6346. else //if wanted resource is more expensive
  6347. {
  6348. val1 = (g / r) + 0.5;
  6349. val2 = 1;
  6350. }
  6351. }
  6352. break;
  6353. case EMarketMode::CREATURE_RESOURCE:
  6354. {
  6355. const double effectivenessArray[] = {0.0, 0.3, 0.45, 0.50, 0.65, 0.7, 0.85, 0.9, 1.0};
  6356. double effectiveness = effectivenessArray[std::min(getMarketEfficiency(), 8)];
  6357. double r = VLC->creh->creatures[id1]->cost[6], //value of given creature in gold
  6358. g = VLC->objh->resVals[id2] / effectiveness; //value of wanted resource
  6359. if(r>g) //if given resource is more expensive than wanted
  6360. {
  6361. val2 = ceil(r / g);
  6362. val1 = 1;
  6363. }
  6364. else //if wanted resource is more expensive
  6365. {
  6366. val1 = (g / r) + 0.5;
  6367. val2 = 1;
  6368. }
  6369. }
  6370. break;
  6371. case EMarketMode::RESOURCE_PLAYER:
  6372. val1 = 1;
  6373. val2 = 1;
  6374. break;
  6375. case EMarketMode::RESOURCE_ARTIFACT:
  6376. {
  6377. double effectiveness = std::min((getMarketEfficiency() + 3.0) / 20.0, 0.6);
  6378. double r = VLC->objh->resVals[id1], //value of offered resource
  6379. g = VLC->arth->artifacts[id2]->price / effectiveness; //value of bought artifact in gold
  6380. if(id1 != 6) //non-gold prices are doubled
  6381. r /= 2;
  6382. val1 = std::max(1, (int)((g / r) + 0.5)); //don't sell arts for less than 1 resource
  6383. val2 = 1;
  6384. }
  6385. break;
  6386. case EMarketMode::ARTIFACT_RESOURCE:
  6387. {
  6388. double effectiveness = std::min((getMarketEfficiency() + 3.0) / 20.0, 0.6);
  6389. double r = VLC->arth->artifacts[id1]->price * effectiveness,
  6390. g = VLC->objh->resVals[id2];
  6391. // if(id2 != 6) //non-gold prices are doubled
  6392. // r /= 2;
  6393. val1 = 1;
  6394. val2 = std::max(1, (int)((r / g) + 0.5)); //at least one resource is given in return
  6395. }
  6396. break;
  6397. case EMarketMode::CREATURE_EXP:
  6398. {
  6399. val1 = 1;
  6400. val2 = (VLC->creh->creatures[id1]->AIValue / 40) * 5;
  6401. }
  6402. break;
  6403. case EMarketMode::ARTIFACT_EXP:
  6404. {
  6405. val1 = 1;
  6406. int givenClass = VLC->arth->artifacts[id1]->getArtClassSerial();
  6407. if(givenClass < 0 || givenClass > 3)
  6408. {
  6409. val2 = 0;
  6410. return false;
  6411. }
  6412. static const int expPerClass[] = {1000, 1500, 3000, 6000};
  6413. val2 = expPerClass[givenClass];
  6414. }
  6415. break;
  6416. default:
  6417. assert(0);
  6418. return false;
  6419. }
  6420. return true;
  6421. }
  6422. bool IMarket::allowsTrade(EMarketMode::EMarketMode mode) const
  6423. {
  6424. return false;
  6425. }
  6426. int IMarket::availableUnits(EMarketMode::EMarketMode mode, int marketItemSerial) const
  6427. {
  6428. switch(mode)
  6429. {
  6430. case EMarketMode::RESOURCE_RESOURCE:
  6431. case EMarketMode::ARTIFACT_RESOURCE:
  6432. case EMarketMode::CREATURE_RESOURCE:
  6433. return -1;
  6434. default:
  6435. return 1;
  6436. }
  6437. }
  6438. std::vector<int> IMarket::availableItemsIds(EMarketMode::EMarketMode mode) const
  6439. {
  6440. std::vector<int> ret;
  6441. switch(mode)
  6442. {
  6443. case EMarketMode::RESOURCE_RESOURCE:
  6444. case EMarketMode::ARTIFACT_RESOURCE:
  6445. case EMarketMode::CREATURE_RESOURCE:
  6446. for (int i = 0; i < 7; i++)
  6447. ret.push_back(i);
  6448. default:
  6449. break;
  6450. }
  6451. return ret;
  6452. }
  6453. const IMarket * IMarket::castFrom(const CGObjectInstance *obj, bool verbose /*= true*/)
  6454. {
  6455. switch(obj->ID)
  6456. {
  6457. case Obj::TOWN:
  6458. return static_cast<const CGTownInstance*>(obj);
  6459. case Obj::ALTAR_OF_SACRIFICE:
  6460. case Obj::BLACK_MARKET:
  6461. case Obj::TRADING_POST:
  6462. case Obj::TRADING_POST_SNOW:
  6463. case Obj::FREELANCERS_GUILD:
  6464. return static_cast<const CGMarket*>(obj);
  6465. case Obj::UNIVERSITY:
  6466. return static_cast<const CGUniversity*>(obj);
  6467. default:
  6468. if(verbose)
  6469. tlog1 << "Cannot cast to IMarket object with ID " << obj->ID << std::endl;
  6470. return NULL;
  6471. }
  6472. }
  6473. IMarket::IMarket(const CGObjectInstance *O)
  6474. :o(O)
  6475. {
  6476. }
  6477. std::vector<EMarketMode::EMarketMode> IMarket::availableModes() const
  6478. {
  6479. std::vector<EMarketMode::EMarketMode> ret;
  6480. for (int i = 0; i < EMarketMode::MARTKET_AFTER_LAST_PLACEHOLDER; i++)
  6481. if(allowsTrade((EMarketMode::EMarketMode)i))
  6482. ret.push_back((EMarketMode::EMarketMode)i);
  6483. return ret;
  6484. }
  6485. void CGMarket::onHeroVisit(const CGHeroInstance * h) const
  6486. {
  6487. openWindow(OpenWindow::MARKET_WINDOW,id.getNum(),h->id.getNum());
  6488. }
  6489. int CGMarket::getMarketEfficiency() const
  6490. {
  6491. return 5;
  6492. }
  6493. bool CGMarket::allowsTrade(EMarketMode::EMarketMode mode) const
  6494. {
  6495. switch(mode)
  6496. {
  6497. case EMarketMode::RESOURCE_RESOURCE:
  6498. case EMarketMode::RESOURCE_PLAYER:
  6499. switch(ID)
  6500. {
  6501. case Obj::TRADING_POST:
  6502. case Obj::TRADING_POST_SNOW:
  6503. return true;
  6504. default:
  6505. return false;
  6506. }
  6507. case EMarketMode::CREATURE_RESOURCE:
  6508. return ID == Obj::FREELANCERS_GUILD;
  6509. //case ARTIFACT_RESOURCE:
  6510. case EMarketMode::RESOURCE_ARTIFACT:
  6511. return ID == Obj::BLACK_MARKET;
  6512. case EMarketMode::ARTIFACT_EXP:
  6513. case EMarketMode::CREATURE_EXP:
  6514. return ID == Obj::ALTAR_OF_SACRIFICE; //TODO? check here for alignment of visiting hero? - would not be coherent with other checks here
  6515. case EMarketMode::RESOURCE_SKILL:
  6516. return ID == Obj::UNIVERSITY;
  6517. default:
  6518. return false;
  6519. }
  6520. }
  6521. int CGMarket::availableUnits(EMarketMode::EMarketMode mode, int marketItemSerial) const
  6522. {
  6523. return -1;
  6524. }
  6525. std::vector<int> CGMarket::availableItemsIds(EMarketMode::EMarketMode mode) const
  6526. {
  6527. switch(mode)
  6528. {
  6529. case EMarketMode::RESOURCE_RESOURCE:
  6530. case EMarketMode::RESOURCE_PLAYER:
  6531. return IMarket::availableItemsIds(mode);
  6532. default:
  6533. return std::vector<int>();
  6534. }
  6535. }
  6536. CGMarket::CGMarket()
  6537. :IMarket(this)
  6538. {
  6539. }
  6540. std::vector<int> CGBlackMarket::availableItemsIds(EMarketMode::EMarketMode mode) const
  6541. {
  6542. switch(mode)
  6543. {
  6544. case EMarketMode::ARTIFACT_RESOURCE:
  6545. return IMarket::availableItemsIds(mode);
  6546. case EMarketMode::RESOURCE_ARTIFACT:
  6547. {
  6548. std::vector<int> ret;
  6549. BOOST_FOREACH(const CArtifact *a, artifacts)
  6550. if(a)
  6551. ret.push_back(a->id);
  6552. else
  6553. ret.push_back(-1);
  6554. return ret;
  6555. }
  6556. default:
  6557. return std::vector<int>();
  6558. }
  6559. }
  6560. void CGBlackMarket::newTurn() const
  6561. {
  6562. if(cb->getDate(Date::DAY_OF_MONTH) != 1) //new month
  6563. return;
  6564. SetAvailableArtifacts saa;
  6565. saa.id = id.getNum();
  6566. cb->pickAllowedArtsSet(saa.arts);
  6567. cb->sendAndApply(&saa);
  6568. }
  6569. void CGUniversity::initObj()
  6570. {
  6571. std::vector <int> toChoose;
  6572. for (int i=0; i<GameConstants::SKILL_QUANTITY; i++)
  6573. if (cb->isAllowed(2,i))
  6574. toChoose.push_back(i);
  6575. if (toChoose.size() < 4)
  6576. {
  6577. tlog0<<"Warning: less then 4 available skills was found by University initializer!\n";
  6578. return;
  6579. }
  6580. for (int i=0; i<4; i++)//get 4 skills
  6581. {
  6582. int skillPos = ran()%toChoose.size();
  6583. skills.push_back(toChoose[skillPos]);//move it to selected
  6584. toChoose.erase(toChoose.begin()+skillPos);//remove from list
  6585. }
  6586. }
  6587. std::vector<int> CGUniversity::availableItemsIds(EMarketMode::EMarketMode mode) const
  6588. {
  6589. switch (mode)
  6590. {
  6591. case EMarketMode::RESOURCE_SKILL:
  6592. return skills;
  6593. default:
  6594. return std::vector <int> ();
  6595. }
  6596. }
  6597. void CGUniversity::onHeroVisit(const CGHeroInstance * h) const
  6598. {
  6599. openWindow(OpenWindow::UNIVERSITY_WINDOW,id.getNum(),h->id.getNum());
  6600. }
  6601. GrowthInfo::Entry::Entry(const std::string &format, int _count)
  6602. : count(_count)
  6603. {
  6604. description = boost::str(boost::format(format) % count);
  6605. }
  6606. GrowthInfo::Entry::Entry(int subID, BuildingID building, int _count)
  6607. : count(_count)
  6608. {
  6609. description = boost::str(boost::format("%s %+d") % VLC->townh->towns[subID].buildings[building]->Name() % count);
  6610. }
  6611. CTownAndVisitingHero::CTownAndVisitingHero()
  6612. {
  6613. setNodeType(TOWN_AND_VISITOR);
  6614. }
  6615. int GrowthInfo::totalGrowth() const
  6616. {
  6617. int ret = 0;
  6618. BOOST_FOREACH(const Entry &entry, entries)
  6619. ret += entry.count;
  6620. return ret;
  6621. }