CObjectHandler.cpp 200 KB

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