CObjectHandler.cpp 199 KB

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