CObjectHandler.cpp 205 KB

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