CObjectHandler.cpp 202 KB

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