2
0

CObjectHandler.cpp 177 KB

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