CObjectHandler.cpp 198 KB

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