CObjectHandler.cpp 176 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464
  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. COPWBonus::COPWBonus (BuildingID index, CGTownInstance *TOWN)
  2414. {
  2415. ID = index;
  2416. town = TOWN;
  2417. id = town->bonusingBuildings.size();
  2418. }
  2419. void COPWBonus::setProperty(ui8 what, ui32 val)
  2420. {
  2421. switch (what)
  2422. {
  2423. case ObjProperty::VISITORS:
  2424. visitors.insert(val);
  2425. break;
  2426. case ObjProperty::STRUCTURE_CLEAR_VISITORS:
  2427. visitors.clear();
  2428. break;
  2429. }
  2430. }
  2431. void COPWBonus::onHeroVisit (const CGHeroInstance * h) const
  2432. {
  2433. ObjectInstanceID heroID = h->id;
  2434. if (town->hasBuilt(ID))
  2435. {
  2436. InfoWindow iw;
  2437. iw.player = h->tempOwner;
  2438. switch (town->subID)
  2439. {
  2440. case ETownType::CASTLE: //Stables
  2441. if (!h->hasBonusFrom(Bonus::OBJECT, Obj::STABLES)) //does not stack with advMap Stables
  2442. {
  2443. GiveBonus gb;
  2444. gb.bonus = Bonus(Bonus::ONE_WEEK, Bonus::LAND_MOVEMENT, Bonus::OBJECT, 600, 94, VLC->generaltexth->arraytxt[100]);
  2445. gb.id = heroID.getNum();
  2446. cb->giveHeroBonus(&gb);
  2447. iw.text << VLC->generaltexth->allTexts[580];
  2448. cb->showInfoDialog(&iw);
  2449. }
  2450. break;
  2451. case ETownType::DUNGEON: //Mana Vortex
  2452. if (visitors.empty() && h->mana <= h->manaLimit() * 2)
  2453. {
  2454. cb->setManaPoints (heroID, 2 * h->manaLimit());
  2455. //TODO: investigate line below
  2456. //cb->setObjProperty (town->id, ObjProperty::VISITED, true);
  2457. iw.text << VLC->generaltexth->allTexts[579];
  2458. cb->showInfoDialog(&iw);
  2459. town->addHeroToStructureVisitors(h, id);
  2460. }
  2461. break;
  2462. }
  2463. }
  2464. }
  2465. CTownBonus::CTownBonus (BuildingID index, CGTownInstance *TOWN)
  2466. {
  2467. ID = index;
  2468. town = TOWN;
  2469. id = town->bonusingBuildings.size();
  2470. }
  2471. void CTownBonus::setProperty (ui8 what, ui32 val)
  2472. {
  2473. if(what == ObjProperty::VISITORS)
  2474. visitors.insert(ObjectInstanceID(val));
  2475. }
  2476. void CTownBonus::onHeroVisit (const CGHeroInstance * h) const
  2477. {
  2478. ObjectInstanceID heroID = h->id;
  2479. if (town->hasBuilt(ID) && visitors.find(heroID) == visitors.end())
  2480. {
  2481. InfoWindow iw;
  2482. PrimarySkill::PrimarySkill what = PrimarySkill::ATTACK;
  2483. int val=0, mid=0;
  2484. switch (ID)
  2485. {
  2486. case BuildingID::SPECIAL_4:
  2487. switch(town->subID)
  2488. {
  2489. case ETownType::TOWER: //wall
  2490. what = PrimarySkill::KNOWLEDGE;
  2491. val = 1;
  2492. mid = 581;
  2493. iw.components.push_back (Component(Component::PRIM_SKILL, 3, 1, 0));
  2494. break;
  2495. case ETownType::INFERNO: //order of fire
  2496. what = PrimarySkill::SPELL_POWER;
  2497. val = 1;
  2498. mid = 582;
  2499. iw.components.push_back (Component(Component::PRIM_SKILL, 2, 1, 0));
  2500. break;
  2501. case ETownType::STRONGHOLD://hall of Valhalla
  2502. what = PrimarySkill::ATTACK;
  2503. val = 1;
  2504. mid = 584;
  2505. iw.components.push_back (Component(Component::PRIM_SKILL, 0, 1, 0));
  2506. break;
  2507. case ETownType::DUNGEON://academy of battle scholars
  2508. what = PrimarySkill::EXPERIENCE;
  2509. val = h->calculateXp(1000);
  2510. mid = 583;
  2511. iw.components.push_back (Component(Component::EXPERIENCE, 0, val, 0));
  2512. break;
  2513. }
  2514. break;
  2515. case BuildingID::SPECIAL_1:
  2516. switch(town->subID)
  2517. {
  2518. case ETownType::FORTRESS: //cage of warlords
  2519. what = PrimarySkill::DEFENSE;
  2520. val = 1;
  2521. mid = 585;
  2522. iw.components.push_back (Component(Component::PRIM_SKILL, 1, 1, 0));
  2523. break;
  2524. }
  2525. break;
  2526. }
  2527. assert(mid);
  2528. iw.player = cb->getOwner(heroID);
  2529. iw.text << VLC->generaltexth->allTexts[mid];
  2530. cb->showInfoDialog(&iw);
  2531. cb->changePrimSkill (cb->getHero(heroID), what, val);
  2532. town->addHeroToStructureVisitors(h, id);
  2533. }
  2534. }
  2535. const std::string & CGCreature::getHoverText() const
  2536. {
  2537. if(stacks.empty())
  2538. {
  2539. static const std::string errorValue("!!!INVALID_STACK!!!");
  2540. //should not happen...
  2541. logGlobal->errorStream() << "Invalid stack at tile " << pos << ": subID=" << subID << "; id=" << id;
  2542. return errorValue; // references to temporary are illegal - use pre-constructed string
  2543. }
  2544. MetaString ms;
  2545. int pom = stacks.begin()->second->getQuantityID();
  2546. pom = 172 + 3*pom;
  2547. ms.addTxt(MetaString::ARRAY_TXT,pom);
  2548. ms << " " ;
  2549. ms.addTxt(MetaString::CRE_PL_NAMES,subID);
  2550. ms.toString(hoverName);
  2551. if(const CGHeroInstance *selHero = cb->getSelectedHero(cb->getCurrentPlayer()))
  2552. {
  2553. const JsonNode & texts = VLC->generaltexth->localizedTexts["adventureMap"]["monsterThreat"];
  2554. hoverName += texts["title"].String();
  2555. int choice;
  2556. double ratio = ((double)getArmyStrength() / selHero->getTotalStrength());
  2557. if (ratio < 0.1) choice = 0;
  2558. else if (ratio < 0.25) choice = 1;
  2559. else if (ratio < 0.6) choice = 2;
  2560. else if (ratio < 0.9) choice = 3;
  2561. else if (ratio < 1.1) choice = 4;
  2562. else if (ratio < 1.3) choice = 5;
  2563. else if (ratio < 1.8) choice = 6;
  2564. else if (ratio < 2.5) choice = 7;
  2565. else if (ratio < 4) choice = 8;
  2566. else if (ratio < 8) choice = 9;
  2567. else if (ratio < 20) choice = 10;
  2568. else choice = 11;
  2569. hoverName += texts["levels"].Vector()[choice].String();
  2570. }
  2571. return hoverName;
  2572. }
  2573. void CGCreature::onHeroVisit( const CGHeroInstance * h ) const
  2574. {
  2575. int action = takenAction(h);
  2576. switch( action ) //decide what we do...
  2577. {
  2578. case FIGHT:
  2579. fight(h);
  2580. break;
  2581. case FLEE: //flee
  2582. {
  2583. flee(h);
  2584. break;
  2585. }
  2586. case JOIN_FOR_FREE: //join for free
  2587. {
  2588. BlockingDialog ynd(true,false);
  2589. ynd.player = h->tempOwner;
  2590. ynd.text.addTxt(MetaString::ADVOB_TXT, 86);
  2591. ynd.text.addReplacement(MetaString::CRE_PL_NAMES, subID);
  2592. cb->showBlockingDialog(&ynd);
  2593. break;
  2594. }
  2595. default: //join for gold
  2596. {
  2597. assert(action > 0);
  2598. //ask if player agrees to pay gold
  2599. BlockingDialog ynd(true,false);
  2600. ynd.player = h->tempOwner;
  2601. std::string tmp = VLC->generaltexth->advobtxt[90];
  2602. boost::algorithm::replace_first(tmp,"%d",boost::lexical_cast<std::string>(getStackCount(SlotID(0))));
  2603. boost::algorithm::replace_first(tmp,"%d",boost::lexical_cast<std::string>(action));
  2604. boost::algorithm::replace_first(tmp,"%s",VLC->creh->creatures[subID]->namePl);
  2605. ynd.text << tmp;
  2606. cb->showBlockingDialog(&ynd);
  2607. break;
  2608. }
  2609. }
  2610. }
  2611. void CGCreature::initObj()
  2612. {
  2613. blockVisit = true;
  2614. switch(character)
  2615. {
  2616. case 0:
  2617. character = -4;
  2618. break;
  2619. case 1:
  2620. character = cb->gameState()->getRandomGenerator().nextInt(1, 7);
  2621. break;
  2622. case 2:
  2623. character = cb->gameState()->getRandomGenerator().nextInt(1, 10);
  2624. break;
  2625. case 3:
  2626. character = cb->gameState()->getRandomGenerator().nextInt(4, 10);
  2627. break;
  2628. case 4:
  2629. character = 10;
  2630. break;
  2631. }
  2632. stacks[SlotID(0)]->setType(CreatureID(subID));
  2633. TQuantity &amount = stacks[SlotID(0)]->count;
  2634. CCreature &c = *VLC->creh->creatures[subID];
  2635. if(amount == 0)
  2636. {
  2637. amount = cb->gameState()->getRandomGenerator().nextInt(c.ammMin, c.ammMax);
  2638. if(amount == 0) //armies with 0 creatures are illegal
  2639. {
  2640. logGlobal->warnStream() << "Problem: stack " << nodeName() << " cannot have 0 creatures. Check properties of " << c.nodeName();
  2641. amount = 1;
  2642. }
  2643. }
  2644. formation.randomFormation = rand();
  2645. temppower = stacks[SlotID(0)]->count * 1000;
  2646. refusedJoining = false;
  2647. }
  2648. void CGCreature::newTurn() const
  2649. {//Works only for stacks of single type of size up to 2 millions
  2650. if (stacks.begin()->second->count < VLC->modh->settings.CREEP_SIZE && cb->getDate(Date::DAY_OF_WEEK) == 1 && cb->getDate(Date::DAY) > 1)
  2651. {
  2652. ui32 power = temppower * (100 + VLC->modh->settings.WEEKLY_GROWTH)/100;
  2653. cb->setObjProperty(id, ObjProperty::MONSTER_COUNT, std::min (power/1000 , (ui32)VLC->modh->settings.CREEP_SIZE)); //set new amount
  2654. cb->setObjProperty(id, ObjProperty::MONSTER_POWER, power); //increase temppower
  2655. }
  2656. if (VLC->modh->modules.STACK_EXP)
  2657. cb->setObjProperty(id, ObjProperty::MONSTER_EXP, VLC->modh->settings.NEUTRAL_STACK_EXP); //for testing purpose
  2658. }
  2659. void CGCreature::setPropertyDer(ui8 what, ui32 val)
  2660. {
  2661. switch (what)
  2662. {
  2663. case ObjProperty::MONSTER_COUNT:
  2664. stacks[SlotID(0)]->count = val;
  2665. break;
  2666. case ObjProperty::MONSTER_POWER:
  2667. temppower = val;
  2668. break;
  2669. case ObjProperty::MONSTER_EXP:
  2670. giveStackExp(val);
  2671. break;
  2672. case ObjProperty::MONSTER_RESTORE_TYPE:
  2673. formation.basicType = val;
  2674. break;
  2675. case ObjProperty::MONSTER_REFUSED_JOIN:
  2676. refusedJoining = val;
  2677. break;
  2678. }
  2679. }
  2680. int CGCreature::takenAction(const CGHeroInstance *h, bool allowJoin) const
  2681. {
  2682. //calculate relative strength of hero and creatures armies
  2683. double relStrength = double(h->getTotalStrength()) / getArmyStrength();
  2684. int powerFactor;
  2685. if(relStrength >= 7)
  2686. powerFactor = 11;
  2687. else if(relStrength >= 1)
  2688. powerFactor = (int)(2*(relStrength-1));
  2689. else if(relStrength >= 0.5)
  2690. powerFactor = -1;
  2691. else if(relStrength >= 0.333)
  2692. powerFactor = -2;
  2693. else
  2694. powerFactor = -3;
  2695. std::set<CreatureID> myKindCres; //what creatures are the same kind as we
  2696. const CCreature * myCreature = VLC->creh->creatures[subID];
  2697. myKindCres.insert(myCreature->idNumber); //we
  2698. myKindCres.insert(myCreature->upgrades.begin(), myCreature->upgrades.end()); //our upgrades
  2699. for(ConstTransitivePtr<CCreature> &crea : VLC->creh->creatures)
  2700. {
  2701. if(vstd::contains(crea->upgrades, myCreature->idNumber)) //it's our base creatures
  2702. myKindCres.insert(crea->idNumber);
  2703. }
  2704. int count = 0, //how many creatures of similar kind has hero
  2705. totalCount = 0;
  2706. for (auto & elem : h->Slots())
  2707. {
  2708. if(vstd::contains(myKindCres,elem.second->type->idNumber))
  2709. count += elem.second->count;
  2710. totalCount += elem.second->count;
  2711. }
  2712. int sympathy = 0; // 0 if hero have no similar creatures
  2713. if(count)
  2714. sympathy++; // 1 - if hero have at least 1 similar creature
  2715. if(count*2 > totalCount)
  2716. sympathy++; // 2 - hero have similar creatures more that 50%
  2717. int charisma = powerFactor + h->getSecSkillLevel(SecondarySkill::DIPLOMACY) + sympathy;
  2718. if(charisma < character) //creatures will fight
  2719. return -2;
  2720. if (allowJoin)
  2721. {
  2722. if(h->getSecSkillLevel(SecondarySkill::DIPLOMACY) + sympathy + 1 >= character)
  2723. return 0; //join for free
  2724. else if(h->getSecSkillLevel(SecondarySkill::DIPLOMACY) * 2 + sympathy + 1 >= character)
  2725. return VLC->creh->creatures[subID]->cost[6] * getStackCount(SlotID(0)); //join for gold
  2726. }
  2727. //we are still here - creatures have not joined hero, flee or fight
  2728. if (charisma > character)
  2729. return -1; //flee
  2730. else
  2731. return -2; //fight
  2732. }
  2733. void CGCreature::fleeDecision(const CGHeroInstance *h, ui32 pursue) const
  2734. {
  2735. if(refusedJoining)
  2736. cb->setObjProperty(id, ObjProperty::MONSTER_REFUSED_JOIN, false);
  2737. if(pursue)
  2738. {
  2739. fight(h);
  2740. }
  2741. else
  2742. {
  2743. cb->removeObject(this);
  2744. }
  2745. }
  2746. void CGCreature::joinDecision(const CGHeroInstance *h, int cost, ui32 accept) const
  2747. {
  2748. if(!accept)
  2749. {
  2750. if(takenAction(h,false) == -1) //they flee
  2751. {
  2752. cb->setObjProperty(id, ObjProperty::MONSTER_REFUSED_JOIN, true);
  2753. flee(h);
  2754. }
  2755. else //they fight
  2756. {
  2757. showInfoDialog(h,87,0);//Insulted by your refusal of their offer, the monsters attack!
  2758. fight(h);
  2759. }
  2760. }
  2761. else //accepted
  2762. {
  2763. if (cb->getResource(h->tempOwner, Res::GOLD) < cost) //player don't have enough gold!
  2764. {
  2765. InfoWindow iw;
  2766. iw.player = h->tempOwner;
  2767. iw.text << std::pair<ui8,ui32>(1,29); //You don't have enough gold
  2768. cb->showInfoDialog(&iw);
  2769. //act as if player refused
  2770. joinDecision(h,cost,false);
  2771. return;
  2772. }
  2773. //take gold
  2774. if(cost)
  2775. cb->giveResource(h->tempOwner,Res::GOLD,-cost);
  2776. cb->tryJoiningArmy(this, h, true, true);
  2777. }
  2778. }
  2779. void CGCreature::fight( const CGHeroInstance *h ) const
  2780. {
  2781. //split stacks
  2782. //TODO: multiple creature types in a stack?
  2783. int basicType = stacks.begin()->second->type->idNumber;
  2784. cb->setObjProperty(id, ObjProperty::MONSTER_RESTORE_TYPE, basicType); //store info about creature stack
  2785. double relativePower = static_cast<double>(h->getTotalStrength()) / getArmyStrength();
  2786. int stacksCount;
  2787. //TODO: number depends on tile type
  2788. if (relativePower < 0.5)
  2789. {
  2790. stacksCount = 7;
  2791. }
  2792. else if (relativePower < 0.67)
  2793. {
  2794. stacksCount = 7;
  2795. }
  2796. else if (relativePower < 1)
  2797. {
  2798. stacksCount = 6;
  2799. }
  2800. else if (relativePower < 1.5)
  2801. {
  2802. stacksCount = 5;
  2803. }
  2804. else if (relativePower < 2)
  2805. {
  2806. stacksCount = 4;
  2807. }
  2808. else
  2809. {
  2810. stacksCount = 3;
  2811. }
  2812. SlotID sourceSlot = stacks.begin()->first;
  2813. SlotID destSlot;
  2814. for (int stacksLeft = stacksCount; stacksLeft > 1; --stacksLeft)
  2815. {
  2816. int stackSize = stacks.begin()->second->count / stacksLeft;
  2817. if (stackSize)
  2818. {
  2819. if ((destSlot = getFreeSlot()).validSlot())
  2820. cb->moveStack(StackLocation(this, sourceSlot), StackLocation(this, destSlot), stackSize);
  2821. else
  2822. {
  2823. logGlobal->warnStream() <<"Warning! Not enough empty slots to split stack!";
  2824. break;
  2825. }
  2826. }
  2827. else break;
  2828. }
  2829. if (stacksCount > 1)
  2830. {
  2831. if (formation.randomFormation % 100 < 50) //upgrade
  2832. {
  2833. SlotID slotId = SlotID(stacks.size() / 2);
  2834. if(ui32 upgradesSize = getStack(slotId).type->upgrades.size())
  2835. {
  2836. auto it = getStack(slotId).type->upgrades.cbegin(); //pick random in case there are more
  2837. std::advance (it, rand() % upgradesSize);
  2838. cb->changeStackType(StackLocation(this, slotId), VLC->creh->creatures[*it]);
  2839. }
  2840. }
  2841. }
  2842. cb->startBattleI(h, this);
  2843. }
  2844. void CGCreature::flee( const CGHeroInstance * h ) const
  2845. {
  2846. BlockingDialog ynd(true,false);
  2847. ynd.player = h->tempOwner;
  2848. ynd.text.addTxt(MetaString::ADVOB_TXT,91);
  2849. ynd.text.addReplacement(MetaString::CRE_PL_NAMES, subID);
  2850. cb->showBlockingDialog(&ynd);
  2851. }
  2852. void CGCreature::battleFinished(const CGHeroInstance *hero, const BattleResult &result) const
  2853. {
  2854. if(result.winner==0)
  2855. {
  2856. cb->removeObject(this);
  2857. }
  2858. else
  2859. {
  2860. //int killedAmount=0;
  2861. //for(std::set<std::pair<ui32,si32> >::iterator i=result->casualties[1].begin(); i!=result->casualties[1].end(); i++)
  2862. // if(i->first == subID)
  2863. // killedAmount += i->second;
  2864. //cb->setAmount(id, slots.find(0)->second.second - killedAmount);
  2865. /*
  2866. MetaString ms;
  2867. int pom = slots.find(0)->second.getQuantityID();
  2868. pom = 174 + 3*pom + 1;
  2869. ms << std::pair<ui8,ui32>(6,pom) << " " << std::pair<ui8,ui32>(7,subID);
  2870. cb->setHoverName(id,&ms);
  2871. cb->setObjProperty(id, 11, slots.begin()->second.count * 1000);
  2872. */
  2873. //merge stacks into one
  2874. TSlots::const_iterator i;
  2875. CCreature * cre = VLC->creh->creatures[formation.basicType];
  2876. for (i = stacks.begin(); i != stacks.end(); i++)
  2877. {
  2878. if (cre->isMyUpgrade(i->second->type))
  2879. {
  2880. cb->changeStackType (StackLocation(this, i->first), cre); //un-upgrade creatures
  2881. }
  2882. }
  2883. //first stack has to be at slot 0 -> if original one got killed, move there first remaining stack
  2884. if(!hasStackAtSlot(SlotID(0)))
  2885. cb->moveStack(StackLocation(this, stacks.begin()->first), StackLocation(this, SlotID(0)), stacks.begin()->second->count);
  2886. while (stacks.size() > 1) //hopefully that's enough
  2887. {
  2888. // 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)
  2889. i = stacks.end();
  2890. i--;
  2891. SlotID slot = getSlotFor(i->second->type);
  2892. if (slot == i->first) //no reason to move stack to its own slot
  2893. break;
  2894. else
  2895. cb->moveStack (StackLocation(this, i->first), StackLocation(this, slot), i->second->count);
  2896. }
  2897. cb->setObjProperty(id, ObjProperty::MONSTER_POWER, stacks.begin()->second->count * 1000); //remember casualties
  2898. }
  2899. }
  2900. void CGCreature::blockingDialogAnswered(const CGHeroInstance *hero, ui32 answer) const
  2901. {
  2902. auto action = takenAction(hero);
  2903. if(!refusedJoining && action >= JOIN_FOR_FREE) //higher means price
  2904. joinDecision(hero, action, answer);
  2905. else if(action != FIGHT)
  2906. fleeDecision(hero, answer);
  2907. else
  2908. assert(0);
  2909. }
  2910. void CGMine::onHeroVisit( const CGHeroInstance * h ) const
  2911. {
  2912. int relations = cb->gameState()->getPlayerRelations(h->tempOwner, tempOwner);
  2913. if(relations == 2) //we're visiting our mine
  2914. {
  2915. cb->showGarrisonDialog(id,h->id,true);
  2916. return;
  2917. }
  2918. else if (relations == 1)//ally
  2919. return;
  2920. if(stacksCount()) //Mine is guarded
  2921. {
  2922. BlockingDialog ynd(true,false);
  2923. ynd.player = h->tempOwner;
  2924. ynd.text.addTxt(MetaString::ADVOB_TXT, subID == 7 ? 84 : 187);
  2925. cb->showBlockingDialog(&ynd);
  2926. return;
  2927. }
  2928. flagMine(h->tempOwner);
  2929. }
  2930. void CGMine::newTurn() const
  2931. {
  2932. if(cb->getDate() == 1)
  2933. return;
  2934. if (tempOwner == PlayerColor::NEUTRAL)
  2935. return;
  2936. cb->giveResource(tempOwner, producedResource, producedQuantity);
  2937. }
  2938. void CGMine::initObj()
  2939. {
  2940. if(subID >= 7) //Abandoned Mine
  2941. {
  2942. //set guardians
  2943. int howManyTroglodytes = cb->gameState()->getRandomGenerator().nextInt(100, 199);
  2944. auto troglodytes = new CStackInstance(CreatureID::TROGLODYTES, howManyTroglodytes);
  2945. putStack(SlotID(0), troglodytes);
  2946. //after map reading tempOwner placeholds bitmask for allowed resources
  2947. std::vector<Res::ERes> possibleResources;
  2948. for (int i = 0; i < PlayerColor::PLAYER_LIMIT_I; i++)
  2949. if(tempOwner.getNum() & 1<<i) //NOTE: reuse of tempOwner
  2950. possibleResources.push_back(static_cast<Res::ERes>(i));
  2951. assert(!possibleResources.empty());
  2952. producedResource = *RandomGeneratorUtil::nextItem(possibleResources, cb->gameState()->getRandomGenerator());
  2953. tempOwner = PlayerColor::NEUTRAL;
  2954. hoverName = VLC->generaltexth->mines[7].first + "\n" + VLC->generaltexth->allTexts[202] + " " + troglodytes->getQuantityTXT(false) + " " + troglodytes->type->namePl;
  2955. }
  2956. else
  2957. {
  2958. producedResource = static_cast<Res::ERes>(subID);
  2959. MetaString ms;
  2960. ms << std::pair<ui8,ui32>(9,producedResource);
  2961. if(tempOwner >= PlayerColor::PLAYER_LIMIT)
  2962. tempOwner = PlayerColor::NEUTRAL;
  2963. else
  2964. ms << " (" << std::pair<ui8,ui32>(6,23+tempOwner.getNum()) << ")";
  2965. ms.toString(hoverName);
  2966. }
  2967. producedQuantity = defaultResProduction();
  2968. }
  2969. void CGMine::flagMine(PlayerColor player) const
  2970. {
  2971. assert(tempOwner != player);
  2972. cb->setOwner(this, player); //not ours? flag it!
  2973. MetaString ms;
  2974. ms << std::pair<ui8,ui32>(9,subID) << "\n(" << std::pair<ui8,ui32>(6,23+player.getNum()) << ")";
  2975. if(subID == 7)
  2976. {
  2977. ms << "(%s)";
  2978. ms.addReplacement(MetaString::RES_NAMES, producedResource);
  2979. }
  2980. cb->setHoverName(this,&ms);
  2981. InfoWindow iw;
  2982. iw.soundID = soundBase::FLAGMINE;
  2983. iw.text.addTxt(MetaString::MINE_EVNTS,producedResource); //not use subID, abandoned mines uses default mine texts
  2984. iw.player = player;
  2985. iw.components.push_back(Component(Component::RESOURCE,producedResource,producedQuantity,-1));
  2986. cb->showInfoDialog(&iw);
  2987. }
  2988. ui32 CGMine::defaultResProduction()
  2989. {
  2990. switch(producedResource)
  2991. {
  2992. case Res::WOOD:
  2993. case Res::ORE:
  2994. return 2;
  2995. case Res::GOLD:
  2996. return 1000;
  2997. default:
  2998. return 1;
  2999. }
  3000. }
  3001. void CGMine::battleFinished(const CGHeroInstance *hero, const BattleResult &result) const
  3002. {
  3003. if(result.winner == 0) //attacker won
  3004. {
  3005. if(subID == 7)
  3006. {
  3007. showInfoDialog(hero->tempOwner, 85, 0);
  3008. }
  3009. flagMine(hero->tempOwner);
  3010. }
  3011. }
  3012. void CGMine::blockingDialogAnswered(const CGHeroInstance *hero, ui32 answer) const
  3013. {
  3014. if(answer)
  3015. cb->startBattleI(hero, this);
  3016. }
  3017. void CGResource::initObj()
  3018. {
  3019. blockVisit = true;
  3020. hoverName = VLC->generaltexth->restypes[subID];
  3021. if(!amount)
  3022. {
  3023. switch(subID)
  3024. {
  3025. case 6:
  3026. amount = cb->gameState()->getRandomGenerator().nextInt(500, 1000);
  3027. break;
  3028. case 0: case 2:
  3029. amount = cb->gameState()->getRandomGenerator().nextInt(6, 10);
  3030. break;
  3031. default:
  3032. amount = cb->gameState()->getRandomGenerator().nextInt(3, 5);
  3033. break;
  3034. }
  3035. }
  3036. }
  3037. void CGResource::onHeroVisit( const CGHeroInstance * h ) const
  3038. {
  3039. if(stacksCount())
  3040. {
  3041. if(message.size())
  3042. {
  3043. BlockingDialog ynd(true,false);
  3044. ynd.player = h->getOwner();
  3045. ynd.text << message;
  3046. cb->showBlockingDialog(&ynd);
  3047. }
  3048. else
  3049. {
  3050. blockingDialogAnswered(h, true); //behave as if player accepted battle
  3051. }
  3052. }
  3053. else
  3054. {
  3055. if(message.length())
  3056. {
  3057. InfoWindow iw;
  3058. iw.player = h->tempOwner;
  3059. iw.text << message;
  3060. cb->showInfoDialog(&iw);
  3061. }
  3062. collectRes(h->getOwner());
  3063. }
  3064. }
  3065. void CGResource::collectRes( PlayerColor player ) const
  3066. {
  3067. cb->giveResource(player, static_cast<Res::ERes>(subID), amount);
  3068. ShowInInfobox sii;
  3069. sii.player = player;
  3070. sii.c = Component(Component::RESOURCE,subID,amount,0);
  3071. sii.text.addTxt(MetaString::ADVOB_TXT,113);
  3072. sii.text.addReplacement(MetaString::RES_NAMES, subID);
  3073. cb->showCompInfo(&sii);
  3074. cb->removeObject(this);
  3075. }
  3076. void CGResource::battleFinished(const CGHeroInstance *hero, const BattleResult &result) const
  3077. {
  3078. if(result.winner == 0) //attacker won
  3079. collectRes(hero->getOwner());
  3080. }
  3081. void CGResource::blockingDialogAnswered(const CGHeroInstance *hero, ui32 answer) const
  3082. {
  3083. if(answer)
  3084. cb->startBattleI(hero, this);
  3085. }
  3086. void CGTeleport::onHeroVisit( const CGHeroInstance * h ) const
  3087. {
  3088. ObjectInstanceID destinationid;
  3089. switch(ID)
  3090. {
  3091. case Obj::MONOLITH1: //one way - find corresponding exit monolith
  3092. if(vstd::contains(objs,Obj::MONOLITH2) && vstd::contains(objs[Obj::MONOLITH2],subID) && objs[Obj::MONOLITH2][subID].size())
  3093. destinationid = objs[Obj::MONOLITH2][subID][rand()%objs[Obj::MONOLITH2][subID].size()];
  3094. else
  3095. logGlobal->warnStream() << "Cannot find corresponding exit monolith for "<< id;
  3096. break;
  3097. case Obj::MONOLITH3://two way monolith - pick any other one
  3098. case Obj::WHIRLPOOL: //Whirlpool
  3099. if(vstd::contains(objs,ID) && vstd::contains(objs[ID],subID) && objs[ID][subID].size()>1)
  3100. {
  3101. while ((destinationid = objs[ID][subID][rand()%objs[ID][subID].size()]) == id); //choose another exit
  3102. if (ID == Obj::WHIRLPOOL)
  3103. {
  3104. if (!h->hasBonusOfType(Bonus::WHIRLPOOL_PROTECTION))
  3105. {
  3106. if (h->Slots().size() > 1 || h->Slots().begin()->second->count > 1)
  3107. { //we can't remove last unit
  3108. SlotID targetstack = h->Slots().begin()->first; //slot numbers may vary
  3109. for(auto i = h->Slots().rbegin(); i != h->Slots().rend(); i++)
  3110. {
  3111. if (h->getPower(targetstack) > h->getPower(i->first))
  3112. {
  3113. targetstack = (i->first);
  3114. }
  3115. }
  3116. TQuantity countToTake = h->getStackCount(targetstack) * 0.5;
  3117. vstd::amax(countToTake, 1);
  3118. InfoWindow iw;
  3119. iw.player = h->tempOwner;
  3120. iw.text.addTxt (MetaString::ADVOB_TXT, 168);
  3121. iw.components.push_back (Component(CStackBasicDescriptor(h->getCreature(targetstack), countToTake)));
  3122. cb->showInfoDialog(&iw);
  3123. cb->changeStackCount(StackLocation(h, targetstack), -countToTake);
  3124. }
  3125. }
  3126. }
  3127. }
  3128. else
  3129. logGlobal->warnStream() << "Cannot find corresponding exit monolith for "<< id;
  3130. break;
  3131. case Obj::SUBTERRANEAN_GATE: //find nearest subterranean gate on the other level
  3132. {
  3133. destinationid = getMatchingGate(id);
  3134. if(destinationid == ObjectInstanceID()) //no exit
  3135. {
  3136. showInfoDialog(h,153,0);//Just inside the entrance you find a large pile of rubble blocking the tunnel. You leave discouraged.
  3137. }
  3138. break;
  3139. }
  3140. }
  3141. if(destinationid == ObjectInstanceID())
  3142. {
  3143. logGlobal->warnStream() << "Cannot find exit... (obj at " << pos << ") :( ";
  3144. return;
  3145. }
  3146. if (ID == Obj::WHIRLPOOL)
  3147. {
  3148. std::set<int3> tiles = cb->getObj(destinationid)->getBlockedPos();
  3149. auto it = tiles.begin();
  3150. std::advance (it, rand() % tiles.size()); //picking random element of set is tiring
  3151. cb->moveHero (h->id, *it + int3(1,0,0), true);
  3152. }
  3153. else
  3154. cb->moveHero (h->id,CGHeroInstance::convertPosition(cb->getObj(destinationid)->pos,true) - getVisitableOffset(), true);
  3155. }
  3156. void CGTeleport::initObj()
  3157. {
  3158. int si = subID;
  3159. switch (ID)
  3160. {
  3161. case Obj::SUBTERRANEAN_GATE://ignore subterranean gates subid
  3162. case Obj::WHIRLPOOL:
  3163. {
  3164. si = 0;
  3165. break;
  3166. }
  3167. default:
  3168. break;
  3169. }
  3170. objs[ID][si].push_back(id);
  3171. }
  3172. void CGTeleport::postInit() //matches subterranean gates into pairs
  3173. {
  3174. //split on underground and surface gates
  3175. std::vector<const CGObjectInstance *> gatesSplit[2]; //surface and underground gates
  3176. for(auto & elem : objs[Obj::SUBTERRANEAN_GATE][0])
  3177. {
  3178. const CGObjectInstance *hlp = cb->getObj(elem);
  3179. gatesSplit[hlp->pos.z].push_back(hlp);
  3180. }
  3181. //sort by position
  3182. std::sort(gatesSplit[0].begin(), gatesSplit[0].end(), [](const CGObjectInstance * a, const CGObjectInstance * b)
  3183. {
  3184. return a->pos < b->pos;
  3185. });
  3186. for(size_t i = 0; i < gatesSplit[0].size(); i++)
  3187. {
  3188. const CGObjectInstance *cur = gatesSplit[0][i];
  3189. //find nearest underground exit
  3190. std::pair<int,double> best(-1,150000); //pair<pos_in_vector, distance>
  3191. for(int j = 0; j < gatesSplit[1].size(); j++)
  3192. {
  3193. const CGObjectInstance *checked = gatesSplit[1][j];
  3194. if(!checked)
  3195. continue;
  3196. double hlp = checked->pos.dist2d(cur->pos);
  3197. if(hlp < best.second)
  3198. {
  3199. best.first = j;
  3200. best.second = hlp;
  3201. }
  3202. }
  3203. if(best.first >= 0) //found pair
  3204. {
  3205. gates.push_back(std::make_pair(cur->id, gatesSplit[1][best.first]->id));
  3206. gatesSplit[1][best.first] = nullptr;
  3207. }
  3208. else
  3209. {
  3210. gates.push_back(std::make_pair(cur->id, ObjectInstanceID()));
  3211. }
  3212. }
  3213. objs.erase(Obj::SUBTERRANEAN_GATE);
  3214. }
  3215. ObjectInstanceID CGTeleport::getMatchingGate(ObjectInstanceID id)
  3216. {
  3217. for(auto & gate : gates)
  3218. {
  3219. if(gate.first == id)
  3220. return gate.second;
  3221. if(gate.second == id)
  3222. return gate.first;
  3223. }
  3224. return ObjectInstanceID();
  3225. }
  3226. void CGArtifact::initObj()
  3227. {
  3228. blockVisit = true;
  3229. if(ID == Obj::ARTIFACT)
  3230. {
  3231. hoverName = VLC->arth->artifacts[subID]->Name();
  3232. if(!storedArtifact->artType)
  3233. storedArtifact->setType(VLC->arth->artifacts[subID]);
  3234. }
  3235. if(ID == Obj::SPELL_SCROLL)
  3236. subID = 1;
  3237. assert(storedArtifact->artType);
  3238. assert(storedArtifact->getParentNodes().size());
  3239. //assert(storedArtifact->artType->id == subID); //this does not stop desync
  3240. }
  3241. void CGArtifact::onHeroVisit( const CGHeroInstance * h ) const
  3242. {
  3243. if(!stacksCount())
  3244. {
  3245. InfoWindow iw;
  3246. iw.player = h->tempOwner;
  3247. switch(ID)
  3248. {
  3249. case Obj::ARTIFACT:
  3250. {
  3251. iw.soundID = soundBase::treasure; //play sound only for non-scroll arts
  3252. iw.components.push_back(Component(Component::ARTIFACT,subID,0,0));
  3253. if(message.length())
  3254. iw.text << message;
  3255. else
  3256. {
  3257. if (VLC->arth->artifacts[subID]->EventText().size())
  3258. iw.text << std::pair<ui8, ui32> (MetaString::ART_EVNTS, subID);
  3259. else //fix for mod artifacts with no event text
  3260. {
  3261. iw.text.addTxt (MetaString::ADVOB_TXT, 183); //% has found treasure
  3262. iw.text.addReplacement (h->name);
  3263. }
  3264. }
  3265. }
  3266. break;
  3267. case Obj::SPELL_SCROLL:
  3268. {
  3269. int spellID = storedArtifact->getGivenSpellID();
  3270. iw.components.push_back (Component(Component::SPELL, spellID,0,0));
  3271. iw.text.addTxt (MetaString::ADVOB_TXT,135);
  3272. iw.text.addReplacement(MetaString::SPELL_NAME, spellID);
  3273. }
  3274. break;
  3275. }
  3276. cb->showInfoDialog(&iw);
  3277. pick(h);
  3278. }
  3279. else
  3280. {
  3281. if(message.size())
  3282. {
  3283. BlockingDialog ynd(true,false);
  3284. ynd.player = h->getOwner();
  3285. ynd.text << message;
  3286. cb->showBlockingDialog(&ynd);
  3287. }
  3288. else
  3289. {
  3290. blockingDialogAnswered(h, true);
  3291. }
  3292. }
  3293. }
  3294. void CGArtifact::pick(const CGHeroInstance * h) const
  3295. {
  3296. cb->giveHeroArtifact(h, storedArtifact, ArtifactPosition::FIRST_AVAILABLE);
  3297. cb->removeObject(this);
  3298. }
  3299. void CGArtifact::battleFinished(const CGHeroInstance *hero, const BattleResult &result) const
  3300. {
  3301. if(result.winner == 0) //attacker won
  3302. pick(hero);
  3303. }
  3304. void CGArtifact::blockingDialogAnswered(const CGHeroInstance *hero, ui32 answer) const
  3305. {
  3306. if(answer)
  3307. cb->startBattleI(hero, this);
  3308. }
  3309. bool CQuest::checkQuest (const CGHeroInstance * h) const
  3310. {
  3311. switch (missionType)
  3312. {
  3313. case MISSION_NONE:
  3314. return true;
  3315. case MISSION_LEVEL:
  3316. if (m13489val <= h->level)
  3317. return true;
  3318. return false;
  3319. case MISSION_PRIMARY_STAT:
  3320. for (int i = 0; i < GameConstants::PRIMARY_SKILLS; ++i)
  3321. {
  3322. if (h->getPrimSkillLevel(static_cast<PrimarySkill::PrimarySkill>(i)) < m2stats[i])
  3323. return false;
  3324. }
  3325. return true;
  3326. case MISSION_KILL_HERO:
  3327. case MISSION_KILL_CREATURE:
  3328. if (!h->cb->getObjByQuestIdentifier(m13489val))
  3329. return true;
  3330. return false;
  3331. case MISSION_ART:
  3332. for (auto & elem : m5arts)
  3333. {
  3334. if (h->hasArt(elem))
  3335. continue;
  3336. return false; //if the artifact was not found
  3337. }
  3338. return true;
  3339. case MISSION_ARMY:
  3340. {
  3341. std::vector<CStackBasicDescriptor>::const_iterator cre;
  3342. TSlots::const_iterator it;
  3343. ui32 count;
  3344. for (cre = m6creatures.begin(); cre != m6creatures.end(); ++cre)
  3345. {
  3346. for (count = 0, it = h->Slots().begin(); it != h->Slots().end(); ++it)
  3347. {
  3348. if (it->second->type == cre->type)
  3349. count += it->second->count;
  3350. }
  3351. if (count < cre->count) //not enough creatures of this kind
  3352. return false;
  3353. }
  3354. }
  3355. return true;
  3356. case MISSION_RESOURCES:
  3357. for (Res::ERes i = Res::WOOD; i <= Res::GOLD; vstd::advance(i, +1)) //including Mithril ?
  3358. { //Quest has no direct access to callback
  3359. if (h->cb->getResource (h->tempOwner, i) < m7resources[i])
  3360. return false;
  3361. }
  3362. return true;
  3363. case MISSION_HERO:
  3364. if (m13489val == h->type->ID.getNum())
  3365. return true;
  3366. return false;
  3367. case MISSION_PLAYER:
  3368. if (m13489val == h->getOwner().getNum())
  3369. return true;
  3370. return false;
  3371. default:
  3372. return false;
  3373. }
  3374. }
  3375. void CQuest::getVisitText (MetaString &iwText, std::vector<Component> &components, bool isCustom, bool firstVisit, const CGHeroInstance * h) const
  3376. {
  3377. std::string text;
  3378. bool failRequirements = (h ? !checkQuest(h) : true);
  3379. if (firstVisit)
  3380. {
  3381. isCustom = isCustomFirst;
  3382. iwText << (text = firstVisitText);
  3383. }
  3384. else if (failRequirements)
  3385. {
  3386. isCustom = isCustomNext;
  3387. iwText << (text = nextVisitText);
  3388. }
  3389. switch (missionType)
  3390. {
  3391. case MISSION_LEVEL:
  3392. components.push_back(Component (Component::EXPERIENCE, 0, m13489val, 0));
  3393. if (!isCustom)
  3394. iwText.addReplacement(m13489val);
  3395. break;
  3396. case MISSION_PRIMARY_STAT:
  3397. {
  3398. MetaString loot;
  3399. for (int i = 0; i < 4; ++i)
  3400. {
  3401. if (m2stats[i])
  3402. {
  3403. components.push_back(Component (Component::PRIM_SKILL, i, m2stats[i], 0));
  3404. loot << "%d %s";
  3405. loot.addReplacement(m2stats[i]);
  3406. loot.addReplacement(VLC->generaltexth->primarySkillNames[i]);
  3407. }
  3408. }
  3409. if (!isCustom)
  3410. iwText.addReplacement(loot.buildList());
  3411. }
  3412. break;
  3413. case MISSION_KILL_HERO:
  3414. components.push_back(Component(Component::HERO_PORTRAIT, heroPortrait, 0, 0));
  3415. if (!isCustom)
  3416. addReplacements(iwText, text);
  3417. break;
  3418. case MISSION_HERO:
  3419. //FIXME: portrait may not match hero, if custom portrait was set in map editor
  3420. components.push_back(Component (Component::HERO_PORTRAIT, VLC->heroh->heroes[m13489val]->imageIndex, 0, 0));
  3421. if (!isCustom)
  3422. iwText.addReplacement(VLC->heroh->heroes[m13489val]->name);
  3423. break;
  3424. case MISSION_KILL_CREATURE:
  3425. {
  3426. components.push_back(Component(stackToKill));
  3427. if (!isCustom)
  3428. {
  3429. addReplacements(iwText, text);
  3430. }
  3431. }
  3432. break;
  3433. case MISSION_ART:
  3434. {
  3435. MetaString loot;
  3436. for (auto & elem : m5arts)
  3437. {
  3438. components.push_back(Component (Component::ARTIFACT, elem, 0, 0));
  3439. loot << "%s";
  3440. loot.addReplacement(MetaString::ART_NAMES, elem);
  3441. }
  3442. if (!isCustom)
  3443. iwText.addReplacement(loot.buildList());
  3444. }
  3445. break;
  3446. case MISSION_ARMY:
  3447. {
  3448. MetaString loot;
  3449. for (auto & elem : m6creatures)
  3450. {
  3451. components.push_back(Component(elem));
  3452. loot << "%s";
  3453. loot.addReplacement(elem);
  3454. }
  3455. if (!isCustom)
  3456. iwText.addReplacement(loot.buildList());
  3457. }
  3458. break;
  3459. case MISSION_RESOURCES:
  3460. {
  3461. MetaString loot;
  3462. for (int i = 0; i < 7; ++i)
  3463. {
  3464. if (m7resources[i])
  3465. {
  3466. components.push_back(Component (Component::RESOURCE, i, m7resources[i], 0));
  3467. loot << "%d %s";
  3468. loot.addReplacement(m7resources[i]);
  3469. loot.addReplacement(MetaString::RES_NAMES, i);
  3470. }
  3471. }
  3472. if (!isCustom)
  3473. iwText.addReplacement(loot.buildList());
  3474. }
  3475. break;
  3476. case MISSION_PLAYER:
  3477. components.push_back(Component (Component::FLAG, m13489val, 0, 0));
  3478. if (!isCustom)
  3479. iwText.addReplacement(VLC->generaltexth->colors[m13489val]);
  3480. break;
  3481. }
  3482. }
  3483. void CQuest::getRolloverText (MetaString &ms, bool onHover) const
  3484. {
  3485. if (onHover)
  3486. ms << "\n\n";
  3487. ms << VLC->generaltexth->quests[missionType-1][onHover ? 3 : 4][textOption];
  3488. switch (missionType)
  3489. {
  3490. case MISSION_LEVEL:
  3491. ms.addReplacement(m13489val);
  3492. break;
  3493. case MISSION_PRIMARY_STAT:
  3494. {
  3495. MetaString loot;
  3496. for (int i = 0; i < 4; ++i)
  3497. {
  3498. if (m2stats[i])
  3499. {
  3500. loot << "%d %s";
  3501. loot.addReplacement(m2stats[i]);
  3502. loot.addReplacement(VLC->generaltexth->primarySkillNames[i]);
  3503. }
  3504. }
  3505. ms.addReplacement(loot.buildList());
  3506. }
  3507. break;
  3508. case MISSION_KILL_HERO:
  3509. ms.addReplacement(heroName);
  3510. break;
  3511. case MISSION_KILL_CREATURE:
  3512. ms.addReplacement(stackToKill);
  3513. break;
  3514. case MISSION_ART:
  3515. {
  3516. MetaString loot;
  3517. for (auto & elem : m5arts)
  3518. {
  3519. loot << "%s";
  3520. loot.addReplacement(MetaString::ART_NAMES, elem);
  3521. }
  3522. ms.addReplacement(loot.buildList());
  3523. }
  3524. break;
  3525. case MISSION_ARMY:
  3526. {
  3527. MetaString loot;
  3528. for (auto & elem : m6creatures)
  3529. {
  3530. loot << "%s";
  3531. loot.addReplacement(elem);
  3532. }
  3533. ms.addReplacement(loot.buildList());
  3534. }
  3535. break;
  3536. case MISSION_RESOURCES:
  3537. {
  3538. MetaString loot;
  3539. for (int i = 0; i < 7; ++i)
  3540. {
  3541. if (m7resources[i])
  3542. {
  3543. loot << "%d %s";
  3544. loot.addReplacement(m7resources[i]);
  3545. loot.addReplacement(MetaString::RES_NAMES, i);
  3546. }
  3547. }
  3548. ms.addReplacement(loot.buildList());
  3549. }
  3550. break;
  3551. case MISSION_HERO:
  3552. ms.addReplacement(VLC->heroh->heroes[m13489val]->name);
  3553. break;
  3554. case MISSION_PLAYER:
  3555. ms.addReplacement(VLC->generaltexth->colors[m13489val]);
  3556. break;
  3557. default:
  3558. break;
  3559. }
  3560. }
  3561. void CQuest::getCompletionText (MetaString &iwText, std::vector<Component> &components, bool isCustom, const CGHeroInstance * h) const
  3562. {
  3563. iwText << completedText;
  3564. switch (missionType)
  3565. {
  3566. case CQuest::MISSION_LEVEL:
  3567. if (!isCustomComplete)
  3568. iwText.addReplacement(m13489val);
  3569. break;
  3570. case CQuest::MISSION_PRIMARY_STAT:
  3571. if (vstd::contains (completedText,'%')) //there's one case when there's nothing to replace
  3572. {
  3573. MetaString loot;
  3574. for (int i = 0; i < 4; ++i)
  3575. {
  3576. if (m2stats[i])
  3577. {
  3578. loot << "%d %s";
  3579. loot.addReplacement(m2stats[i]);
  3580. loot.addReplacement(VLC->generaltexth->primarySkillNames[i]);
  3581. }
  3582. }
  3583. if (!isCustomComplete)
  3584. iwText.addReplacement(loot.buildList());
  3585. }
  3586. break;
  3587. case CQuest::MISSION_ART:
  3588. {
  3589. MetaString loot;
  3590. for (auto & elem : m5arts)
  3591. {
  3592. loot << "%s";
  3593. loot.addReplacement(MetaString::ART_NAMES, elem);
  3594. }
  3595. if (!isCustomComplete)
  3596. iwText.addReplacement(loot.buildList());
  3597. }
  3598. break;
  3599. case CQuest::MISSION_ARMY:
  3600. {
  3601. MetaString loot;
  3602. for (auto & elem : m6creatures)
  3603. {
  3604. loot << "%s";
  3605. loot.addReplacement(elem);
  3606. }
  3607. if (!isCustomComplete)
  3608. iwText.addReplacement(loot.buildList());
  3609. }
  3610. break;
  3611. case CQuest::MISSION_RESOURCES:
  3612. {
  3613. MetaString loot;
  3614. for (int i = 0; i < 7; ++i)
  3615. {
  3616. if (m7resources[i])
  3617. {
  3618. loot << "%d %s";
  3619. loot.addReplacement(m7resources[i]);
  3620. loot.addReplacement(MetaString::RES_NAMES, i);
  3621. }
  3622. }
  3623. if (!isCustomComplete)
  3624. iwText.addReplacement(loot.buildList());
  3625. }
  3626. break;
  3627. case MISSION_KILL_HERO:
  3628. case MISSION_KILL_CREATURE:
  3629. if (!isCustomComplete)
  3630. addReplacements(iwText, completedText);
  3631. break;
  3632. case MISSION_HERO:
  3633. if (!isCustomComplete)
  3634. iwText.addReplacement(VLC->heroh->heroes[m13489val]->name);
  3635. break;
  3636. case MISSION_PLAYER:
  3637. if (!isCustomComplete)
  3638. iwText.addReplacement(VLC->generaltexth->colors[m13489val]);
  3639. break;
  3640. }
  3641. }
  3642. void CGSeerHut::setObjToKill()
  3643. {
  3644. if (quest->missionType == CQuest::MISSION_KILL_CREATURE)
  3645. {
  3646. quest->stackToKill = getCreatureToKill(false)->getStack(SlotID(0)); //FIXME: stacks tend to disappear (desync?) on server :?
  3647. assert(quest->stackToKill.type);
  3648. quest->stackToKill.count = 0; //no count in info window
  3649. quest->stackDirection = checkDirection();
  3650. }
  3651. else if (quest->missionType == CQuest::MISSION_KILL_HERO)
  3652. {
  3653. quest->heroName = getHeroToKill(false)->name;
  3654. quest->heroPortrait = getHeroToKill(false)->portrait;
  3655. }
  3656. }
  3657. void CGSeerHut::init()
  3658. {
  3659. seerName = *RandomGeneratorUtil::nextItem(VLC->generaltexth->seerNames, cb->gameState()->getRandomGenerator());
  3660. quest->textOption = cb->gameState()->getRandomGenerator().nextInt(2);
  3661. }
  3662. void CGSeerHut::initObj()
  3663. {
  3664. init();
  3665. quest->progress = CQuest::NOT_ACTIVE;
  3666. if (quest->missionType)
  3667. {
  3668. if (!quest->isCustomFirst)
  3669. quest->firstVisitText = VLC->generaltexth->quests[quest->missionType-1][0][quest->textOption];
  3670. if (!quest->isCustomNext)
  3671. quest->nextVisitText = VLC->generaltexth->quests[quest->missionType-1][1][quest->textOption];
  3672. if (!quest->isCustomComplete)
  3673. quest->completedText = VLC->generaltexth->quests[quest->missionType-1][2][quest->textOption];
  3674. }
  3675. else
  3676. {
  3677. quest->progress = CQuest::COMPLETE;
  3678. quest->firstVisitText = VLC->generaltexth->seerEmpty[quest->textOption];
  3679. }
  3680. }
  3681. void CGSeerHut::getRolloverText (MetaString &text, bool onHover) const
  3682. {
  3683. quest->getRolloverText (text, onHover);//TODO: simplify?
  3684. if (!onHover)
  3685. text.addReplacement(seerName);
  3686. }
  3687. const std::string & CGSeerHut::getHoverText() const
  3688. {
  3689. switch (ID)
  3690. {
  3691. case Obj::SEER_HUT:
  3692. if (quest->progress != CQuest::NOT_ACTIVE)
  3693. {
  3694. hoverName = VLC->generaltexth->allTexts[347];
  3695. boost::algorithm::replace_first(hoverName,"%s", seerName);
  3696. }
  3697. else //just seer hut
  3698. hoverName = VLC->generaltexth->names[ID];
  3699. break;
  3700. case Obj::QUEST_GUARD:
  3701. hoverName = VLC->generaltexth->names[ID];
  3702. break;
  3703. default:
  3704. logGlobal->debugStream() << "unrecognized quest object";
  3705. }
  3706. if (quest->progress & quest->missionType) //rollover when the quest is active
  3707. {
  3708. MetaString ms;
  3709. getRolloverText (ms, true);
  3710. hoverName += ms.toString();
  3711. }
  3712. return hoverName;
  3713. }
  3714. void CQuest::addReplacements(MetaString &out, const std::string &base) const
  3715. {
  3716. switch(missionType)
  3717. {
  3718. case MISSION_KILL_CREATURE:
  3719. out.addReplacement(stackToKill);
  3720. if (std::count(base.begin(), base.end(), '%') == 2) //say where is placed monster
  3721. {
  3722. out.addReplacement(VLC->generaltexth->arraytxt[147+stackDirection]);
  3723. }
  3724. break;
  3725. case MISSION_KILL_HERO:
  3726. out.addReplacement(heroName);
  3727. break;
  3728. }
  3729. }
  3730. bool IQuestObject::checkQuest(const CGHeroInstance* h) const
  3731. {
  3732. return quest->checkQuest(h);
  3733. }
  3734. void IQuestObject::getVisitText (MetaString &text, std::vector<Component> &components, bool isCustom, bool FirstVisit, const CGHeroInstance * h) const
  3735. {
  3736. quest->getVisitText (text,components, isCustom, FirstVisit, h);
  3737. }
  3738. void CGSeerHut::getCompletionText(MetaString &text, std::vector<Component> &components, bool isCustom, const CGHeroInstance * h) const
  3739. {
  3740. quest->getCompletionText (text, components, isCustom, h);
  3741. switch (rewardType)
  3742. {
  3743. case EXPERIENCE: components.push_back(Component (Component::EXPERIENCE, 0, h->calculateXp(rVal), 0));
  3744. break;
  3745. case MANA_POINTS: components.push_back(Component (Component::PRIM_SKILL, 5, rVal, 0));
  3746. break;
  3747. case MORALE_BONUS: components.push_back(Component (Component::MORALE, 0, rVal, 0));
  3748. break;
  3749. case LUCK_BONUS: components.push_back(Component (Component::LUCK, 0, rVal, 0));
  3750. break;
  3751. case RESOURCES: components.push_back(Component (Component::RESOURCE, rID, rVal, 0));
  3752. break;
  3753. case PRIMARY_SKILL: components.push_back(Component (Component::PRIM_SKILL, rID, rVal, 0));
  3754. break;
  3755. case SECONDARY_SKILL: components.push_back(Component (Component::SEC_SKILL, rID, rVal, 0));
  3756. break;
  3757. case ARTIFACT: components.push_back(Component (Component::ARTIFACT, rID, 0, 0));
  3758. break;
  3759. case SPELL: components.push_back(Component (Component::SPELL, rID, 0, 0));
  3760. break;
  3761. case CREATURE: components.push_back(Component (Component::CREATURE, rID, rVal, 0));
  3762. break;
  3763. }
  3764. }
  3765. void CGSeerHut::setPropertyDer (ui8 what, ui32 val)
  3766. {
  3767. switch (what)
  3768. {
  3769. case 10:
  3770. quest->progress = static_cast<CQuest::Eprogress>(val);
  3771. break;
  3772. }
  3773. }
  3774. void CGSeerHut::newTurn() const
  3775. {
  3776. if (quest->lastDay >= 0 && quest->lastDay < cb->getDate()-1) //time is up
  3777. {
  3778. cb->setObjProperty (id, 10, CQuest::COMPLETE);
  3779. }
  3780. }
  3781. void CGSeerHut::onHeroVisit( const CGHeroInstance * h ) const
  3782. {
  3783. InfoWindow iw;
  3784. iw.player = h->getOwner();
  3785. if (quest->progress < CQuest::COMPLETE)
  3786. {
  3787. bool firstVisit = !quest->progress;
  3788. bool failRequirements = !checkQuest(h);
  3789. bool isCustom=false;
  3790. if (firstVisit)
  3791. {
  3792. isCustom = quest->isCustomFirst;
  3793. cb->setObjProperty (id, 10, CQuest::IN_PROGRESS);
  3794. AddQuest aq;
  3795. aq.quest = QuestInfo (quest, this, visitablePos());
  3796. aq.player = h->tempOwner;
  3797. cb->sendAndApply (&aq); //TODO: merge with setObjProperty?
  3798. }
  3799. else if (failRequirements)
  3800. {
  3801. isCustom = quest->isCustomNext;
  3802. }
  3803. if (firstVisit || failRequirements)
  3804. {
  3805. getVisitText (iw.text, iw.components, isCustom, firstVisit, h);
  3806. cb->showInfoDialog(&iw);
  3807. }
  3808. if (!failRequirements) // propose completion, also on first visit
  3809. {
  3810. BlockingDialog bd (true, false);
  3811. bd.player = h->getOwner();
  3812. bd.soundID = soundBase::QUEST;
  3813. getCompletionText (bd.text, bd.components, isCustom, h);
  3814. cb->showBlockingDialog (&bd);
  3815. return;
  3816. }
  3817. }
  3818. else
  3819. {
  3820. iw.text << VLC->generaltexth->seerEmpty[quest->textOption];
  3821. if (ID == Obj::SEER_HUT)
  3822. iw.text.addReplacement(seerName);
  3823. cb->showInfoDialog(&iw);
  3824. }
  3825. }
  3826. int CGSeerHut::checkDirection() const
  3827. {
  3828. int3 cord = getCreatureToKill()->pos;
  3829. if ((double)cord.x/(double)cb->getMapSize().x < 0.34) //north
  3830. {
  3831. if ((double)cord.y/(double)cb->getMapSize().y < 0.34) //northwest
  3832. return 8;
  3833. else if ((double)cord.y/(double)cb->getMapSize().y < 0.67) //north
  3834. return 1;
  3835. else //northeast
  3836. return 2;
  3837. }
  3838. else if ((double)cord.x/(double)cb->getMapSize().x < 0.67) //horizontal
  3839. {
  3840. if ((double)cord.y/(double)cb->getMapSize().y < 0.34) //west
  3841. return 7;
  3842. else if ((double)cord.y/(double)cb->getMapSize().y < 0.67) //central
  3843. return 9;
  3844. else //east
  3845. return 3;
  3846. }
  3847. else //south
  3848. {
  3849. if ((double)cord.y/(double)cb->getMapSize().y < 0.34) //southwest
  3850. return 6;
  3851. else if ((double)cord.y/(double)cb->getMapSize().y < 0.67) //south
  3852. return 5;
  3853. else //southeast
  3854. return 4;
  3855. }
  3856. }
  3857. void CGSeerHut::finishQuest(const CGHeroInstance * h, ui32 accept) const
  3858. {
  3859. if (accept)
  3860. {
  3861. switch (quest->missionType)
  3862. {
  3863. case CQuest::MISSION_ART:
  3864. for (auto & elem : quest->m5arts)
  3865. {
  3866. cb->removeArtifact(ArtifactLocation(h, h->getArtPos(elem, false)));
  3867. }
  3868. break;
  3869. case CQuest::MISSION_ARMY:
  3870. cb->takeCreatures(h->id, quest->m6creatures);
  3871. break;
  3872. case CQuest::MISSION_RESOURCES:
  3873. for (int i = 0; i < 7; ++i)
  3874. {
  3875. cb->giveResource(h->getOwner(), static_cast<Res::ERes>(i), -quest->m7resources[i]);
  3876. }
  3877. break;
  3878. default:
  3879. break;
  3880. }
  3881. cb->setObjProperty (id, 10, CQuest::COMPLETE); //mission complete
  3882. completeQuest(h); //make sure to remove QuestGuard at the very end
  3883. }
  3884. }
  3885. void CGSeerHut::completeQuest (const CGHeroInstance * h) const //reward
  3886. {
  3887. switch (rewardType)
  3888. {
  3889. case EXPERIENCE:
  3890. {
  3891. TExpType expVal = h->calculateXp(rVal);
  3892. cb->changePrimSkill(h, PrimarySkill::EXPERIENCE, expVal, false);
  3893. break;
  3894. }
  3895. case MANA_POINTS:
  3896. {
  3897. cb->setManaPoints(h->id, h->mana+rVal);
  3898. break;
  3899. }
  3900. case MORALE_BONUS: case LUCK_BONUS:
  3901. {
  3902. Bonus hb(Bonus::ONE_WEEK, (rewardType == 3 ? Bonus::MORALE : Bonus::LUCK),
  3903. Bonus::OBJECT, rVal, h->id.getNum(), "", -1);
  3904. GiveBonus gb;
  3905. gb.id = h->id.getNum();
  3906. gb.bonus = hb;
  3907. cb->giveHeroBonus(&gb);
  3908. }
  3909. break;
  3910. case RESOURCES:
  3911. cb->giveResource(h->getOwner(), static_cast<Res::ERes>(rID), rVal);
  3912. break;
  3913. case PRIMARY_SKILL:
  3914. cb->changePrimSkill(h, static_cast<PrimarySkill::PrimarySkill>(rID), rVal, false);
  3915. break;
  3916. case SECONDARY_SKILL:
  3917. cb->changeSecSkill(h, SecondarySkill(rID), rVal, false);
  3918. break;
  3919. case ARTIFACT:
  3920. cb->giveHeroNewArtifact(h, VLC->arth->artifacts[rID],ArtifactPosition::FIRST_AVAILABLE);
  3921. break;
  3922. case SPELL:
  3923. {
  3924. std::set<SpellID> spell;
  3925. spell.insert (SpellID(rID));
  3926. cb->changeSpells(h, true, spell);
  3927. }
  3928. break;
  3929. case CREATURE:
  3930. {
  3931. CCreatureSet creatures;
  3932. creatures.setCreature(SlotID(0), CreatureID(rID), rVal);
  3933. cb->giveCreatures(this, h, creatures, false);
  3934. }
  3935. break;
  3936. default:
  3937. break;
  3938. }
  3939. }
  3940. const CGHeroInstance * CGSeerHut::getHeroToKill(bool allowNull) const
  3941. {
  3942. const CGObjectInstance *o = cb->getObjByQuestIdentifier(quest->m13489val);
  3943. if(allowNull && !o)
  3944. return nullptr;
  3945. assert(o && (o->ID == Obj::HERO || o->ID == Obj::PRISON));
  3946. return static_cast<const CGHeroInstance*>(o);
  3947. }
  3948. const CGCreature * CGSeerHut::getCreatureToKill(bool allowNull) const
  3949. {
  3950. const CGObjectInstance *o = cb->getObjByQuestIdentifier(quest->m13489val);
  3951. if(allowNull && !o)
  3952. return nullptr;
  3953. assert(o && o->ID == Obj::MONSTER);
  3954. return static_cast<const CGCreature*>(o);
  3955. }
  3956. void CGSeerHut::blockingDialogAnswered(const CGHeroInstance *hero, ui32 answer) const
  3957. {
  3958. finishQuest(hero, answer);
  3959. }
  3960. void CGQuestGuard::init()
  3961. {
  3962. blockVisit = true;
  3963. quest->textOption = cb->gameState()->getRandomGenerator().nextInt(3, 5);
  3964. }
  3965. void CGQuestGuard::completeQuest(const CGHeroInstance *h) const
  3966. {
  3967. cb->removeObject(this);
  3968. }
  3969. void CGWitchHut::initObj()
  3970. {
  3971. ability = *RandomGeneratorUtil::nextItem(allowedAbilities, cb->gameState()->getRandomGenerator());
  3972. }
  3973. void CGWitchHut::onHeroVisit( const CGHeroInstance * h ) const
  3974. {
  3975. InfoWindow iw;
  3976. iw.soundID = soundBase::gazebo;
  3977. iw.player = h->getOwner();
  3978. if(!wasVisited(h->tempOwner))
  3979. cb->setObjProperty(id, 10, h->tempOwner.getNum());
  3980. ui32 txt_id;
  3981. if(h->getSecSkillLevel(SecondarySkill(ability))) //you already know this skill
  3982. {
  3983. txt_id =172;
  3984. }
  3985. else if(!h->canLearnSkill()) //already all skills slots used
  3986. {
  3987. txt_id = 173;
  3988. }
  3989. else //give sec skill
  3990. {
  3991. iw.components.push_back(Component(Component::SEC_SKILL, ability, 1, 0));
  3992. txt_id = 171;
  3993. cb->changeSecSkill(h, SecondarySkill(ability), 1, true);
  3994. }
  3995. iw.text.addTxt(MetaString::ADVOB_TXT,txt_id);
  3996. iw.text.addReplacement(MetaString::SEC_SKILL_NAME, ability);
  3997. cb->showInfoDialog(&iw);
  3998. }
  3999. const std::string & CGWitchHut::getHoverText() const
  4000. {
  4001. hoverName = VLC->generaltexth->names[ID];
  4002. if(wasVisited(cb->getLocalPlayer()))
  4003. {
  4004. hoverName += "\n" + VLC->generaltexth->allTexts[356]; // + (learn %s)
  4005. boost::algorithm::replace_first(hoverName,"%s",VLC->generaltexth->skillName[ability]);
  4006. const CGHeroInstance *h = cb->getSelectedHero(cb->getCurrentPlayer());
  4007. if(h && h->getSecSkillLevel(SecondarySkill(ability))) //hero knows that ability
  4008. hoverName += "\n\n" + VLC->generaltexth->allTexts[357]; // (Already learned)
  4009. }
  4010. return hoverName;
  4011. }
  4012. void CGMagicWell::onHeroVisit( const CGHeroInstance * h ) const
  4013. {
  4014. int message;
  4015. if(h->hasBonusFrom(Bonus::OBJECT,ID)) //has already visited Well today
  4016. {
  4017. message = 78;//"A second drink at the well in one day will not help you."
  4018. }
  4019. else if(h->mana < h->manaLimit())
  4020. {
  4021. giveDummyBonus(h->id);
  4022. cb->setManaPoints(h->id,h->manaLimit());
  4023. message = 77;
  4024. }
  4025. else
  4026. {
  4027. message = 79;
  4028. }
  4029. showInfoDialog(h,message,soundBase::faerie);
  4030. }
  4031. const std::string & CGMagicWell::getHoverText() const
  4032. {
  4033. getNameVis(hoverName);
  4034. return hoverName;
  4035. }
  4036. void CGPandoraBox::initObj()
  4037. {
  4038. blockVisit = (ID==Obj::PANDORAS_BOX); //block only if it's really pandora's box (events also derive from that class)
  4039. hasGuardians = stacks.size();
  4040. }
  4041. void CGPandoraBox::onHeroVisit(const CGHeroInstance * h) const
  4042. {
  4043. BlockingDialog bd (true, false);
  4044. bd.player = h->getOwner();
  4045. bd.soundID = soundBase::QUEST;
  4046. bd.text.addTxt (MetaString::ADVOB_TXT, 14);
  4047. cb->showBlockingDialog (&bd);
  4048. }
  4049. void CGPandoraBox::giveContentsUpToExp(const CGHeroInstance *h) const
  4050. {
  4051. cb->removeAfterVisit(this);
  4052. InfoWindow iw;
  4053. iw.player = h->getOwner();
  4054. bool changesPrimSkill = false;
  4055. for (auto & elem : primskills)
  4056. {
  4057. if(elem)
  4058. {
  4059. changesPrimSkill = true;
  4060. break;
  4061. }
  4062. }
  4063. if(gainedExp || changesPrimSkill || abilities.size())
  4064. {
  4065. TExpType expVal = h->calculateXp(gainedExp);
  4066. //getText(iw,afterBattle,175,h); //wtf?
  4067. iw.text.addTxt(MetaString::ADVOB_TXT, 175); //%s learns something
  4068. iw.text.addReplacement(h->name);
  4069. if(expVal)
  4070. iw.components.push_back(Component(Component::EXPERIENCE,0,expVal,0));
  4071. for(int i=0; i<primskills.size(); i++)
  4072. if(primskills[i])
  4073. iw.components.push_back(Component(Component::PRIM_SKILL,i,primskills[i],0));
  4074. for(int i=0; i<abilities.size(); i++)
  4075. iw.components.push_back(Component(Component::SEC_SKILL,abilities[i],abilityLevels[i],0));
  4076. cb->showInfoDialog(&iw);
  4077. //give sec skills
  4078. for(int i=0; i<abilities.size(); i++)
  4079. {
  4080. int curLev = h->getSecSkillLevel(abilities[i]);
  4081. if( (curLev && curLev < abilityLevels[i]) || (h->canLearnSkill() ))
  4082. {
  4083. cb->changeSecSkill(h,abilities[i],abilityLevels[i],true);
  4084. }
  4085. }
  4086. //give prim skills
  4087. for(int i=0; i<primskills.size(); i++)
  4088. if(primskills[i])
  4089. cb->changePrimSkill(h,static_cast<PrimarySkill::PrimarySkill>(i),primskills[i],false);
  4090. assert(!cb->isVisitCoveredByAnotherQuery(this, h));
  4091. //give exp
  4092. if(expVal)
  4093. cb->changePrimSkill(h, PrimarySkill::EXPERIENCE, expVal, false);
  4094. }
  4095. if(!cb->isVisitCoveredByAnotherQuery(this, h))
  4096. giveContentsAfterExp(h);
  4097. //Otherwise continuation occurs via post-level-up callback.
  4098. }
  4099. void CGPandoraBox::giveContentsAfterExp(const CGHeroInstance *h) const
  4100. {
  4101. bool hadGuardians = hasGuardians; //copy, because flag will be emptied after issuing first post-battle message
  4102. std::string msg = message; //in case box is removed in the meantime
  4103. InfoWindow iw;
  4104. iw.player = h->getOwner();
  4105. if(spells.size())
  4106. {
  4107. std::set<SpellID> spellsToGive;
  4108. iw.components.clear();
  4109. if (spells.size() > 1)
  4110. {
  4111. iw.text.addTxt(MetaString::ADVOB_TXT, 188); //%s learns spells
  4112. }
  4113. else
  4114. {
  4115. iw.text.addTxt(MetaString::ADVOB_TXT, 184); //%s learns a spell
  4116. }
  4117. iw.text.addReplacement(h->name);
  4118. std::vector<ConstTransitivePtr<CSpell> > * sp = &VLC->spellh->objects;
  4119. for(auto i=spells.cbegin(); i != spells.cend(); i++)
  4120. {
  4121. if ((*sp)[*i]->level <= h->getSecSkillLevel(SecondarySkill::WISDOM) + 2) //enough wisdom
  4122. {
  4123. iw.components.push_back(Component(Component::SPELL,*i,0,0));
  4124. spellsToGive.insert(*i);
  4125. }
  4126. }
  4127. if(!spellsToGive.empty())
  4128. {
  4129. cb->changeSpells(h,true,spellsToGive);
  4130. cb->showInfoDialog(&iw);
  4131. }
  4132. }
  4133. if(manaDiff)
  4134. {
  4135. getText(iw,hadGuardians,manaDiff,176,177,h);
  4136. iw.components.push_back(Component(Component::PRIM_SKILL,5,manaDiff,0));
  4137. cb->showInfoDialog(&iw);
  4138. cb->setManaPoints(h->id, h->mana + manaDiff);
  4139. }
  4140. if(moraleDiff)
  4141. {
  4142. getText(iw,hadGuardians,moraleDiff,178,179,h);
  4143. iw.components.push_back(Component(Component::MORALE,0,moraleDiff,0));
  4144. cb->showInfoDialog(&iw);
  4145. GiveBonus gb;
  4146. gb.bonus = Bonus(Bonus::ONE_BATTLE,Bonus::MORALE,Bonus::OBJECT,moraleDiff,id.getNum(),"");
  4147. gb.id = h->id.getNum();
  4148. cb->giveHeroBonus(&gb);
  4149. }
  4150. if(luckDiff)
  4151. {
  4152. getText(iw,hadGuardians,luckDiff,180,181,h);
  4153. iw.components.push_back(Component(Component::LUCK,0,luckDiff,0));
  4154. cb->showInfoDialog(&iw);
  4155. GiveBonus gb;
  4156. gb.bonus = Bonus(Bonus::ONE_BATTLE,Bonus::LUCK,Bonus::OBJECT,luckDiff,id.getNum(),"");
  4157. gb.id = h->id.getNum();
  4158. cb->giveHeroBonus(&gb);
  4159. }
  4160. iw.components.clear();
  4161. iw.text.clear();
  4162. for(int i=0; i<resources.size(); i++)
  4163. {
  4164. if(resources[i] < 0)
  4165. iw.components.push_back(Component(Component::RESOURCE,i,resources[i],0));
  4166. }
  4167. if(iw.components.size())
  4168. {
  4169. getText(iw,hadGuardians,182,h);
  4170. cb->showInfoDialog(&iw);
  4171. }
  4172. iw.components.clear();
  4173. iw.text.clear();
  4174. for(int i=0; i<resources.size(); i++)
  4175. {
  4176. if(resources[i] > 0)
  4177. iw.components.push_back(Component(Component::RESOURCE,i,resources[i],0));
  4178. }
  4179. if(iw.components.size())
  4180. {
  4181. getText(iw,hadGuardians,183,h);
  4182. cb->showInfoDialog(&iw);
  4183. }
  4184. iw.components.clear();
  4185. // getText(iw,afterBattle,183,h);
  4186. iw.text.addTxt(MetaString::ADVOB_TXT, 183); //% has found treasure
  4187. iw.text.addReplacement(h->name);
  4188. for(auto & elem : artifacts)
  4189. {
  4190. iw.components.push_back(Component(Component::ARTIFACT,elem,0,0));
  4191. if(iw.components.size() >= 14)
  4192. {
  4193. cb->showInfoDialog(&iw);
  4194. iw.components.clear();
  4195. iw.text.addTxt(MetaString::ADVOB_TXT, 183); //% has found treasure - once more?
  4196. iw.text.addReplacement(h->name);
  4197. }
  4198. }
  4199. if(iw.components.size())
  4200. {
  4201. cb->showInfoDialog(&iw);
  4202. }
  4203. for(int i=0; i<resources.size(); i++)
  4204. if(resources[i])
  4205. cb->giveResource(h->getOwner(),static_cast<Res::ERes>(i),resources[i]);
  4206. for(auto & elem : artifacts)
  4207. cb->giveHeroNewArtifact(h, VLC->arth->artifacts[elem],ArtifactPosition::FIRST_AVAILABLE);
  4208. iw.components.clear();
  4209. iw.text.clear();
  4210. if (creatures.Slots().size())
  4211. { //this part is taken straight from creature bank
  4212. MetaString loot;
  4213. for(auto & elem : creatures.Slots())
  4214. { //build list of joined creatures
  4215. iw.components.push_back(Component(*elem.second));
  4216. loot << "%s";
  4217. loot.addReplacement(*elem.second);
  4218. }
  4219. if (creatures.Slots().size() == 1 && creatures.Slots().begin()->second->count == 1)
  4220. iw.text.addTxt(MetaString::ADVOB_TXT, 185);
  4221. else
  4222. iw.text.addTxt(MetaString::ADVOB_TXT, 186);
  4223. iw.text.addReplacement(loot.buildList());
  4224. iw.text.addReplacement(h->name);
  4225. cb->showInfoDialog(&iw);
  4226. cb->giveCreatures(this, h, creatures, true);
  4227. }
  4228. if(!hasGuardians && msg.size())
  4229. {
  4230. iw.text << msg;
  4231. cb->showInfoDialog(&iw);
  4232. }
  4233. }
  4234. void CGPandoraBox::getText( InfoWindow &iw, bool &afterBattle, int text, const CGHeroInstance * h ) const
  4235. {
  4236. if(afterBattle || !message.size())
  4237. {
  4238. iw.text.addTxt(MetaString::ADVOB_TXT,text);//%s has lost treasure.
  4239. iw.text.addReplacement(h->name);
  4240. }
  4241. else
  4242. {
  4243. iw.text << message;
  4244. afterBattle = true;
  4245. }
  4246. }
  4247. void CGPandoraBox::getText( InfoWindow &iw, bool &afterBattle, int val, int negative, int positive, const CGHeroInstance * h ) const
  4248. {
  4249. iw.components.clear();
  4250. iw.text.clear();
  4251. if(afterBattle || !message.size())
  4252. {
  4253. iw.text.addTxt(MetaString::ADVOB_TXT,val < 0 ? negative : positive); //%s's luck takes a turn for the worse / %s's luck increases
  4254. iw.text.addReplacement(h->name);
  4255. }
  4256. else
  4257. {
  4258. iw.text << message;
  4259. afterBattle = true;
  4260. }
  4261. }
  4262. void CGPandoraBox::battleFinished(const CGHeroInstance *hero, const BattleResult &result) const
  4263. {
  4264. if(result.winner)
  4265. return;
  4266. giveContentsUpToExp(hero);
  4267. }
  4268. void CGPandoraBox::blockingDialogAnswered(const CGHeroInstance *hero, ui32 answer) const
  4269. {
  4270. if (answer)
  4271. {
  4272. if (stacksCount() > 0) //if pandora's box is protected by army
  4273. {
  4274. showInfoDialog(hero,16,0);
  4275. cb->startBattleI(hero, this); //grants things after battle
  4276. }
  4277. else if (message.size() == 0 && resources.size() == 0
  4278. && primskills.size() == 0 && abilities.size() == 0
  4279. && abilityLevels.size() == 0 && artifacts.size() == 0
  4280. && spells.size() == 0 && creatures.Slots().size() > 0
  4281. && gainedExp == 0 && manaDiff == 0 && moraleDiff == 0 && luckDiff == 0) //if it gives nothing without battle
  4282. {
  4283. showInfoDialog(hero,15,0);
  4284. cb->removeObject(this);
  4285. }
  4286. else //if it gives something without battle
  4287. {
  4288. giveContentsUpToExp(hero);
  4289. }
  4290. }
  4291. }
  4292. void CGPandoraBox::heroLevelUpDone(const CGHeroInstance *hero) const
  4293. {
  4294. giveContentsAfterExp(hero);
  4295. }
  4296. void CGEvent::onHeroVisit( const CGHeroInstance * h ) const
  4297. {
  4298. if(!(availableFor & (1 << h->tempOwner.getNum())))
  4299. return;
  4300. if(cb->getPlayerSettings(h->tempOwner)->playerID)
  4301. {
  4302. if(humanActivate)
  4303. activated(h);
  4304. }
  4305. else if(computerActivate)
  4306. activated(h);
  4307. }
  4308. void CGEvent::activated( const CGHeroInstance * h ) const
  4309. {
  4310. if(stacksCount() > 0)
  4311. {
  4312. InfoWindow iw;
  4313. iw.player = h->tempOwner;
  4314. if(message.size())
  4315. iw.text << message;
  4316. else
  4317. iw.text.addTxt(MetaString::ADVOB_TXT, 16);
  4318. cb->showInfoDialog(&iw);
  4319. cb->startBattleI(h, this);
  4320. }
  4321. else
  4322. {
  4323. giveContentsUpToExp(h);
  4324. }
  4325. }
  4326. void CGObservatory::onHeroVisit( const CGHeroInstance * h ) const
  4327. {
  4328. InfoWindow iw;
  4329. iw.player = h->tempOwner;
  4330. switch (ID)
  4331. {
  4332. case Obj::REDWOOD_OBSERVATORY:
  4333. case Obj::PILLAR_OF_FIRE:
  4334. {
  4335. iw.soundID = soundBase::LIGHTHOUSE;
  4336. iw.text.addTxt(MetaString::ADVOB_TXT,98 + (ID==Obj::PILLAR_OF_FIRE));
  4337. FoWChange fw;
  4338. fw.player = h->tempOwner;
  4339. fw.mode = 1;
  4340. cb->getTilesInRange (fw.tiles, pos, 20, h->tempOwner, 1);
  4341. cb->sendAndApply (&fw);
  4342. break;
  4343. }
  4344. case Obj::COVER_OF_DARKNESS:
  4345. {
  4346. iw.text.addTxt (MetaString::ADVOB_TXT, 31);
  4347. hideTiles(h->tempOwner, 20);
  4348. break;
  4349. }
  4350. }
  4351. cb->showInfoDialog(&iw);
  4352. }
  4353. void CGShrine::onHeroVisit( const CGHeroInstance * h ) const
  4354. {
  4355. if(spell == SpellID::NONE)
  4356. {
  4357. logGlobal->errorStream() << "Not initialized shrine visited!";
  4358. return;
  4359. }
  4360. if(!wasVisited(h->tempOwner))
  4361. cb->setObjProperty(id, 10, h->tempOwner.getNum());
  4362. InfoWindow iw;
  4363. iw.soundID = soundBase::temple;
  4364. iw.player = h->getOwner();
  4365. iw.text.addTxt(MetaString::ADVOB_TXT,127 + ID - 88);
  4366. iw.text.addTxt(MetaString::SPELL_NAME,spell);
  4367. iw.text << ".";
  4368. if(!h->getArt(ArtifactPosition::SPELLBOOK))
  4369. {
  4370. iw.text.addTxt(MetaString::ADVOB_TXT,131);
  4371. }
  4372. else if(ID == Obj::SHRINE_OF_MAGIC_THOUGHT && !h->getSecSkillLevel(SecondarySkill::WISDOM)) //it's third level spell and hero doesn't have wisdom
  4373. {
  4374. iw.text.addTxt(MetaString::ADVOB_TXT,130);
  4375. }
  4376. else if(vstd::contains(h->spells,spell))//hero already knows the spell
  4377. {
  4378. iw.text.addTxt(MetaString::ADVOB_TXT,174);
  4379. }
  4380. else //give spell
  4381. {
  4382. std::set<SpellID> spells;
  4383. spells.insert(spell);
  4384. cb->changeSpells(h, true, spells);
  4385. iw.components.push_back(Component(Component::SPELL,spell,0,0));
  4386. }
  4387. cb->showInfoDialog(&iw);
  4388. }
  4389. void CGShrine::initObj()
  4390. {
  4391. if(spell == SpellID::NONE) //spell not set
  4392. {
  4393. int level = ID-87;
  4394. std::vector<SpellID> possibilities;
  4395. cb->getAllowedSpells (possibilities, level);
  4396. if(possibilities.empty())
  4397. {
  4398. logGlobal->errorStream() << "Error: cannot init shrine, no allowed spells!";
  4399. return;
  4400. }
  4401. spell = *RandomGeneratorUtil::nextItem(possibilities, cb->gameState()->getRandomGenerator());
  4402. }
  4403. }
  4404. const std::string & CGShrine::getHoverText() const
  4405. {
  4406. hoverName = VLC->generaltexth->names[ID];
  4407. if(wasVisited(cb->getCurrentPlayer())) //TODO: use local player, not current
  4408. {
  4409. hoverName += "\n" + VLC->generaltexth->allTexts[355]; // + (learn %s)
  4410. boost::algorithm::replace_first(hoverName,"%s", spell.toSpell()->name);
  4411. const CGHeroInstance *h = cb->getSelectedHero(cb->getCurrentPlayer());
  4412. if(h && vstd::contains(h->spells,spell)) //hero knows that ability
  4413. hoverName += "\n\n" + VLC->generaltexth->allTexts[354]; // (Already learned)
  4414. }
  4415. return hoverName;
  4416. }
  4417. void CGSignBottle::initObj()
  4418. {
  4419. //if no text is set than we pick random from the predefined ones
  4420. if(message.empty())
  4421. {
  4422. message = *RandomGeneratorUtil::nextItem(VLC->generaltexth->randsign, cb->gameState()->getRandomGenerator());
  4423. }
  4424. if(ID == Obj::OCEAN_BOTTLE)
  4425. {
  4426. blockVisit = true;
  4427. }
  4428. }
  4429. void CGSignBottle::onHeroVisit( const CGHeroInstance * h ) const
  4430. {
  4431. InfoWindow iw;
  4432. iw.soundID = soundBase::STORE;
  4433. iw.player = h->getOwner();
  4434. iw.text << message;
  4435. cb->showInfoDialog(&iw);
  4436. if(ID == Obj::OCEAN_BOTTLE)
  4437. cb->removeObject(this);
  4438. }
  4439. //TODO: remove
  4440. //void CGScholar::giveAnyBonus( const CGHeroInstance * h ) const
  4441. //{
  4442. //
  4443. //}
  4444. void CGScholar::onHeroVisit( const CGHeroInstance * h ) const
  4445. {
  4446. EBonusType type = bonusType;
  4447. int bid = bonusID;
  4448. //check if the bonus if applicable, if not - give primary skill (always possible)
  4449. int ssl = h->getSecSkillLevel(SecondarySkill(bid)); //current sec skill level, used if bonusType == 1
  4450. if((type == SECONDARY_SKILL
  4451. && ((ssl == 3) || (!ssl && !h->canLearnSkill()))) ////hero already has expert level in the skill or (don't know skill and doesn't have free slot)
  4452. || (type == SPELL && (!h->getArt(ArtifactPosition::SPELLBOOK) || vstd::contains(h->spells, (ui32) bid)
  4453. || ( SpellID(bid).toSpell()->level > h->getSecSkillLevel(SecondarySkill::WISDOM) + 2)
  4454. ))) //hero doesn't have a spellbook or already knows the spell or doesn't have Wisdom
  4455. {
  4456. type = PRIM_SKILL;
  4457. bid = cb->gameState()->getRandomGenerator().nextInt(GameConstants::PRIMARY_SKILLS - 1);
  4458. }
  4459. InfoWindow iw;
  4460. iw.soundID = soundBase::gazebo;
  4461. iw.player = h->getOwner();
  4462. iw.text.addTxt(MetaString::ADVOB_TXT,115);
  4463. switch (type)
  4464. {
  4465. case PRIM_SKILL:
  4466. cb->changePrimSkill(h,static_cast<PrimarySkill::PrimarySkill>(bid),+1);
  4467. iw.components.push_back(Component(Component::PRIM_SKILL,bid,+1,0));
  4468. break;
  4469. case SECONDARY_SKILL:
  4470. cb->changeSecSkill(h,SecondarySkill(bid),+1);
  4471. iw.components.push_back(Component(Component::SEC_SKILL,bid,ssl+1,0));
  4472. break;
  4473. case SPELL:
  4474. {
  4475. std::set<SpellID> hlp;
  4476. hlp.insert(SpellID(bid));
  4477. cb->changeSpells(h,true,hlp);
  4478. iw.components.push_back(Component(Component::SPELL,bid,0,0));
  4479. }
  4480. break;
  4481. default:
  4482. logGlobal->errorStream() << "Error: wrong bonus type (" << (int)type << ") for Scholar!\n";
  4483. return;
  4484. }
  4485. cb->showInfoDialog(&iw);
  4486. cb->removeObject(this);
  4487. }
  4488. void CGScholar::initObj()
  4489. {
  4490. blockVisit = true;
  4491. if(bonusType == RANDOM)
  4492. {
  4493. bonusType = static_cast<EBonusType>(cb->gameState()->getRandomGenerator().nextInt(2));
  4494. switch(bonusType)
  4495. {
  4496. case PRIM_SKILL:
  4497. bonusID = cb->gameState()->getRandomGenerator().nextInt(GameConstants::PRIMARY_SKILLS -1);
  4498. break;
  4499. case SECONDARY_SKILL:
  4500. bonusID = cb->gameState()->getRandomGenerator().nextInt(GameConstants::SKILL_QUANTITY -1);
  4501. break;
  4502. case SPELL:
  4503. std::vector<SpellID> possibilities;
  4504. for (int i = 1; i < 6; ++i)
  4505. cb->getAllowedSpells (possibilities, i);
  4506. bonusID = *RandomGeneratorUtil::nextItem(possibilities, cb->gameState()->getRandomGenerator());
  4507. break;
  4508. }
  4509. }
  4510. }
  4511. void CGGarrison::onHeroVisit (const CGHeroInstance *h) const
  4512. {
  4513. int ally = cb->gameState()->getPlayerRelations(h->tempOwner, tempOwner);
  4514. if (!ally && stacksCount() > 0) {
  4515. //TODO: Find a way to apply magic garrison effects in battle.
  4516. cb->startBattleI(h, this);
  4517. return;
  4518. }
  4519. //New owner.
  4520. if (!ally)
  4521. cb->setOwner(this, h->tempOwner);
  4522. cb->showGarrisonDialog(id, h->id, removableUnits);
  4523. }
  4524. ui8 CGGarrison::getPassableness() const
  4525. {
  4526. if ( !stacksCount() )//empty - anyone can visit
  4527. return GameConstants::ALL_PLAYERS;
  4528. if ( tempOwner == PlayerColor::NEUTRAL )//neutral guarded - no one can visit
  4529. return 0;
  4530. ui8 mask = 0;
  4531. TeamState * ts = cb->gameState()->getPlayerTeam(tempOwner);
  4532. for(PlayerColor it : ts->players)
  4533. mask |= 1<<it.getNum(); //allies - add to possible visitors
  4534. return mask;
  4535. }
  4536. void CGGarrison::battleFinished(const CGHeroInstance *hero, const BattleResult &result) const
  4537. {
  4538. if (result.winner == 0)
  4539. onHeroVisit(hero);
  4540. }
  4541. void CBank::initObj()
  4542. {
  4543. index = VLC->objh->bankObjToIndex(this);
  4544. bc = nullptr;
  4545. daycounter = 0;
  4546. multiplier = 1;
  4547. }
  4548. const std::string & CBank::getHoverText() const
  4549. {
  4550. bool visited = (bc == nullptr);
  4551. hoverName = VLC->objh->creBanksNames[index] + " " + visitedTxt(visited);
  4552. return hoverName;
  4553. }
  4554. void CBank::reset(ui16 var1) //prevents desync
  4555. {
  4556. ui8 chance = 0;
  4557. for (auto & elem : VLC->objh->banksInfo[index])
  4558. {
  4559. if (var1 < (chance += elem->chance))
  4560. {
  4561. bc = elem;
  4562. break;
  4563. }
  4564. }
  4565. artifacts.clear();
  4566. }
  4567. void CBank::initialize() const
  4568. {
  4569. cb->setObjProperty(id, ObjProperty::BANK_RESET, cb->gameState()->getRandomGenerator().nextInt()); //synchronous reset
  4570. for (ui8 i = 0; i <= 3; i++)
  4571. {
  4572. for (ui8 n = 0; n < bc->artifacts[i]; n++)
  4573. {
  4574. CArtifact::EartClass artClass;
  4575. switch(i)
  4576. {
  4577. case 0: artClass = CArtifact::ART_TREASURE; break;
  4578. case 1: artClass = CArtifact::ART_MINOR; break;
  4579. case 2: artClass = CArtifact::ART_MAJOR; break;
  4580. case 3: artClass = CArtifact::ART_RELIC; break;
  4581. default: assert(0); continue;
  4582. }
  4583. int artID = VLC->arth->pickRandomArtifact(cb->gameState()->getRandomGenerator(), artClass);
  4584. cb->setObjProperty(id, ObjProperty::BANK_ADD_ARTIFACT, artID);
  4585. }
  4586. }
  4587. cb->setObjProperty(id, ObjProperty::BANK_INIT_ARMY, cb->gameState()->getRandomGenerator().nextInt()); //get army
  4588. }
  4589. void CBank::setPropertyDer (ui8 what, ui32 val)
  4590. /// random values are passed as arguments and processed identically on all clients
  4591. {
  4592. switch (what)
  4593. {
  4594. case ObjProperty::BANK_DAYCOUNTER: //daycounter
  4595. if (val == 0)
  4596. daycounter = 1; //yes, 1
  4597. else
  4598. daycounter++;
  4599. break;
  4600. case ObjProperty::BANK_MULTIPLIER: //multiplier, in percent
  4601. multiplier = val / 100.0;
  4602. break;
  4603. case 13: //bank preset
  4604. bc = VLC->objh->banksInfo[index][val];
  4605. break;
  4606. case ObjProperty::BANK_RESET:
  4607. reset (val%100);
  4608. break;
  4609. case ObjProperty::BANK_CLEAR_CONFIG:
  4610. bc = nullptr;
  4611. break;
  4612. case ObjProperty::BANK_CLEAR_ARTIFACTS: //remove rewards from Derelict Ship
  4613. artifacts.clear();
  4614. break;
  4615. case ObjProperty::BANK_INIT_ARMY: //set ArmedInstance army
  4616. {
  4617. int upgraded = 0;
  4618. if (val%100 < bc->upgradeChance) //once again anti-desync
  4619. upgraded = 1;
  4620. switch (bc->guards.size())
  4621. {
  4622. case 1:
  4623. for (int i = 0; i < 4; ++i)
  4624. setCreature (SlotID(i), bc->guards[0].first, bc->guards[0].second / 5 );
  4625. setCreature (SlotID(4), CreatureID(bc->guards[0].first + upgraded), bc->guards[0].second / 5 );
  4626. break;
  4627. case 4:
  4628. {
  4629. if (bc->guards.back().second) //all stacks are present
  4630. {
  4631. for (auto & elem : bc->guards)
  4632. {
  4633. setCreature (SlotID(stacksCount()), elem.first, elem.second);
  4634. }
  4635. }
  4636. else if (bc->guards[2].second)//Wraiths are present, split two stacks in Crypt
  4637. {
  4638. setCreature (SlotID(0), bc->guards[0].first, bc->guards[0].second / 2 );
  4639. setCreature (SlotID(1), bc->guards[1].first, bc->guards[1].second / 2);
  4640. setCreature (SlotID(2), CreatureID(bc->guards[2].first + upgraded), bc->guards[2].second);
  4641. setCreature (SlotID(3), bc->guards[1].first, bc->guards[1].second / 2 );
  4642. setCreature (SlotID(4), bc->guards[0].first, bc->guards[0].second - (bc->guards[0].second / 2) );
  4643. }
  4644. else //split both stacks
  4645. {
  4646. for (int i = 0; i < 3; ++i) //skellies
  4647. setCreature (SlotID(2*i), bc->guards[0].first, bc->guards[0].second / 3);
  4648. for (int i = 0; i < 2; ++i) //zombies
  4649. setCreature (SlotID(2*i+1), bc->guards[1].first, bc->guards[1].second / 2);
  4650. }
  4651. }
  4652. break;
  4653. default:
  4654. logGlobal->warnStream() << "Error: Unexpected army data: " << bc->guards.size() <<" items found";
  4655. return;
  4656. }
  4657. }
  4658. break;
  4659. case ObjProperty::BANK_ADD_ARTIFACT: //add Artifact
  4660. {
  4661. artifacts.push_back (val);
  4662. break;
  4663. }
  4664. }
  4665. }
  4666. void CBank::newTurn() const
  4667. {
  4668. if (bc == nullptr)
  4669. {
  4670. if (cb->getDate() == 1)
  4671. initialize(); //initialize on first day
  4672. else if (daycounter >= 28 && (subID < 13 || subID > 16)) //no reset for Emissaries
  4673. {
  4674. initialize();
  4675. cb->setObjProperty (id, ObjProperty::BANK_DAYCOUNTER, 0); //daycounter 0
  4676. if (ID == Obj::DERELICT_SHIP && cb->getDate() > 1)
  4677. {
  4678. cb->setObjProperty (id, ObjProperty::BANK_MULTIPLIER, 0);//ugly hack to make derelict ships usable only once
  4679. cb->setObjProperty (id, ObjProperty::BANK_CLEAR_ARTIFACTS, 0);
  4680. }
  4681. }
  4682. else
  4683. cb->setObjProperty (id, ObjProperty::BANK_DAYCOUNTER, 1); //daycounter++
  4684. }
  4685. }
  4686. bool CBank::wasVisited (PlayerColor player) const
  4687. {
  4688. return !bc;
  4689. }
  4690. void CBank::onHeroVisit (const CGHeroInstance * h) const
  4691. {
  4692. if (bc)
  4693. {
  4694. int banktext = 0;
  4695. switch (ID)
  4696. {
  4697. case Obj::CREATURE_BANK:
  4698. banktext = 32;
  4699. break;
  4700. case Obj::DERELICT_SHIP:
  4701. banktext = 41;
  4702. break;
  4703. case Obj::DRAGON_UTOPIA:
  4704. banktext = 47;
  4705. break;
  4706. case Obj::CRYPT:
  4707. banktext = 119;
  4708. break;
  4709. case Obj::SHIPWRECK:
  4710. banktext = 122;
  4711. break;
  4712. }
  4713. BlockingDialog bd (true, false);
  4714. bd.player = h->getOwner();
  4715. bd.soundID = soundBase::ROGUE;
  4716. bd.text.addTxt(MetaString::ADVOB_TXT,banktext);
  4717. if (ID == Obj::CREATURE_BANK)
  4718. bd.text.addReplacement(VLC->objh->creBanksNames[index]);
  4719. cb->showBlockingDialog (&bd);
  4720. }
  4721. else
  4722. {
  4723. InfoWindow iw;
  4724. iw.soundID = soundBase::GRAVEYARD;
  4725. iw.player = h->getOwner();
  4726. if (ID == Obj::CRYPT) //morale penalty for empty Crypt
  4727. {
  4728. GiveBonus gbonus;
  4729. gbonus.id = h->id.getNum();
  4730. gbonus.bonus.duration = Bonus::ONE_BATTLE;
  4731. gbonus.bonus.source = Bonus::OBJECT;
  4732. gbonus.bonus.sid = ID;
  4733. gbonus.bdescr << "\n" << VLC->generaltexth->arraytxt[98];
  4734. gbonus.bonus.type = Bonus::MORALE;
  4735. gbonus.bonus.val = -1;
  4736. cb->giveHeroBonus(&gbonus);
  4737. iw.text << VLC->generaltexth->advobtxt[120];
  4738. iw.components.push_back (Component (Component::MORALE, 0 , -1, 0));
  4739. }
  4740. else
  4741. {
  4742. iw.text << VLC->generaltexth->advobtxt[33];
  4743. iw.text.addReplacement(VLC->objh->creBanksNames[index]);
  4744. }
  4745. cb->showInfoDialog(&iw);
  4746. }
  4747. }
  4748. void CBank::battleFinished(const CGHeroInstance *hero, const BattleResult &result) const
  4749. {
  4750. if (result.winner == 0)
  4751. {
  4752. int textID = -1;
  4753. InfoWindow iw;
  4754. iw.player = hero->getOwner();
  4755. MetaString loot;
  4756. switch (ID)
  4757. {
  4758. case Obj::CREATURE_BANK: case Obj::DRAGON_UTOPIA:
  4759. textID = 34;
  4760. break;
  4761. case Obj::DERELICT_SHIP:
  4762. if (multiplier)
  4763. textID = 43;
  4764. else
  4765. {
  4766. GiveBonus gbonus;
  4767. gbonus.id = hero->id.getNum();
  4768. gbonus.bonus.duration = Bonus::ONE_BATTLE;
  4769. gbonus.bonus.source = Bonus::OBJECT;
  4770. gbonus.bonus.sid = ID;
  4771. gbonus.bdescr << "\n" << VLC->generaltexth->arraytxt[101];
  4772. gbonus.bonus.type = Bonus::MORALE;
  4773. gbonus.bonus.val = -1;
  4774. cb->giveHeroBonus(&gbonus);
  4775. textID = 42;
  4776. iw.components.push_back (Component (Component::MORALE, 0 , -1, 0));
  4777. }
  4778. break;
  4779. case Obj::CRYPT:
  4780. if (bc->resources.size() != 0)
  4781. textID = 121;
  4782. else
  4783. {
  4784. iw.components.push_back (Component (Component::MORALE, 0 , -1, 0));
  4785. GiveBonus gbonus;
  4786. gbonus.id = hero->id.getNum();
  4787. gbonus.bonus.duration = Bonus::ONE_BATTLE;
  4788. gbonus.bonus.source = Bonus::OBJECT;
  4789. gbonus.bonus.sid = ID;
  4790. gbonus.bdescr << "\n" << VLC->generaltexth->arraytxt[ID];
  4791. gbonus.bonus.type = Bonus::MORALE;
  4792. gbonus.bonus.val = -1;
  4793. cb->giveHeroBonus(&gbonus);
  4794. textID = 120;
  4795. iw.components.push_back (Component (Component::MORALE, 0 , -1, 0));
  4796. }
  4797. break;
  4798. case Obj::SHIPWRECK:
  4799. if (bc->resources.size())
  4800. textID = 124;
  4801. else
  4802. textID = 123;
  4803. break;
  4804. }
  4805. //grant resources
  4806. if (textID != 42) //empty derelict ship gives no cash
  4807. {
  4808. for (int it = 0; it < bc->resources.size(); it++)
  4809. {
  4810. if (bc->resources[it] != 0)
  4811. {
  4812. iw.components.push_back (Component (Component::RESOURCE, it, bc->resources[it], 0));
  4813. loot << "%d %s";
  4814. loot.addReplacement(iw.components.back().val);
  4815. loot.addReplacement(MetaString::RES_NAMES, iw.components.back().subtype);
  4816. cb->giveResource (hero->getOwner(), static_cast<Res::ERes>(it), bc->resources[it]);
  4817. }
  4818. }
  4819. }
  4820. //grant artifacts
  4821. for (auto & elem : artifacts)
  4822. {
  4823. iw.components.push_back (Component (Component::ARTIFACT, elem, 0, 0));
  4824. loot << "%s";
  4825. loot.addReplacement(MetaString::ART_NAMES, elem);
  4826. cb->giveHeroNewArtifact (hero, VLC->arth->artifacts[elem], ArtifactPosition::FIRST_AVAILABLE);
  4827. }
  4828. //display loot
  4829. if (!iw.components.empty())
  4830. {
  4831. iw.text.addTxt (MetaString::ADVOB_TXT, textID);
  4832. if (textID == 34)
  4833. {
  4834. iw.text.addReplacement(MetaString::CRE_PL_NAMES, result.casualties[1].begin()->first);
  4835. iw.text.addReplacement(loot.buildList());
  4836. }
  4837. cb->showInfoDialog(&iw);
  4838. }
  4839. loot.clear();
  4840. iw.components.clear();
  4841. iw.text.clear();
  4842. //grant creatures
  4843. CCreatureSet ourArmy;
  4844. for (auto it = bc->creatures.cbegin(); it != bc->creatures.cend(); it++)
  4845. {
  4846. SlotID slot = ourArmy.getSlotFor(it->first);
  4847. ourArmy.addToSlot(slot, it->first, it->second);
  4848. }
  4849. for (auto & elem : ourArmy.Slots())
  4850. {
  4851. iw.components.push_back(Component(*elem.second));
  4852. loot << "%s";
  4853. loot.addReplacement(*elem.second);
  4854. }
  4855. if (ourArmy.Slots().size())
  4856. {
  4857. if (ourArmy.Slots().size() == 1 && ourArmy.Slots().begin()->second->count == 1)
  4858. iw.text.addTxt (MetaString::ADVOB_TXT, 185);
  4859. else
  4860. iw.text.addTxt (MetaString::ADVOB_TXT, 186);
  4861. iw.text.addReplacement(loot.buildList());
  4862. iw.text.addReplacement(hero->name);
  4863. cb->showInfoDialog(&iw);
  4864. cb->giveCreatures(this, hero, ourArmy, false);
  4865. }
  4866. cb->setObjProperty (id, ObjProperty::BANK_CLEAR_CONFIG, 0); //bc = nullptr
  4867. }
  4868. }
  4869. void CBank::blockingDialogAnswered(const CGHeroInstance *hero, ui32 answer) const
  4870. {
  4871. if (answer)
  4872. {
  4873. cb->startBattleI(hero, this, true);
  4874. }
  4875. }
  4876. void CGPyramid::initObj()
  4877. {
  4878. std::vector<SpellID> available;
  4879. cb->getAllowedSpells (available, 5);
  4880. if (available.size())
  4881. {
  4882. bc = VLC->objh->banksInfo[21].front(); //TODO: remove hardcoded value?
  4883. spell = *RandomGeneratorUtil::nextItem(available, cb->gameState()->getRandomGenerator());
  4884. }
  4885. else
  4886. {
  4887. logGlobal->errorStream() <<"No spells available for Pyramid! Object set to empty.";
  4888. }
  4889. setPropertyDer(ObjProperty::BANK_INIT_ARMY, cb->gameState()->getRandomGenerator().nextInt()); //set guards at game start
  4890. }
  4891. const std::string & CGPyramid::getHoverText() const
  4892. {
  4893. hoverName = VLC->objh->creBanksNames[21]+ " " + visitedTxt((bc==nullptr));
  4894. return hoverName;
  4895. }
  4896. void CGPyramid::onHeroVisit (const CGHeroInstance * h) const
  4897. {
  4898. if (bc)
  4899. {
  4900. BlockingDialog bd (true, false);
  4901. bd.player = h->getOwner();
  4902. bd.soundID = soundBase::MYSTERY;
  4903. bd.text << VLC->generaltexth->advobtxt[105];
  4904. cb->showBlockingDialog(&bd);
  4905. }
  4906. else
  4907. {
  4908. InfoWindow iw;
  4909. iw.player = h->getOwner();
  4910. iw.text << VLC->generaltexth->advobtxt[107];
  4911. iw.components.push_back (Component (Component::LUCK, 0 , -2, 0));
  4912. GiveBonus gb;
  4913. gb.bonus = Bonus(Bonus::ONE_BATTLE,Bonus::LUCK,Bonus::OBJECT,-2,id.getNum(),VLC->generaltexth->arraytxt[70]);
  4914. gb.id = h->id.getNum();
  4915. cb->giveHeroBonus(&gb);
  4916. cb->showInfoDialog(&iw);
  4917. }
  4918. }
  4919. void CGPyramid::battleFinished(const CGHeroInstance *hero, const BattleResult &result) const
  4920. {
  4921. if (result.winner == 0)
  4922. {
  4923. InfoWindow iw;
  4924. iw.player = hero->getOwner();
  4925. iw.text.addTxt (MetaString::ADVOB_TXT, 106);
  4926. iw.text.addTxt (MetaString::SPELL_NAME, spell);
  4927. if (!hero->getArt(ArtifactPosition::SPELLBOOK))
  4928. iw.text.addTxt (MetaString::ADVOB_TXT, 109); //no spellbook
  4929. else if (hero->getSecSkillLevel(SecondarySkill::WISDOM) < 3)
  4930. iw.text.addTxt (MetaString::ADVOB_TXT, 108); //no expert Wisdom
  4931. else
  4932. {
  4933. std::set<SpellID> spells;
  4934. spells.insert (SpellID(spell));
  4935. cb->changeSpells (hero, true, spells);
  4936. iw.components.push_back(Component (Component::SPELL, spell, 0, 0));
  4937. }
  4938. cb->showInfoDialog(&iw);
  4939. cb->setObjProperty (id, ObjProperty::BANK_CLEAR_CONFIG, 0);
  4940. }
  4941. }
  4942. void CGKeys::setPropertyDer (ui8 what, ui32 val) //101-108 - enable key for player 1-8
  4943. {
  4944. if (what >= 101 && what <= (100 + PlayerColor::PLAYER_LIMIT_I))
  4945. {
  4946. PlayerColor player(what-101);
  4947. playerKeyMap[player].insert((ui8)val);
  4948. }
  4949. else
  4950. logGlobal->errorStream() << boost::format("Unexpected properties requested to set: what=%d, val=%d") % (int)what % val;
  4951. }
  4952. bool CGKeys::wasMyColorVisited (PlayerColor player) const
  4953. {
  4954. if (vstd::contains(playerKeyMap[player], subID)) //creates set if it's not there
  4955. return true;
  4956. else
  4957. return false;
  4958. }
  4959. const std::string& CGKeys::getHoverText() const
  4960. {
  4961. bool visited = wasMyColorVisited (cb->getLocalPlayer());
  4962. hoverName = getName() + "\n" + visitedTxt(visited);
  4963. return hoverName;
  4964. }
  4965. const std::string CGKeys::getName() const
  4966. {
  4967. std::string name;
  4968. name = VLC->generaltexth->tentColors[subID] + " " + VLC->generaltexth->names[ID];
  4969. return name;
  4970. }
  4971. bool CGKeymasterTent::wasVisited (PlayerColor player) const
  4972. {
  4973. return wasMyColorVisited (player);
  4974. }
  4975. void CGKeymasterTent::onHeroVisit( const CGHeroInstance * h ) const
  4976. {
  4977. int txt_id;
  4978. if (!wasMyColorVisited (h->getOwner()) )
  4979. {
  4980. cb->setObjProperty(id, h->tempOwner.getNum()+101, subID);
  4981. txt_id=19;
  4982. }
  4983. else
  4984. txt_id=20;
  4985. showInfoDialog(h,txt_id,soundBase::CAVEHEAD);
  4986. }
  4987. void CGBorderGuard::initObj()
  4988. {
  4989. //ui32 m13489val = subID; //store color as quest info
  4990. blockVisit = true;
  4991. }
  4992. void CGBorderGuard::getVisitText (MetaString &text, std::vector<Component> &components, bool isCustom, bool FirstVisit, const CGHeroInstance * h) const
  4993. {
  4994. text << std::pair<ui8,ui32>(11,18);
  4995. }
  4996. void CGBorderGuard::getRolloverText (MetaString &text, bool onHover) const
  4997. {
  4998. if (!onHover)
  4999. text << VLC->generaltexth->tentColors[subID] << " " << VLC->generaltexth->names[Obj::KEYMASTER];
  5000. }
  5001. bool CGBorderGuard::checkQuest (const CGHeroInstance * h) const
  5002. {
  5003. return wasMyColorVisited (h->tempOwner);
  5004. }
  5005. void CGBorderGuard::onHeroVisit( const CGHeroInstance * h ) const
  5006. {
  5007. if (wasMyColorVisited (h->getOwner()) )
  5008. {
  5009. BlockingDialog bd (true, false);
  5010. bd.player = h->getOwner();
  5011. bd.soundID = soundBase::QUEST;
  5012. bd.text.addTxt (MetaString::ADVOB_TXT, 17);
  5013. cb->showBlockingDialog (&bd);
  5014. }
  5015. else
  5016. {
  5017. showInfoDialog(h,18,soundBase::CAVEHEAD);
  5018. AddQuest aq;
  5019. aq.quest = QuestInfo (quest, this, visitablePos());
  5020. aq.player = h->tempOwner;
  5021. cb->sendAndApply (&aq);
  5022. //TODO: add this quest only once OR check for multiple instances later
  5023. }
  5024. }
  5025. void CGBorderGuard::blockingDialogAnswered(const CGHeroInstance *hero, ui32 answer) const
  5026. {
  5027. if (answer)
  5028. cb->removeObject(this);
  5029. }
  5030. void CGBorderGate::onHeroVisit( const CGHeroInstance * h ) const //TODO: passability
  5031. {
  5032. if (!wasMyColorVisited (h->getOwner()) )
  5033. {
  5034. showInfoDialog(h,18,0);
  5035. AddQuest aq;
  5036. aq.quest = QuestInfo (quest, this, visitablePos());
  5037. aq.player = h->tempOwner;
  5038. cb->sendAndApply (&aq);
  5039. }
  5040. }
  5041. ui8 CGBorderGate::getPassableness() const
  5042. {
  5043. ui8 ret = 0;
  5044. for (int i = 0; i < PlayerColor::PLAYER_LIMIT_I; i++)
  5045. ret |= wasMyColorVisited(PlayerColor(i))<<i;
  5046. return ret;
  5047. }
  5048. void CGMagi::initObj()
  5049. {
  5050. if (ID == Obj::EYE_OF_MAGI)
  5051. {
  5052. blockVisit = true;
  5053. eyelist[subID].push_back(id);
  5054. }
  5055. }
  5056. void CGMagi::onHeroVisit(const CGHeroInstance * h) const
  5057. {
  5058. if (ID == Obj::HUT_OF_MAGI)
  5059. {
  5060. showInfoDialog(h, 61, soundBase::LIGHTHOUSE);
  5061. if (!eyelist[subID].empty())
  5062. {
  5063. CenterView cv;
  5064. cv.player = h->tempOwner;
  5065. cv.focusTime = 2000;
  5066. FoWChange fw;
  5067. fw.player = h->tempOwner;
  5068. fw.mode = 1;
  5069. for(auto it : eyelist[subID])
  5070. {
  5071. const CGObjectInstance *eye = cb->getObj(it);
  5072. cb->getTilesInRange (fw.tiles, eye->pos, 10, h->tempOwner, 1);
  5073. cb->sendAndApply(&fw);
  5074. cv.pos = eye->pos;
  5075. cb->sendAndApply(&cv);
  5076. }
  5077. cv.pos = h->getPosition(false);
  5078. cb->sendAndApply(&cv);
  5079. }
  5080. }
  5081. else if (ID == Obj::EYE_OF_MAGI)
  5082. {
  5083. showInfoDialog(h,48,soundBase::invalid);
  5084. }
  5085. }
  5086. void CGBoat::initObj()
  5087. {
  5088. hero = nullptr;
  5089. }
  5090. void CGSirens::initObj()
  5091. {
  5092. blockVisit = true;
  5093. }
  5094. const std::string & CGSirens::getHoverText() const
  5095. {
  5096. getNameVis(hoverName);
  5097. return hoverName;
  5098. }
  5099. void CGSirens::onHeroVisit( const CGHeroInstance * h ) const
  5100. {
  5101. InfoWindow iw;
  5102. iw.soundID = soundBase::DANGER;
  5103. iw.player = h->tempOwner;
  5104. if(h->hasBonusFrom(Bonus::OBJECT,ID)) //has already visited Sirens
  5105. {
  5106. iw.text.addTxt(MetaString::ADVOB_TXT,133);
  5107. }
  5108. else
  5109. {
  5110. giveDummyBonus(h->id, Bonus::ONE_BATTLE);
  5111. TExpType xp = 0;
  5112. for (auto i = h->Slots().begin(); i != h->Slots().end(); i++)
  5113. {
  5114. TQuantity drown = i->second->count * 0.3;
  5115. if(drown)
  5116. {
  5117. cb->changeStackCount(StackLocation(h, i->first), -drown);
  5118. xp += drown * i->second->type->valOfBonuses(Bonus::STACK_HEALTH);
  5119. }
  5120. }
  5121. if(xp)
  5122. {
  5123. xp = h->calculateXp(xp);
  5124. iw.text.addTxt(MetaString::ADVOB_TXT,132);
  5125. iw.text.addReplacement(xp);
  5126. cb->changePrimSkill(h, PrimarySkill::EXPERIENCE, xp, false);
  5127. }
  5128. else
  5129. {
  5130. iw.text.addTxt(MetaString::ADVOB_TXT,134);
  5131. }
  5132. }
  5133. cb->showInfoDialog(&iw);
  5134. }
  5135. //bool IShipyard::validLocation() const
  5136. //{
  5137. // std::vector<int3> offsets;
  5138. // getOutOffsets(offsets);
  5139. //
  5140. // TerrainTile *tile;
  5141. // for(int i = 0; i < offsets.size(); i++)
  5142. // if((tile = IObjectInterface::cb->getTile(o->pos + offsets[i])) && tile->terType == TerrainTile::water) //tile is in the map and is water
  5143. // return true;
  5144. // return false;
  5145. //}
  5146. int3 IBoatGenerator::bestLocation() const
  5147. {
  5148. std::vector<int3> offsets;
  5149. getOutOffsets(offsets);
  5150. for (auto & offset : offsets)
  5151. {
  5152. if (const TerrainTile *tile = IObjectInterface::cb->getTile(o->pos + offset, false)) //tile is in the map
  5153. {
  5154. if (tile->terType == ETerrainType::WATER && (!tile->blocked || tile->blockingObjects.front()->ID == 8)) //and is water and is not blocked or is blocked by boat
  5155. return o->pos + offset;
  5156. }
  5157. }
  5158. return int3 (-1,-1,-1);
  5159. }
  5160. IBoatGenerator::EGeneratorState IBoatGenerator::shipyardStatus() const
  5161. {
  5162. int3 tile = bestLocation();
  5163. const TerrainTile *t = IObjectInterface::cb->getTile(tile);
  5164. if(!t)
  5165. return TILE_BLOCKED; //no available water
  5166. else if(!t->blockingObjects.size())
  5167. return GOOD; //OK
  5168. else if(t->blockingObjects.front()->ID == Obj::BOAT)
  5169. return BOAT_ALREADY_BUILT; //blocked with boat
  5170. else
  5171. return TILE_BLOCKED; //blocked
  5172. }
  5173. int IBoatGenerator::getBoatType() const
  5174. {
  5175. //We make good ships by default
  5176. return 1;
  5177. }
  5178. IBoatGenerator::IBoatGenerator(const CGObjectInstance *O)
  5179. : o(O)
  5180. {
  5181. }
  5182. void IBoatGenerator::getProblemText(MetaString &out, const CGHeroInstance *visitor) const
  5183. {
  5184. switch(shipyardStatus())
  5185. {
  5186. case BOAT_ALREADY_BUILT:
  5187. out.addTxt(MetaString::GENERAL_TXT, 51);
  5188. break;
  5189. case TILE_BLOCKED:
  5190. if(visitor)
  5191. {
  5192. out.addTxt(MetaString::GENERAL_TXT, 134);
  5193. out.addReplacement(visitor->name);
  5194. }
  5195. else
  5196. out.addTxt(MetaString::ADVOB_TXT, 189);
  5197. break;
  5198. case NO_WATER:
  5199. logGlobal->errorStream() << "Shipyard without water!!! " << o->pos << "\t" << o->id;
  5200. return;
  5201. }
  5202. }
  5203. void IShipyard::getBoatCost( std::vector<si32> &cost ) const
  5204. {
  5205. cost.resize(GameConstants::RESOURCE_QUANTITY);
  5206. cost[Res::WOOD] = 10;
  5207. cost[Res::GOLD] = 1000;
  5208. }
  5209. IShipyard::IShipyard(const CGObjectInstance *O)
  5210. : IBoatGenerator(O)
  5211. {
  5212. }
  5213. IShipyard * IShipyard::castFrom( CGObjectInstance *obj )
  5214. {
  5215. if(!obj)
  5216. return nullptr;
  5217. if(obj->ID == Obj::TOWN)
  5218. {
  5219. return static_cast<CGTownInstance*>(obj);
  5220. }
  5221. else if(obj->ID == Obj::SHIPYARD)
  5222. {
  5223. return static_cast<CGShipyard*>(obj);
  5224. }
  5225. else
  5226. {
  5227. return nullptr;
  5228. }
  5229. }
  5230. const IShipyard * IShipyard::castFrom( const CGObjectInstance *obj )
  5231. {
  5232. return castFrom(const_cast<CGObjectInstance*>(obj));
  5233. }
  5234. CGShipyard::CGShipyard()
  5235. :IShipyard(this)
  5236. {
  5237. }
  5238. void CGShipyard::getOutOffsets( std::vector<int3> &offsets ) const
  5239. {
  5240. // H J L K I
  5241. // A x S x B
  5242. // C E G F D
  5243. offsets += int3(-3,0,0), int3(1,0,0), //AB
  5244. int3(-3,1,0), int3(1,1,0), int3(-2,1,0), int3(0,1,0), int3(-1,1,0), //CDEFG
  5245. int3(-3,-1,0), int3(1,-1,0), int3(-2,-1,0), int3(0,-1,0), int3(-1,-1,0); //HIJKL
  5246. }
  5247. void CGShipyard::onHeroVisit( const CGHeroInstance * h ) const
  5248. {
  5249. if(!cb->gameState()->getPlayerRelations(tempOwner, h->tempOwner))
  5250. cb->setOwner(this, h->tempOwner);
  5251. auto s = shipyardStatus();
  5252. if(s != IBoatGenerator::GOOD)
  5253. {
  5254. InfoWindow iw;
  5255. iw.player = tempOwner;
  5256. getProblemText(iw.text, h);
  5257. cb->showInfoDialog(&iw);
  5258. }
  5259. else
  5260. {
  5261. openWindow(OpenWindow::SHIPYARD_WINDOW,id.getNum(),h->id.getNum());
  5262. }
  5263. }
  5264. void CCartographer::onHeroVisit( const CGHeroInstance * h ) const
  5265. {
  5266. if (!wasVisited (h->getOwner()) ) //if hero has not visited yet this cartographer
  5267. {
  5268. if (cb->getResource(h->tempOwner, Res::GOLD) >= 1000) //if he can afford a map
  5269. {
  5270. //ask if he wants to buy one
  5271. int text=0;
  5272. switch (subID)
  5273. {
  5274. case 0:
  5275. text = 25;
  5276. break;
  5277. case 1:
  5278. text = 26;
  5279. break;
  5280. case 2:
  5281. text = 27;
  5282. break;
  5283. default:
  5284. logGlobal->warnStream() << "Unrecognized subtype of cartographer";
  5285. }
  5286. assert(text);
  5287. BlockingDialog bd (true, false);
  5288. bd.player = h->getOwner();
  5289. bd.soundID = soundBase::LIGHTHOUSE;
  5290. bd.text.addTxt (MetaString::ADVOB_TXT, text);
  5291. cb->showBlockingDialog (&bd);
  5292. }
  5293. else //if he cannot afford
  5294. {
  5295. showInfoDialog(h,28,soundBase::CAVEHEAD);
  5296. }
  5297. }
  5298. else //if he already visited carographer
  5299. {
  5300. showInfoDialog(h,24,soundBase::CAVEHEAD);
  5301. }
  5302. }
  5303. void CCartographer::blockingDialogAnswered(const CGHeroInstance *hero, ui32 answer) const
  5304. {
  5305. if (answer) //if hero wants to buy map
  5306. {
  5307. cb->giveResource (hero->tempOwner, Res::GOLD, -1000);
  5308. FoWChange fw;
  5309. fw.mode = 1;
  5310. fw.player = hero->tempOwner;
  5311. //subIDs of different types of cartographers:
  5312. //water = 0; land = 1; underground = 2;
  5313. cb->getAllTiles (fw.tiles, hero->tempOwner, subID - 1, !subID + 1); //reveal appropriate tiles
  5314. cb->sendAndApply (&fw);
  5315. cb->setObjProperty (id, 10, hero->tempOwner.getNum());
  5316. }
  5317. }
  5318. void CGDenOfthieves::onHeroVisit (const CGHeroInstance * h) const
  5319. {
  5320. cb->showThievesGuildWindow(h->tempOwner, id);
  5321. }
  5322. void CGObelisk::onHeroVisit( const CGHeroInstance * h ) const
  5323. {
  5324. InfoWindow iw;
  5325. iw.player = h->tempOwner;
  5326. TeamState *ts = cb->gameState()->getPlayerTeam(h->tempOwner);
  5327. assert(ts);
  5328. TeamID team = ts->id;
  5329. if(!wasVisited(team))
  5330. {
  5331. iw.text.addTxt(MetaString::ADVOB_TXT, 96);
  5332. cb->sendAndApply(&iw);
  5333. cb->setObjProperty(id, 20, h->tempOwner.getNum()); //increment general visited obelisks counter
  5334. openWindow(OpenWindow::PUZZLE_MAP, h->tempOwner.getNum());
  5335. cb->setObjProperty(id, 10, h->tempOwner.getNum()); //mark that particular obelisk as visited
  5336. }
  5337. else
  5338. {
  5339. iw.text.addTxt(MetaString::ADVOB_TXT, 97);
  5340. cb->sendAndApply(&iw);
  5341. }
  5342. }
  5343. void CGObelisk::initObj()
  5344. {
  5345. obeliskCount++;
  5346. }
  5347. const std::string & CGObelisk::getHoverText() const
  5348. {
  5349. bool visited = wasVisited(cb->getLocalPlayer());
  5350. hoverName = VLC->generaltexth->names[ID] + " " + visitedTxt(visited);
  5351. return hoverName;
  5352. }
  5353. void CGObelisk::setPropertyDer( ui8 what, ui32 val )
  5354. {
  5355. CPlayersVisited::setPropertyDer(what, val);
  5356. switch(what)
  5357. {
  5358. case 20:
  5359. assert(val < PlayerColor::PLAYER_LIMIT_I);
  5360. visited[TeamID(val)]++;
  5361. if(visited[TeamID(val)] > obeliskCount)
  5362. {
  5363. logGlobal->errorStream() << "Error: Visited " << visited[TeamID(val)] << "\t\t" << obeliskCount;
  5364. assert(0);
  5365. }
  5366. break;
  5367. }
  5368. }
  5369. void CGLighthouse::onHeroVisit( const CGHeroInstance * h ) const
  5370. {
  5371. if(h->tempOwner != tempOwner)
  5372. {
  5373. PlayerColor oldOwner = tempOwner;
  5374. cb->setOwner(this,h->tempOwner); //not ours? flag it!
  5375. showInfoDialog(h,69,soundBase::LIGHTHOUSE);
  5376. giveBonusTo(h->tempOwner);
  5377. if(oldOwner < PlayerColor::PLAYER_LIMIT) //remove bonus from old owner
  5378. {
  5379. RemoveBonus rb(RemoveBonus::PLAYER);
  5380. rb.whoID = oldOwner.getNum();
  5381. rb.source = Bonus::OBJECT;
  5382. rb.id = id.getNum();
  5383. cb->sendAndApply(&rb);
  5384. }
  5385. }
  5386. }
  5387. void CGLighthouse::initObj()
  5388. {
  5389. if(tempOwner < PlayerColor::PLAYER_LIMIT)
  5390. {
  5391. giveBonusTo(tempOwner);
  5392. }
  5393. }
  5394. const std::string & CGLighthouse::getHoverText() const
  5395. {
  5396. hoverName = VLC->generaltexth->names[ID];
  5397. //TODO: owned by %s player
  5398. return hoverName;
  5399. }
  5400. void CGLighthouse::giveBonusTo( PlayerColor player ) const
  5401. {
  5402. GiveBonus gb(GiveBonus::PLAYER);
  5403. gb.bonus.type = Bonus::SEA_MOVEMENT;
  5404. gb.bonus.val = 500;
  5405. gb.id = player.getNum();
  5406. gb.bonus.duration = Bonus::PERMANENT;
  5407. gb.bonus.source = Bonus::OBJECT;
  5408. gb.bonus.sid = id.getNum();
  5409. cb->sendAndApply(&gb);
  5410. }
  5411. void CArmedInstance::randomizeArmy(int type)
  5412. {
  5413. for (auto & elem : stacks)
  5414. {
  5415. int & randID = elem.second->idRand;
  5416. if(randID >= 0)
  5417. {
  5418. int level = randID / 2;
  5419. bool upgrade = randID % 2;
  5420. elem.second->setType(VLC->townh->factions[type]->town->creatures[level][upgrade]);
  5421. randID = -1;
  5422. }
  5423. assert(elem.second->valid(false));
  5424. assert(elem.second->armyObj == this);
  5425. }
  5426. return;
  5427. }
  5428. CArmedInstance::CArmedInstance()
  5429. {
  5430. battle = nullptr;
  5431. }
  5432. //int CArmedInstance::valOfGlobalBonuses(CSelector selector) const
  5433. //{
  5434. //// if (tempOwner != NEUTRAL_PLAYER)
  5435. // return cb->gameState()->players[tempOwner].valOfBonuses(selector);
  5436. //}
  5437. void CArmedInstance::updateMoraleBonusFromArmy()
  5438. {
  5439. if(!validTypes(false)) //object not randomized, don't bother
  5440. return;
  5441. Bonus *b = getBonusList().getFirst(Selector::sourceType(Bonus::ARMY).And(Selector::type(Bonus::MORALE)));
  5442. if(!b)
  5443. {
  5444. b = new Bonus(Bonus::PERMANENT, Bonus::MORALE, Bonus::ARMY, 0, -1);
  5445. addNewBonus(b);
  5446. }
  5447. //number of alignments and presence of undead
  5448. std::set<TFaction> factions;
  5449. bool hasUndead = false;
  5450. for(auto slot : Slots())
  5451. {
  5452. const CStackInstance * inst = slot.second;
  5453. const CCreature * creature = VLC->creh->creatures[inst->getCreatureID()];
  5454. factions.insert(creature->faction);
  5455. // Check for undead flag instead of faction (undead mummies are neutral)
  5456. hasUndead |= inst->hasBonusOfType(Bonus::UNDEAD);
  5457. }
  5458. size_t factionsInArmy = factions.size(); //town garrison seems to take both sets into account
  5459. // Take Angelic Alliance troop-mixing freedom of non-evil units into account.
  5460. if (hasBonusOfType(Bonus::NONEVIL_ALIGNMENT_MIX))
  5461. {
  5462. size_t mixableFactions = 0;
  5463. for(TFaction f : factions)
  5464. {
  5465. if (VLC->townh->factions[f]->alignment != EAlignment::EVIL)
  5466. mixableFactions++;
  5467. }
  5468. if (mixableFactions > 0)
  5469. factionsInArmy -= mixableFactions - 1;
  5470. }
  5471. if(factionsInArmy == 1)
  5472. {
  5473. b->val = +1;
  5474. b->description = VLC->generaltexth->arraytxt[115]; //All troops of one alignment +1
  5475. }
  5476. else if (!factions.empty()) // no bonus from empty garrison
  5477. {
  5478. b->val = 2 - factionsInArmy;
  5479. b->description = boost::str(boost::format(VLC->generaltexth->arraytxt[114]) % factionsInArmy % b->val); //Troops of %d alignments %d
  5480. }
  5481. boost::algorithm::trim(b->description);
  5482. //-1 modifier for any Undead unit in army
  5483. const ui8 UNDEAD_MODIFIER_ID = -2;
  5484. Bonus *undeadModifier = getBonusList().getFirst(Selector::source(Bonus::ARMY, UNDEAD_MODIFIER_ID));
  5485. if(hasUndead)
  5486. {
  5487. if(!undeadModifier)
  5488. addNewBonus(new Bonus(Bonus::PERMANENT, Bonus::MORALE, Bonus::ARMY, -1, UNDEAD_MODIFIER_ID, VLC->generaltexth->arraytxt[116]));
  5489. }
  5490. else if(undeadModifier)
  5491. removeBonus(undeadModifier);
  5492. }
  5493. void CArmedInstance::armyChanged()
  5494. {
  5495. updateMoraleBonusFromArmy();
  5496. }
  5497. CBonusSystemNode * CArmedInstance::whereShouldBeAttached(CGameState *gs)
  5498. {
  5499. if(tempOwner < PlayerColor::PLAYER_LIMIT)
  5500. return gs->getPlayer(tempOwner);
  5501. else
  5502. return &gs->globalEffects;
  5503. }
  5504. CBonusSystemNode * CArmedInstance::whatShouldBeAttached()
  5505. {
  5506. return this;
  5507. }
  5508. bool IMarket::getOffer(int id1, int id2, int &val1, int &val2, EMarketMode::EMarketMode mode) const
  5509. {
  5510. switch(mode)
  5511. {
  5512. case EMarketMode::RESOURCE_RESOURCE:
  5513. {
  5514. double effectiveness = std::min((getMarketEfficiency() + 1.0) / 20.0, 0.5);
  5515. double r = VLC->objh->resVals[id1], //value of given resource
  5516. g = VLC->objh->resVals[id2] / effectiveness; //value of wanted resource
  5517. if(r>g) //if given resource is more expensive than wanted
  5518. {
  5519. val2 = ceil(r / g);
  5520. val1 = 1;
  5521. }
  5522. else //if wanted resource is more expensive
  5523. {
  5524. val1 = (g / r) + 0.5;
  5525. val2 = 1;
  5526. }
  5527. }
  5528. break;
  5529. case EMarketMode::CREATURE_RESOURCE:
  5530. {
  5531. const double effectivenessArray[] = {0.0, 0.3, 0.45, 0.50, 0.65, 0.7, 0.85, 0.9, 1.0};
  5532. double effectiveness = effectivenessArray[std::min(getMarketEfficiency(), 8)];
  5533. double r = VLC->creh->creatures[id1]->cost[6], //value of given creature in gold
  5534. g = VLC->objh->resVals[id2] / effectiveness; //value of wanted resource
  5535. if(r>g) //if given resource is more expensive than wanted
  5536. {
  5537. val2 = ceil(r / g);
  5538. val1 = 1;
  5539. }
  5540. else //if wanted resource is more expensive
  5541. {
  5542. val1 = (g / r) + 0.5;
  5543. val2 = 1;
  5544. }
  5545. }
  5546. break;
  5547. case EMarketMode::RESOURCE_PLAYER:
  5548. val1 = 1;
  5549. val2 = 1;
  5550. break;
  5551. case EMarketMode::RESOURCE_ARTIFACT:
  5552. {
  5553. double effectiveness = std::min((getMarketEfficiency() + 3.0) / 20.0, 0.6);
  5554. double r = VLC->objh->resVals[id1], //value of offered resource
  5555. g = VLC->arth->artifacts[id2]->price / effectiveness; //value of bought artifact in gold
  5556. if(id1 != 6) //non-gold prices are doubled
  5557. r /= 2;
  5558. val1 = std::max(1, (int)((g / r) + 0.5)); //don't sell arts for less than 1 resource
  5559. val2 = 1;
  5560. }
  5561. break;
  5562. case EMarketMode::ARTIFACT_RESOURCE:
  5563. {
  5564. double effectiveness = std::min((getMarketEfficiency() + 3.0) / 20.0, 0.6);
  5565. double r = VLC->arth->artifacts[id1]->price * effectiveness,
  5566. g = VLC->objh->resVals[id2];
  5567. // if(id2 != 6) //non-gold prices are doubled
  5568. // r /= 2;
  5569. val1 = 1;
  5570. val2 = std::max(1, (int)((r / g) + 0.5)); //at least one resource is given in return
  5571. }
  5572. break;
  5573. case EMarketMode::CREATURE_EXP:
  5574. {
  5575. val1 = 1;
  5576. val2 = (VLC->creh->creatures[id1]->AIValue / 40) * 5;
  5577. }
  5578. break;
  5579. case EMarketMode::ARTIFACT_EXP:
  5580. {
  5581. val1 = 1;
  5582. int givenClass = VLC->arth->artifacts[id1]->getArtClassSerial();
  5583. if(givenClass < 0 || givenClass > 3)
  5584. {
  5585. val2 = 0;
  5586. return false;
  5587. }
  5588. static const int expPerClass[] = {1000, 1500, 3000, 6000};
  5589. val2 = expPerClass[givenClass];
  5590. }
  5591. break;
  5592. default:
  5593. assert(0);
  5594. return false;
  5595. }
  5596. return true;
  5597. }
  5598. bool IMarket::allowsTrade(EMarketMode::EMarketMode mode) const
  5599. {
  5600. return false;
  5601. }
  5602. int IMarket::availableUnits(EMarketMode::EMarketMode mode, int marketItemSerial) const
  5603. {
  5604. switch(mode)
  5605. {
  5606. case EMarketMode::RESOURCE_RESOURCE:
  5607. case EMarketMode::ARTIFACT_RESOURCE:
  5608. case EMarketMode::CREATURE_RESOURCE:
  5609. return -1;
  5610. default:
  5611. return 1;
  5612. }
  5613. }
  5614. std::vector<int> IMarket::availableItemsIds(EMarketMode::EMarketMode mode) const
  5615. {
  5616. std::vector<int> ret;
  5617. switch(mode)
  5618. {
  5619. case EMarketMode::RESOURCE_RESOURCE:
  5620. case EMarketMode::ARTIFACT_RESOURCE:
  5621. case EMarketMode::CREATURE_RESOURCE:
  5622. for (int i = 0; i < 7; i++)
  5623. ret.push_back(i);
  5624. }
  5625. return ret;
  5626. }
  5627. const IMarket * IMarket::castFrom(const CGObjectInstance *obj, bool verbose /*= true*/)
  5628. {
  5629. switch(obj->ID)
  5630. {
  5631. case Obj::TOWN:
  5632. return static_cast<const CGTownInstance*>(obj);
  5633. case Obj::ALTAR_OF_SACRIFICE:
  5634. case Obj::BLACK_MARKET:
  5635. case Obj::TRADING_POST:
  5636. case Obj::TRADING_POST_SNOW:
  5637. case Obj::FREELANCERS_GUILD:
  5638. return static_cast<const CGMarket*>(obj);
  5639. case Obj::UNIVERSITY:
  5640. return static_cast<const CGUniversity*>(obj);
  5641. default:
  5642. if(verbose)
  5643. logGlobal->errorStream() << "Cannot cast to IMarket object with ID " << obj->ID;
  5644. return nullptr;
  5645. }
  5646. }
  5647. IMarket::IMarket(const CGObjectInstance *O)
  5648. :o(O)
  5649. {
  5650. }
  5651. std::vector<EMarketMode::EMarketMode> IMarket::availableModes() const
  5652. {
  5653. std::vector<EMarketMode::EMarketMode> ret;
  5654. for (int i = 0; i < EMarketMode::MARTKET_AFTER_LAST_PLACEHOLDER; i++)
  5655. if(allowsTrade((EMarketMode::EMarketMode)i))
  5656. ret.push_back((EMarketMode::EMarketMode)i);
  5657. return ret;
  5658. }
  5659. void CGMarket::onHeroVisit(const CGHeroInstance * h) const
  5660. {
  5661. openWindow(OpenWindow::MARKET_WINDOW,id.getNum(),h->id.getNum());
  5662. }
  5663. int CGMarket::getMarketEfficiency() const
  5664. {
  5665. return 5;
  5666. }
  5667. bool CGMarket::allowsTrade(EMarketMode::EMarketMode mode) const
  5668. {
  5669. switch(mode)
  5670. {
  5671. case EMarketMode::RESOURCE_RESOURCE:
  5672. case EMarketMode::RESOURCE_PLAYER:
  5673. switch(ID)
  5674. {
  5675. case Obj::TRADING_POST:
  5676. case Obj::TRADING_POST_SNOW:
  5677. return true;
  5678. default:
  5679. return false;
  5680. }
  5681. case EMarketMode::CREATURE_RESOURCE:
  5682. return ID == Obj::FREELANCERS_GUILD;
  5683. //case ARTIFACT_RESOURCE:
  5684. case EMarketMode::RESOURCE_ARTIFACT:
  5685. return ID == Obj::BLACK_MARKET;
  5686. case EMarketMode::ARTIFACT_EXP:
  5687. case EMarketMode::CREATURE_EXP:
  5688. return ID == Obj::ALTAR_OF_SACRIFICE; //TODO? check here for alignment of visiting hero? - would not be coherent with other checks here
  5689. case EMarketMode::RESOURCE_SKILL:
  5690. return ID == Obj::UNIVERSITY;
  5691. default:
  5692. return false;
  5693. }
  5694. }
  5695. int CGMarket::availableUnits(EMarketMode::EMarketMode mode, int marketItemSerial) const
  5696. {
  5697. return -1;
  5698. }
  5699. std::vector<int> CGMarket::availableItemsIds(EMarketMode::EMarketMode mode) const
  5700. {
  5701. switch(mode)
  5702. {
  5703. case EMarketMode::RESOURCE_RESOURCE:
  5704. case EMarketMode::RESOURCE_PLAYER:
  5705. return IMarket::availableItemsIds(mode);
  5706. default:
  5707. return std::vector<int>();
  5708. }
  5709. }
  5710. CGMarket::CGMarket()
  5711. :IMarket(this)
  5712. {
  5713. }
  5714. std::vector<int> CGBlackMarket::availableItemsIds(EMarketMode::EMarketMode mode) const
  5715. {
  5716. switch(mode)
  5717. {
  5718. case EMarketMode::ARTIFACT_RESOURCE:
  5719. return IMarket::availableItemsIds(mode);
  5720. case EMarketMode::RESOURCE_ARTIFACT:
  5721. {
  5722. std::vector<int> ret;
  5723. for(const CArtifact *a : artifacts)
  5724. if(a)
  5725. ret.push_back(a->id);
  5726. else
  5727. ret.push_back(-1);
  5728. return ret;
  5729. }
  5730. default:
  5731. return std::vector<int>();
  5732. }
  5733. }
  5734. void CGBlackMarket::newTurn() const
  5735. {
  5736. if(cb->getDate(Date::DAY_OF_MONTH) != 1) //new month
  5737. return;
  5738. SetAvailableArtifacts saa;
  5739. saa.id = id.getNum();
  5740. cb->pickAllowedArtsSet(saa.arts);
  5741. cb->sendAndApply(&saa);
  5742. }
  5743. void CGUniversity::initObj()
  5744. {
  5745. std::vector<int> toChoose;
  5746. for(int i = 0; i < GameConstants::SKILL_QUANTITY; ++i)
  5747. {
  5748. if(cb->isAllowed(2, i))
  5749. {
  5750. toChoose.push_back(i);
  5751. }
  5752. }
  5753. if(toChoose.size() < 4)
  5754. {
  5755. logGlobal->warnStream()<<"Warning: less then 4 available skills was found by University initializer!";
  5756. return;
  5757. }
  5758. // get 4 skills
  5759. for(int i = 0; i < 4; ++i)
  5760. {
  5761. // move randomly one skill to selected and remove from list
  5762. auto it = RandomGeneratorUtil::nextItem(toChoose, cb->gameState()->getRandomGenerator());
  5763. skills.push_back(*it);
  5764. toChoose.erase(it);
  5765. }
  5766. }
  5767. std::vector<int> CGUniversity::availableItemsIds(EMarketMode::EMarketMode mode) const
  5768. {
  5769. switch (mode)
  5770. {
  5771. case EMarketMode::RESOURCE_SKILL:
  5772. return skills;
  5773. default:
  5774. return std::vector <int> ();
  5775. }
  5776. }
  5777. void CGUniversity::onHeroVisit(const CGHeroInstance * h) const
  5778. {
  5779. openWindow(OpenWindow::UNIVERSITY_WINDOW,id.getNum(),h->id.getNum());
  5780. }
  5781. GrowthInfo::Entry::Entry(const std::string &format, int _count)
  5782. : count(_count)
  5783. {
  5784. description = boost::str(boost::format(format) % count);
  5785. }
  5786. GrowthInfo::Entry::Entry(int subID, BuildingID building, int _count)
  5787. : count(_count)
  5788. {
  5789. description = boost::str(boost::format("%s %+d") % VLC->townh->factions[subID]->town->buildings.at(building)->Name() % count);
  5790. }
  5791. CTownAndVisitingHero::CTownAndVisitingHero()
  5792. {
  5793. setNodeType(TOWN_AND_VISITOR);
  5794. }
  5795. int GrowthInfo::totalGrowth() const
  5796. {
  5797. int ret = 0;
  5798. for(const Entry &entry : entries)
  5799. ret += entry.count;
  5800. return ret;
  5801. }