mob.cpp 193 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452
  1. // Copyright (c) rAthena Dev Teams - Licensed under GNU GPL
  2. // For more information, see LICENCE in the main folder
  3. #include "mob.hpp"
  4. #include <algorithm>
  5. #include <map>
  6. #include <math.h>
  7. #include <stdlib.h>
  8. #include <unordered_map>
  9. #include <vector>
  10. #include "../common/cbasetypes.hpp"
  11. #include "../common/db.hpp"
  12. #include "../common/ers.hpp"
  13. #include "../common/malloc.hpp"
  14. #include "../common/nullpo.hpp"
  15. #include "../common/random.hpp"
  16. #include "../common/showmsg.hpp"
  17. #include "../common/socket.hpp"
  18. #include "../common/strlib.hpp"
  19. #include "../common/timer.hpp"
  20. #include "../common/utilities.hpp"
  21. #include "../common/utils.hpp"
  22. #include "achievement.hpp"
  23. #include "battle.hpp"
  24. #include "clif.hpp"
  25. #include "elemental.hpp"
  26. #include "guild.hpp"
  27. #include "homunculus.hpp"
  28. #include "intif.hpp"
  29. #include "itemdb.hpp"
  30. #include "log.hpp"
  31. #include "map.hpp"
  32. #include "mercenary.hpp"
  33. #include "npc.hpp"
  34. #include "party.hpp"
  35. #include "path.hpp"
  36. #include "pc.hpp"
  37. #include "pet.hpp"
  38. #include "quest.hpp"
  39. using namespace rathena;
  40. #define ACTIVE_AI_RANGE 2 //Distance added on top of 'AREA_SIZE' at which mobs enter active AI mode.
  41. #define IDLE_SKILL_INTERVAL 10 //Active idle skills should be triggered every 1 second (1000/MIN_MOBTHINKTIME)
  42. const t_tick MOB_MAX_DELAY = 24 * 3600 * 1000;
  43. #define MAX_MINCHASE 30 //Max minimum chase value to use for mobs.
  44. #define RUDE_ATTACKED_COUNT 1 //After how many rude-attacks should the skill be used?
  45. // On official servers, monsters will only seek targets that are closer to walk to than their
  46. // search range. The search range is affected depending on if the monster is walking or not.
  47. // On some maps there can be a quite long path for just walking two cells in a direction and
  48. // the client does not support displaying walk paths that are longer than 14 cells, so this
  49. // option reduces position lag in such situation. But doing a complex search for every possible
  50. // target, might be CPU intensive.
  51. // Disable this to make monsters not do any path search when looking for a target (old behavior).
  52. #define ACTIVEPATHSEARCH
  53. // Limits for the monster database
  54. #define MIN_MOB_DB 1000
  55. #define MAX_MOB_DB 3999
  56. #define MIN_MOB_DB2 20020
  57. #define MAX_MOB_DB2 31999
  58. // These define the range of available IDs for clones. [Valaris]
  59. #define MOB_CLONE_START MAX_MOB_DB
  60. #define MOB_CLONE_END MIN_MOB_DB2
  61. // holds Monster Spawn informations
  62. std::unordered_map<uint16, std::vector<spawn_info>> mob_spawn_data;
  63. //Dynamic mob chat database
  64. std::map<short,struct mob_chat> mob_chat_db;
  65. struct mob_chat *mob_chat(short id) {
  66. return util::map_find( mob_chat_db, id );
  67. }
  68. //Dynamic item drop ratio database for per-item drop ratio modifiers overriding global drop ratios.
  69. #define MAX_ITEMRATIO_MOBS 10
  70. struct s_mob_item_drop_ratio {
  71. t_itemid nameid;
  72. int drop_ratio;
  73. unsigned short mob_id[MAX_ITEMRATIO_MOBS];
  74. };
  75. static DBMap *mob_item_drop_ratio;
  76. /// Mob skill struct for temporary storage
  77. struct s_mob_skill_db {
  78. int32 mob_id; ///< Monster ID. -1 boss types, -2 normal types, -3 all monsters
  79. std::vector<std::shared_ptr<s_mob_skill>> skill; ///< Skills
  80. };
  81. std::unordered_map<int32, std::shared_ptr<s_mob_skill_db>> mob_skill_db; /// Monster skill temporary db. s_mob_skill_db -> mobid
  82. static struct eri *item_drop_ers; //For loot drops delay structures.
  83. static struct eri *item_drop_list_ers;
  84. struct s_randomsummon_entry {
  85. uint16 mob_id;
  86. uint32 rate;
  87. };
  88. struct s_randomsummon_group {
  89. uint8 random_id;
  90. struct s_randomsummon_entry *list;
  91. uint16 count;
  92. };
  93. static DBMap *mob_summon_db; /// Random Summon DB. struct s_randomsummon_group -> group_id
  94. /*==========================================
  95. * Local prototype declaration (only required thing)
  96. *------------------------------------------*/
  97. static TIMER_FUNC(mob_spawn_guardian_sub);
  98. int mob_skill_id2skill_idx(int mob_id,uint16 skill_id);
  99. /*========================================== [Playtester]
  100. * Removes all characters that spotted the monster but are no longer online
  101. * @param md: Monster whose spotted log should be cleaned
  102. *------------------------------------------*/
  103. void mob_clean_spotted(struct mob_data *md) {
  104. int i;
  105. for (i = 0; i < DAMAGELOG_SIZE; i++) {
  106. if (md->spotted_log[i] && !map_charid2sd(md->spotted_log[i]))
  107. md->spotted_log[i] = 0;
  108. }
  109. }
  110. /*========================================== [Playtester]
  111. * Adds a char_id to the spotted log of a monster
  112. * @param md: Monster to whose spotted log char_id should be added
  113. * @param char_id: Char_id to add to the spotted log
  114. *------------------------------------------*/
  115. void mob_add_spotted(struct mob_data *md, uint32 char_id) {
  116. int i;
  117. //Check if char_id is already logged
  118. for (i = 0; i < DAMAGELOG_SIZE; i++) {
  119. if (md->spotted_log[i] == char_id)
  120. return;
  121. }
  122. //Not logged, add char_id to first empty slot
  123. for (i = 0; i < DAMAGELOG_SIZE; i++) {
  124. if (md->spotted_log[i] == 0) {
  125. md->spotted_log[i] = char_id;
  126. return;
  127. }
  128. }
  129. }
  130. /*========================================== [Playtester]
  131. * Checks if a monster was spotted
  132. * @param md: Monster to check
  133. * @return Returns true if the monster is spotted, otherwise 0
  134. *------------------------------------------*/
  135. bool mob_is_spotted(struct mob_data *md) {
  136. int i;
  137. //Check if monster is spotted
  138. for (i = 0; i < DAMAGELOG_SIZE; i++) {
  139. if (md->spotted_log[i] != 0)
  140. return true; //Spotted
  141. }
  142. return false; //Not spotted
  143. }
  144. /**
  145. * Tomb spawn time calculations
  146. * @param nd: NPC data
  147. */
  148. int mvptomb_setdelayspawn(struct npc_data *nd) {
  149. if (nd->u.tomb.spawn_timer != INVALID_TIMER)
  150. delete_timer(nd->u.tomb.spawn_timer, mvptomb_delayspawn);
  151. nd->u.tomb.spawn_timer = add_timer(gettick() + battle_config.mvp_tomb_delay, mvptomb_delayspawn, nd->bl.id, 0);
  152. return 0;
  153. }
  154. /**
  155. * Tomb spawn with delay (timer function)
  156. * @param tid: Timer ID
  157. * @param tick: Time
  158. * @param id: Block list ID
  159. * @param data: Used for add_timer_func_list
  160. */
  161. TIMER_FUNC(mvptomb_delayspawn){
  162. struct npc_data *nd = BL_CAST(BL_NPC, map_id2bl(id));
  163. if (nd) {
  164. if (nd->u.tomb.spawn_timer != tid) {
  165. ShowError("mvptomb_delayspawn: Timer mismatch: %d != %d\n", tid, nd->u.tomb.spawn_timer);
  166. return 0;
  167. }
  168. nd->u.tomb.spawn_timer = INVALID_TIMER;
  169. clif_spawn(&nd->bl);
  170. }
  171. return 0;
  172. }
  173. /**
  174. * Create and display a tombstone on the map
  175. * @param md: the mob to create a tombstone for
  176. * @param killer: name of player who killed the mob
  177. * @param time: time of mob's death
  178. * @author [GreenBox]
  179. */
  180. void mvptomb_create(struct mob_data *md, char *killer, time_t time)
  181. {
  182. struct npc_data *nd;
  183. if ( md->tomb_nid )
  184. mvptomb_destroy(md);
  185. CREATE(nd, struct npc_data, 1);
  186. nd->bl.id = md->tomb_nid = npc_get_new_npc_id();
  187. nd->ud.dir = md->ud.dir;
  188. nd->bl.m = md->bl.m;
  189. nd->bl.x = md->bl.x;
  190. nd->bl.y = md->bl.y;
  191. nd->bl.type = BL_NPC;
  192. safestrncpy(nd->name, msg_txt(NULL,656), sizeof(nd->name));
  193. nd->class_ = 565;
  194. nd->speed = 200;
  195. nd->subtype = NPCTYPE_TOMB;
  196. nd->u.tomb.md = md;
  197. nd->u.tomb.kill_time = time;
  198. nd->u.tomb.spawn_timer = INVALID_TIMER;
  199. if (killer)
  200. safestrncpy(nd->u.tomb.killer_name, killer, NAME_LENGTH);
  201. else
  202. nd->u.tomb.killer_name[0] = '\0';
  203. map_addnpc(nd->bl.m, nd);
  204. if(map_addblock(&nd->bl))
  205. return;
  206. status_set_viewdata(&nd->bl, nd->class_);
  207. status_change_init(&nd->bl);
  208. unit_dataset(&nd->bl);
  209. mvptomb_setdelayspawn(nd);
  210. }
  211. /**
  212. * Destroys MVP Tomb
  213. * @param md: Mob data
  214. */
  215. void mvptomb_destroy(struct mob_data *md) {
  216. struct npc_data *nd;
  217. if ( (nd = map_id2nd(md->tomb_nid)) ) {
  218. int16 i;
  219. struct map_data *mapdata = map_getmapdata(nd->bl.m);
  220. clif_clearunit_area(&nd->bl,CLR_OUTSIGHT);
  221. map_delblock(&nd->bl);
  222. ARR_FIND( 0, mapdata->npc_num, i, mapdata->npc[i] == nd );
  223. if( !(i == mapdata->npc_num) ) {
  224. mapdata->npc_num--;
  225. mapdata->npc[i] = mapdata->npc[mapdata->npc_num];
  226. mapdata->npc[mapdata->npc_num] = NULL;
  227. }
  228. map_deliddb(&nd->bl);
  229. aFree(nd);
  230. }
  231. md->tomb_nid = 0;
  232. }
  233. /**
  234. * Sub function for mob namesearch. Here is defined which are accepted.
  235. */
  236. static bool mobdb_searchname_sub(uint16 mob_id, const char * const str, bool full_cmp)
  237. {
  238. std::shared_ptr<s_mob_db> mob = mob_db.find(mob_id);
  239. if (mob == nullptr)
  240. return false;
  241. if( mobdb_checkid(mob_id) <= 0 )
  242. return false; // invalid mob_id (includes clone check)
  243. if(!mob->base_exp && !mob->job_exp && !mob_has_spawn(mob_id))
  244. return false; // Monsters with no base/job exp and no spawn point are, by this criteria, considered "slave mobs" and excluded from search results
  245. if( full_cmp ) {
  246. // str must equal the db value
  247. if( strcmpi(mob->name.c_str(), str) == 0 ||
  248. strcmpi(mob->jname.c_str(), str) == 0 ||
  249. strcmpi(mob->sprite.c_str(), str) == 0 )
  250. return true;
  251. } else {
  252. // str must be in the db value
  253. if( stristr(mob->name.c_str(), str) != NULL ||
  254. stristr(mob->jname.c_str(), str) != NULL ||
  255. stristr(mob->sprite.c_str(), str) != NULL )
  256. return true;
  257. }
  258. return false;
  259. }
  260. /**
  261. * Searches for the Mobname
  262. */
  263. uint16 mobdb_searchname_(const char * const str, bool full_cmp)
  264. {
  265. for( auto const &mobdb_pair : mob_db ) {
  266. const uint16 mob_id = mobdb_pair.first;
  267. if( mobdb_searchname_sub(mob_id, str, full_cmp) )
  268. return mob_id;
  269. }
  270. return 0;
  271. }
  272. uint16 mobdb_searchname(const char * const str)
  273. {
  274. return mobdb_searchname_(str, true);
  275. }
  276. std::shared_ptr<s_mob_db> mobdb_search_aegisname( const char* str ){
  277. for( auto &mobdb_pair : mob_db ){
  278. if( strcmpi( str, mobdb_pair.second->sprite.c_str() ) == 0 ){
  279. return mobdb_pair.second;
  280. }
  281. }
  282. return nullptr;
  283. }
  284. /*==========================================
  285. * Founds up to N matches. Returns number of matches [Skotlex]
  286. *------------------------------------------*/
  287. int mobdb_searchname_array_(const char *str, uint16 * out, int size, bool full_cmp)
  288. {
  289. unsigned short count = 0;
  290. for( auto const &mobdb_pair : mob_db ) {
  291. const uint16 mob_id = mobdb_pair.first;
  292. if( mobdb_searchname_sub(mob_id, str, full_cmp) ) {
  293. if( count < size )
  294. out[count] = mob_id;
  295. count++;
  296. }
  297. }
  298. return count;
  299. }
  300. int mobdb_searchname_array(const char *str, uint16 * out, int size)
  301. {
  302. return mobdb_searchname_array_(str, out, size, false);
  303. }
  304. /*==========================================
  305. * Id Mob is checked.
  306. *------------------------------------------*/
  307. int mobdb_checkid(const int id)
  308. {
  309. if (!mob_db.exists(id))
  310. return 0;
  311. if (mob_is_clone(id)) //checkid is used mostly for random ID based code, therefore clone mobs are out of the question.
  312. return 0;
  313. return id;
  314. }
  315. /*==========================================
  316. * Returns the view data associated to this mob class.
  317. *------------------------------------------*/
  318. struct view_data * mob_get_viewdata(int mob_id)
  319. {
  320. std::shared_ptr<s_mob_db> db = mob_db.find(mob_id);
  321. if (db == nullptr)
  322. return nullptr;
  323. return &db->vd;
  324. }
  325. e_mob_bosstype s_mob_db::get_bosstype(){
  326. if( status_has_mode( &this->status, MD_MVP ) ){
  327. return BOSSTYPE_MVP;
  328. }else if( this->status.class_ == CLASS_BOSS ){
  329. return BOSSTYPE_MINIBOSS;
  330. }else{
  331. return BOSSTYPE_NONE;
  332. }
  333. }
  334. e_mob_bosstype mob_data::get_bosstype(){
  335. if( this->db != nullptr ){
  336. return this->db->get_bosstype();
  337. }else{
  338. return BOSSTYPE_NONE;
  339. }
  340. }
  341. /**
  342. * Create unique view data associated to a spawned monster.
  343. * @param md: Mob to adjust
  344. */
  345. void mob_set_dynamic_viewdata( struct mob_data* md ){
  346. // If it is a valid monster and it has not already been created
  347. if( md && !md->vd_changed ){
  348. // Allocate a dynamic entry
  349. struct view_data* vd = (struct view_data*)aMalloc( sizeof( struct view_data ) );
  350. // Copy the current values
  351. memcpy( vd, md->vd, sizeof( struct view_data ) );
  352. // Update the pointer to the new entry
  353. md->vd = vd;
  354. // Flag it as changed so it is freed later on
  355. md->vd_changed = true;
  356. }
  357. }
  358. /**
  359. * Free any view data associated to a spawned monster.
  360. * @param md: Mob to free
  361. */
  362. void mob_free_dynamic_viewdata( struct mob_data* md ){
  363. // If it is a valid monster and it has already been allocated
  364. if( md && md->vd_changed ){
  365. // Free it
  366. aFree( md->vd );
  367. // Remove the reference
  368. md->vd = NULL;
  369. // Unflag it as changed
  370. md->vd_changed = false;
  371. }
  372. }
  373. /*==========================================
  374. * Cleans up mob-spawn data to make it "valid"
  375. *------------------------------------------*/
  376. int mob_parse_dataset(struct spawn_data *data)
  377. {
  378. size_t len;
  379. if ((!mobdb_checkid(data->id) && !mob_is_clone(data->id)) || !data->num)
  380. return 0;
  381. if( ( len = strlen(data->eventname) ) > 0 )
  382. {
  383. if( data->eventname[len-1] == '"' )
  384. data->eventname[len-1] = '\0'; //Remove trailing quote.
  385. if( data->eventname[0] == '"' ) //Strip leading quotes
  386. memmove(data->eventname, data->eventname+1, len-1);
  387. }
  388. if(strcmp(data->name,"--en--")==0)
  389. safestrncpy(data->name, mob_db.find(data->id)->name.c_str(), sizeof(data->name));
  390. else if(strcmp(data->name,"--ja--")==0)
  391. safestrncpy(data->name, mob_db.find(data->id)->jname.c_str(), sizeof(data->name));
  392. return 1;
  393. }
  394. /*==========================================
  395. * Generates the basic mob data using the spawn_data provided.
  396. *------------------------------------------*/
  397. struct mob_data* mob_spawn_dataset(struct spawn_data *data)
  398. {
  399. struct mob_data *md = (struct mob_data*)aCalloc(1, sizeof(struct mob_data));
  400. md->bl.id= npc_get_new_npc_id();
  401. md->bl.type = BL_MOB;
  402. md->bl.m = data->m;
  403. md->bl.x = data->x;
  404. md->bl.y = data->y;
  405. md->mob_id = data->id;
  406. md->state.boss = data->state.boss;
  407. md->db = mob_db.find(md->mob_id);
  408. if (data->level > 0 && data->level <= MAX_LEVEL)
  409. md->level = data->level;
  410. memcpy(md->name, data->name, NAME_LENGTH);
  411. if (data->state.ai)
  412. md->special_state.ai = data->state.ai;
  413. if (data->state.size)
  414. md->special_state.size = data->state.size;
  415. if (data->eventname[0] && strlen(data->eventname) >= 4)
  416. safestrncpy(md->npc_event, data->eventname, EVENT_NAME_LENGTH);
  417. if(status_has_mode(&md->db->status,MD_LOOTER))
  418. md->lootitems = (struct s_mob_lootitem *)aCalloc(LOOTITEM_SIZE,sizeof(struct s_mob_lootitem));
  419. md->spawn_timer = INVALID_TIMER;
  420. md->deletetimer = INVALID_TIMER;
  421. md->skill_idx = -1;
  422. status_set_viewdata(&md->bl, md->mob_id);
  423. status_change_init(&md->bl);
  424. unit_dataset(&md->bl);
  425. map_addiddb(&md->bl);
  426. return md;
  427. }
  428. /*==========================================
  429. * Fetches a random mob_id [Skotlex]
  430. * type: Where to fetch from (see enum e_random_monster)
  431. * flag: Type of checks to apply (see enum e_random_monster_flags)
  432. * lv: Mob level to check against
  433. *------------------------------------------*/
  434. int mob_get_random_id(int type, enum e_random_monster_flags flag, int lv)
  435. {
  436. struct s_randomsummon_group *msummon = (struct s_randomsummon_group *)idb_get(mob_summon_db, type);
  437. if (type == MOBG_Bloody_Dead_Branch && flag&RMF_MOB_NOT_BOSS)
  438. flag = static_cast<e_random_monster_flags>(flag&~RMF_MOB_NOT_BOSS);
  439. if (!msummon) {
  440. ShowError("mob_get_random_id: Invalid type (%d) of random monster.\n", type);
  441. return 0;
  442. }
  443. if (!msummon->count) {
  444. ShowError("mob_get_random_id: Random monster type %d is not defined.\n", type);
  445. return 0;
  446. }
  447. std::shared_ptr<s_mob_db> mob;
  448. int i = 0, mob_id = 0, rand = 0;
  449. struct s_randomsummon_entry *entry = nullptr;
  450. do {
  451. rand = rnd()%msummon->count;
  452. entry = &msummon->list[rand];
  453. mob_id = entry->mob_id;
  454. mob = mob_db.find(mob_id);
  455. } while ((rand == 0 || // Skip default first
  456. mob == nullptr ||
  457. mob_is_clone(mob_id) ||
  458. (flag&RMF_DB_RATE && (entry->rate < 1000000 && entry->rate <= rnd() % 1000000)) ||
  459. (flag&RMF_CHECK_MOB_LV && lv < mob->lv) ||
  460. (flag&RMF_MOB_NOT_BOSS && status_has_mode(&mob->status,MD_STATUSIMMUNE) ) ||
  461. (flag&RMF_MOB_NOT_SPAWN && !mob_has_spawn(mob_id)) ||
  462. (flag&RMF_MOB_NOT_PLANT && status_has_mode(&mob->status,MD_IGNOREMELEE|MD_IGNOREMAGIC|MD_IGNORERANGED|MD_IGNOREMISC) )
  463. ) && (i++) < MAX_MOB_DB && msummon->count > 1);
  464. if (i >= MAX_MOB_DB && &msummon->list[0]) {
  465. ShowError("mob_get_random_id: no suitable monster found, use fallback for given list. Last_MobID: %d\n", mob_id);
  466. mob_id = msummon->list[0].mob_id;
  467. }
  468. return mob_id;
  469. }
  470. /*==========================================
  471. * Kill Steal Protection [Zephyrus]
  472. *------------------------------------------*/
  473. bool mob_ksprotected (struct block_list *src, struct block_list *target)
  474. {
  475. struct block_list *s_bl, *t_bl;
  476. struct map_session_data
  477. *sd, // Source
  478. *t_sd; // Mob Target
  479. struct mob_data *md;
  480. t_tick tick = gettick();
  481. if( !battle_config.ksprotection )
  482. return false; // KS Protection Disabled
  483. if( !(md = BL_CAST(BL_MOB,target)) )
  484. return false; // Tarjet is not MOB
  485. if( (s_bl = battle_get_master(src)) == nullptr )
  486. s_bl = src;
  487. if( !(sd = BL_CAST(BL_PC,s_bl)) )
  488. return false; // Master is not PC
  489. t_bl = map_id2bl(md->target_id);
  490. if( !t_bl || (s_bl = battle_get_master(t_bl)) == nullptr )
  491. s_bl = t_bl;
  492. t_sd = BL_CAST(BL_PC,s_bl);
  493. do {
  494. struct status_change_entry *sce;
  495. struct map_session_data *pl_sd; // Owner
  496. struct map_data *mapdata = map_getmapdata(md->bl.m);
  497. char output[128];
  498. if( mapdata->flag[MF_ALLOWKS] || mapdata_flag_ks(mapdata) )
  499. return false; // Ignores GVG, PVP and AllowKS map flags
  500. if( md->get_bosstype() == BOSSTYPE_MVP || md->master_id )
  501. return false; // MVP, Slaves mobs ignores KS
  502. if( (sce = md->sc.data[SC_KSPROTECTED]) == nullptr )
  503. break; // No KS Protected
  504. if( sd->bl.id == sce->val1 || // Same Owner
  505. (sce->val2 == 2 && sd->status.party_id && sd->status.party_id == sce->val3) || // Party KS allowed
  506. (sce->val2 == 3 && sd->status.guild_id && sd->status.guild_id == sce->val4) ) // Guild KS allowed
  507. break;
  508. if( t_sd && (
  509. (sce->val2 == 1 && sce->val1 != t_sd->bl.id) ||
  510. (sce->val2 == 2 && sce->val3 && sce->val3 != t_sd->status.party_id) ||
  511. (sce->val2 == 3 && sce->val4 && sce->val4 != t_sd->status.guild_id)) )
  512. break;
  513. if( (pl_sd = map_id2sd(sce->val1)) == NULL || pl_sd->bl.m != md->bl.m )
  514. break;
  515. if( !pl_sd->state.noks )
  516. return false; // No KS Protected, but normal players should be protected too
  517. // Message to KS
  518. if( DIFF_TICK(sd->ks_floodprotect_tick, tick) <= 0 )
  519. {
  520. sprintf(output, "[KS Warning!! - Owner : %s]", pl_sd->status.name);
  521. clif_messagecolor(&sd->bl, color_table[COLOR_LIGHT_GREEN], output, false, SELF);
  522. sd->ks_floodprotect_tick = tick + 2000;
  523. }
  524. // Message to Owner
  525. if( DIFF_TICK(pl_sd->ks_floodprotect_tick, tick) <= 0 )
  526. {
  527. sprintf(output, "[Watch out! %s is trying to KS you!]", sd->status.name);
  528. clif_messagecolor(&pl_sd->bl, color_table[COLOR_LIGHT_GREEN], output, false, SELF);
  529. pl_sd->ks_floodprotect_tick = tick + 2000;
  530. }
  531. return true;
  532. } while(0);
  533. status_change_start(src, target, SC_KSPROTECTED, 10000, sd->bl.id, sd->state.noks, sd->status.party_id, sd->status.guild_id, battle_config.ksprotection, SCSTART_NOAVOID);
  534. return false;
  535. }
  536. struct mob_data *mob_once_spawn_sub(struct block_list *bl, int16 m, int16 x, int16 y, const char *mobname, int mob_id, const char *event, unsigned int size, enum mob_ai ai)
  537. {
  538. struct spawn_data data;
  539. memset(&data, 0, sizeof(struct spawn_data)); //why ? this might screw attribute object and cause leak..
  540. data.m = m;
  541. data.num = 1;
  542. data.id = mob_id;
  543. data.state.size = size;
  544. data.state.ai = ai;
  545. if (mobname)
  546. safestrncpy(data.name, mobname, sizeof(data.name));
  547. else
  548. if (battle_config.override_mob_names == 1)
  549. strcpy(data.name, "--en--");
  550. else
  551. strcpy(data.name, "--ja--");
  552. if (event)
  553. safestrncpy(data.eventname, event, sizeof(data.eventname));
  554. // Locate spot next to player.
  555. if (bl && (x < 0 || y < 0))
  556. map_search_freecell(bl, m, &x, &y, 1, 1, 0);
  557. struct map_data *mapdata = map_getmapdata(m);
  558. // if none found, pick random position on map
  559. if (x <= 0 || x >= mapdata->xs || y <= 0 || y >= mapdata->ys)
  560. map_search_freecell(NULL, m, &x, &y, -1, -1, 1);
  561. data.x = x;
  562. data.y = y;
  563. if (!mob_parse_dataset(&data))
  564. return nullptr;
  565. return mob_spawn_dataset(&data);
  566. }
  567. /*==========================================
  568. * Spawn a single mob on the specified coordinates.
  569. *------------------------------------------*/
  570. int mob_once_spawn(struct map_session_data* sd, int16 m, int16 x, int16 y, const char* mobname, int mob_id, int amount, const char* event, unsigned int size, enum mob_ai ai)
  571. {
  572. struct mob_data* md = nullptr;
  573. int count, lv;
  574. if (m < 0 || amount <= 0)
  575. return 0; // invalid input
  576. lv = (sd) ? sd->status.base_level : 255;
  577. for (count = 0; count < amount; count++)
  578. {
  579. int c = (mob_id >= 0) ? mob_id : mob_get_random_id(-mob_id - 1, (battle_config.random_monster_checklv) ? static_cast<e_random_monster_flags>(RMF_DB_RATE|RMF_CHECK_MOB_LV) : RMF_DB_RATE, lv);
  580. md = mob_once_spawn_sub((sd) ? &sd->bl : NULL, m, x, y, mobname, c, event, size, ai);
  581. if (!md)
  582. continue;
  583. if (mob_id == MOBID_EMPERIUM)
  584. {
  585. struct guild_castle* gc = guild_mapindex2gc(map_getmapdata(m)->index);
  586. struct guild* g = (gc) ? guild_search(gc->guild_id) : nullptr;
  587. if (gc)
  588. {
  589. md->guardian_data = (struct guardian_data*)aCalloc(1, sizeof(struct guardian_data));
  590. md->guardian_data->castle = gc;
  591. md->guardian_data->number = MAX_GUARDIANS;
  592. md->guardian_data->guild_id = gc->guild_id;
  593. if (g)
  594. {
  595. md->guardian_data->emblem_id = g->emblem_id;
  596. memcpy(md->guardian_data->guild_name, g->name, NAME_LENGTH);
  597. }
  598. else if (gc->guild_id) //Guild not yet available, retry in 5.
  599. add_timer(gettick()+5000,mob_spawn_guardian_sub,md->bl.id,md->guardian_data->guild_id);
  600. }
  601. } // end addition [Valaris]
  602. mob_spawn(md);
  603. if (mob_id < 0 && battle_config.dead_branch_active)
  604. //Behold Aegis's masterful decisions yet again...
  605. //"I understand the "Aggressive" part, but the "Can Move" and "Can Attack" is just stupid" - Poki#3
  606. sc_start4(NULL,&md->bl, SC_MODECHANGE, 100, 1, 0, MD_AGGRESSIVE|MD_CANATTACK|MD_CANMOVE|MD_ANGRY, 0, 60000);
  607. }
  608. return (md) ? md->bl.id : 0; // id of last spawned mob
  609. }
  610. /*==========================================
  611. * Spawn mobs in the specified area.
  612. *------------------------------------------*/
  613. int mob_once_spawn_area(struct map_session_data* sd, int16 m, int16 x0, int16 y0, int16 x1, int16 y1, const char* mobname, int mob_id, int amount, const char* event, unsigned int size, enum mob_ai ai)
  614. {
  615. int i, max, id = 0;
  616. int lx = -1, ly = -1;
  617. if (m < 0 || amount <= 0)
  618. return 0; // invalid input
  619. // normalize x/y coordinates
  620. if (x0 > x1)
  621. SWAP(x0, x1);
  622. if (y0 > y1)
  623. SWAP(y0, y1);
  624. // choose a suitable max. number of attempts
  625. max = (y1 - y0 + 1)*(x1 - x0 + 1)*3;
  626. if (max > 1000)
  627. max = 1000;
  628. // spawn mobs, one by one
  629. for (i = 0; i < amount; i++)
  630. {
  631. int x, y;
  632. int j = 0;
  633. // find a suitable map cell
  634. do {
  635. x = rnd()%(x1-x0+1)+x0;
  636. y = rnd()%(y1-y0+1)+y0;
  637. j++;
  638. } while (map_getcell(m,x,y,CELL_CHKNOPASS) && j < max);
  639. if (j == max)
  640. {// attempt to find an available cell failed
  641. if (lx == -1 && ly == -1)
  642. return 0; // total failure
  643. // fallback to last good x/y pair
  644. x = lx;
  645. y = ly;
  646. }
  647. // record last successful coordinates
  648. lx = x;
  649. ly = y;
  650. id = mob_once_spawn(sd, m, x, y, mobname, mob_id, 1, event, size, ai);
  651. }
  652. return id; // id of last spawned mob
  653. }
  654. /*==========================================
  655. * Set a Guardian's guild data [Skotlex]
  656. *------------------------------------------*/
  657. static TIMER_FUNC(mob_spawn_guardian_sub){
  658. //Needed because the guild_data may not be available at guardian spawn time.
  659. struct block_list* bl = map_id2bl(id);
  660. struct mob_data* md;
  661. struct guild* g;
  662. int guardup_lv;
  663. if (bl == nullptr) //It is possible mob was already removed from map when the castle has no owner. [Skotlex]
  664. return 0;
  665. if (bl->type != BL_MOB)
  666. {
  667. ShowError("mob_spawn_guardian_sub: Block error!\n");
  668. return 0;
  669. }
  670. md = (struct mob_data*)bl;
  671. nullpo_ret(md->guardian_data);
  672. g = guild_search((int)data);
  673. if (g == nullptr)
  674. { //Liberate castle, if the guild is not found this is an error! [Skotlex]
  675. ShowError("mob_spawn_guardian_sub: Couldn't load guild %d!\n", (int)data);
  676. if (md->mob_id == MOBID_EMPERIUM)
  677. { //Not sure this is the best way, but otherwise we'd be invoking this for ALL guardians spawned later on.
  678. md->guardian_data->guild_id = 0;
  679. if (md->guardian_data->castle->guild_id) //Free castle up.
  680. {
  681. ShowNotice("Clearing ownership of castle %d (%s)\n", md->guardian_data->castle->castle_id, md->guardian_data->castle->castle_name);
  682. guild_castledatasave(md->guardian_data->castle->castle_id, CD_GUILD_ID, 0);
  683. }
  684. } else {
  685. if (md->guardian_data->number >= 0 && md->guardian_data->number < MAX_GUARDIANS && md->guardian_data->castle->guardian[md->guardian_data->number].visible)
  686. guild_castledatasave(md->guardian_data->castle->castle_id, CD_ENABLED_GUARDIAN00 + md->guardian_data->number,0);
  687. unit_free(&md->bl,CLR_OUTSIGHT); //Remove guardian.
  688. }
  689. return 0;
  690. }
  691. guardup_lv = guild_checkskill(g,GD_GUARDUP);
  692. md->guardian_data->emblem_id = g->emblem_id;
  693. memcpy(md->guardian_data->guild_name, g->name, NAME_LENGTH);
  694. md->guardian_data->guardup_lv = guardup_lv;
  695. if( guardup_lv )
  696. status_calc_mob(md, SCO_NONE); //Give bonuses.
  697. return 0;
  698. }
  699. /*==========================================
  700. * Summoning Guardians [Valaris]
  701. *------------------------------------------*/
  702. int mob_spawn_guardian(const char* mapname, int16 x, int16 y, const char* mobname, int mob_id, const char* event, int guardian, bool has_index)
  703. {
  704. struct mob_data *md=nullptr;
  705. struct spawn_data data;
  706. struct guild *g=nullptr;
  707. struct guild_castle *gc;
  708. int16 m;
  709. memset(&data, 0, sizeof(struct spawn_data)); //fixme
  710. data.num = 1;
  711. m=map_mapname2mapid(mapname);
  712. if(m<0)
  713. {
  714. ShowWarning("mob_spawn_guardian: Map [%s] not found.\n", mapname);
  715. return 0;
  716. }
  717. data.m = m;
  718. data.num = 1;
  719. if(mob_id<=0) {
  720. mob_id = mob_get_random_id(-mob_id-1, RMF_DB_RATE, 0);
  721. if (!mob_id) return 0;
  722. }
  723. data.id = mob_id;
  724. if( !has_index )
  725. {
  726. guardian = -1;
  727. }
  728. else if( guardian < 0 || guardian >= MAX_GUARDIANS )
  729. {
  730. ShowError("mob_spawn_guardian: Invalid guardian index %d for guardian %d (castle map %s)\n", guardian, mob_id, mapname);
  731. return 0;
  732. }
  733. if((x<=0 || y<=0) && !map_search_freecell(NULL, m, &x, &y, -1,-1, 1))
  734. {
  735. ShowWarning("mob_spawn_guardian: Couldn't locate a spawn cell for guardian class %d (index %d) at castle map %s\n",mob_id, guardian, mapname);
  736. return 0;
  737. }
  738. data.x = x;
  739. data.y = y;
  740. safestrncpy(data.name, mobname, sizeof(data.name));
  741. safestrncpy(data.eventname, event, sizeof(data.eventname));
  742. if (!mob_parse_dataset(&data))
  743. return 0;
  744. gc=guild_mapname2gc(mapname);
  745. if (gc == NULL)
  746. {
  747. ShowError("mob_spawn_guardian: No castle set at map %s\n", mapname);
  748. return 0;
  749. }
  750. if (!gc->guild_id)
  751. ShowWarning("mob_spawn_guardian: Spawning guardian %d on a castle with no guild (castle map %s)\n", mob_id, mapname);
  752. else
  753. g = guild_search(gc->guild_id);
  754. if( has_index && gc->guardian[guardian].id )
  755. { //Check if guardian already exists, refuse to spawn if so.
  756. struct mob_data *md2 = (TBL_MOB*)map_id2bl(gc->guardian[guardian].id);
  757. if (md2 && md2->bl.type == BL_MOB &&
  758. md2->guardian_data && md2->guardian_data->number == guardian)
  759. {
  760. ShowError("mob_spawn_guardian: Attempted to spawn guardian in position %d which already has a guardian (castle map %s)\n", guardian, mapname);
  761. return 0;
  762. }
  763. }
  764. md = mob_spawn_dataset(&data);
  765. md->guardian_data = (struct guardian_data*)aCalloc(1, sizeof(struct guardian_data));
  766. md->guardian_data->number = guardian;
  767. md->guardian_data->guild_id = gc->guild_id;
  768. md->guardian_data->castle = gc;
  769. if( has_index )
  770. {// permanent guardian
  771. gc->guardian[guardian].id = md->bl.id;
  772. }
  773. else
  774. {// temporary guardian
  775. int i;
  776. ARR_FIND(0, gc->temp_guardians_max, i, gc->temp_guardians[i] == 0);
  777. if( i == gc->temp_guardians_max )
  778. {
  779. ++(gc->temp_guardians_max);
  780. RECREATE(gc->temp_guardians, int, gc->temp_guardians_max);
  781. }
  782. gc->temp_guardians[i] = md->bl.id;
  783. }
  784. if (g)
  785. {
  786. md->guardian_data->emblem_id = g->emblem_id;
  787. memcpy (md->guardian_data->guild_name, g->name, NAME_LENGTH);
  788. md->guardian_data->guardup_lv = guild_checkskill(g,GD_GUARDUP);
  789. } else if (md->guardian_data->guild_id)
  790. add_timer(gettick()+5000,mob_spawn_guardian_sub,md->bl.id,md->guardian_data->guild_id);
  791. mob_spawn(md);
  792. return md->bl.id;
  793. }
  794. /*==========================================
  795. * Summoning BattleGround [Zephyrus]
  796. *------------------------------------------*/
  797. int mob_spawn_bg(const char* mapname, int16 x, int16 y, const char* mobname, int mob_id, const char* event, unsigned int bg_id)
  798. {
  799. struct mob_data *md = nullptr;
  800. struct spawn_data data;
  801. int16 m;
  802. if( (m = map_mapname2mapid(mapname)) < 0 )
  803. {
  804. ShowWarning("mob_spawn_bg: Map [%s] not found.\n", mapname);
  805. return 0;
  806. }
  807. memset(&data, 0, sizeof(struct spawn_data));
  808. data.m = m;
  809. data.num = 1;
  810. if( mob_id <= 0 )
  811. {
  812. mob_id = mob_get_random_id(-mob_id-1, RMF_DB_RATE, 0);
  813. if( !mob_id ) return 0;
  814. }
  815. data.id = mob_id;
  816. if( (x <= 0 || y <= 0) && !map_search_freecell(NULL, m, &x, &y, -1,-1, 1) )
  817. {
  818. ShowWarning("mob_spawn_bg: Couldn't locate a spawn cell for guardian class %d (bg_id %d) at map %s\n",mob_id, bg_id, mapname);
  819. return 0;
  820. }
  821. data.x = x;
  822. data.y = y;
  823. safestrncpy(data.name, mobname, sizeof(data.name));
  824. safestrncpy(data.eventname, event, sizeof(data.eventname));
  825. if( !mob_parse_dataset(&data) )
  826. return 0;
  827. md = mob_spawn_dataset(&data);
  828. mob_spawn(md);
  829. md->bg_id = bg_id; // BG Team ID
  830. return md->bl.id;
  831. }
  832. /*==========================================
  833. * Reachability to a Specification ID existence place
  834. * state indicates type of 'seek' mob should do:
  835. * - MSS_LOOT: Looking for item, path must be easy.
  836. * - MSS_RUSH: Chasing attacking player, path is complex
  837. * - MSS_FOLLOW: Initiative/support seek, path is complex
  838. *------------------------------------------*/
  839. int mob_can_reach(struct mob_data *md,struct block_list *bl,int range, int state)
  840. {
  841. int easy = 0;
  842. nullpo_ret(md);
  843. nullpo_ret(bl);
  844. switch (state) {
  845. case MSS_RUSH:
  846. case MSS_FOLLOW:
  847. easy = 0; //(battle_config.mob_ai&0x1?0:1);
  848. break;
  849. case MSS_LOOT:
  850. default:
  851. easy = 1;
  852. break;
  853. }
  854. return unit_can_reach_bl(&md->bl, bl, range, easy, NULL, NULL);
  855. }
  856. /*==========================================
  857. * Links nearby mobs (supportive mobs)
  858. *------------------------------------------*/
  859. int mob_linksearch(struct block_list *bl,va_list ap)
  860. {
  861. struct mob_data *md;
  862. int mob_id;
  863. struct block_list *target;
  864. t_tick tick;
  865. nullpo_ret(bl);
  866. md=(struct mob_data *)bl;
  867. mob_id = va_arg(ap, int);
  868. target = va_arg(ap, struct block_list *);
  869. tick=va_arg(ap, t_tick);
  870. if (md->mob_id == mob_id && status_has_mode(&md->status,MD_ASSIST) && DIFF_TICK(md->last_linktime, tick) < MIN_MOBLINKTIME
  871. && !md->target_id)
  872. {
  873. md->last_linktime = tick;
  874. if( mob_can_reach(md,target,md->db->range2, MSS_FOLLOW) ){ // Reachability judging
  875. md->target_id = target->id;
  876. md->min_chase=md->db->range3;
  877. return 1;
  878. }
  879. }
  880. return 0;
  881. }
  882. /*==========================================
  883. * mob spawn with delay (timer function)
  884. *------------------------------------------*/
  885. TIMER_FUNC(mob_delayspawn){
  886. struct block_list* bl = map_id2bl(id);
  887. struct mob_data* md = BL_CAST(BL_MOB, bl);
  888. if( md )
  889. {
  890. if( md->spawn_timer != tid )
  891. {
  892. ShowError("mob_delayspawn: Timer mismatch: %d != %d\n", tid, md->spawn_timer);
  893. return 0;
  894. }
  895. md->spawn_timer = INVALID_TIMER;
  896. mob_spawn(md);
  897. }
  898. return 0;
  899. }
  900. /*==========================================
  901. * spawn timing calculation
  902. *------------------------------------------*/
  903. int mob_setdelayspawn(struct mob_data *md)
  904. {
  905. unsigned int spawntime;
  906. if (!md->spawn) //Doesn't has respawn data!
  907. return unit_free(&md->bl,CLR_DEAD);
  908. spawntime = md->spawn->delay1; //Base respawn time
  909. if (md->spawn->delay2) //random variance
  910. spawntime+= rnd()%md->spawn->delay2;
  911. //Apply the spawn delay fix [Skotlex]
  912. std::shared_ptr<s_mob_db> db = mob_db.find(md->spawn->id);
  913. if (status_has_mode(&db->status,MD_STATUSIMMUNE)) { // Status Immune
  914. if (battle_config.boss_spawn_delay != 100) {
  915. // Divide by 100 first to prevent overflows
  916. //(precision loss is minimal as duration is in ms already)
  917. spawntime = spawntime/100*battle_config.boss_spawn_delay;
  918. }
  919. } else if (status_has_mode(&db->status,MD_IGNOREMELEE|MD_IGNOREMAGIC|MD_IGNORERANGED|MD_IGNOREMISC)) { // Plant type
  920. if (battle_config.plant_spawn_delay != 100) {
  921. spawntime = spawntime/100*battle_config.plant_spawn_delay;
  922. }
  923. } else if (battle_config.mob_spawn_delay != 100) { //Normal mobs
  924. spawntime = spawntime/100*battle_config.mob_spawn_delay;
  925. }
  926. if (spawntime < 5000) //Monsters should never respawn faster than within 5 seconds
  927. spawntime = 5000;
  928. if( md->spawn_timer != INVALID_TIMER )
  929. delete_timer(md->spawn_timer, mob_delayspawn);
  930. md->spawn_timer = add_timer(gettick()+spawntime, mob_delayspawn, md->bl.id, 0);
  931. return 0;
  932. }
  933. int mob_count_sub(struct block_list *bl, va_list ap) {
  934. int mobid[10], i;
  935. ARR_FIND(0, 10, i, (mobid[i] = va_arg(ap, int)) == 0); //fetch till 0
  936. if (mobid[0]) { //if there one let's check it otherwise go backward
  937. TBL_MOB *md = BL_CAST(BL_MOB, bl);
  938. ARR_FIND(0, 10, i, md->mob_id == mobid[i]);
  939. return (i < 10) ? 1 : 0;
  940. }
  941. return 1; //backward compatibility
  942. }
  943. /**
  944. * Mob spawning. Initialization is also variously here. (Spawn a mob in a map)
  945. * @param md : mob data to spawn
  946. * @return 0:spawned, 1:delayed, 2:error
  947. */
  948. int mob_spawn (struct mob_data *md)
  949. {
  950. int i=0;
  951. t_tick tick = gettick();
  952. md->last_thinktime = tick;
  953. if (md->bl.prev != NULL)
  954. unit_remove_map(&md->bl,CLR_RESPAWN);
  955. else
  956. if (md->spawn && md->mob_id != md->spawn->id)
  957. {
  958. md->mob_id = md->spawn->id;
  959. status_set_viewdata(&md->bl, md->mob_id);
  960. md->db = mob_db.find(md->mob_id);
  961. memcpy(md->name,md->spawn->name,NAME_LENGTH);
  962. }
  963. if (md->spawn) { //Respawn data
  964. md->bl.m = md->spawn->m;
  965. md->bl.x = md->spawn->x;
  966. md->bl.y = md->spawn->y;
  967. if( (md->bl.x == 0 && md->bl.y == 0) || md->spawn->xs || md->spawn->ys )
  968. { //Monster can be spawned on an area.
  969. if( !map_search_freecell(&md->bl, -1, &md->bl.x, &md->bl.y, md->spawn->xs, md->spawn->ys, battle_config.no_spawn_on_player?4:0) )
  970. { // retry again later
  971. if( md->spawn_timer != INVALID_TIMER )
  972. delete_timer(md->spawn_timer, mob_delayspawn);
  973. md->spawn_timer = add_timer(tick+5000,mob_delayspawn,md->bl.id,0);
  974. return 1;
  975. }
  976. }
  977. else if( battle_config.no_spawn_on_player > 99 && map_foreachinallrange(mob_count_sub, &md->bl, AREA_SIZE, BL_PC) )
  978. { // retry again later (players on sight)
  979. if( md->spawn_timer != INVALID_TIMER )
  980. delete_timer(md->spawn_timer, mob_delayspawn);
  981. md->spawn_timer = add_timer(tick+5000,mob_delayspawn,md->bl.id,0);
  982. return 1;
  983. }
  984. }
  985. memset(&md->state, 0, sizeof(md->state));
  986. status_calc_mob(md, SCO_FIRST);
  987. md->attacked_id = 0;
  988. md->norm_attacked_id = 0;
  989. md->target_id = 0;
  990. md->move_fail_count = 0;
  991. md->ud.state.attack_continue = 0;
  992. md->ud.target_to = 0;
  993. md->ud.dir = 0;
  994. if( md->spawn_timer != INVALID_TIMER ) {
  995. delete_timer(md->spawn_timer, mob_delayspawn);
  996. md->spawn_timer = INVALID_TIMER;
  997. }
  998. // md->master_id = 0;
  999. md->master_dist = 0;
  1000. md->state.aggressive = status_has_mode(&md->status,MD_ANGRY)?1:0;
  1001. md->state.skillstate = MSS_IDLE;
  1002. md->next_walktime = tick+rnd()%1000+MIN_RANDOMWALKTIME;
  1003. md->last_linktime = tick;
  1004. md->dmgtick = tick - 5000;
  1005. md->last_pcneartime = 0;
  1006. t_tick c = tick - MOB_MAX_DELAY;
  1007. for (i = 0; i < MAX_MOBSKILL; i++)
  1008. md->skilldelay[i] = c;
  1009. for (i = 0; i < DAMAGELOG_SIZE; i++)
  1010. md->spotted_log[i] = 0;
  1011. memset(md->dmglog, 0, sizeof(md->dmglog));
  1012. md->tdmg = 0;
  1013. if (md->lootitems)
  1014. memset(md->lootitems, 0, sizeof(*md->lootitems));
  1015. md->lootitem_count = 0;
  1016. if(md->db->option)
  1017. // Added for carts, falcons and pecos for cloned monsters. [Valaris]
  1018. md->sc.option = md->db->option;
  1019. // MvP tomb [GreenBox]
  1020. if ( md->tomb_nid )
  1021. mvptomb_destroy(md);
  1022. if(map_addblock(&md->bl))
  1023. return 2;
  1024. if( map_getmapdata(md->bl.m)->users )
  1025. clif_spawn(&md->bl);
  1026. skill_unit_move(&md->bl,tick,1);
  1027. mobskill_use(md, tick, MSC_SPAWN);
  1028. return 0;
  1029. }
  1030. /*==========================================
  1031. * Determines if the mob can change target. [Skotlex]
  1032. *------------------------------------------*/
  1033. static int mob_can_changetarget(struct mob_data* md, struct block_list* target, enum e_mode mode)
  1034. {
  1035. // Special feature that makes monsters always attack the person that provoked them
  1036. if(battle_config.mob_ai&0x800 && md->state.provoke_flag)
  1037. {
  1038. if (md->state.provoke_flag == target->id)
  1039. return 1;
  1040. else if (!(battle_config.mob_ai&0x4))
  1041. return 0;
  1042. }
  1043. switch (md->state.skillstate) {
  1044. case MSS_BERSERK:
  1045. if (!(mode&MD_CHANGETARGETMELEE))
  1046. return 0;
  1047. if (!(battle_config.mob_ai&0x80) && md->norm_attacked_id != target->id)
  1048. return 0;
  1049. return (battle_config.mob_ai&0x4 || check_distance_bl(&md->bl, target, md->status.rhw.range+1));
  1050. case MSS_RUSH:
  1051. return (mode&MD_CHANGETARGETCHASE);
  1052. case MSS_FOLLOW:
  1053. case MSS_ANGRY:
  1054. case MSS_IDLE:
  1055. case MSS_WALK:
  1056. case MSS_LOOT:
  1057. return 1;
  1058. default:
  1059. return 0;
  1060. }
  1061. }
  1062. /*==========================================
  1063. * Determination for an attack of a monster
  1064. *------------------------------------------*/
  1065. int mob_target(struct mob_data *md,struct block_list *bl,int dist)
  1066. {
  1067. nullpo_ret(md);
  1068. nullpo_ret(bl);
  1069. // Nothing will be carried out if there is no mind of changing TAGE by TAGE ending.
  1070. if(md->target_id && !mob_can_changetarget(md, bl, status_get_mode(&md->bl)))
  1071. return 0;
  1072. if(!status_check_skilluse(&md->bl, bl, 0, 0))
  1073. return 0;
  1074. md->target_id = bl->id; // Since there was no disturbance, it locks on to target.
  1075. if (md->state.provoke_flag && bl->id != md->state.provoke_flag)
  1076. md->state.provoke_flag = 0;
  1077. // When an angry monster is provoked, it will switch to retaliate AI
  1078. if (md->state.provoke_flag && md->state.aggressive)
  1079. md->state.aggressive = 0;
  1080. md->min_chase=dist+md->db->range3;
  1081. if(md->min_chase>MAX_MINCHASE)
  1082. md->min_chase=MAX_MINCHASE;
  1083. return 0;
  1084. }
  1085. /*==========================================
  1086. * The ?? routine of an active monster
  1087. *------------------------------------------*/
  1088. static int mob_ai_sub_hard_activesearch(struct block_list *bl,va_list ap)
  1089. {
  1090. struct mob_data *md;
  1091. struct block_list **target;
  1092. enum e_mode mode;
  1093. int dist;
  1094. nullpo_ret(bl);
  1095. md=va_arg(ap,struct mob_data *);
  1096. target= va_arg(ap,struct block_list**);
  1097. mode= static_cast<enum e_mode>(va_arg(ap, int));
  1098. //If can't seek yet, not an enemy, or you can't attack it, skip.
  1099. if ((*target) == bl || !status_check_skilluse(&md->bl, bl, 0, 0))
  1100. return 0;
  1101. if ((mode&MD_TARGETWEAK) && status_get_lv(bl) >= md->level-5)
  1102. return 0;
  1103. if(battle_check_target(&md->bl,bl,BCT_ENEMY)<=0)
  1104. return 0;
  1105. switch (bl->type)
  1106. {
  1107. case BL_PC:
  1108. if (((TBL_PC*)bl)->state.gangsterparadise &&
  1109. !status_has_mode(&md->status,MD_STATUSIMMUNE))
  1110. return 0; //Gangster paradise protection.
  1111. default:
  1112. if (battle_config.hom_setting&HOMSET_FIRST_TARGET &&
  1113. (*target) && (*target)->type == BL_HOM && bl->type != BL_HOM)
  1114. return 0; //For some reason Homun targets are never overriden.
  1115. dist = distance_bl(&md->bl, bl);
  1116. if(
  1117. ((*target) == NULL || !check_distance_bl(&md->bl, *target, dist)) &&
  1118. battle_check_range(&md->bl,bl,md->db->range2)
  1119. ) { //Pick closest target?
  1120. #ifdef ACTIVEPATHSEARCH
  1121. struct walkpath_data wpd;
  1122. if (!path_search(&wpd, md->bl.m, md->bl.x, md->bl.y, bl->x, bl->y, 0, CELL_CHKWALL)) // Count walk path cells
  1123. return 0;
  1124. //Standing monsters use range2, walking monsters use range3
  1125. if ((md->ud.walktimer == INVALID_TIMER && wpd.path_len > md->db->range2)
  1126. || (md->ud.walktimer != INVALID_TIMER && wpd.path_len > md->db->range3))
  1127. return 0;
  1128. #endif
  1129. (*target) = bl;
  1130. md->target_id=bl->id;
  1131. md->min_chase= dist + md->db->range3;
  1132. if(md->min_chase>MAX_MINCHASE)
  1133. md->min_chase=MAX_MINCHASE;
  1134. return 1;
  1135. }
  1136. break;
  1137. }
  1138. return 0;
  1139. }
  1140. /*==========================================
  1141. * chase target-change routine.
  1142. *------------------------------------------*/
  1143. static int mob_ai_sub_hard_changechase(struct block_list *bl,va_list ap)
  1144. {
  1145. struct mob_data *md;
  1146. struct block_list **target;
  1147. nullpo_ret(bl);
  1148. md=va_arg(ap,struct mob_data *);
  1149. target= va_arg(ap,struct block_list**);
  1150. //If can't seek yet, not an enemy, or you can't attack it, skip.
  1151. if ((*target) == bl ||
  1152. battle_check_target(&md->bl,bl,BCT_ENEMY)<=0 ||
  1153. !status_check_skilluse(&md->bl, bl, 0, 0))
  1154. return 0;
  1155. if(battle_check_range (&md->bl, bl, md->status.rhw.range))
  1156. {
  1157. (*target) = bl;
  1158. md->target_id=bl->id;
  1159. md->min_chase= md->db->range3;
  1160. }
  1161. return 1;
  1162. }
  1163. /*==========================================
  1164. * finds nearby bg ally for guardians looking for users to follow.
  1165. *------------------------------------------*/
  1166. static int mob_ai_sub_hard_bg_ally(struct block_list *bl,va_list ap) {
  1167. struct mob_data *md;
  1168. struct block_list **target;
  1169. nullpo_ret(bl);
  1170. md=va_arg(ap,struct mob_data *);
  1171. target= va_arg(ap,struct block_list**);
  1172. if( status_check_skilluse(&md->bl, bl, 0, 0) && battle_check_target(&md->bl,bl,BCT_ENEMY)<=0 ) {
  1173. (*target) = bl;
  1174. }
  1175. return 1;
  1176. }
  1177. /*==========================================
  1178. * loot monster item search
  1179. *------------------------------------------*/
  1180. static int mob_ai_sub_hard_lootsearch(struct block_list *bl,va_list ap)
  1181. {
  1182. struct mob_data* md;
  1183. struct block_list **target;
  1184. int dist;
  1185. md = va_arg(ap,struct mob_data *);
  1186. target = va_arg(ap,struct block_list**);
  1187. dist = distance_bl(&md->bl, bl);
  1188. if (mob_can_reach(md,bl,dist+1, MSS_LOOT) && (
  1189. (*target) == nullptr ||
  1190. (battle_config.monster_loot_search_type && md->target_id > bl->id) ||
  1191. (!battle_config.monster_loot_search_type && !check_distance_bl(&md->bl, *target, dist)) // New target closer than previous one.
  1192. ))
  1193. {
  1194. (*target) = bl;
  1195. md->target_id = bl->id;
  1196. md->min_chase = md->db->range3;
  1197. }
  1198. else if (!battle_config.monster_loot_search_type)
  1199. mob_stop_walking(md, 1); // Stop walking immediately if item is no longer on the ground.
  1200. return 0;
  1201. }
  1202. static int mob_warpchase_sub(struct block_list *bl,va_list ap) {
  1203. struct block_list *target;
  1204. struct npc_data **target_nd;
  1205. struct npc_data *nd;
  1206. int *min_distance;
  1207. int cur_distance;
  1208. target= va_arg(ap, struct block_list*);
  1209. target_nd= va_arg(ap, struct npc_data**);
  1210. min_distance= va_arg(ap, int*);
  1211. nd = (TBL_NPC*) bl;
  1212. if(nd->subtype != NPCTYPE_WARP)
  1213. return 0; //Not a warp
  1214. if(nd->u.warp.mapindex != map_getmapdata(target->m)->index)
  1215. return 0; //Does not lead to the same map.
  1216. cur_distance = distance_blxy(target, nd->u.warp.x, nd->u.warp.y);
  1217. if (cur_distance < *min_distance)
  1218. { //Pick warp that leads closest to target.
  1219. *target_nd = nd;
  1220. *min_distance = cur_distance;
  1221. return 1;
  1222. }
  1223. return 0;
  1224. }
  1225. /*==========================================
  1226. * Processing of slave monsters
  1227. *------------------------------------------*/
  1228. static int mob_ai_sub_hard_slavemob(struct mob_data *md,t_tick tick)
  1229. {
  1230. struct block_list *bl;
  1231. bl=map_id2bl(md->master_id);
  1232. if (!bl || status_isdead(bl)) {
  1233. status_kill(&md->bl);
  1234. return 1;
  1235. }
  1236. if (bl->prev == nullptr)
  1237. return 0; //Master not on a map? Could be warping, do not process.
  1238. if(status_has_mode(&md->status,MD_CANMOVE))
  1239. { //If the mob can move, follow around. [Check by Skotlex]
  1240. int old_dist = md->master_dist;
  1241. // Distance with between slave and master is measured.
  1242. md->master_dist = distance_bl(&md->bl, bl);
  1243. if (battle_config.slave_stick_with_master) {
  1244. // Since the master was in near immediately before, teleport is carried out and it pursues.
  1245. if (bl->m != md->bl.m || (old_dist < 10 && md->master_dist > 18) || md->master_dist > MAX_MINCHASE) {
  1246. md->master_dist = 0;
  1247. unit_warp(&md->bl, bl->m, bl->x, bl->y, CLR_TELEPORT);
  1248. return 1;
  1249. }
  1250. }
  1251. if(md->target_id) //Slave is busy with a target.
  1252. return 0;
  1253. // Approach master if within view range, chase back to Master's area also if standing on top of the master.
  1254. if ((md->master_dist > MOB_SLAVEDISTANCE || md->master_dist == 0) && unit_can_move(&md->bl)) {
  1255. int16 x = bl->x, y = bl->y;
  1256. if (map_search_freecell(&md->bl, bl->m, &x, &y, MOB_SLAVEDISTANCE, MOB_SLAVEDISTANCE, 1)) {
  1257. if (unit_walktoxy(&md->bl, x, y, 0) == 0) { // Slave is too far from master (outside of battle_config.max_walk_path range), stay put
  1258. mob_stop_walking(md, USW_FIXPOS);
  1259. return 0; // Fail here so target will be picked back up when in range
  1260. } else { // Slave will walk back to master if in range
  1261. mob_stop_attack(md);
  1262. return 1;
  1263. }
  1264. }
  1265. }
  1266. } else if (bl->m != md->bl.m && map_flag_gvg2(md->bl.m)) {
  1267. //Delete the summoned mob if it's in a gvg ground and the master is elsewhere. [Skotlex]
  1268. status_kill(&md->bl);
  1269. return 1;
  1270. }
  1271. //Avoid attempting to lock the master's target too often to avoid unnecessary overload. [Skotlex]
  1272. if (DIFF_TICK(md->last_linktime, tick) < MIN_MOBLINKTIME && !md->target_id)
  1273. {
  1274. struct unit_data *ud = unit_bl2ud(bl);
  1275. md->last_linktime = tick;
  1276. if (ud) {
  1277. struct block_list *tbl=nullptr;
  1278. if (ud->target && ud->state.attack_continue)
  1279. tbl = map_id2bl(ud->target);
  1280. else if (ud->target_to && ud->state.attack_continue)
  1281. tbl = map_id2bl(ud->target_to);
  1282. else if (ud->skilltarget) {
  1283. tbl = map_id2bl(ud->skilltarget);
  1284. //Required check as skilltarget is not always an enemy. [Skotlex]
  1285. if (tbl && battle_check_target(&md->bl, tbl, BCT_ENEMY) <= 0)
  1286. tbl = nullptr;
  1287. }
  1288. if (tbl && status_check_skilluse(&md->bl, tbl, 0, 0)) {
  1289. md->target_id=tbl->id;
  1290. md->min_chase=md->db->range3+distance_bl(&md->bl, tbl);
  1291. if(md->min_chase>MAX_MINCHASE)
  1292. md->min_chase=MAX_MINCHASE;
  1293. return 1;
  1294. }
  1295. }
  1296. }
  1297. return 0;
  1298. }
  1299. /*==========================================
  1300. * A lock of target is stopped and mob moves to a standby state.
  1301. * This also triggers idle skill/movement since the AI can get stuck
  1302. * when trying to pick new targets when the current chosen target is
  1303. * unreachable.
  1304. *------------------------------------------*/
  1305. int mob_unlocktarget(struct mob_data *md, t_tick tick)
  1306. {
  1307. nullpo_ret(md);
  1308. switch (md->state.skillstate) {
  1309. case MSS_WALK:
  1310. if (md->ud.walktimer != INVALID_TIMER)
  1311. break;
  1312. //Because it is not unset when the mob finishes walking.
  1313. md->state.skillstate = MSS_IDLE;
  1314. case MSS_IDLE:
  1315. // Idle skill.
  1316. if (!(++md->ud.walk_count%IDLE_SKILL_INTERVAL) && mobskill_use(md, tick, -1))
  1317. break;
  1318. //Random walk.
  1319. if (!md->master_id &&
  1320. DIFF_TICK(md->next_walktime, tick) <= 0 &&
  1321. !mob_randomwalk(md,tick))
  1322. //Delay next random walk when this one failed.
  1323. md->next_walktime = tick+rnd()%1000;
  1324. break;
  1325. default:
  1326. mob_stop_attack(md);
  1327. mob_stop_walking(md,1); //Stop chasing.
  1328. if (status_has_mode(&md->status,MD_ANGRY) && !md->state.aggressive)
  1329. md->state.aggressive = 1; //Restore angry state when switching to idle
  1330. md->state.skillstate = MSS_IDLE;
  1331. if(battle_config.mob_ai&0x8) //Walk instantly after dropping target
  1332. md->next_walktime = tick+rnd()%1000;
  1333. else
  1334. md->next_walktime = tick+rnd()%1000+MIN_RANDOMWALKTIME;
  1335. break;
  1336. }
  1337. if (md->target_id) {
  1338. md->target_id=0;
  1339. md->ud.target_to = 0;
  1340. unit_set_target(&md->ud, 0);
  1341. }
  1342. if (battle_config.official_cell_stack_limit > 0
  1343. && (md->min_chase == md->db->range3 || battle_config.mob_ai & 0x8)
  1344. && map_count_oncell(md->bl.m, md->bl.x, md->bl.y, BL_CHAR | BL_NPC, 1) > battle_config.official_cell_stack_limit) {
  1345. unit_walktoxy(&md->bl, md->bl.x, md->bl.y, 8);
  1346. }
  1347. return 0;
  1348. }
  1349. /*==========================================
  1350. * Random walk
  1351. *------------------------------------------*/
  1352. int mob_randomwalk(struct mob_data *md,t_tick tick)
  1353. {
  1354. const int d=7;
  1355. int i,c,r,rdir,dx,dy,max;
  1356. int speed;
  1357. nullpo_ret(md);
  1358. if(DIFF_TICK(md->next_walktime,tick)>0 ||
  1359. status_has_mode(&md->status,MD_NORANDOMWALK) ||
  1360. !unit_can_move(&md->bl) ||
  1361. !status_has_mode(&md->status,MD_CANMOVE))
  1362. return 0;
  1363. r=rnd();
  1364. rdir=rnd()%4; // Randomize direction in which we iterate to prevent monster cluttering up in one corner
  1365. dx=r%(d*2+1)-d;
  1366. dy=r/(d*2+1)%(d*2+1)-d;
  1367. max=(d*2+1)*(d*2+1);
  1368. for(i=0;i<max;i++){ // Search of a movable place
  1369. int x = dx + md->bl.x;
  1370. int y = dy + md->bl.y;
  1371. if(((x != md->bl.x) || (y != md->bl.y)) && map_getcell(md->bl.m,x,y,CELL_CHKPASS) && unit_walktoxy(&md->bl,x,y,0)){
  1372. break;
  1373. }
  1374. // Could not move to cell, try the 7th cell in direction randomly decided by rdir
  1375. // We don't move step-by-step because this will make monster stick to the walls
  1376. switch(rdir) {
  1377. case 0:
  1378. dx += d;
  1379. if (dx > d) {
  1380. dx -= d*2+1;
  1381. dy += d;
  1382. if (dy > d) {
  1383. dy -= d*2+1;
  1384. }
  1385. }
  1386. break;
  1387. case 1:
  1388. dx -= d;
  1389. if (dx < -d) {
  1390. dx += d*2+1;
  1391. dy -= d;
  1392. if (dy < -d) {
  1393. dy += d*2+1;
  1394. }
  1395. }
  1396. break;
  1397. case 2:
  1398. dy += d;
  1399. if (dy > d) {
  1400. dy -= d*2+1;
  1401. dx += d;
  1402. if (dx > d) {
  1403. dx -= d*2+1;
  1404. }
  1405. }
  1406. break;
  1407. case 3:
  1408. dy -= d;
  1409. if (dy < -d) {
  1410. dy += d*2+1;
  1411. dx -= d;
  1412. if (dx < -d) {
  1413. dx += d*2+1;
  1414. }
  1415. }
  1416. break;
  1417. }
  1418. }
  1419. if(i==max){
  1420. // None of the available cells worked, try again next interval
  1421. if(battle_config.mob_stuck_warning) {
  1422. md->move_fail_count++;
  1423. if(md->move_fail_count>1000){
  1424. ShowWarning("MOB can't move. random spawn %d, class = %d, at %s (%d,%d)\n",md->bl.id,md->mob_id,map_getmapdata(md->bl.m)->name, md->bl.x, md->bl.y);
  1425. md->move_fail_count=0;
  1426. mob_spawn(md);
  1427. }
  1428. }
  1429. return 0;
  1430. }
  1431. speed=status_get_speed(&md->bl);
  1432. for(i=c=0;i<md->ud.walkpath.path_len;i++){ // The next walk start time is calculated.
  1433. if( direction_diagonal( md->ud.walkpath.path[i] ) )
  1434. c+=speed*MOVE_DIAGONAL_COST/MOVE_COST;
  1435. else
  1436. c+=speed;
  1437. }
  1438. md->state.skillstate=MSS_WALK;
  1439. md->move_fail_count=0;
  1440. md->next_walktime = tick+rnd()%1000+MIN_RANDOMWALKTIME+c;
  1441. return 1;
  1442. }
  1443. int mob_warpchase(struct mob_data *md, struct block_list *target)
  1444. {
  1445. struct npc_data *warp = nullptr;
  1446. int distance = AREA_SIZE;
  1447. if (!(target && battle_config.mob_ai&0x40 && battle_config.mob_warp&1))
  1448. return 0; //Can't warp chase.
  1449. if (target->m == md->bl.m && check_distance_bl(&md->bl, target, AREA_SIZE))
  1450. return 0; //No need to do a warp chase.
  1451. if (md->ud.walktimer != INVALID_TIMER &&
  1452. map_getcell(md->bl.m,md->ud.to_x,md->ud.to_y,CELL_CHKNPC))
  1453. return 1; //Already walking to a warp.
  1454. //Search for warps within mob's viewing range.
  1455. map_foreachinallrange(mob_warpchase_sub, &md->bl,
  1456. md->db->range2, BL_NPC, target, &warp, &distance);
  1457. if (warp && unit_walktobl(&md->bl, &warp->bl, 1, 1))
  1458. return 1;
  1459. return 0;
  1460. }
  1461. /*==========================================
  1462. * AI of MOB whose is near a Player
  1463. *------------------------------------------*/
  1464. static bool mob_ai_sub_hard(struct mob_data *md, t_tick tick)
  1465. {
  1466. struct block_list *tbl = nullptr, *abl = nullptr;
  1467. enum e_mode mode;
  1468. int view_range, can_move;
  1469. if(md->bl.prev == nullptr || md->status.hp == 0)
  1470. return false;
  1471. if (DIFF_TICK(tick, md->last_thinktime) < MIN_MOBTHINKTIME)
  1472. return false;
  1473. md->last_thinktime = tick;
  1474. if (md->ud.skilltimer != INVALID_TIMER)
  1475. return false;
  1476. // Abnormalities
  1477. if(( md->sc.opt1 > 0 && md->sc.opt1 != OPT1_STONEWAIT && md->sc.opt1 != OPT1_BURNING )
  1478. || md->sc.data[SC_BLADESTOP] || md->sc.data[SC__MANHOLE] || md->sc.data[SC_CURSEDCIRCLE_TARGET]) {//Should reset targets.
  1479. md->target_id = md->attacked_id = md->norm_attacked_id = 0;
  1480. return false;
  1481. }
  1482. if (md->sc.count && md->sc.data[SC_BLIND])
  1483. view_range = 3;
  1484. else
  1485. view_range = md->db->range2;
  1486. mode = status_get_mode(&md->bl);
  1487. can_move = (mode&MD_CANMOVE) && unit_can_move(&md->bl);
  1488. if (md->target_id)
  1489. { //Check validity of current target. [Skotlex]
  1490. tbl = map_id2bl(md->target_id);
  1491. if (!tbl || tbl->m != md->bl.m ||
  1492. (md->ud.attacktimer == INVALID_TIMER && !status_check_skilluse(&md->bl, tbl, 0, 0)) ||
  1493. (md->ud.walktimer != INVALID_TIMER && !(battle_config.mob_ai&0x1) && !check_distance_bl(&md->bl, tbl, md->min_chase)) ||
  1494. (
  1495. tbl->type == BL_PC &&
  1496. ((((TBL_PC*)tbl)->state.gangsterparadise && !(mode&MD_STATUSIMMUNE)) ||
  1497. ((TBL_PC*)tbl)->invincible_timer != INVALID_TIMER)
  1498. )) { //No valid target
  1499. if (mob_warpchase(md, tbl))
  1500. return true; //Chasing this target.
  1501. if (tbl && md->ud.walktimer != INVALID_TIMER && (!can_move || md->ud.walkpath.path_pos <= battle_config.mob_chase_refresh))
  1502. return true; //Walk at least "mob_chase_refresh" cells before dropping the target unless target is non-existent
  1503. mob_unlocktarget(md, tick); //Unlock target
  1504. tbl = NULL;
  1505. }
  1506. }
  1507. // Check for target change.
  1508. if( md->attacked_id && mode&MD_CANATTACK )
  1509. {
  1510. if( md->attacked_id == md->target_id )
  1511. { //Rude attacked check.
  1512. if( !battle_check_range(&md->bl, tbl, md->status.rhw.range)
  1513. && ( //Can't attack back and can't reach back.
  1514. (!can_move && DIFF_TICK(tick, md->ud.canmove_tick) > 0 && (battle_config.mob_ai&0x2 || md->sc.data[SC_SPIDERWEB]
  1515. || md->sc.data[SC_BITE] || md->sc.data[SC_VACUUM_EXTREME] || md->sc.data[SC_THORNSTRAP]
  1516. || md->sc.data[SC__MANHOLE] // Not yet confirmed if boss will teleport once it can't reach target.
  1517. || md->walktoxy_fail_count > 0)
  1518. )
  1519. || !mob_can_reach(md, tbl, md->min_chase, MSS_RUSH)
  1520. )
  1521. && md->state.attacked_count++ >= RUDE_ATTACKED_COUNT
  1522. && !mobskill_use(md, tick, MSC_RUDEATTACKED) // If can't rude Attack
  1523. && can_move && unit_escape(&md->bl, tbl, rnd()%10 +1)) // Attempt escape
  1524. { //Escaped
  1525. md->attacked_id = md->norm_attacked_id = 0;
  1526. return true;
  1527. }
  1528. }
  1529. else
  1530. if( (abl = map_id2bl(md->attacked_id)) && (!tbl || mob_can_changetarget(md, abl, mode)) )
  1531. {
  1532. int dist;
  1533. if( md->bl.m != abl->m || abl->prev == NULL
  1534. || (dist = distance_bl(&md->bl, abl)) >= MAX_MINCHASE // Attacker longer than visual area
  1535. || battle_check_target(&md->bl, abl, BCT_ENEMY) <= 0 // Attacker is not enemy of mob
  1536. || (battle_config.mob_ai&0x2 && !status_check_skilluse(&md->bl, abl, 0, 0)) // Cannot normal attack back to Attacker
  1537. || (!battle_check_range(&md->bl, abl, md->status.rhw.range) // Not on Melee Range and ...
  1538. && ( // Reach check
  1539. (!can_move && DIFF_TICK(tick, md->ud.canmove_tick) > 0 && (battle_config.mob_ai&0x2 || md->sc.data[SC_SPIDERWEB]
  1540. || md->sc.data[SC_BITE] || md->sc.data[SC_VACUUM_EXTREME] || md->sc.data[SC_THORNSTRAP]
  1541. || md->sc.data[SC__MANHOLE] // Not yet confirmed if boss will teleport once it can't reach target.
  1542. || md->walktoxy_fail_count > 0)
  1543. )
  1544. || !mob_can_reach(md, abl, dist+md->db->range3, MSS_RUSH)
  1545. )
  1546. ) )
  1547. { // Rude attacked
  1548. if (abl->id != md->bl.id //Self damage does not cause rude attack
  1549. && md->state.attacked_count++ >= RUDE_ATTACKED_COUNT
  1550. && !mobskill_use(md, tick, MSC_RUDEATTACKED) && can_move
  1551. && !tbl && unit_escape(&md->bl, abl, rnd()%10 +1))
  1552. { //Escaped.
  1553. //TODO: Maybe it shouldn't attempt to run if it has another, valid target?
  1554. md->attacked_id = md->norm_attacked_id = 0;
  1555. return true;
  1556. }
  1557. }
  1558. else
  1559. if (!(battle_config.mob_ai&0x2) && !status_check_skilluse(&md->bl, abl, 0, 0))
  1560. {
  1561. //Can't attack back, but didn't invoke a rude attacked skill...
  1562. }
  1563. else
  1564. { //Attackable
  1565. //If a monster can change the target to the attacker, it will change the target
  1566. md->target_id = md->attacked_id; // set target
  1567. if (md->state.attacked_count)
  1568. md->state.attacked_count--; //Should we reset rude attack count?
  1569. md->min_chase = dist+md->db->range3;
  1570. if(md->min_chase>MAX_MINCHASE)
  1571. md->min_chase=MAX_MINCHASE;
  1572. tbl = abl; //Set the new target
  1573. }
  1574. }
  1575. //Clear it since it's been checked for already.
  1576. md->attacked_id = md->norm_attacked_id = 0;
  1577. }
  1578. bool slave_lost_target = false;
  1579. // Processing of slave monster
  1580. if (md->master_id > 0) {
  1581. if (mob_ai_sub_hard_slavemob(md, tick) == 1)
  1582. return true;
  1583. slave_lost_target = true;
  1584. }
  1585. // Scan area for targets
  1586. if (!tbl && can_move && mode&MD_LOOTER && md->lootitems && DIFF_TICK(tick, md->ud.canact_tick) > 0 &&
  1587. (md->lootitem_count < LOOTITEM_SIZE || battle_config.monster_loot_type != 1))
  1588. { // Scan area for items to loot, avoid trying to loot if the mob is full and can't consume the items.
  1589. map_foreachinshootrange (mob_ai_sub_hard_lootsearch, &md->bl, view_range, BL_ITEM, md, &tbl);
  1590. }
  1591. if ((mode&MD_AGGRESSIVE && (!tbl || slave_lost_target)) || md->state.skillstate == MSS_FOLLOW)
  1592. {
  1593. map_foreachinallrange (mob_ai_sub_hard_activesearch, &md->bl, view_range, DEFAULT_ENEMY_TYPE(md), md, &tbl, mode);
  1594. }
  1595. else
  1596. if (mode&MD_CHANGECHASE && (md->state.skillstate == MSS_RUSH || md->state.skillstate == MSS_FOLLOW))
  1597. {
  1598. int search_size;
  1599. search_size = view_range<md->status.rhw.range ? view_range:md->status.rhw.range;
  1600. map_foreachinallrange (mob_ai_sub_hard_changechase, &md->bl, search_size, DEFAULT_ENEMY_TYPE(md), md, &tbl);
  1601. }
  1602. if (!tbl) { //No targets available.
  1603. /* bg guardians follow allies when no targets nearby */
  1604. if( md->bg_id && mode&MD_CANATTACK ) {
  1605. if( md->ud.walktimer != INVALID_TIMER )
  1606. return true;/* we are already moving */
  1607. map_foreachinallrange (mob_ai_sub_hard_bg_ally, &md->bl, view_range, BL_PC, md, &tbl, mode);
  1608. if( tbl ) {
  1609. if( distance_blxy(&md->bl, tbl->x, tbl->y) <= 3 || unit_walktobl(&md->bl, tbl, 1, 1) )
  1610. return true;/* we're moving or close enough don't unlock the target. */
  1611. }
  1612. }
  1613. //This handles triggering idle/walk skill.
  1614. mob_unlocktarget(md, tick);
  1615. return true;
  1616. }
  1617. //Target exists, attack or loot as applicable.
  1618. if (tbl->type == BL_ITEM)
  1619. { //Loot time.
  1620. struct flooritem_data *fitem;
  1621. if (md->ud.target == tbl->id && md->ud.walktimer != INVALID_TIMER)
  1622. return true; //Already locked.
  1623. if (md->lootitems == NULL)
  1624. { //Can't loot...
  1625. mob_unlocktarget(md, tick);
  1626. return true;
  1627. }
  1628. if (!check_distance_bl(&md->bl, tbl, 0))
  1629. { //Still not within loot range.
  1630. if (!(mode&MD_CANMOVE))
  1631. { //A looter that can't move? Real smart.
  1632. mob_unlocktarget(md, tick);
  1633. return true;
  1634. }
  1635. if (!can_move) //Stuck. Wait before walking.
  1636. return true;
  1637. md->state.skillstate = MSS_LOOT;
  1638. if (!unit_walktobl(&md->bl, tbl, 0, 1))
  1639. mob_unlocktarget(md, tick); //Can't loot...
  1640. return true;
  1641. }
  1642. //Within looting range.
  1643. if (md->ud.attacktimer != INVALID_TIMER)
  1644. return true; //Busy attacking?
  1645. fitem = (struct flooritem_data *)tbl;
  1646. //Logs items, taken by (L)ooter Mobs [Lupus]
  1647. log_pick_mob(md, LOG_TYPE_LOOT, fitem->item.amount, &fitem->item);
  1648. if (md->lootitem_count < LOOTITEM_SIZE) {
  1649. memcpy (&md->lootitems[md->lootitem_count].item, &fitem->item, sizeof(md->lootitems[0].item));
  1650. md->lootitems[md->lootitem_count].mob_id = fitem->mob_id;
  1651. md->lootitem_count++;
  1652. } else { //Destroy first looted item...
  1653. if (md->lootitems[0].item.card[0] == CARD0_PET)
  1654. intif_delete_petdata(MakeDWord(md->lootitems[0].item.card[1],md->lootitems[0].item.card[2]));
  1655. memmove(&md->lootitems[0], &md->lootitems[1], (LOOTITEM_SIZE-1)*sizeof(md->lootitems[0]));
  1656. memcpy (&md->lootitems[LOOTITEM_SIZE-1].item, &fitem->item, sizeof(md->lootitems[0].item));
  1657. md->lootitems[LOOTITEM_SIZE-1].mob_id = fitem->mob_id;
  1658. }
  1659. if (pcdb_checkid(md->vd->class_))
  1660. { //Give them walk act/delay to properly mimic players. [Skotlex]
  1661. clif_takeitem(&md->bl,tbl);
  1662. md->ud.canact_tick = tick + md->status.amotion;
  1663. unit_set_walkdelay(&md->bl, tick, md->status.amotion, 1);
  1664. }
  1665. //Clear item.
  1666. map_clearflooritem(tbl);
  1667. mob_unlocktarget(md, tick);
  1668. return true;
  1669. }
  1670. //Attempt to attack.
  1671. //At this point we know the target is attackable, we just gotta check if the range matches.
  1672. if (battle_check_range(&md->bl, tbl, md->status.rhw.range) && !(md->sc.option&OPTION_HIDE))
  1673. { //Target within range and able to use normal attack, engage
  1674. if (md->ud.target != tbl->id || md->ud.attacktimer == INVALID_TIMER)
  1675. { //Only attack if no more attack delay left
  1676. if(tbl->type == BL_PC)
  1677. mob_log_damage(md, tbl, 0); //Log interaction (counts as 'attacker' for the exp bonus)
  1678. if( !(mode&MD_RANDOMTARGET) )
  1679. unit_attack(&md->bl,tbl->id,1);
  1680. else { // Attack once and find a new random target
  1681. int search_size = (view_range < md->status.rhw.range) ? view_range : md->status.rhw.range;
  1682. unit_attack(&md->bl, tbl->id, 0);
  1683. if ((tbl = battle_getenemy(&md->bl, DEFAULT_ENEMY_TYPE(md), search_size))) {
  1684. md->target_id = tbl->id;
  1685. md->min_chase = md->db->range3;
  1686. }
  1687. }
  1688. }
  1689. return true;
  1690. }
  1691. //Monsters in berserk state, unable to use normal attacks, will always attempt a skill
  1692. if(md->ud.walktimer == INVALID_TIMER && (md->state.skillstate == MSS_BERSERK || md->state.skillstate == MSS_ANGRY))
  1693. {
  1694. if (DIFF_TICK(md->ud.canmove_tick, tick) <= MIN_MOBTHINKTIME && DIFF_TICK(md->ud.canact_tick, tick) < -MIN_MOBTHINKTIME*IDLE_SKILL_INTERVAL)
  1695. { //Only use skill if able to walk on next tick and not used a skill the last second
  1696. if (mobskill_use(md, tick, -1))
  1697. return true;
  1698. }
  1699. }
  1700. //Target still in attack range, no need to chase the target
  1701. if(battle_check_range(&md->bl, tbl, md->status.rhw.range))
  1702. return true;
  1703. //Only update target cell / drop target after having moved at least "mob_chase_refresh" cells
  1704. if(md->ud.walktimer != INVALID_TIMER && (!can_move || md->ud.walkpath.path_pos <= battle_config.mob_chase_refresh))
  1705. return true;
  1706. //Out of range...
  1707. if (!(mode&MD_CANMOVE) || (!can_move && DIFF_TICK(tick, md->ud.canmove_tick) > 0))
  1708. { //Can't chase. Immobile and trapped mobs should unlock target and use an idle skill.
  1709. if (md->ud.attacktimer == INVALID_TIMER)
  1710. { //Only unlock target if no more attack delay left
  1711. //This handles triggering idle/walk skill.
  1712. mob_unlocktarget(md,tick);
  1713. }
  1714. return true;
  1715. }
  1716. if (md->ud.walktimer != INVALID_TIMER && md->ud.target == tbl->id &&
  1717. (
  1718. !(battle_config.mob_ai&0x1) ||
  1719. check_distance_blxy(tbl, md->ud.to_x, md->ud.to_y, md->status.rhw.range)
  1720. )) //Current target tile is still within attack range.
  1721. return true;
  1722. //Follow up if possible.
  1723. //Hint: Chase skills are handled in the walktobl routine
  1724. if(!mob_can_reach(md, tbl, md->min_chase, MSS_RUSH) ||
  1725. !unit_walktobl(&md->bl, tbl, md->status.rhw.range, 2))
  1726. mob_unlocktarget(md,tick);
  1727. return true;
  1728. }
  1729. static int mob_ai_sub_hard_timer(struct block_list *bl,va_list ap)
  1730. {
  1731. struct mob_data *md = (struct mob_data*)bl;
  1732. uint32 char_id = va_arg(ap, uint32);
  1733. t_tick tick = va_arg(ap, t_tick);
  1734. if (mob_ai_sub_hard(md, tick))
  1735. { //Hard AI triggered.
  1736. mob_add_spotted(md, char_id);
  1737. md->last_pcneartime = tick;
  1738. }
  1739. return 0;
  1740. }
  1741. /*==========================================
  1742. * Serious processing for mob in PC field of view (foreachclient)
  1743. *------------------------------------------*/
  1744. static int mob_ai_sub_foreachclient(struct map_session_data *sd,va_list ap)
  1745. {
  1746. t_tick tick=va_arg(ap,t_tick);
  1747. map_foreachinallrange(mob_ai_sub_hard_timer,&sd->bl, AREA_SIZE+ACTIVE_AI_RANGE, BL_MOB, sd->status.char_id, tick);
  1748. return 0;
  1749. }
  1750. /*==========================================
  1751. * Negligent mode MOB AI (PC is not in near)
  1752. *------------------------------------------*/
  1753. static int mob_ai_sub_lazy(struct mob_data *md, va_list args)
  1754. {
  1755. nullpo_ret(md);
  1756. if(md->bl.prev == NULL)
  1757. return 0;
  1758. t_tick tick = va_arg(args,t_tick);
  1759. if (battle_config.mob_ai&0x20 && map_getmapdata(md->bl.m)->users>0)
  1760. return (int)mob_ai_sub_hard(md, tick);
  1761. if (md->bl.prev==NULL || md->status.hp == 0)
  1762. return 1;
  1763. if(battle_config.mob_active_time &&
  1764. md->last_pcneartime &&
  1765. !status_has_mode(&md->status,MD_STATUSIMMUNE) &&
  1766. DIFF_TICK(tick,md->last_thinktime) > MIN_MOBTHINKTIME)
  1767. {
  1768. if (DIFF_TICK(tick,md->last_pcneartime) < battle_config.mob_active_time)
  1769. return (int)mob_ai_sub_hard(md, tick);
  1770. md->last_pcneartime = 0;
  1771. }
  1772. if(battle_config.boss_active_time &&
  1773. md->last_pcneartime &&
  1774. status_has_mode(&md->status,MD_STATUSIMMUNE) &&
  1775. DIFF_TICK(tick,md->last_thinktime) > MIN_MOBTHINKTIME)
  1776. {
  1777. if (DIFF_TICK(tick,md->last_pcneartime) < battle_config.boss_active_time)
  1778. return (int)mob_ai_sub_hard(md, tick);
  1779. md->last_pcneartime = 0;
  1780. }
  1781. //Clean the spotted log
  1782. mob_clean_spotted(md);
  1783. if(DIFF_TICK(tick,md->last_thinktime)< 10*MIN_MOBTHINKTIME)
  1784. return 0;
  1785. md->last_thinktime=tick;
  1786. if (md->master_id) {
  1787. mob_ai_sub_hard_slavemob (md,tick);
  1788. return 0;
  1789. }
  1790. if( DIFF_TICK(md->next_walktime,tick) < 0 && status_has_mode(&md->status,MD_CANMOVE) && unit_can_move(&md->bl) )
  1791. {
  1792. // Move probability for mobs away from players
  1793. // In Aegis, this is 100% for mobs that have been activated by players and none otherwise.
  1794. if( mob_is_spotted(md) &&
  1795. ((!status_has_mode(&md->status,MD_STATUSIMMUNE) && rnd()%100 < battle_config.mob_nopc_move_rate) ||
  1796. (status_has_mode(&md->status,MD_STATUSIMMUNE) && rnd()%100 < battle_config.boss_nopc_move_rate)))
  1797. mob_randomwalk(md, tick);
  1798. }
  1799. else if( md->ud.walktimer == INVALID_TIMER )
  1800. {
  1801. //Because it is not unset when the mob finishes walking.
  1802. md->state.skillstate = MSS_IDLE;
  1803. // Probability for mobs far from players from doing their IDLE skill.
  1804. // In Aegis, this is 100% for mobs that have been activated by players and none otherwise.
  1805. if( mob_is_spotted(md) &&
  1806. ((!status_has_mode(&md->status,MD_STATUSIMMUNE) && rnd()%100 < battle_config.mob_nopc_idleskill_rate) ||
  1807. (status_has_mode(&md->status,MD_STATUSIMMUNE) && rnd()%100 < battle_config.boss_nopc_idleskill_rate)))
  1808. mobskill_use(md, tick, -1);
  1809. }
  1810. return 0;
  1811. }
  1812. /*==========================================
  1813. * Negligent processing for mob outside PC field of view (interval timer function)
  1814. *------------------------------------------*/
  1815. static TIMER_FUNC(mob_ai_lazy){
  1816. map_foreachmob(mob_ai_sub_lazy,tick);
  1817. return 0;
  1818. }
  1819. /*==========================================
  1820. * Serious processing for mob in PC field of view (interval timer function)
  1821. *------------------------------------------*/
  1822. static TIMER_FUNC(mob_ai_hard){
  1823. if (battle_config.mob_ai&0x20)
  1824. map_foreachmob(mob_ai_sub_lazy,tick);
  1825. else
  1826. map_foreachpc(mob_ai_sub_foreachclient,tick);
  1827. return 0;
  1828. }
  1829. /**
  1830. * Assign random option values to an item
  1831. * @param item_option: Random option on the item
  1832. * @param option: Options to assign
  1833. */
  1834. void mob_setitem_option(s_item_randomoption &item_option, const std::shared_ptr<s_random_opt_group_entry> &option) {
  1835. item_option.id = option->id;
  1836. item_option.value = rnd_value(option->min_value, option->max_value);
  1837. item_option.param = option->param;
  1838. }
  1839. /**
  1840. * Set random option for item when dropped from monster
  1841. * @param item: Item data
  1842. * @param mobdrop: Drop data
  1843. * @author [Cydh]
  1844. **/
  1845. void mob_setdropitem_option(item *item, s_mob_drop *mobdrop) {
  1846. if (!item || !mobdrop)
  1847. return;
  1848. std::shared_ptr<s_random_opt_group> group = random_option_group.find(mobdrop->randomopt_group);
  1849. if (group != nullptr) {
  1850. // Apply Must options
  1851. for (size_t i = 0; i < group->slots.size(); i++) {
  1852. // Try to apply an entry
  1853. for (size_t j = 0, max = group->slots[static_cast<uint16>(i)].size() * 3; j < max; j++) {
  1854. std::shared_ptr<s_random_opt_group_entry> option = util::vector_random(group->slots[static_cast<uint16>(i)]);
  1855. if (rnd() % 10000 < option->chance) {
  1856. mob_setitem_option(item->option[i], option);
  1857. break;
  1858. }
  1859. }
  1860. // If no entry was applied, assign one
  1861. if (item->option[i].id == 0) {
  1862. std::shared_ptr<s_random_opt_group_entry> option = util::vector_random(group->slots[static_cast<uint16>(i)]);
  1863. // Apply an entry without checking the chance
  1864. mob_setitem_option(item->option[i], option);
  1865. }
  1866. }
  1867. // Apply Random options (if available)
  1868. if (group->max_random > 0) {
  1869. for (size_t i = 0; i < min(group->max_random, MAX_ITEM_RDM_OPT); i++) {
  1870. // If item already has an option in this slot, skip it
  1871. if (item->option[i].id > 0)
  1872. continue;
  1873. std::shared_ptr<s_random_opt_group_entry> option = util::vector_random(group->random_options);
  1874. if (rnd() % 10000 < option->chance)
  1875. mob_setitem_option(item->option[i], option);
  1876. }
  1877. }
  1878. }
  1879. }
  1880. /*==========================================
  1881. * Initializes the delay drop structure for mob-dropped items.
  1882. *------------------------------------------*/
  1883. static struct item_drop* mob_setdropitem(struct s_mob_drop *mobdrop, int qty, unsigned short mob_id)
  1884. {
  1885. struct item_drop *drop = ers_alloc(item_drop_ers, struct item_drop);
  1886. memset(&drop->item_data, 0, sizeof(struct item));
  1887. drop->item_data.nameid = mobdrop->nameid;
  1888. drop->item_data.amount = qty;
  1889. drop->item_data.identify = itemdb_isidentified(mobdrop->nameid);
  1890. mob_setdropitem_option(&drop->item_data, mobdrop);
  1891. drop->mob_id = mob_id;
  1892. drop->next = NULL;
  1893. return drop;
  1894. }
  1895. /*==========================================
  1896. * Initializes the delay drop structure for mob-looted items.
  1897. *------------------------------------------*/
  1898. static struct item_drop* mob_setlootitem(struct s_mob_lootitem *item, unsigned short mob_id)
  1899. {
  1900. struct item_drop *drop = ers_alloc(item_drop_ers, struct item_drop);
  1901. memcpy(&drop->item_data, item, sizeof(struct item));
  1902. /**
  1903. * Conditions for lotted item, so it can be announced when player pick it up
  1904. * 1. Not-dropped other than monster. (This will be done later on pc_takeitem/party_share_loot)
  1905. * 2. The mob_id is become the last lootter, instead of the real monster who drop it.
  1906. **/
  1907. drop->mob_id = item->mob_id;
  1908. drop->next = NULL;
  1909. return drop;
  1910. }
  1911. /*==========================================
  1912. * item drop with delay (timer function)
  1913. *------------------------------------------*/
  1914. static TIMER_FUNC(mob_delay_item_drop){
  1915. struct item_drop_list *list;
  1916. struct item_drop *ditem;
  1917. list = (struct item_drop_list *)data;
  1918. ditem = list->item;
  1919. while (ditem) {
  1920. struct item_drop *ditem_prev;
  1921. map_addflooritem(&ditem->item_data,ditem->item_data.amount,
  1922. list->m,list->x,list->y,
  1923. list->first_charid,list->second_charid,list->third_charid,4,ditem->mob_id,true);
  1924. ditem_prev = ditem;
  1925. ditem = ditem->next;
  1926. ers_free(item_drop_ers, ditem_prev);
  1927. }
  1928. ers_free(item_drop_list_ers, list);
  1929. return 0;
  1930. }
  1931. /*==========================================
  1932. * Sets the item_drop into the item_drop_list.
  1933. * Also performs logging and autoloot if enabled.
  1934. * rate is the drop-rate of the item, required for autoloot.
  1935. * flag : Killed only by homunculus/mercenary?
  1936. *------------------------------------------*/
  1937. static void mob_item_drop(struct mob_data *md, struct item_drop_list *dlist, struct item_drop *ditem, int loot, int drop_rate, bool flag)
  1938. {
  1939. TBL_PC* sd;
  1940. bool test_autoloot;
  1941. //Logs items, dropped by mobs [Lupus]
  1942. log_pick_mob(md, loot?LOG_TYPE_LOOT:LOG_TYPE_PICKDROP_MONSTER, -ditem->item_data.amount, &ditem->item_data);
  1943. sd = map_charid2sd(dlist->first_charid);
  1944. if( sd == NULL ) sd = map_charid2sd(dlist->second_charid);
  1945. if( sd == NULL ) sd = map_charid2sd(dlist->third_charid);
  1946. test_autoloot = sd
  1947. && (drop_rate <= sd->state.autoloot || pc_isautolooting(sd, ditem->item_data.nameid))
  1948. && (flag ? ((battle_config.homunculus_autoloot ? (battle_config.hom_idle_no_share == 0 || !pc_isidle_hom(sd)) : 0) || (battle_config.mercenary_autoloot ? (battle_config.mer_idle_no_share == 0 || !pc_isidle_mer(sd)) : 0)) :
  1949. (battle_config.idle_no_autoloot == 0 || DIFF_TICK(last_tick, sd->idletime) < battle_config.idle_no_autoloot));
  1950. #ifdef AUTOLOOT_DISTANCE
  1951. test_autoloot = test_autoloot && sd->bl.m == md->bl.m
  1952. && check_distance_blxy(&sd->bl, dlist->x, dlist->y, AUTOLOOT_DISTANCE);
  1953. #endif
  1954. if( test_autoloot ) { //Autoloot.
  1955. struct party_data *p = party_search(sd->status.party_id);
  1956. if ((itemdb_search(ditem->item_data.nameid))->flag.broadcast &&
  1957. (!p || !(p->party.item & 2)) // Somehow, if party's pickup distribution is 'Even Share', no announcemet
  1958. )
  1959. intif_broadcast_obtain_special_item(sd, ditem->item_data.nameid, md->mob_id, ITEMOBTAIN_TYPE_MONSTER_ITEM);
  1960. if (party_share_loot(party_search(sd->status.party_id),
  1961. sd, &ditem->item_data, sd->status.char_id) == 0
  1962. ) {
  1963. ers_free(item_drop_ers, ditem);
  1964. return;
  1965. }
  1966. }
  1967. ditem->next = dlist->item;
  1968. dlist->item = ditem;
  1969. }
  1970. TIMER_FUNC(mob_timer_delete){
  1971. struct block_list* bl = map_id2bl(id);
  1972. struct mob_data* md = BL_CAST(BL_MOB, bl);
  1973. if( md )
  1974. {
  1975. if( md->deletetimer != tid )
  1976. {
  1977. ShowError("mob_timer_delete: Timer mismatch: %d != %d\n", tid, md->deletetimer);
  1978. return 0;
  1979. }
  1980. //for Alchemist CANNIBALIZE [Lupus]
  1981. md->deletetimer = INVALID_TIMER;
  1982. unit_free(bl, CLR_TELEPORT);
  1983. }
  1984. return 0;
  1985. }
  1986. /*==========================================
  1987. *
  1988. *------------------------------------------*/
  1989. int mob_deleteslave_sub(struct block_list *bl,va_list ap)
  1990. {
  1991. struct mob_data *md;
  1992. int id;
  1993. nullpo_ret(bl);
  1994. nullpo_ret(md = (struct mob_data *)bl);
  1995. id=va_arg(ap,int);
  1996. if(md->master_id > 0 && md->master_id == id )
  1997. status_kill(bl);
  1998. return 0;
  1999. }
  2000. /*==========================================
  2001. *
  2002. *------------------------------------------*/
  2003. int mob_deleteslave(struct mob_data *md)
  2004. {
  2005. nullpo_ret(md);
  2006. map_foreachinmap(mob_deleteslave_sub, md->bl.m, BL_MOB,md->bl.id);
  2007. return 0;
  2008. }
  2009. // Mob respawning through KAIZEL or NPC_REBIRTH [Skotlex]
  2010. TIMER_FUNC(mob_respawn){
  2011. struct block_list *bl = map_id2bl(id);
  2012. if(!bl) return 0;
  2013. status_revive(bl, (uint8)data, 0);
  2014. return 1;
  2015. }
  2016. void mob_log_damage(struct mob_data *md, struct block_list *src, int damage)
  2017. {
  2018. uint32 char_id = 0;
  2019. int flag = MDLF_NORMAL;
  2020. if( damage < 0 )
  2021. return; //Do nothing for absorbed damage.
  2022. if( !damage && !(src->type&DEFAULT_ENEMY_TYPE(md)) )
  2023. return; //Do not log non-damaging effects from non-enemies.
  2024. switch( src->type )
  2025. {
  2026. case BL_PC:
  2027. {
  2028. struct map_session_data *sd = (TBL_PC*)src;
  2029. char_id = sd->status.char_id;
  2030. if( damage )
  2031. md->attacked_id = src->id;
  2032. break;
  2033. }
  2034. case BL_HOM:
  2035. {
  2036. struct homun_data *hd = (TBL_HOM*)src;
  2037. flag = MDLF_HOMUN;
  2038. if( hd->master )
  2039. char_id = hd->master->status.char_id;
  2040. if( damage )
  2041. md->attacked_id = src->id;
  2042. break;
  2043. }
  2044. case BL_MER:
  2045. {
  2046. struct mercenary_data *mer = (TBL_MER*)src;
  2047. if( mer->master )
  2048. char_id = mer->master->status.char_id;
  2049. if( damage )
  2050. md->attacked_id = src->id;
  2051. break;
  2052. }
  2053. case BL_PET:
  2054. {
  2055. struct pet_data *pd = (TBL_PET*)src;
  2056. flag = MDLF_PET;
  2057. if( pd->master )
  2058. {
  2059. char_id = pd->master->status.char_id;
  2060. if( damage ) //Let mobs retaliate against the pet's master [Skotlex]
  2061. md->attacked_id = pd->master->bl.id;
  2062. }
  2063. break;
  2064. }
  2065. case BL_MOB:
  2066. {
  2067. struct mob_data* md2 = (TBL_MOB*)src;
  2068. if( md2->special_state.ai && md2->master_id )
  2069. {
  2070. struct map_session_data* msd = map_id2sd(md2->master_id);
  2071. if( msd )
  2072. char_id = msd->status.char_id;
  2073. }
  2074. if( !damage )
  2075. break;
  2076. //Let players decide whether to retaliate versus the master or the mob. [Skotlex]
  2077. if( md2->master_id && battle_config.retaliate_to_master )
  2078. md->attacked_id = md2->master_id;
  2079. else
  2080. md->attacked_id = src->id;
  2081. break;
  2082. }
  2083. case BL_ELEM:
  2084. {
  2085. struct elemental_data *ele = (TBL_ELEM*)src;
  2086. if( ele->master )
  2087. char_id = ele->master->status.char_id;
  2088. if( damage )
  2089. md->attacked_id = src->id;
  2090. break;
  2091. }
  2092. default: //For all unhandled types.
  2093. md->attacked_id = src->id;
  2094. }
  2095. //Self damage increases tap bonus
  2096. if (!char_id && src->id == md->bl.id && damage > 0) {
  2097. char_id = src->id;
  2098. flag = MDLF_SELF;
  2099. }
  2100. if( char_id )
  2101. { //Log damage...
  2102. int i,minpos;
  2103. unsigned int mindmg;
  2104. for(i=0,minpos=DAMAGELOG_SIZE-1,mindmg=UINT_MAX;i<DAMAGELOG_SIZE;i++){
  2105. if(md->dmglog[i].id==char_id &&
  2106. md->dmglog[i].flag==flag)
  2107. break;
  2108. if(md->dmglog[i].id==0) { //Store data in first empty slot.
  2109. md->dmglog[i].id = char_id;
  2110. md->dmglog[i].flag= flag;
  2111. if( md->get_bosstype() == BOSSTYPE_MVP )
  2112. pc_damage_log_add(map_charid2sd(char_id),md->bl.id);
  2113. break;
  2114. }
  2115. if(md->dmglog[i].dmg<mindmg && i)
  2116. { //Never overwrite first hit slot (he gets double exp bonus)
  2117. minpos=i;
  2118. mindmg=md->dmglog[i].dmg;
  2119. }
  2120. }
  2121. if(i<DAMAGELOG_SIZE)
  2122. md->dmglog[i].dmg+=damage;
  2123. else {
  2124. md->dmglog[minpos].id = char_id;
  2125. md->dmglog[minpos].flag= flag;
  2126. md->dmglog[minpos].dmg = damage;
  2127. if( md->get_bosstype() == BOSSTYPE_MVP )
  2128. pc_damage_log_add(map_charid2sd(char_id),md->bl.id);
  2129. }
  2130. }
  2131. return;
  2132. }
  2133. //Call when a mob has received damage.
  2134. void mob_damage(struct mob_data *md, struct block_list *src, int damage)
  2135. {
  2136. if( src != nullptr && md->special_state.ai == AI_SPHERE && !md->dmglog[0].id ) {//LOne WOlf explained that ANYONE can trigger the marine countdown skill. [Skotlex]
  2137. md->state.alchemist = 1;
  2138. mobskill_use(md, gettick(), MSC_ALCHEMIST);
  2139. unit_escape(&md->bl, src, 7, 2);
  2140. }
  2141. if (src && damage > 0) { //Store total damage...
  2142. if (UINT_MAX - (unsigned int)damage > md->tdmg)
  2143. md->tdmg += damage;
  2144. else if (md->tdmg == UINT_MAX)
  2145. damage = 0; //Stop recording damage once the cap has been reached.
  2146. else { //Cap damage log...
  2147. damage = (int)(UINT_MAX - md->tdmg);
  2148. md->tdmg = UINT_MAX;
  2149. }
  2150. if ((src != &md->bl) && md->state.aggressive) //No longer aggressive, change to retaliate AI.
  2151. md->state.aggressive = 0;
  2152. //Log damage
  2153. mob_log_damage(md, src, damage);
  2154. md->dmgtick = gettick();
  2155. }
  2156. if (battle_config.show_mob_info&3)
  2157. clif_name_area(&md->bl);
  2158. #if PACKETVER >= 20120404
  2159. if (battle_config.monster_hp_bars_info && !map_getmapflag(md->bl.m, MF_HIDEMOBHPBAR)) {
  2160. int i;
  2161. for(i = 0; i < DAMAGELOG_SIZE; i++){ // must show hp bar to all char who already hit the mob.
  2162. struct map_session_data *sd = map_charid2sd(md->dmglog[i].id);
  2163. if( sd && check_distance_bl(&md->bl, &sd->bl, AREA_SIZE) ) // check if in range
  2164. clif_monster_hp_bar(md, sd->fd);
  2165. }
  2166. }
  2167. #endif
  2168. }
  2169. /*==========================================
  2170. * Signals death of mob.
  2171. * type&1 -> no drops, type&2 -> no exp
  2172. *------------------------------------------*/
  2173. int mob_dead(struct mob_data *md, struct block_list *src, int type)
  2174. {
  2175. struct status_data *status;
  2176. struct map_session_data *sd = NULL, *tmpsd[DAMAGELOG_SIZE];
  2177. struct map_session_data *mvp_sd = NULL, *second_sd = NULL, *third_sd = NULL;
  2178. struct {
  2179. struct party_data *p;
  2180. int id,zeny;
  2181. t_exp base_exp;
  2182. t_exp job_exp;
  2183. } pt[DAMAGELOG_SIZE];
  2184. int i, temp, count, m = md->bl.m;
  2185. int dmgbltypes = 0; // bitfield of all bl types, that caused damage to the mob and are elligible for exp distribution
  2186. unsigned int mvp_damage;
  2187. t_tick tick = gettick();
  2188. bool rebirth, homkillonly, merckillonly;
  2189. status = &md->status;
  2190. if( src && src->type == BL_PC ) {
  2191. sd = (struct map_session_data *)src;
  2192. mvp_sd = sd;
  2193. }
  2194. if( md->guardian_data && md->guardian_data->number >= 0 && md->guardian_data->number < MAX_GUARDIANS )
  2195. guild_castledatasave(md->guardian_data->castle->castle_id, CD_ENABLED_GUARDIAN00 + md->guardian_data->number,0);
  2196. if( src ) { // Use Dead skill only if not killed by Script or Command
  2197. md->status.hp = 1;
  2198. md->state.skillstate = MSS_DEAD;
  2199. mobskill_use(md,tick,-1);
  2200. md->status.hp = 0;
  2201. }
  2202. map_freeblock_lock();
  2203. memset(pt,0,sizeof(pt));
  2204. if(src && src->type == BL_MOB)
  2205. mob_unlocktarget((struct mob_data *)src,tick);
  2206. // filter out entries not eligible for exp distribution
  2207. memset(tmpsd,0,sizeof(tmpsd));
  2208. for(i = 0, count = 0, mvp_damage = 0; i < DAMAGELOG_SIZE && md->dmglog[i].id; i++) {
  2209. struct map_session_data* tsd = NULL;
  2210. if (md->dmglog[i].flag == MDLF_SELF) {
  2211. //Self damage counts as exp tap
  2212. count++;
  2213. continue;
  2214. }
  2215. tsd = map_charid2sd(md->dmglog[i].id);
  2216. if (tsd == NULL)
  2217. continue; // skip empty entries
  2218. if (tsd->bl.m != m)
  2219. continue; // skip players not on this map
  2220. count++; //Only logged into same map chars are counted for the total.
  2221. if (pc_isdead(tsd))
  2222. continue; // skip dead players
  2223. if (md->dmglog[i].flag == MDLF_HOMUN && !hom_is_active(tsd->hd))
  2224. continue; // skip homunc's share if inactive
  2225. if (md->dmglog[i].flag == MDLF_PET && (!tsd->status.pet_id || !tsd->pd))
  2226. continue; // skip pet's share if inactive
  2227. if(md->dmglog[i].dmg > mvp_damage) {
  2228. third_sd = second_sd;
  2229. second_sd = mvp_sd;
  2230. mvp_sd = tsd;
  2231. mvp_damage = md->dmglog[i].dmg;
  2232. }
  2233. tmpsd[i] = tsd; // record as valid damage-log entry
  2234. switch( md->dmglog[i].flag ) {
  2235. case MDLF_NORMAL: dmgbltypes|= BL_PC; break;
  2236. case MDLF_HOMUN: dmgbltypes|= BL_HOM; break;
  2237. case MDLF_PET: dmgbltypes|= BL_PET; break;
  2238. }
  2239. }
  2240. // determines, if the monster was killed by homunculus' damage only
  2241. homkillonly = (bool)( ( dmgbltypes&BL_HOM ) && !( dmgbltypes&~BL_HOM ) );
  2242. // determines if the monster was killed by mercenary damage only
  2243. merckillonly = (bool)((dmgbltypes & BL_MER) && !(dmgbltypes & ~BL_MER));
  2244. if(!battle_config.exp_calc_type && count > 1) { //Apply first-attacker 200% exp share bonus
  2245. //TODO: Determine if this should go before calculating the MVP player instead of after.
  2246. if (UINT_MAX - md->dmglog[0].dmg > md->tdmg) {
  2247. md->tdmg += md->dmglog[0].dmg;
  2248. md->dmglog[0].dmg<<=1;
  2249. } else {
  2250. md->dmglog[0].dmg+= UINT_MAX - md->tdmg;
  2251. md->tdmg = UINT_MAX;
  2252. }
  2253. }
  2254. if(!(type&2) && //No exp
  2255. (!map_getmapflag(m, MF_PVP) || battle_config.pvp_exp) && //Pvp no exp rule [MouseJstr]
  2256. (!md->master_id || !md->special_state.ai) && //Only player-summoned mobs do not give exp. [Skotlex]
  2257. (!map_getmapflag(m, MF_NOBASEEXP) || !map_getmapflag(m, MF_NOJOBEXP)) //Gives Exp
  2258. ) { //Experience calculation.
  2259. int bonus = 100; //Bonus on top of your share (common to all attackers).
  2260. int pnum = 0;
  2261. #ifndef RENEWAL
  2262. if (md->sc.data[SC_RICHMANKIM])
  2263. bonus += md->sc.data[SC_RICHMANKIM]->val2;
  2264. #else
  2265. if (sd && sd->sc.data[SC_RICHMANKIM])
  2266. bonus += sd->sc.data[SC_RICHMANKIM]->val2;
  2267. #endif
  2268. if(sd) {
  2269. temp = status_get_class(&md->bl);
  2270. if(sd->sc.data[SC_MIRACLE]) i = 2; //All mobs are Star Targets
  2271. else
  2272. ARR_FIND(0, MAX_PC_FEELHATE, i, temp == sd->hate_mob[i] &&
  2273. (battle_config.allow_skill_without_day || sg_info[i].day_func()));
  2274. if(i<MAX_PC_FEELHATE && (temp=pc_checkskill(sd,sg_info[i].bless_id)))
  2275. bonus += (i==2?20:10)*temp;
  2276. }
  2277. if(battle_config.mobs_level_up && md->level > md->db->lv) // [Valaris]
  2278. bonus += (md->level-md->db->lv)*battle_config.mobs_level_up_exp_rate;
  2279. for(i = 0; i < DAMAGELOG_SIZE && md->dmglog[i].id; i++) {
  2280. int flag=1,zeny=0;
  2281. t_exp base_exp, job_exp;
  2282. double per; //Your share of the mob's exp
  2283. if (!tmpsd[i]) continue;
  2284. if (!battle_config.exp_calc_type && md->tdmg)
  2285. //jAthena's exp formula based on total damage.
  2286. per = (double)md->dmglog[i].dmg/(double)md->tdmg;
  2287. else {
  2288. //eAthena's exp formula based on max hp.
  2289. per = (double)md->dmglog[i].dmg/(double)status->max_hp;
  2290. if (per > 2) per = 2; // prevents unlimited exp gain
  2291. }
  2292. if (count>1 && battle_config.exp_bonus_attacker) {
  2293. //Exp bonus per additional attacker.
  2294. if (count > battle_config.exp_bonus_max_attacker)
  2295. count = battle_config.exp_bonus_max_attacker;
  2296. per += per*((count-1)*battle_config.exp_bonus_attacker)/100.;
  2297. }
  2298. // change experience for different sized monsters [Valaris]
  2299. if (battle_config.mob_size_influence) {
  2300. switch( md->special_state.size ) {
  2301. case SZ_MEDIUM:
  2302. per /= 2.;
  2303. break;
  2304. case SZ_BIG:
  2305. per *= 2.;
  2306. break;
  2307. }
  2308. }
  2309. if( md->dmglog[i].flag == MDLF_PET )
  2310. per *= battle_config.pet_attack_exp_rate/100.;
  2311. if(battle_config.zeny_from_mobs && md->level) {
  2312. // zeny calculation moblv + random moblv [Valaris]
  2313. zeny=(int) ((md->level+rnd()%md->level)*per*bonus/100.);
  2314. if( md->get_bosstype() == BOSSTYPE_MVP )
  2315. zeny*=rnd()%250;
  2316. }
  2317. if (map_getmapflag(m, MF_NOBASEEXP) || !md->db->base_exp)
  2318. base_exp = 0;
  2319. else {
  2320. double exp = apply_rate2(md->db->base_exp, per, 1);
  2321. exp = apply_rate(exp, bonus);
  2322. exp = apply_rate(exp, map_getmapflag(m, MF_BEXP));
  2323. base_exp = (t_exp)cap_value(exp, 1, MAX_EXP);
  2324. }
  2325. if (map_getmapflag(m, MF_NOJOBEXP) || !md->db->job_exp
  2326. #ifndef RENEWAL
  2327. || md->dmglog[i].flag == MDLF_HOMUN // Homun earned job-exp is always lost.
  2328. #endif
  2329. )
  2330. job_exp = 0;
  2331. else {
  2332. double exp = apply_rate2(md->db->job_exp, per, 1);
  2333. exp = apply_rate(exp, bonus);
  2334. exp = apply_rate(exp, map_getmapflag(m, MF_JEXP));
  2335. job_exp = (t_exp)cap_value(exp, 1, MAX_EXP);
  2336. }
  2337. if ((base_exp > 0 || job_exp > 0) && md->dmglog[i].flag == MDLF_HOMUN && homkillonly && battle_config.hom_idle_no_share && pc_isidle_hom(tmpsd[i]))
  2338. base_exp = job_exp = 0;
  2339. if ( ( temp = tmpsd[i]->status.party_id)>0 ) {
  2340. int j;
  2341. for( j = 0; j < pnum && pt[j].id != temp; j++ ); //Locate party.
  2342. if( j == pnum ) { //Possibly add party.
  2343. pt[pnum].p = party_search(temp);
  2344. if(pt[pnum].p && pt[pnum].p->party.exp) {
  2345. pt[pnum].id = temp;
  2346. pt[pnum].base_exp = base_exp;
  2347. pt[pnum].job_exp = job_exp;
  2348. pt[pnum].zeny = zeny; // zeny share [Valaris]
  2349. pnum++;
  2350. flag = 0;
  2351. }
  2352. } else { //Add to total
  2353. pt[j].base_exp = util::safe_addition_cap( pt[j].base_exp, base_exp, MAX_EXP );
  2354. pt[j].job_exp = util::safe_addition_cap( pt[j].job_exp, job_exp, MAX_EXP );
  2355. pt[j].zeny += zeny; // zeny share [Valaris]
  2356. flag = 0;
  2357. }
  2358. }
  2359. #ifdef RENEWAL
  2360. if (base_exp && tmpsd[i] && tmpsd[i]->hd)
  2361. hom_gainexp(tmpsd[i]->hd, base_exp * battle_config.homunculus_exp_gain / 100); // Homunculus only receive 10% of EXP
  2362. #else
  2363. if (base_exp && md->dmglog[i].flag == MDLF_HOMUN) //tmpsd[i] is null if it has no homunc.
  2364. hom_gainexp(tmpsd[i]->hd, base_exp);
  2365. #endif
  2366. if(flag) {
  2367. if(base_exp || job_exp) {
  2368. if( md->dmglog[i].flag != MDLF_PET || battle_config.pet_attack_exp_to_master ) {
  2369. #ifdef RENEWAL_EXP
  2370. int rate = pc_level_penalty_mod( tmpsd[i], PENALTY_EXP, nullptr, md );
  2371. if (rate != 100) {
  2372. if (base_exp)
  2373. base_exp = (t_exp)cap_value(apply_rate(base_exp, rate), 1, MAX_EXP);
  2374. if (job_exp)
  2375. job_exp = (t_exp)cap_value(apply_rate(job_exp, rate), 1, MAX_EXP);
  2376. }
  2377. #endif
  2378. pc_gainexp(tmpsd[i], &md->bl, base_exp, job_exp, 0);
  2379. }
  2380. }
  2381. if(zeny) // zeny from mobs [Valaris]
  2382. pc_getzeny(tmpsd[i], zeny, LOG_TYPE_PICKDROP_MONSTER, NULL);
  2383. }
  2384. if( md->get_bosstype() == BOSSTYPE_MVP )
  2385. pc_damage_log_clear(tmpsd[i],md->bl.id);
  2386. }
  2387. for( i = 0; i < pnum; i++ ) //Party share.
  2388. party_exp_share(pt[i].p, &md->bl, pt[i].base_exp,pt[i].job_exp,pt[i].zeny);
  2389. } //End EXP giving.
  2390. if( !(type&1) && !map_getmapflag(m, MF_NOMOBLOOT) && !md->state.rebirth && (
  2391. !md->special_state.ai || //Non special mob
  2392. battle_config.alchemist_summon_reward == 2 || //All summoned give drops
  2393. (md->special_state.ai==AI_SPHERE && battle_config.alchemist_summon_reward == 1) //Marine Sphere Drops items.
  2394. ) )
  2395. { // Item Drop
  2396. struct item_drop_list *dlist = ers_alloc(item_drop_list_ers, struct item_drop_list);
  2397. struct item_drop *ditem;
  2398. struct item_data* it = NULL;
  2399. int drop_rate;
  2400. #ifdef RENEWAL_DROP
  2401. int drop_modifier = pc_level_penalty_mod( mvp_sd != nullptr ? mvp_sd : second_sd != nullptr ? second_sd : third_sd, PENALTY_DROP, nullptr, md );
  2402. #endif
  2403. dlist->m = md->bl.m;
  2404. dlist->x = md->bl.x;
  2405. dlist->y = md->bl.y;
  2406. dlist->first_charid = (mvp_sd ? mvp_sd->status.char_id : 0);
  2407. dlist->second_charid = (second_sd ? second_sd->status.char_id : 0);
  2408. dlist->third_charid = (third_sd ? third_sd->status.char_id : 0);
  2409. dlist->item = NULL;
  2410. for (i = 0; i < MAX_MOB_DROP_TOTAL; i++) {
  2411. if (md->db->dropitem[i].nameid == 0)
  2412. continue;
  2413. if ( !(it = itemdb_exists(md->db->dropitem[i].nameid)) )
  2414. continue;
  2415. drop_rate = md->db->dropitem[i].rate;
  2416. if (drop_rate <= 0) {
  2417. if (battle_config.drop_rate0item)
  2418. continue;
  2419. drop_rate = 1;
  2420. }
  2421. // change drops depending on monsters size [Valaris]
  2422. if (battle_config.mob_size_influence) {
  2423. if (md->special_state.size == SZ_MEDIUM && drop_rate >= 2)
  2424. drop_rate /= 2;
  2425. else if( md->special_state.size == SZ_BIG)
  2426. drop_rate *= 2;
  2427. }
  2428. if (src) {
  2429. //Drops affected by luk as a fixed increase [Valaris]
  2430. if (battle_config.drops_by_luk)
  2431. drop_rate += status_get_luk(src)*battle_config.drops_by_luk/100;
  2432. //Drops affected by luk as a % increase [Skotlex]
  2433. if (battle_config.drops_by_luk2)
  2434. drop_rate += (int)(0.5+drop_rate*status_get_luk(src)*battle_config.drops_by_luk2/10000.);
  2435. }
  2436. // Player specific drop rate adjustments
  2437. if( sd ){
  2438. int drop_rate_bonus = 0;
  2439. // pk_mode increase drops if 20 level difference [Valaris]
  2440. if( battle_config.pk_mode && (int)(md->level - sd->status.base_level) >= 20 )
  2441. drop_rate = (int)(drop_rate*1.25);
  2442. // Add class and race specific bonuses
  2443. drop_rate_bonus += sd->indexed_bonus.dropaddclass[md->status.class_] + sd->indexed_bonus.dropaddclass[CLASS_ALL];
  2444. drop_rate_bonus += sd->indexed_bonus.dropaddrace[md->status.race] + sd->indexed_bonus.dropaddrace[RC_ALL];
  2445. // Increase drop rate if user has SC_ITEMBOOST
  2446. if (sd->sc.data[SC_ITEMBOOST])
  2447. drop_rate_bonus += sd->sc.data[SC_ITEMBOOST]->val1;
  2448. drop_rate_bonus = (int)(0.5 + drop_rate * drop_rate_bonus / 100.);
  2449. // Now rig the drop rate to never be over 90% unless it is originally >90%.
  2450. drop_rate = i32max(drop_rate, cap_value(drop_rate_bonus, 0, 9000));
  2451. if (pc_isvip(sd)) { // Increase item drop rate for VIP.
  2452. drop_rate += (int)(0.5 + drop_rate * battle_config.vip_drop_increase / 100.);
  2453. drop_rate = min(drop_rate,10000); //cap it to 100%
  2454. }
  2455. }
  2456. #ifdef RENEWAL_DROP
  2457. if( drop_modifier != 100 ) {
  2458. drop_rate = apply_rate(drop_rate, drop_modifier);
  2459. if( drop_rate < 1 )
  2460. drop_rate = 1;
  2461. }
  2462. #endif
  2463. // attempt to drop the item
  2464. if (rnd() % 10000 >= drop_rate)
  2465. continue;
  2466. if( mvp_sd && it->type == IT_PETEGG ) {
  2467. pet_create_egg(mvp_sd, md->db->dropitem[i].nameid);
  2468. continue;
  2469. }
  2470. ditem = mob_setdropitem(&md->db->dropitem[i], 1, md->mob_id);
  2471. //A Rare Drop Global Announce by Lupus
  2472. if( mvp_sd && drop_rate <= battle_config.rare_drop_announce ) {
  2473. char message[128];
  2474. sprintf (message, msg_txt(NULL,541), mvp_sd->status.name, md->name, it->ename.c_str(), (float)drop_rate/100);
  2475. //MSG: "'%s' won %s's %s (chance: %0.02f%%)"
  2476. intif_broadcast(message,strlen(message)+1,BC_DEFAULT);
  2477. }
  2478. // Announce first, or else ditem will be freed. [Lance]
  2479. // By popular demand, use base drop rate for autoloot code. [Skotlex]
  2480. mob_item_drop(md, dlist, ditem, 0, battle_config.autoloot_adjust ? drop_rate : md->db->dropitem[i].rate, homkillonly || merckillonly);
  2481. }
  2482. // Ore Discovery [Celest]
  2483. if (sd == mvp_sd && pc_checkskill(sd,BS_FINDINGORE)>0 && battle_config.finding_ore_rate/10 >= rnd()%10000) {
  2484. struct s_mob_drop mobdrop;
  2485. memset(&mobdrop, 0, sizeof(struct s_mob_drop));
  2486. mobdrop.nameid = itemdb_searchrandomid(IG_FINDINGORE,1);
  2487. ditem = mob_setdropitem(&mobdrop, 1, md->mob_id);
  2488. mob_item_drop(md, dlist, ditem, 0, battle_config.finding_ore_rate/10, homkillonly || merckillonly);
  2489. }
  2490. if(sd) {
  2491. // process script-granted extra drop bonuses
  2492. t_itemid dropid = 0;
  2493. for (const auto &it : sd->add_drop) {
  2494. struct s_mob_drop mobdrop;
  2495. if (!&it || (!it.nameid && !it.group))
  2496. continue;
  2497. if ((it.race < RC_NONE_ && it.race == -md->mob_id) || //Race < RC_NONE_, use mob_id
  2498. (it.race == RC_ALL || it.race == status->race) || //Matched race
  2499. (it.class_ == CLASS_ALL || it.class_ == status->class_)) //Matched class
  2500. {
  2501. //Check if the bonus item drop rate should be multiplied with mob level/10 [Lupus]
  2502. if (it.rate < 0) {
  2503. //It's negative, then it should be multiplied. with mob_level/10
  2504. //rate = base_rate * (mob_level/10) + 1
  2505. drop_rate = (-it.rate) * md->level / 10 + 1;
  2506. drop_rate = cap_value(drop_rate, max(battle_config.item_drop_adddrop_min,1), min(battle_config.item_drop_adddrop_max,10000));
  2507. }
  2508. else
  2509. //it's positive, then it goes as it is
  2510. drop_rate = it.rate;
  2511. if (rnd()%10000 >= drop_rate)
  2512. continue;
  2513. dropid = (it.nameid > 0) ? it.nameid : itemdb_searchrandomid(it.group,1);
  2514. memset(&mobdrop, 0, sizeof(struct s_mob_drop));
  2515. mobdrop.nameid = dropid;
  2516. mob_item_drop(md, dlist, mob_setdropitem(&mobdrop,1,md->mob_id), 0, drop_rate, homkillonly || merckillonly);
  2517. }
  2518. }
  2519. // process script-granted zeny bonus (get_zeny_num) [Skotlex]
  2520. if( sd->bonus.get_zeny_num && rnd()%100 < sd->bonus.get_zeny_rate ) {
  2521. i = sd->bonus.get_zeny_num > 0 ? sd->bonus.get_zeny_num : -md->level * sd->bonus.get_zeny_num;
  2522. if (!i) i = 1;
  2523. pc_getzeny(sd, 1+rnd()%i, LOG_TYPE_PICKDROP_MONSTER, NULL);
  2524. }
  2525. }
  2526. // process items looted by the mob
  2527. if (md->lootitems) {
  2528. for (i = 0; i < md->lootitem_count; i++)
  2529. mob_item_drop(md, dlist, mob_setlootitem(&md->lootitems[i], md->mob_id), 1, 10000, homkillonly || merckillonly);
  2530. }
  2531. if (dlist->item) //There are drop items.
  2532. add_timer(tick + (!battle_config.delay_battle_damage?500:0), mob_delay_item_drop, 0, (intptr_t)dlist);
  2533. else //No drops
  2534. ers_free(item_drop_list_ers, dlist);
  2535. } else if (md->lootitems && md->lootitem_count) { //Loot MUST drop!
  2536. struct item_drop_list *dlist = ers_alloc(item_drop_list_ers, struct item_drop_list);
  2537. dlist->m = md->bl.m;
  2538. dlist->x = md->bl.x;
  2539. dlist->y = md->bl.y;
  2540. dlist->first_charid = (mvp_sd ? mvp_sd->status.char_id : 0);
  2541. dlist->second_charid = (second_sd ? second_sd->status.char_id : 0);
  2542. dlist->third_charid = (third_sd ? third_sd->status.char_id : 0);
  2543. dlist->item = NULL;
  2544. for (i = 0; i < md->lootitem_count; i++)
  2545. mob_item_drop(md, dlist, mob_setlootitem(&md->lootitems[i], md->mob_id), 1, 10000, homkillonly || merckillonly);
  2546. add_timer(tick + (!battle_config.delay_battle_damage?500:0), mob_delay_item_drop, 0, (intptr_t)dlist);
  2547. }
  2548. if( mvp_sd && md->get_bosstype() == BOSSTYPE_MVP ){
  2549. t_itemid log_mvp_nameid = 0;
  2550. t_exp log_mvp_exp = 0;
  2551. clif_mvp_effect( mvp_sd );
  2552. //mapflag: noexp check [Lorky]
  2553. if( md->db->mexp > 0 && !( map_getmapflag( m, MF_NOBASEEXP ) || type&2 ) ){
  2554. log_mvp_exp = md->db->mexp;
  2555. #if defined(RENEWAL_EXP)
  2556. int penalty = pc_level_penalty_mod( mvp_sd, PENALTY_MVP_EXP, nullptr, md );
  2557. log_mvp_exp = cap_value( apply_rate( log_mvp_exp, penalty ), 0, MAX_EXP );
  2558. #endif
  2559. if( battle_config.exp_bonus_attacker > 0 && count > 1 ){
  2560. if( count > battle_config.exp_bonus_max_attacker ){
  2561. count = battle_config.exp_bonus_max_attacker;
  2562. }
  2563. log_mvp_exp += log_mvp_exp * ( battle_config.exp_bonus_attacker * ( count - 1 ) ) / 100;
  2564. }
  2565. log_mvp_exp = cap_value( log_mvp_exp, 1, MAX_EXP );
  2566. clif_mvp_exp( mvp_sd, log_mvp_exp );
  2567. pc_gainexp( mvp_sd, &md->bl, log_mvp_exp, 0, 0 );
  2568. }
  2569. if( !(map_getmapflag(m, MF_NOMVPLOOT) || type&1) ) {
  2570. //Order might be random depending on item_drop_mvp_mode config setting
  2571. struct s_mob_drop mdrop[MAX_MVP_DROP_TOTAL];
  2572. memset(&mdrop,0,sizeof(mdrop));
  2573. if(battle_config.item_drop_mvp_mode == 1) {
  2574. //Random order
  2575. for(i = 0; i < MAX_MVP_DROP_TOTAL; i++) {
  2576. while( 1 ) {
  2577. uint8 va = rnd()%MAX_MVP_DROP_TOTAL;
  2578. if (mdrop[va].nameid == 0) {
  2579. if (md->db->mvpitem[i].nameid > 0)
  2580. memcpy(&mdrop[va],&md->db->mvpitem[i],sizeof(mdrop[va]));
  2581. break;
  2582. }
  2583. }
  2584. }
  2585. } else {
  2586. //Normal order
  2587. for(i = 0; i < MAX_MVP_DROP_TOTAL; i++) {
  2588. if (md->db->mvpitem[i].nameid > 0)
  2589. memcpy(&mdrop[i],&md->db->mvpitem[i],sizeof(mdrop[i]));
  2590. }
  2591. }
  2592. #if defined(RENEWAL_DROP)
  2593. int penalty = pc_level_penalty_mod( mvp_sd, PENALTY_MVP_DROP, nullptr, md );
  2594. #endif
  2595. for(i = 0; i < MAX_MVP_DROP_TOTAL; i++) {
  2596. struct item_data *i_data;
  2597. if(mdrop[i].nameid == 0 || !(i_data = itemdb_exists(mdrop[i].nameid)))
  2598. continue;
  2599. temp = mdrop[i].rate;
  2600. #if defined(RENEWAL_DROP)
  2601. temp = cap_value( apply_rate( temp, penalty ), 0, 10000 );
  2602. #endif
  2603. if (temp != 10000) {
  2604. if(temp <= 0 && !battle_config.drop_rate0item)
  2605. temp = 1;
  2606. if(rnd()%10000 >= temp) //if ==0, then it doesn't drop
  2607. continue;
  2608. }
  2609. struct item item = {};
  2610. item.nameid=mdrop[i].nameid;
  2611. item.identify= itemdb_isidentified(item.nameid);
  2612. clif_mvp_item(mvp_sd,item.nameid);
  2613. log_mvp_nameid = item.nameid;
  2614. //A Rare MVP Drop Global Announce by Lupus
  2615. if(temp<=battle_config.rare_drop_announce) {
  2616. char message[128];
  2617. sprintf (message, msg_txt(NULL,541), mvp_sd->status.name, md->name, i_data->ename.c_str(), temp/100.);
  2618. //MSG: "'%s' won %s's %s (chance: %0.02f%%)"
  2619. intif_broadcast(message,strlen(message)+1,BC_DEFAULT);
  2620. }
  2621. mob_setdropitem_option(&item, &mdrop[i]);
  2622. if((temp = pc_additem(mvp_sd,&item,1,LOG_TYPE_PICKDROP_PLAYER)) != 0) {
  2623. clif_additem(mvp_sd,0,0,temp);
  2624. map_addflooritem(&item,1,mvp_sd->bl.m,mvp_sd->bl.x,mvp_sd->bl.y,mvp_sd->status.char_id,(second_sd?second_sd->status.char_id:0),(third_sd?third_sd->status.char_id:0),1,0,true);
  2625. }
  2626. if (i_data->flag.broadcast)
  2627. intif_broadcast_obtain_special_item(mvp_sd, item.nameid, md->mob_id, ITEMOBTAIN_TYPE_MONSTER_ITEM);
  2628. //Logs items, MVP prizes [Lupus]
  2629. log_pick_mob(md, LOG_TYPE_MVP, -1, &item);
  2630. //If item_drop_mvp_mode is not 2, then only one item should be granted
  2631. if(battle_config.item_drop_mvp_mode != 2) {
  2632. break;
  2633. }
  2634. }
  2635. }
  2636. log_mvpdrop(mvp_sd, md->mob_id, log_mvp_nameid, log_mvp_exp);
  2637. }
  2638. if (type&2 && !sd && md->mob_id == MOBID_EMPERIUM)
  2639. //Emperium destroyed by script. Discard mvp character. [Skotlex]
  2640. mvp_sd = NULL;
  2641. rebirth = ( md->sc.data[SC_KAIZEL] || (md->sc.data[SC_REBIRTH] && !md->state.rebirth) );
  2642. if( !rebirth ) { // Only trigger event on final kill
  2643. if( src ) {
  2644. switch( src->type ) { //allowed type
  2645. case BL_PET:
  2646. case BL_HOM:
  2647. case BL_MER:
  2648. case BL_ELEM:
  2649. case BL_MOB:
  2650. sd = BL_CAST(BL_PC,battle_get_master(src));
  2651. }
  2652. }
  2653. if (sd) {
  2654. std::shared_ptr<s_mob_db> mission_mdb = mob_db.find(sd->mission_mobid), mob = mob_db.find(md->mob_id);
  2655. if ((sd->mission_mobid == md->mob_id) || (mission_mdb != nullptr &&
  2656. ((battle_config.taekwon_mission_mobname == 1 && util::vector_exists(status_get_race2(&md->bl), RC2_GOBLIN) && util::vector_exists(mission_mdb->race2, RC2_GOBLIN)) ||
  2657. (battle_config.taekwon_mission_mobname == 2 && mob->jname.compare(mission_mdb->jname) == 0))))
  2658. { //TK_MISSION [Skotlex]
  2659. if (++(sd->mission_count) >= 100 && (temp = mob_get_random_id(MOBG_Branch_Of_Dead_Tree, static_cast<e_random_monster_flags>(RMF_CHECK_MOB_LV|RMF_MOB_NOT_BOSS|RMF_MOB_NOT_SPAWN), sd->status.base_level)))
  2660. {
  2661. pc_addfame(sd, battle_config.fame_taekwon_mission);
  2662. sd->mission_mobid = temp;
  2663. pc_setglobalreg(sd, add_str(TKMISSIONID_VAR), temp);
  2664. sd->mission_count = 0;
  2665. clif_mission_info(sd, temp, 0);
  2666. }
  2667. pc_setglobalreg(sd, add_str(TKMISSIONCOUNT_VAR), sd->mission_count);
  2668. }
  2669. if (sd->status.party_id)
  2670. map_foreachinallrange(quest_update_objective_sub, &md->bl, AREA_SIZE, BL_PC, sd->status.party_id, md);
  2671. else if (sd->avail_quests)
  2672. quest_update_objective(sd, md);
  2673. if (achievement_db.mobexists(md->mob_id)) {
  2674. if (battle_config.achievement_mob_share > 0 && sd->status.party_id > 0)
  2675. map_foreachinallrange(achievement_update_objective_sub, &md->bl, AREA_SIZE, BL_PC, sd->status.party_id, md->mob_id);
  2676. else
  2677. achievement_update_objective(sd, AG_BATTLE, 1, md->mob_id);
  2678. }
  2679. // The master or Mercenary can increase the kill count
  2680. if (sd->md && src && (src->type == BL_PC || src->type == BL_MER) && mob->lv > sd->status.base_level / 2)
  2681. mercenary_kills(sd->md);
  2682. }
  2683. if( md->npc_event[0] && !md->state.npc_killmonster ) {
  2684. if( sd && battle_config.mob_npc_event_type ) {
  2685. pc_setparam(sd, SP_KILLEDGID, md->bl.id);
  2686. pc_setparam(sd, SP_KILLEDRID, md->mob_id);
  2687. pc_setparam(sd, SP_KILLERRID, sd->bl.id);
  2688. npc_event(sd,md->npc_event,0);
  2689. } else if( mvp_sd ) {
  2690. pc_setparam(mvp_sd, SP_KILLEDGID, md->bl.id);
  2691. pc_setparam(mvp_sd, SP_KILLEDRID, md->mob_id);
  2692. pc_setparam(mvp_sd, SP_KILLERRID, sd?sd->bl.id:0);
  2693. npc_event(mvp_sd,md->npc_event,0);
  2694. } else
  2695. npc_event_do(md->npc_event);
  2696. } else if( mvp_sd && !md->state.npc_killmonster ) {
  2697. pc_setparam(mvp_sd, SP_KILLEDGID, md->bl.id);
  2698. pc_setparam(mvp_sd, SP_KILLEDRID, md->mob_id);
  2699. npc_script_event(mvp_sd, NPCE_KILLNPC); // PCKillNPC [Lance]
  2700. }
  2701. }
  2702. if(md->deletetimer != INVALID_TIMER) {
  2703. delete_timer(md->deletetimer,mob_timer_delete);
  2704. md->deletetimer = INVALID_TIMER;
  2705. }
  2706. /**
  2707. * Only loops if necessary (e.g. a poring would never need to loop)
  2708. **/
  2709. if( md->can_summon )
  2710. mob_deleteslave(md);
  2711. map_freeblock_unlock();
  2712. if( !rebirth ) {
  2713. if( pcdb_checkid(md->vd->class_) ) {//Player mobs are not removed automatically by the client.
  2714. /* first we set them dead, then we delay the outsight effect */
  2715. clif_clearunit_area(&md->bl,CLR_DEAD);
  2716. clif_clearunit_delayed(&md->bl, CLR_OUTSIGHT,tick+3000);
  2717. } else
  2718. /**
  2719. * We give the client some time to breath and this allows it to display anything it'd like with the dead corpose
  2720. * For example, this delay allows it to display soul drain effect
  2721. **/
  2722. clif_clearunit_delayed(&md->bl, CLR_DEAD, tick+250);
  2723. }
  2724. if(!md->spawn){ //Tell status_damage to remove it from memory.
  2725. struct unit_data *ud = unit_bl2ud(&md->bl);
  2726. // If the unit is currently in a walk script, it will be removed there
  2727. return ud->state.walk_script ? 3 : 5; // Note: Actually, it's 4. Oh well...
  2728. }
  2729. // MvP tomb [GreenBox]
  2730. if (battle_config.mvp_tomb_enabled && md->spawn->state.boss && map_getmapflag(md->bl.m, MF_NOTOMB) != 1)
  2731. mvptomb_create(md, mvp_sd ? mvp_sd->status.name : NULL, time(NULL));
  2732. if( !rebirth )
  2733. mob_setdelayspawn(md); //Set respawning.
  2734. return 3; //Remove from map.
  2735. }
  2736. /**
  2737. * Resurect a mob with x hp (reset value and respawn on map)
  2738. * @param md : mob pointer
  2739. * @param hp : hp to resurect him with, @FIXME unused atm
  2740. */
  2741. void mob_revive(struct mob_data *md, unsigned int hp)
  2742. {
  2743. t_tick tick = gettick();
  2744. md->state.skillstate = MSS_IDLE;
  2745. md->last_thinktime = tick;
  2746. md->next_walktime = tick+rnd()%1000+MIN_RANDOMWALKTIME;
  2747. md->last_linktime = tick;
  2748. md->last_pcneartime = 0;
  2749. memset(md->dmglog, 0, sizeof(md->dmglog)); // Reset the damage done on the rebirthed monster, otherwise will grant full exp + damage done. [Valaris]
  2750. md->tdmg = 0;
  2751. if (!md->bl.prev){
  2752. if(map_addblock(&md->bl))
  2753. return;
  2754. }
  2755. clif_spawn(&md->bl);
  2756. skill_unit_move(&md->bl,tick,1);
  2757. mobskill_use(md, tick, MSC_SPAWN);
  2758. if (battle_config.show_mob_info&3)
  2759. clif_name_area(&md->bl);
  2760. }
  2761. int mob_guardian_guildchange(struct mob_data *md)
  2762. {
  2763. struct guild *g;
  2764. nullpo_ret(md);
  2765. if (!md->guardian_data)
  2766. return 0;
  2767. if (md->guardian_data->castle->guild_id == 0)
  2768. { //Castle with no owner? Delete the guardians.
  2769. if (md->mob_id == MOBID_EMPERIUM)
  2770. { //But don't delete the emperium, just clear it's guild-data
  2771. md->guardian_data->guild_id = 0;
  2772. md->guardian_data->emblem_id = 0;
  2773. md->guardian_data->guild_name[0] = '\0';
  2774. } else {
  2775. if (md->guardian_data->number >= 0 && md->guardian_data->number < MAX_GUARDIANS && md->guardian_data->castle->guardian[md->guardian_data->number].visible)
  2776. guild_castledatasave(md->guardian_data->castle->castle_id, CD_ENABLED_GUARDIAN00 + md->guardian_data->number, 0);
  2777. unit_free(&md->bl,CLR_OUTSIGHT); //Remove guardian.
  2778. }
  2779. return 0;
  2780. }
  2781. g = guild_search(md->guardian_data->castle->guild_id);
  2782. if (g == NULL)
  2783. { //Properly remove guardian info from Castle data.
  2784. ShowError("mob_guardian_guildchange: New Guild (id %d) does not exists!\n", md->guardian_data->guild_id);
  2785. if (md->guardian_data->number >= 0 && md->guardian_data->number < MAX_GUARDIANS)
  2786. guild_castledatasave(md->guardian_data->castle->castle_id, CD_ENABLED_GUARDIAN00 + md->guardian_data->number, 0);
  2787. unit_free(&md->bl,CLR_OUTSIGHT);
  2788. return 0;
  2789. }
  2790. md->guardian_data->guild_id = g->guild_id;
  2791. md->guardian_data->emblem_id = g->emblem_id;
  2792. md->guardian_data->guardup_lv = guild_checkskill(g,GD_GUARDUP);
  2793. memcpy(md->guardian_data->guild_name, g->name, NAME_LENGTH);
  2794. return 1;
  2795. }
  2796. /*==========================================
  2797. * Pick a random class for the mob
  2798. *------------------------------------------*/
  2799. int mob_random_class(int *value, size_t count)
  2800. {
  2801. nullpo_ret(value);
  2802. // no count specified, look into the array manually, but take only max 5 elements
  2803. if (count < 1) {
  2804. count = 0;
  2805. while(count < 5 && mobdb_checkid(value[count])) count++;
  2806. if(count < 1) // nothing found
  2807. return 0;
  2808. } else {
  2809. // check if at least the first value is valid
  2810. if(mobdb_checkid(value[0]) == 0)
  2811. return 0;
  2812. }
  2813. //Pick a random value, hoping it exists. [Skotlex]
  2814. return mobdb_checkid(value[rnd()%count]);
  2815. }
  2816. /**
  2817. * Returns the SpawnInfos of the mob_db entry (mob_spawn_data[mobid])
  2818. * if mobid is not in mob_spawn_data returns empty spawn_info vector
  2819. * @param mob_id - Looking for spawns of this Monster ID
  2820. */
  2821. const std::vector<spawn_info> mob_get_spawns(uint16 mob_id)
  2822. {
  2823. auto mob_spawn_it = mob_spawn_data.find(mob_id);
  2824. if ( mob_spawn_it != mob_spawn_data.end() )
  2825. return mob_spawn_it->second;
  2826. return std::vector<spawn_info>();
  2827. }
  2828. /**
  2829. * Checks if a monster is spawned. Returns true if yes, false otherwise.
  2830. * @param mob_id - Monster ID which is checked
  2831. */
  2832. bool mob_has_spawn(uint16 mob_id)
  2833. {
  2834. // It's enough to check if the monster is in mob_spawn_data, because
  2835. // none or empty spawns are ignored. Thus the monster is spawned.
  2836. return mob_spawn_data.find(mob_id) != mob_spawn_data.end();
  2837. }
  2838. /**
  2839. * Adds a spawn info to the specific mob. (To mob_spawn_data)
  2840. * @param mob_id - Monster ID spawned
  2841. * @param new_spawn - spawn_info holding the map and quantity of the spawn
  2842. */
  2843. void mob_add_spawn(uint16 mob_id, const struct spawn_info& new_spawn)
  2844. {
  2845. unsigned short m = new_spawn.mapindex;
  2846. if( new_spawn.qty <= 0 )
  2847. return; //ignore empty spawns
  2848. std::vector<spawn_info>& spawns = mob_spawn_data[mob_id];
  2849. // Search if the map is already in spawns
  2850. auto itSameMap = std::find_if(spawns.begin(), spawns.end(),
  2851. [&m] (const spawn_info &s) { return (s.mapindex == m); });
  2852. if( itSameMap != spawns.end() )
  2853. itSameMap->qty += new_spawn.qty; // add quantity, if map is found
  2854. else
  2855. spawns.push_back(new_spawn); // else, add the whole spawn info
  2856. // sort spawns by spawn quantity
  2857. std::sort(spawns.begin(), spawns.end(),
  2858. [](const spawn_info & a, const spawn_info & b) -> bool
  2859. { return a.qty > b.qty; });
  2860. /** Note
  2861. Spawns are sorted after every addition. This makes reloadscript slower, but
  2862. some spawns may be added directly by loadscript or something similar.
  2863. */
  2864. }
  2865. /*==========================================
  2866. * Change mob base class
  2867. *------------------------------------------*/
  2868. int mob_class_change (struct mob_data *md, int mob_id)
  2869. {
  2870. t_tick tick = gettick();
  2871. int i, hp_rate;
  2872. nullpo_ret(md);
  2873. if( md->bl.prev == NULL )
  2874. return 0;
  2875. if (!mob_id || !mobdb_checkid(mob_id))
  2876. return 0;
  2877. //Disable class changing for some targets...
  2878. if (md->guardian_data)
  2879. return 0; //Guardians/Emperium
  2880. if (util::vector_exists(status_get_race2(&md->bl), RC2_TREASURE))
  2881. return 0; //Treasure Boxes
  2882. if( md->special_state.ai > AI_ATTACK )
  2883. return 0; //Marine Spheres and Floras.
  2884. if( mob_is_clone(md->mob_id) )
  2885. return 0; //Clones
  2886. if( md->mob_id == mob_id )
  2887. return 0; //Nothing to change.
  2888. hp_rate = get_percentage(md->status.hp, md->status.max_hp);
  2889. md->mob_id = mob_id;
  2890. md->db = mob_db.find(mob_id);
  2891. if (battle_config.override_mob_names==1)
  2892. memcpy(md->name,md->db->name.c_str(),NAME_LENGTH);
  2893. else
  2894. memcpy(md->name,md->db->jname.c_str(),NAME_LENGTH);
  2895. status_change_end(&md->bl,SC_KEEPING,INVALID_TIMER); // End before calling status_calc_mob().
  2896. status_change_end(&md->bl,SC_BARRIER,INVALID_TIMER);
  2897. mob_stop_attack(md);
  2898. mob_stop_walking(md, 0);
  2899. unit_skillcastcancel(&md->bl, 0);
  2900. status_set_viewdata(&md->bl, mob_id);
  2901. clif_mob_class_change(md,md->vd->class_);
  2902. status_calc_mob(md,SCO_FIRST);
  2903. md->ud.state.speed_changed = 1; //Speed change update.
  2904. if (battle_config.monster_class_change_recover) {
  2905. memset(md->dmglog, 0, sizeof(md->dmglog));
  2906. md->tdmg = 0;
  2907. } else {
  2908. md->status.hp = md->status.max_hp*hp_rate/100;
  2909. if(md->status.hp < 1) md->status.hp = 1;
  2910. }
  2911. t_tick c = tick - MOB_MAX_DELAY;
  2912. for(i=0;i<MAX_MOBSKILL;i++)
  2913. md->skilldelay[i] = c;
  2914. if (md->lootitems == NULL && status_has_mode(&md->db->status,MD_LOOTER))
  2915. md->lootitems = (struct s_mob_lootitem *)aCalloc(LOOTITEM_SIZE,sizeof(struct s_mob_lootitem));
  2916. //Targets should be cleared no morph
  2917. md->target_id = md->attacked_id = md->norm_attacked_id = 0;
  2918. //Need to update name display.
  2919. clif_name_area(&md->bl);
  2920. return 0;
  2921. }
  2922. /*==========================================
  2923. * mob heal, update display hp info of mob for players
  2924. *------------------------------------------*/
  2925. void mob_heal(struct mob_data *md,unsigned int heal)
  2926. {
  2927. if (battle_config.show_mob_info&3)
  2928. clif_name_area(&md->bl);
  2929. #if PACKETVER >= 20120404
  2930. if (battle_config.monster_hp_bars_info && !map_getmapflag(md->bl.m, MF_HIDEMOBHPBAR)) {
  2931. int i;
  2932. for(i = 0; i < DAMAGELOG_SIZE; i++)// must show hp bar to all char who already hit the mob.
  2933. if( md->dmglog[i].id ) {
  2934. struct map_session_data *sd = map_charid2sd(md->dmglog[i].id);
  2935. if( sd && check_distance_bl(&md->bl, &sd->bl, AREA_SIZE) ) // check if in range
  2936. clif_monster_hp_bar(md, sd->fd);
  2937. }
  2938. }
  2939. #endif
  2940. }
  2941. /*==========================================
  2942. * Added by RoVeRT
  2943. *------------------------------------------*/
  2944. int mob_warpslave_sub(struct block_list *bl,va_list ap)
  2945. {
  2946. struct mob_data *md=(struct mob_data *)bl;
  2947. struct block_list *master;
  2948. short x,y,range=0;
  2949. master = va_arg(ap, struct block_list*);
  2950. range = va_arg(ap, int);
  2951. if(md->master_id!=master->id)
  2952. return 0;
  2953. map_search_freecell(master, 0, &x, &y, range, range, 0);
  2954. unit_warp(&md->bl, master->m, x, y,CLR_TELEPORT);
  2955. return 1;
  2956. }
  2957. /*==========================================
  2958. * Added by RoVeRT
  2959. * Warps slaves. Range is the area around the master that they can
  2960. * appear in randomly.
  2961. *------------------------------------------*/
  2962. int mob_warpslave(struct block_list *bl, int range)
  2963. {
  2964. if (range < 1)
  2965. range = 1; //Min range needed to avoid crashes and stuff. [Skotlex]
  2966. return map_foreachinmap(mob_warpslave_sub, bl->m, BL_MOB, bl, range);
  2967. }
  2968. /*==========================================
  2969. * Counts slave sub, curently checking if mob master is the given ID.
  2970. *------------------------------------------*/
  2971. int mob_countslave_sub(struct block_list *bl,va_list ap)
  2972. {
  2973. int id;
  2974. struct mob_data *md;
  2975. id=va_arg(ap,int);
  2976. md = (struct mob_data *)bl;
  2977. if( md->master_id==id )
  2978. return 1;
  2979. return 0;
  2980. }
  2981. /*==========================================
  2982. * Counts the number of slaves a mob has on the map.
  2983. *------------------------------------------*/
  2984. int mob_countslave(struct block_list *bl)
  2985. {
  2986. return map_foreachinmap(mob_countslave_sub, bl->m, BL_MOB,bl->id);
  2987. }
  2988. /*==========================================
  2989. * Summons amount slaves contained in the value[5] array using round-robin. [adapted by Skotlex]
  2990. *------------------------------------------*/
  2991. int mob_summonslave(struct mob_data *md2,int *value,int amount,uint16 skill_id)
  2992. {
  2993. struct mob_data *md;
  2994. struct spawn_data data;
  2995. int count = 0,k=0,hp_rate=0;
  2996. nullpo_ret(md2);
  2997. nullpo_ret(value);
  2998. memset(&data, 0, sizeof(struct spawn_data));
  2999. data.m = md2->bl.m;
  3000. data.x = md2->bl.x;
  3001. data.y = md2->bl.y;
  3002. data.num = 1;
  3003. data.state.size = md2->special_state.size;
  3004. data.state.ai = md2->special_state.ai;
  3005. if(mobdb_checkid(value[0]) == 0)
  3006. return 0;
  3007. /**
  3008. * Flags this monster is able to summon; saves a worth amount of memory upon deletion
  3009. **/
  3010. md2->can_summon = 1;
  3011. while(count < 5 && mobdb_checkid(value[count])) count++;
  3012. if(count < 1) return 0;
  3013. if (amount > 0 && amount < count) { //Do not start on 0, pick some random sub subset [Skotlex]
  3014. k = rnd()%count;
  3015. amount+=k; //Increase final value by same amount to preserve total number to summon.
  3016. }
  3017. if (!battle_config.monster_class_change_recover &&
  3018. (skill_id == NPC_TRANSFORMATION || skill_id == NPC_METAMORPHOSIS))
  3019. hp_rate = get_percentage(md2->status.hp, md2->status.max_hp);
  3020. for(;k<amount;k++) {
  3021. short x,y;
  3022. data.id = value[k%count]; //Summon slaves in round-robin fashion. [Skotlex]
  3023. if (mobdb_checkid(data.id) == 0)
  3024. continue;
  3025. if (skill_id != NPC_DEATHSUMMON && map_search_freecell(&md2->bl, 0, &x, &y, MOB_SLAVEDISTANCE, MOB_SLAVEDISTANCE, 0)) {
  3026. data.x = x;
  3027. data.y = y;
  3028. } else {
  3029. data.x = md2->bl.x;
  3030. data.y = md2->bl.y;
  3031. }
  3032. //These two need to be loaded from the db for each slave.
  3033. if(battle_config.override_mob_names==1)
  3034. strcpy(data.name,"--en--");
  3035. else
  3036. strcpy(data.name,"--ja--");
  3037. if (!mob_parse_dataset(&data))
  3038. continue;
  3039. md= mob_spawn_dataset(&data);
  3040. if(skill_id == NPC_SUMMONSLAVE){
  3041. md->master_id=md2->bl.id;
  3042. md->special_state.ai = md2->special_state.ai;
  3043. }
  3044. mob_spawn(md);
  3045. if (hp_rate) //Scale HP
  3046. md->status.hp = md->status.max_hp*hp_rate/100;
  3047. if (skill_id == NPC_SUMMONSLAVE) // Only appies to NPC_SUMMONSLAVE
  3048. status_calc_slave_mode(md, md2); // Inherit the aggressive mode of the master.
  3049. if (md2->state.copy_master_mode)
  3050. md->status.mode = md2->status.mode;
  3051. clif_skill_nodamage(&md->bl,&md->bl,skill_id,amount,1);
  3052. }
  3053. return 0;
  3054. }
  3055. /*==========================================
  3056. * MOBskill lookup (get skillindex through skill_id)
  3057. * Returns -1 if not found.
  3058. *------------------------------------------*/
  3059. int mob_skill_id2skill_idx(int mob_id,uint16 skill_id)
  3060. {
  3061. std::shared_ptr<s_mob_db> mob = mob_db.find(mob_id);
  3062. if (mob == nullptr)
  3063. return -1;
  3064. std::vector<std::shared_ptr<s_mob_skill>> &skills = mob->skill;
  3065. if (skills.empty())
  3066. return -1;
  3067. for (int i = 0; i < skills.size(); i++) {
  3068. if (skills[i]->skill_id == skill_id)
  3069. return i;
  3070. }
  3071. return -1;
  3072. }
  3073. /*==========================================
  3074. * Friendly Mob whose HP is decreasing by a nearby MOB is looked for.
  3075. *------------------------------------------*/
  3076. int mob_getfriendhprate_sub(struct block_list *bl,va_list ap)
  3077. {
  3078. int min_rate, max_rate,rate;
  3079. struct block_list **fr;
  3080. struct mob_data *md;
  3081. md = va_arg(ap,struct mob_data *);
  3082. min_rate=va_arg(ap,int);
  3083. max_rate=va_arg(ap,int);
  3084. fr=va_arg(ap,struct block_list **);
  3085. if( md->bl.id == bl->id && !(battle_config.mob_ai&0x10))
  3086. return 0;
  3087. if ((*fr) != NULL) //A friend was already found.
  3088. return 0;
  3089. if (battle_check_target(&md->bl,bl,BCT_ENEMY)>0)
  3090. return 0;
  3091. rate = get_percentage(status_get_hp(bl), status_get_max_hp(bl));
  3092. if (rate >= min_rate && rate <= max_rate)
  3093. (*fr) = bl;
  3094. return 1;
  3095. }
  3096. static struct block_list *mob_getfriendhprate(struct mob_data *md,int min_rate,int max_rate)
  3097. {
  3098. struct block_list *fr=NULL;
  3099. int type = BL_MOB;
  3100. nullpo_retr(NULL, md);
  3101. if (md->special_state.ai) //Summoned creatures. [Skotlex]
  3102. type = BL_PC;
  3103. map_foreachinallrange(mob_getfriendhprate_sub, &md->bl, 8, type,md,min_rate,max_rate,&fr);
  3104. return fr;
  3105. }
  3106. /*==========================================
  3107. * Check hp rate of its master
  3108. *------------------------------------------*/
  3109. struct block_list *mob_getmasterhpltmaxrate(struct mob_data *md,int rate)
  3110. {
  3111. if( md && md->master_id > 0 )
  3112. {
  3113. struct block_list *bl = map_id2bl(md->master_id);
  3114. if( bl && get_percentage(status_get_hp(bl), status_get_max_hp(bl)) < rate )
  3115. return bl;
  3116. }
  3117. return NULL;
  3118. }
  3119. /*==========================================
  3120. * What a status state suits by nearby MOB is looked for.
  3121. *------------------------------------------*/
  3122. int mob_getfriendstatus_sub(struct block_list *bl,va_list ap)
  3123. {
  3124. int cond1,cond2;
  3125. struct mob_data **fr, *md, *mmd;
  3126. int flag=0;
  3127. nullpo_ret(bl);
  3128. nullpo_ret(md=(struct mob_data *)bl);
  3129. nullpo_ret(mmd=va_arg(ap,struct mob_data *));
  3130. if( mmd->bl.id == bl->id && !(battle_config.mob_ai&0x10) )
  3131. return 0;
  3132. if (battle_check_target(&mmd->bl,bl,BCT_ENEMY)>0)
  3133. return 0;
  3134. cond1=va_arg(ap,int);
  3135. cond2=va_arg(ap,int);
  3136. fr=va_arg(ap,struct mob_data **);
  3137. if( cond2==-1 ){
  3138. int j;
  3139. for(j=SC_COMMON_MIN;j<=SC_COMMON_MAX && !flag;j++){
  3140. if ((flag=(md->sc.data[j] != NULL))) //Once an effect was found, break out. [Skotlex]
  3141. break;
  3142. }
  3143. }else
  3144. flag=( md->sc.data[cond2] != NULL );
  3145. if( flag^( cond1==MSC_FRIENDSTATUSOFF ) )
  3146. (*fr)=md;
  3147. return 0;
  3148. }
  3149. struct mob_data *mob_getfriendstatus(struct mob_data *md,int cond1,int cond2)
  3150. {
  3151. struct mob_data* fr = NULL;
  3152. nullpo_ret(md);
  3153. map_foreachinallrange(mob_getfriendstatus_sub, &md->bl, 8,BL_MOB, md,cond1,cond2,&fr);
  3154. return fr;
  3155. }
  3156. /*==========================================
  3157. * Skill use judging
  3158. *------------------------------------------*/
  3159. int mobskill_use(struct mob_data *md, t_tick tick, int event)
  3160. {
  3161. struct block_list *fbl = NULL; //Friend bl, which can either be a BL_PC or BL_MOB depending on the situation. [Skotlex]
  3162. struct block_list *bl;
  3163. struct mob_data *fmd = NULL;
  3164. int i,j,n;
  3165. short skill_target;
  3166. nullpo_ret(md);
  3167. std::vector<std::shared_ptr<s_mob_skill>> &ms = md->db->skill;
  3168. if (!battle_config.mob_skill_rate || md->ud.skilltimer != INVALID_TIMER || ms.empty() || status_has_mode(&md->status,MD_NOCAST))
  3169. return 0;
  3170. if (event == -1 && DIFF_TICK(md->ud.canact_tick, tick) > 0)
  3171. return 0; //Skill act delay only affects non-event skills.
  3172. //Pick a starting position and loop from that.
  3173. i = battle_config.mob_ai&0x100?rnd()%ms.size():0;
  3174. for (n = 0; n < ms.size(); i++, n++) {
  3175. int c2, flag = 0;
  3176. if (i == ms.size())
  3177. i = 0;
  3178. if (DIFF_TICK(tick, md->skilldelay[i]) < ms[i]->delay)
  3179. continue;
  3180. c2 = ms[i]->cond2;
  3181. if (ms[i]->state != md->state.skillstate) {
  3182. if (md->state.skillstate != MSS_DEAD && (ms[i]->state == MSS_ANY ||
  3183. (ms[i]->state == MSS_ANYTARGET && md->target_id && md->state.skillstate != MSS_LOOT)
  3184. )) //ANYTARGET works with any state as long as there's a target. [Skotlex]
  3185. ;
  3186. else
  3187. continue;
  3188. }
  3189. if (rnd() % 10000 > ms[i]->permillage) //Lupus (max value = 10000)
  3190. continue;
  3191. if (ms[i]->cond1 == event)
  3192. flag = 1; //Trigger skill.
  3193. else if (ms[i]->cond1 == MSC_SKILLUSED)
  3194. flag = ((event & 0xffff) == MSC_SKILLUSED && ((event >> 16) == c2 || c2 == 0));
  3195. else if(event == -1){
  3196. //Avoid entering on defined events to avoid "hyper-active skill use" due to the overflow of calls to this function in battle.
  3197. switch (ms[i]->cond1)
  3198. {
  3199. case MSC_ALWAYS:
  3200. flag = 1; break;
  3201. case MSC_MYHPLTMAXRATE: // HP< maxhp%
  3202. flag = get_percentage(md->status.hp, md->status.max_hp);
  3203. flag = (flag <= c2);
  3204. break;
  3205. case MSC_MYHPINRATE:
  3206. flag = get_percentage(md->status.hp, md->status.max_hp);
  3207. flag = (flag >= c2 && flag <= ms[i]->val[0]);
  3208. break;
  3209. case MSC_MYSTATUSON: // status[num] on
  3210. case MSC_MYSTATUSOFF: // status[num] off
  3211. if (!md->sc.count) {
  3212. flag = 0;
  3213. } else if (ms[i]->cond2 == -1) {
  3214. for (j = SC_COMMON_MIN; j <= SC_COMMON_MAX; j++)
  3215. if ((flag = (md->sc.data[j]!=NULL)) != 0)
  3216. break;
  3217. } else {
  3218. flag = (md->sc.data[ms[i]->cond2]!=NULL);
  3219. }
  3220. flag ^= (ms[i]->cond1 == MSC_MYSTATUSOFF); break;
  3221. case MSC_FRIENDHPLTMAXRATE: // friend HP < maxhp%
  3222. flag = ((fbl = mob_getfriendhprate(md, 0, ms[i]->cond2)) != NULL); break;
  3223. case MSC_FRIENDHPINRATE :
  3224. flag = ((fbl = mob_getfriendhprate(md, ms[i]->cond2, ms[i]->val[0])) != NULL); break;
  3225. case MSC_FRIENDSTATUSON: // friend status[num] on
  3226. case MSC_FRIENDSTATUSOFF: // friend status[num] off
  3227. flag = ((fmd = mob_getfriendstatus(md, ms[i]->cond1, ms[i]->cond2)) != NULL); break;
  3228. case MSC_SLAVELT: // slave < num
  3229. flag = (mob_countslave(&md->bl) < c2 ); break;
  3230. case MSC_ATTACKPCGT: // attack pc > num
  3231. flag = (unit_counttargeted(&md->bl) > c2); break;
  3232. case MSC_SLAVELE: // slave <= num
  3233. flag = (mob_countslave(&md->bl) <= c2 ); break;
  3234. case MSC_ATTACKPCGE: // attack pc >= num
  3235. flag = (unit_counttargeted(&md->bl) >= c2); break;
  3236. case MSC_AFTERSKILL:
  3237. flag = (md->ud.skill_id == c2); break;
  3238. case MSC_RUDEATTACKED:
  3239. flag = (md->state.attacked_count >= RUDE_ATTACKED_COUNT);
  3240. if (flag) md->state.attacked_count = 0; //Rude attacked count should be reset after the skill condition is met. Thanks to Komurka [Skotlex]
  3241. break;
  3242. case MSC_MASTERHPLTMAXRATE:
  3243. flag = ((fbl = mob_getmasterhpltmaxrate(md, ms[i]->cond2)) != NULL); break;
  3244. case MSC_MASTERATTACKED:
  3245. flag = (md->master_id > 0 && (fbl=map_id2bl(md->master_id)) && unit_counttargeted(fbl) > 0); break;
  3246. case MSC_ALCHEMIST:
  3247. flag = (md->state.alchemist);
  3248. break;
  3249. }
  3250. }
  3251. if (!flag)
  3252. continue; //Skill requisite failed to be fulfilled.
  3253. //Execute skill
  3254. skill_target = status_has_mode(&md->db->status,MD_RANDOMTARGET) ? MST_RANDOM : ms[i]->target;
  3255. if (skill_get_casttype(ms[i]->skill_id) == CAST_GROUND)
  3256. { //Ground skill.
  3257. short x, y;
  3258. switch (skill_target) {
  3259. case MST_RANDOM: //Pick a random enemy within skill range.
  3260. bl = battle_getenemy(&md->bl, DEFAULT_ENEMY_TYPE(md),
  3261. skill_get_range2(&md->bl, ms[i]->skill_id, ms[i]->skill_lv, true));
  3262. break;
  3263. case MST_TARGET:
  3264. case MST_AROUND5:
  3265. case MST_AROUND6:
  3266. case MST_AROUND7:
  3267. case MST_AROUND8:
  3268. bl = map_id2bl(md->target_id);
  3269. break;
  3270. case MST_MASTER:
  3271. bl = &md->bl;
  3272. if (md->master_id)
  3273. bl = map_id2bl(md->master_id);
  3274. if (bl) //Otherwise, fall through.
  3275. break;
  3276. case MST_FRIEND:
  3277. bl = fbl?fbl:(fmd?&fmd->bl:&md->bl);
  3278. break;
  3279. default:
  3280. bl = &md->bl;
  3281. break;
  3282. }
  3283. if (!bl) continue;
  3284. x = bl->x;
  3285. y = bl->y;
  3286. // Look for an area to cast the spell around...
  3287. if (skill_target >= MST_AROUND5) {
  3288. j = skill_target >= MST_AROUND1?
  3289. (skill_target-MST_AROUND1) +1:
  3290. (skill_target-MST_AROUND5) +1;
  3291. map_search_freecell(&md->bl, md->bl.m, &x, &y, j, j, 3);
  3292. }
  3293. md->skill_idx = i;
  3294. map_freeblock_lock();
  3295. if (!battle_check_range(&md->bl, bl, skill_get_range2(&md->bl, ms[i]->skill_id, ms[i]->skill_lv, true)) ||
  3296. !unit_skilluse_pos2(&md->bl, x, y, ms[i]->skill_id, ms[i]->skill_lv, ms[i]->casttime, ms[i]->cancel))
  3297. {
  3298. map_freeblock_unlock();
  3299. continue;
  3300. }
  3301. } else {
  3302. //Targetted skill
  3303. switch (skill_target) {
  3304. case MST_RANDOM: //Pick a random enemy within skill range.
  3305. bl = battle_getenemy(&md->bl, DEFAULT_ENEMY_TYPE(md),
  3306. skill_get_range2(&md->bl, ms[i]->skill_id, ms[i]->skill_lv, true));
  3307. break;
  3308. case MST_TARGET:
  3309. bl = map_id2bl(md->target_id);
  3310. break;
  3311. case MST_MASTER:
  3312. bl = &md->bl;
  3313. if (md->master_id)
  3314. bl = map_id2bl(md->master_id);
  3315. if (bl) //Otherwise, fall through.
  3316. break;
  3317. case MST_FRIEND:
  3318. if (fbl) {
  3319. bl = fbl;
  3320. break;
  3321. } else if (fmd) {
  3322. bl = &fmd->bl;
  3323. break;
  3324. } // else fall through
  3325. default:
  3326. bl = &md->bl;
  3327. break;
  3328. }
  3329. if (!bl) continue;
  3330. md->skill_idx = i;
  3331. map_freeblock_lock();
  3332. if (!battle_check_range(&md->bl, bl, skill_get_range2(&md->bl, ms[i]->skill_id, ms[i]->skill_lv, true)) ||
  3333. !unit_skilluse_id2(&md->bl, bl->id, ms[i]->skill_id, ms[i]->skill_lv, ms[i]->casttime, ms[i]->cancel))
  3334. {
  3335. map_freeblock_unlock();
  3336. continue;
  3337. }
  3338. }
  3339. //Skill used. Post-setups...
  3340. if ( ms[i]->msg_id ){ //Display color message [SnakeDrak]
  3341. struct mob_chat *mc = mob_chat(ms[i]->msg_id);
  3342. if (mc) {
  3343. std::string name = md->name, output;
  3344. std::size_t unique = name.find("#");
  3345. if (unique != std::string::npos)
  3346. name = name.substr(0, unique); // discard extra name identifier if present [Daegaladh]
  3347. output = name + " : " + mc->msg;
  3348. clif_messagecolor(&md->bl, mc->color, output.c_str(), true, AREA_CHAT_WOC);
  3349. }
  3350. }
  3351. if(!(battle_config.mob_ai&0x200)) { //pass on delay to same skill.
  3352. for (j = 0; j < ms.size(); j++)
  3353. if (ms[j]->skill_id == ms[i]->skill_id)
  3354. md->skilldelay[j]=tick;
  3355. } else
  3356. md->skilldelay[i]=tick;
  3357. map_freeblock_unlock();
  3358. return 1;
  3359. }
  3360. //No skill was used.
  3361. md->skill_idx = -1;
  3362. return 0;
  3363. }
  3364. /*==========================================
  3365. * Skill use event processing
  3366. *------------------------------------------*/
  3367. int mobskill_event(struct mob_data *md, struct block_list *src, t_tick tick, int flag)
  3368. {
  3369. int target_id, res = 0;
  3370. if(md->bl.prev == NULL || md->status.hp == 0)
  3371. return 0;
  3372. target_id = md->target_id;
  3373. if (!target_id || battle_config.mob_changetarget_byskill)
  3374. md->target_id = src->id;
  3375. if (flag == -1)
  3376. res = mobskill_use(md, tick, MSC_CASTTARGETED);
  3377. else if ((flag&0xffff) == MSC_SKILLUSED)
  3378. res = mobskill_use(md, tick, flag);
  3379. else if (flag&BF_SHORT)
  3380. res = mobskill_use(md, tick, MSC_CLOSEDATTACKED);
  3381. else if (flag&BF_LONG && !(flag&BF_MAGIC)) //Long-attacked should not include magic.
  3382. res = mobskill_use(md, tick, MSC_LONGRANGEATTACKED);
  3383. if (!res)
  3384. //Restore previous target only if skill condition failed to trigger. [Skotlex]
  3385. md->target_id = target_id;
  3386. //Otherwise check if the target is an enemy, and unlock if needed.
  3387. else if (battle_check_target(&md->bl, src, BCT_ENEMY) <= 0)
  3388. md->target_id = target_id;
  3389. return res;
  3390. }
  3391. // Player cloned mobs. [Valaris]
  3392. int mob_is_clone(int mob_id)
  3393. {
  3394. if(mob_id < MOB_CLONE_START || mob_id > MOB_CLONE_END)
  3395. return 0;
  3396. if (!mob_db.exists(mob_id))
  3397. return 0;
  3398. return mob_id;
  3399. }
  3400. /**
  3401. * Previously, using skill_nocast with flag 16
  3402. * @param skill_id
  3403. * @return True:If disabled, False:If enabled
  3404. * @!TODO : Move this hardcodes!
  3405. **/
  3406. static bool mob_clone_disabled_skills(uint16 skill_id) {
  3407. switch (skill_id) {
  3408. case PR_TURNUNDEAD:
  3409. case PR_MAGNUS:
  3410. return true;
  3411. }
  3412. return false;
  3413. }
  3414. //Flag values:
  3415. //&1: Set special ai (fight mobs, not players)
  3416. //If mode is not passed, a default aggressive mode is used.
  3417. //If master_id is passed, clone is attached to him.
  3418. //Returns: ID of newly crafted copy.
  3419. int mob_clone_spawn(struct map_session_data *sd, int16 m, int16 x, int16 y, const char *event, int master_id, enum e_mode mode, int flag, unsigned int duration)
  3420. {
  3421. int mob_id;
  3422. int i,j,inf, fd;
  3423. struct mob_data *md;
  3424. struct status_data *status;
  3425. nullpo_ret(sd);
  3426. if(pc_isdead(sd) && master_id && flag&1)
  3427. return 0;
  3428. ARR_FIND( MOB_CLONE_START, MOB_CLONE_END, mob_id, !mob_db.exists(mob_id) );
  3429. if(mob_id >= MOB_CLONE_END)
  3430. return 0;
  3431. std::shared_ptr<s_mob_db> db = std::make_shared<s_mob_db>();
  3432. mob_db.put( mob_id, db );
  3433. status = &db->status;
  3434. db->sprite = sd->status.name;
  3435. db->name = sd->status.name;
  3436. db->jname = sd->status.name;
  3437. db->lv=status_get_lv(&sd->bl);
  3438. memcpy(status, &sd->base_status, sizeof(struct status_data));
  3439. status->rhw.atk2= status->dex + status->rhw.atk + status->rhw.atk2; //Max ATK
  3440. status->rhw.atk = status->dex; //Min ATK
  3441. if (status->lhw.atk) {
  3442. status->lhw.atk2= status->dex + status->lhw.atk + status->lhw.atk2; //Max ATK
  3443. status->lhw.atk = status->dex; //Min ATK
  3444. }
  3445. if (mode) //User provided mode.
  3446. status->mode = mode;
  3447. else if (flag&1) //Friendly Character, remove looting.
  3448. status->mode = static_cast<enum e_mode>(status->mode&(~MD_LOOTER));
  3449. status->hp = status->max_hp;
  3450. status->sp = status->max_sp;
  3451. memcpy(&db->vd, &sd->vd, sizeof(struct view_data));
  3452. db->base_exp=1;
  3453. db->job_exp=1;
  3454. db->range2=AREA_SIZE; //Let them have the same view-range as players.
  3455. db->range3=AREA_SIZE; //Min chase of a screen.
  3456. db->option=sd->sc.option;
  3457. /**
  3458. * We temporarily disable sd's fd so it doesn't receive the messages from skill_check_condition_castbegin
  3459. **/
  3460. fd = sd->fd;
  3461. sd->fd = 0;
  3462. //Go Backwards to give better priority to advanced skills.
  3463. for (i=0,j = MAX_SKILL_TREE-1;j>=0 && i< MAX_MOBSKILL ;j--) {
  3464. uint16 skill_id = skill_tree[pc_class2idx(sd->status.class_)][j].skill_id;
  3465. uint16 sk_idx = 0;
  3466. if (!skill_id || !(sk_idx = skill_get_index(skill_id)) || sd->status.skill[sk_idx].lv < 1 ||
  3467. skill_get_inf2_(skill_id, { INF2_ISWEDDING, INF2_ISGUILD }) ||
  3468. mob_clone_disabled_skills(skill_id)
  3469. )
  3470. continue;
  3471. //Normal aggressive mob, disable skills that cannot help them fight
  3472. //against players (those with flags UF_NOMOB and UF_NOPC are specific
  3473. //to always aid players!) [Skotlex]
  3474. if (!(flag&1) &&
  3475. skill_get_unit_id(skill_id) &&
  3476. skill_get_unit_flag_(skill_id, { UF_NOMOB, UF_NOPC }))
  3477. continue;
  3478. /**
  3479. * The clone should be able to cast the skill (e.g. have the required weapon) bugreport:5299)
  3480. **/
  3481. if( !skill_check_condition_castbegin(sd,skill_id,sd->status.skill[sk_idx].lv) )
  3482. continue;
  3483. std::shared_ptr<s_mob_skill> ms = std::make_shared<s_mob_skill>();
  3484. ms->skill_id = skill_id;
  3485. ms->skill_lv = sd->status.skill[sk_idx].lv;
  3486. ms->state = MSS_ANY;
  3487. ms->permillage = 500*battle_config.mob_skill_rate/100; //Default chance of all skills: 5%
  3488. ms->emotion = -1;
  3489. ms->cancel = 0;
  3490. ms->casttime = skill_castfix(&sd->bl,skill_id, ms->skill_lv);
  3491. ms->delay = 5000+skill_delayfix(&sd->bl,skill_id, ms->skill_lv);
  3492. ms->msg_id = 0;
  3493. inf = skill_get_inf(skill_id);
  3494. if (inf&INF_ATTACK_SKILL) {
  3495. ms->target = MST_TARGET;
  3496. ms->cond1 = MSC_ALWAYS;
  3497. if (skill_get_range(skill_id, ms->skill_lv) > 3)
  3498. ms->state = MSS_ANYTARGET;
  3499. else
  3500. ms->state = MSS_BERSERK;
  3501. } else if(inf&INF_GROUND_SKILL) {
  3502. if (skill_get_inf2(skill_id, INF2_ISTRAP)) { //Traps!
  3503. ms->state = MSS_IDLE;
  3504. ms->target = MST_AROUND2;
  3505. ms->delay = 60000;
  3506. } else if (skill_get_unit_target(skill_id) == BCT_ENEMY) { //Target Enemy
  3507. ms->state = MSS_ANYTARGET;
  3508. ms->target = MST_TARGET;
  3509. ms->cond1 = MSC_ALWAYS;
  3510. } else { //Target allies
  3511. ms->target = MST_FRIEND;
  3512. ms->cond1 = MSC_FRIENDHPLTMAXRATE;
  3513. ms->cond2 = 95;
  3514. }
  3515. } else if (inf&INF_SELF_SKILL) {
  3516. if (skill_get_inf2(skill_id, INF2_NOTARGETSELF)) { //auto-select target skill.
  3517. ms->target = MST_TARGET;
  3518. ms->cond1 = MSC_ALWAYS;
  3519. if (skill_get_range(skill_id, ms->skill_lv) > 3) {
  3520. ms->state = MSS_ANYTARGET;
  3521. } else {
  3522. ms->state = MSS_BERSERK;
  3523. }
  3524. } else { //Self skill
  3525. ms->target = MST_SELF;
  3526. ms->cond1 = MSC_MYHPLTMAXRATE;
  3527. ms->cond2 = 90;
  3528. ms->permillage = 2000;
  3529. //Delay: Remove the stock 5 secs and add half of the support time.
  3530. ms->delay += -5000 +(skill_get_time(skill_id, ms->skill_lv) + skill_get_time2(skill_id, ms->skill_lv))/2;
  3531. if (ms->delay < 5000)
  3532. ms->delay = 5000; //With a minimum of 5 secs.
  3533. }
  3534. } else if (inf&INF_SUPPORT_SKILL) {
  3535. ms->target = MST_FRIEND;
  3536. ms->cond1 = MSC_FRIENDHPLTMAXRATE;
  3537. ms->cond2 = 90;
  3538. if (skill_id == AL_HEAL)
  3539. ms->permillage = 5000; //Higher skill rate usage for heal.
  3540. else if (skill_id == ALL_RESURRECTION)
  3541. ms->cond2 = 1;
  3542. //Delay: Remove the stock 5 secs and add half of the support time.
  3543. ms->delay += -5000 +(skill_get_time(skill_id, ms->skill_lv) + skill_get_time2(skill_id, ms->skill_lv))/2;
  3544. if (ms->delay < 2000)
  3545. ms->delay = 2000; //With a minimum of 2 secs.
  3546. if (i+1 < MAX_MOBSKILL) { //duplicate this so it also triggers on self.
  3547. ms->target = MST_SELF;
  3548. ms->cond1 = MSC_MYHPLTMAXRATE;
  3549. db->skill.insert(db->skill.begin() + i, ms);
  3550. ++i;
  3551. }
  3552. } else {
  3553. switch (skill_id) { //Certain Special skills that are passive, and thus, never triggered.
  3554. case MO_TRIPLEATTACK:
  3555. case TF_DOUBLE:
  3556. case GS_CHAINACTION:
  3557. ms->state = MSS_BERSERK;
  3558. ms->target = MST_TARGET;
  3559. ms->cond1 = MSC_ALWAYS;
  3560. ms->permillage = skill_id==MO_TRIPLEATTACK?(3000-ms->skill_lv*100):(ms->skill_lv*500);
  3561. ms->delay -= 5000; //Remove the added delay as these could trigger on "all hits".
  3562. break;
  3563. default: //Untreated Skill
  3564. continue;
  3565. }
  3566. }
  3567. if (battle_config.mob_skill_rate!= 100)
  3568. ms->permillage = ms->permillage*battle_config.mob_skill_rate/100;
  3569. if (battle_config.mob_skill_delay != 100)
  3570. ms->delay = ms->delay*battle_config.mob_skill_delay/100;
  3571. db->skill.push_back(ms);
  3572. ++i;
  3573. }
  3574. /**
  3575. * We grant the session it's fd value back.
  3576. **/
  3577. sd->fd = fd;
  3578. //Finally, spawn it.
  3579. md = mob_once_spawn_sub(&sd->bl, m, x, y, "--en--", mob_id, event, SZ_SMALL, AI_NONE);
  3580. if (!md) return 0; //Failed?
  3581. md->special_state.clone = 1;
  3582. if (master_id || flag || duration) { //Further manipulate crafted char.
  3583. if (flag&1) //Friendly Character
  3584. md->special_state.ai = AI_ATTACK;
  3585. if (master_id) //Attach to Master
  3586. md->master_id = master_id;
  3587. if (duration) //Auto Delete after a while.
  3588. {
  3589. if( md->deletetimer != INVALID_TIMER )
  3590. delete_timer(md->deletetimer, mob_timer_delete);
  3591. md->deletetimer = add_timer (gettick() + duration, mob_timer_delete, md->bl.id, 0);
  3592. }
  3593. }
  3594. mob_spawn(md);
  3595. return md->bl.id;
  3596. }
  3597. int mob_clone_delete(struct mob_data *md){
  3598. uint32 mob_id = md->mob_id;
  3599. if (mob_is_clone(mob_id)) {
  3600. mob_db.erase(mob_id);
  3601. //Clear references to the db
  3602. md->db = NULL;
  3603. md->vd = NULL;
  3604. return 1;
  3605. }
  3606. return 0;
  3607. }
  3608. //Adjusts the drop rate of item according to the criteria given. [Skotlex]
  3609. static unsigned int mob_drop_adjust(int baserate, int rate_adjust, unsigned short rate_min, unsigned short rate_max)
  3610. {
  3611. double rate = baserate;
  3612. if (battle_config.logarithmic_drops && rate_adjust > 0 && rate_adjust != 100 && baserate > 0) //Logarithmic drops equation by Ishizu-Chan
  3613. //Equation: Droprate(x,y) = x * (5 - log(x)) ^ (ln(y) / ln(5))
  3614. //x is the normal Droprate, y is the Modificator.
  3615. rate = rate * pow((5.0 - log10(rate)), (log(rate_adjust/100.) / log(5.0))) + 0.5;
  3616. else
  3617. //Classical linear rate adjustment.
  3618. rate = rate * rate_adjust/100;
  3619. return (unsigned int)cap_value(rate,rate_min,rate_max);
  3620. }
  3621. /**
  3622. * Check if global item drop rate is overriden for given item
  3623. * in db/mob_item_ratio.txt
  3624. * @param nameid ID of the item
  3625. * @param mob_id ID of the monster
  3626. * @param rate_adjust pointer to store ratio if found
  3627. */
  3628. static void item_dropratio_adjust(t_itemid nameid, int mob_id, int *rate_adjust)
  3629. {
  3630. struct s_mob_item_drop_ratio *item_ratio = (struct s_mob_item_drop_ratio *)uidb_get(mob_item_drop_ratio, nameid);
  3631. if( item_ratio) {
  3632. if( item_ratio->mob_id[0] ) { // only for listed mobs
  3633. int i;
  3634. ARR_FIND(0, MAX_ITEMRATIO_MOBS, i, item_ratio->mob_id[i] == mob_id);
  3635. if( i < MAX_ITEMRATIO_MOBS ) // found
  3636. *rate_adjust = item_ratio->drop_ratio;
  3637. }
  3638. else // for all mobs
  3639. *rate_adjust = item_ratio->drop_ratio;
  3640. }
  3641. }
  3642. const std::string MobDatabase::getDefaultLocation() {
  3643. return std::string(db_path) + "/mob_db.yml";
  3644. }
  3645. bool MobDatabase::parseDropNode(const std::string& nodeName, const YAML::Node& node, uint8 max, s_mob_drop *drops) {
  3646. const YAML::Node &dropNode = node[nodeName];
  3647. uint16 i;
  3648. // Find first empty spot
  3649. for( i = 0; i < max; i++ ){
  3650. if( drops[i].nameid == 0 ){
  3651. break;
  3652. }
  3653. }
  3654. for (const YAML::Node &dropit : dropNode) {
  3655. uint16 index;
  3656. if (this->nodeExists(dropit, "Index")) {
  3657. if (!this->asUInt16(dropit, "Index", index))
  3658. return false;
  3659. if (index >= max) {
  3660. this->invalidWarning(dropit["Index"], "Invalid monster %s index %hu. Must be between 0~%hu, skipping.\n", nodeName.c_str(), index, max - 1);
  3661. continue;
  3662. }
  3663. if( this->nodeExists( dropit, "Clear" ) ){
  3664. bool clear;
  3665. if( !this->asBool( dropit, "Clear", clear ) ){
  3666. return false;
  3667. }
  3668. if( clear ){
  3669. // Clear specific index
  3670. drops[index] = {};
  3671. if( !this->nodeExists( dropit, "Item" ) ){
  3672. // Continue with next yaml node
  3673. continue;
  3674. }
  3675. }
  3676. }
  3677. } else {
  3678. // Find next empty slot
  3679. for( ; i < max; i++ ){
  3680. if( drops[i].nameid == 0 ){
  3681. break;
  3682. }
  3683. }
  3684. // No empty slots anymore
  3685. if (i >= max) {
  3686. this->invalidWarning(dropit, "Maximum of %d monster %s met, skipping.\n", max, nodeName.c_str());
  3687. continue;
  3688. }
  3689. // Use free index and increment it for the next entry
  3690. index = i++;
  3691. if( this->nodeExists( dropit, "Clear" ) ){
  3692. bool clear;
  3693. if( !this->asBool( dropit, "Clear", clear ) ){
  3694. return false;
  3695. }
  3696. if( clear ){
  3697. // Clear all
  3698. for( uint8 j = 0; j < max; j++ ){
  3699. drops[j] = {};
  3700. }
  3701. // Reset current index for next entry
  3702. i = 0;
  3703. if( !this->nodeExists( dropit, "Item" ) ){
  3704. // Continue with next yaml node
  3705. continue;
  3706. }
  3707. }
  3708. }
  3709. }
  3710. std::string item_name;
  3711. if (!this->asString(dropit, "Item", item_name))
  3712. return false;
  3713. item_data *item = itemdb_search_aegisname(item_name.c_str());
  3714. if (item == nullptr) {
  3715. this->invalidWarning(dropit["Item"], "Monster %s item %s does not exist, skipping.\n", nodeName.c_str(), item_name.c_str());
  3716. continue;
  3717. }
  3718. uint16 rate;
  3719. if (!this->asUInt16Rate(dropit, "Rate", rate))
  3720. return false;
  3721. bool steal = false;
  3722. if (this->nodeExists(dropit, "StealProtected")) {
  3723. if (!this->asBool(dropit, "StealProtected", steal))
  3724. return false;
  3725. }
  3726. uint16 group = 0;
  3727. if (this->nodeExists(dropit, "RandomOptionGroup")) {
  3728. std::string group_name;
  3729. if (!this->asString(dropit, "RandomOptionGroup", group_name))
  3730. return false;
  3731. if (!random_option_group.option_get_id(group_name.c_str(), group))
  3732. this->invalidWarning(dropit["RandomOptionGroup"], "Unknown random option group %s for monster %s, defaulting to no group.\n", group_name.c_str(), nodeName.c_str());
  3733. }
  3734. drops[index].nameid = item->nameid;
  3735. drops[index].rate = rate;
  3736. drops[index].steal_protected = steal;
  3737. drops[index].randomopt_group = group;
  3738. }
  3739. return true;
  3740. }
  3741. /**
  3742. * Reads and parses an entry from the mob_db.
  3743. * @param node: YAML node containing the entry.
  3744. * @return count of successfully parsed rows
  3745. */
  3746. uint64 MobDatabase::parseBodyNode(const YAML::Node &node) {
  3747. uint32 mob_id;
  3748. if (!this->asUInt32(node, "Id", mob_id))
  3749. return 0;
  3750. if (!((mob_id > MIN_MOB_DB && mob_id < MAX_MOB_DB) || (mob_id > MIN_MOB_DB2 && mob_id < MAX_MOB_DB2))) {
  3751. this->invalidWarning(node["Id"], "Invalid monster ID %d, must be in range %d-%d or %d-%d.\n", mob_id, MIN_MOB_DB, MAX_MOB_DB, MIN_MOB_DB2, MAX_MOB_DB2);
  3752. return false;
  3753. }
  3754. std::shared_ptr<s_mob_db> mob = this->find(mob_id);
  3755. bool exists = mob != nullptr;
  3756. if (!exists) {
  3757. if (!this->nodesExist(node, { "AegisName", "Name" }))
  3758. return 0;
  3759. mob = std::make_shared<s_mob_db>();
  3760. mob->vd.class_ = static_cast<uint16>(mob_id);
  3761. }
  3762. if (this->nodeExists(node, "AegisName")) {
  3763. std::string name;
  3764. if (!this->asString(node, "AegisName", name))
  3765. return 0;
  3766. name.resize(NAME_LENGTH);
  3767. mob->sprite = name;
  3768. }
  3769. if (this->nodeExists(node, "Name")) {
  3770. std::string name;
  3771. if (!this->asString(node, "Name", name))
  3772. return 0;
  3773. name.resize(NAME_LENGTH);
  3774. mob->name = name;
  3775. }
  3776. if (this->nodeExists(node, "JapaneseName")) {
  3777. std::string name;
  3778. if (!this->asString(node, "JapaneseName", name))
  3779. return 0;
  3780. name.resize(NAME_LENGTH);
  3781. mob->jname = name;
  3782. } else {
  3783. if (!exists)
  3784. mob->jname = mob->name;
  3785. }
  3786. if (this->nodeExists(node, "Level")) {
  3787. uint16 level;
  3788. if (!this->asUInt16(node, "Level", level))
  3789. return 0;
  3790. mob->lv = level;
  3791. } else {
  3792. if (!exists)
  3793. mob->lv = 1;
  3794. }
  3795. if (this->nodeExists(node, "Hp")) {
  3796. uint32 hp;
  3797. if (!this->asUInt32(node, "Hp", hp))
  3798. return 0;
  3799. mob->status.max_hp = hp;
  3800. } else {
  3801. if (!exists)
  3802. mob->status.max_hp = 1;
  3803. }
  3804. if (this->nodeExists(node, "Sp")) {
  3805. uint32 sp;
  3806. if (!this->asUInt32(node, "Sp", sp))
  3807. return 0;
  3808. mob->status.max_sp = sp;
  3809. } else {
  3810. if (!exists)
  3811. mob->status.max_sp = 1;
  3812. }
  3813. if (this->nodeExists(node, "BaseExp")) {
  3814. t_exp exp;
  3815. if (!this->asUInt64(node, "BaseExp", exp))
  3816. return 0;
  3817. mob->base_exp = static_cast<t_exp>(cap_value((double)exp * (double)battle_config.base_exp_rate / 100., 0, MAX_EXP));
  3818. } else {
  3819. if (!exists)
  3820. mob->base_exp = 0;
  3821. }
  3822. if (this->nodeExists(node, "JobExp")) {
  3823. t_exp exp;
  3824. if (!this->asUInt64(node, "JobExp", exp))
  3825. return 0;
  3826. mob->job_exp = static_cast<t_exp>(cap_value((double)exp * (double)battle_config.job_exp_rate / 100., 0, MAX_EXP));
  3827. } else {
  3828. if (!exists)
  3829. mob->job_exp = 0;
  3830. }
  3831. if (this->nodeExists(node, "MvpExp")) {
  3832. t_exp exp;
  3833. if (!this->asUInt64(node, "MvpExp", exp))
  3834. return 0;
  3835. mob->mexp = static_cast<t_exp>(cap_value((double)exp * (double)battle_config.mvp_exp_rate / 100., 0, MAX_EXP));
  3836. } else {
  3837. if (!exists)
  3838. mob->mexp = 0;
  3839. }
  3840. if (this->nodeExists(node, "Attack")) {
  3841. uint16 atk;
  3842. if (!this->asUInt16(node, "Attack", atk))
  3843. return 0;
  3844. mob->status.rhw.atk = atk;
  3845. } else {
  3846. if (!exists)
  3847. mob->status.rhw.atk = 0;
  3848. }
  3849. if (this->nodeExists(node, "Attack2")) {
  3850. uint16 atk;
  3851. if (!this->asUInt16(node, "Attack2", atk))
  3852. return 0;
  3853. #ifdef RENEWAL
  3854. mob->status.rhw.matk = atk;
  3855. #else
  3856. mob->status.rhw.atk2 = atk;
  3857. #endif
  3858. } else {
  3859. if (!exists)
  3860. #ifdef RENEWAL
  3861. mob->status.rhw.matk = 0;
  3862. #else
  3863. mob->status.rhw.atk2 = 0;
  3864. #endif
  3865. }
  3866. if (this->nodeExists(node, "Defense")) {
  3867. uint16 def;
  3868. if (!this->asUInt16(node, "Defense", def))
  3869. return 0;
  3870. if (def < DEFTYPE_MIN || def > DEFTYPE_MAX) {
  3871. this->invalidWarning(node["Defense"], "Invalid monster defense %d, capping...\n", def);
  3872. def = cap_value(def, DEFTYPE_MIN, DEFTYPE_MAX);
  3873. }
  3874. mob->status.def = static_cast<defType>(def);
  3875. } else {
  3876. if (!exists)
  3877. mob->status.def = 0;
  3878. }
  3879. if (this->nodeExists(node, "MagicDefense")) {
  3880. uint16 def;
  3881. if (!this->asUInt16(node, "MagicDefense", def))
  3882. return 0;
  3883. if (def < DEFTYPE_MIN || def > DEFTYPE_MAX) {
  3884. this->invalidWarning(node["MagicDefense"], "Invalid monster magic defense %d, capping...\n", def);
  3885. def = cap_value(def, DEFTYPE_MIN, DEFTYPE_MAX);
  3886. }
  3887. mob->status.mdef = static_cast<defType>(def);
  3888. } else {
  3889. if (!exists)
  3890. mob->status.mdef = 0;
  3891. }
  3892. if (this->nodeExists(node, "Str")) {
  3893. uint16 stat;
  3894. if (!this->asUInt16(node, "Str", stat))
  3895. return 0;
  3896. mob->status.str = max(1, stat);
  3897. } else {
  3898. if (!exists)
  3899. mob->status.str = 1;
  3900. }
  3901. if (this->nodeExists(node, "Agi")) {
  3902. uint16 stat;
  3903. if (!this->asUInt16(node, "Agi", stat))
  3904. return 0;
  3905. mob->status.agi = max(1, stat);
  3906. } else {
  3907. if (!exists)
  3908. mob->status.agi = 1;
  3909. }
  3910. if (this->nodeExists(node, "Vit")) {
  3911. uint16 stat;
  3912. if (!this->asUInt16(node, "Vit", stat))
  3913. return 0;
  3914. mob->status.vit = max(1, stat);
  3915. } else {
  3916. if (!exists)
  3917. mob->status.vit = 1;
  3918. }
  3919. if (this->nodeExists(node, "Int")) {
  3920. uint16 stat;
  3921. if (!this->asUInt16(node, "Int", stat))
  3922. return 0;
  3923. mob->status.int_ = max(1, stat);
  3924. } else {
  3925. if (!exists)
  3926. mob->status.int_ = 1;
  3927. }
  3928. if (this->nodeExists(node, "Dex")) {
  3929. uint16 stat;
  3930. if (!this->asUInt16(node, "Dex", stat))
  3931. return 0;
  3932. mob->status.dex = max(1, stat);
  3933. } else {
  3934. if (!exists)
  3935. mob->status.dex = 1;
  3936. }
  3937. if (this->nodeExists(node, "Luk")) {
  3938. uint16 stat;
  3939. if (!this->asUInt16(node, "Luk", stat))
  3940. return 0;
  3941. mob->status.luk = max(1, stat);
  3942. } else {
  3943. if (!exists)
  3944. mob->status.luk = 1;
  3945. }
  3946. if (this->nodeExists(node, "AttackRange")) {
  3947. uint16 range;
  3948. if (!this->asUInt16(node, "AttackRange", range))
  3949. return 0;
  3950. mob->status.rhw.range = range;
  3951. } else {
  3952. if (!exists)
  3953. mob->status.rhw.range = 0;
  3954. }
  3955. if (this->nodeExists(node, "SkillRange")) {
  3956. uint16 range;
  3957. if (!this->asUInt16(node, "SkillRange", range))
  3958. return 0;
  3959. mob->range2 = range;
  3960. } else {
  3961. if (!exists)
  3962. mob->range2 = 0;
  3963. }
  3964. if (this->nodeExists(node, "ChaseRange")) {
  3965. uint16 range;
  3966. if (!this->asUInt16(node, "ChaseRange", range))
  3967. return 0;
  3968. mob->range3 = range;
  3969. } else {
  3970. if (!exists)
  3971. mob->range3 = 0;
  3972. }
  3973. if (this->nodeExists(node, "Size")) {
  3974. std::string size;
  3975. if (!this->asString(node, "Size", size))
  3976. return 0;
  3977. std::string size_constant = "Size_" + size;
  3978. int64 constant;
  3979. if (!script_get_constant(size_constant.c_str(), &constant)) {
  3980. this->invalidWarning(node["Size"], "Unknown monster size %s, defaulting to Size_Small.\n", size.c_str());
  3981. constant = SZ_SMALL;
  3982. }
  3983. if (constant < SZ_SMALL || constant > SZ_BIG) {
  3984. this->invalidWarning(node["Size"], "Invalid monster size %s, defaulting to Size_Small.\n", size.c_str());
  3985. constant = SZ_SMALL;
  3986. }
  3987. mob->status.size = static_cast<e_size>(constant);
  3988. } else {
  3989. if (!exists)
  3990. mob->status.size = SZ_SMALL;
  3991. }
  3992. if (this->nodeExists(node, "Race")) {
  3993. std::string race;
  3994. if (!this->asString(node, "Race", race))
  3995. return 0;
  3996. std::string race_constant = "RC_" + race;
  3997. int64 constant;
  3998. if (!script_get_constant(race_constant.c_str(), &constant)) {
  3999. this->invalidWarning(node["Race"], "Unknown monster race %s, defaulting to RC_FORMLESS.\n", race.c_str());
  4000. constant = RC_FORMLESS;
  4001. }
  4002. if (!CHK_RACE(constant)) {
  4003. this->invalidWarning(node["Race"], "Invalid monster race %s, defaulting to RC_FORMLESS.\n", race.c_str());
  4004. constant = RC_FORMLESS;
  4005. }
  4006. mob->status.race = static_cast<e_race>(constant);
  4007. } else {
  4008. if (!exists)
  4009. mob->status.race = RC_FORMLESS;
  4010. }
  4011. if (this->nodeExists(node, "RaceGroups")) {
  4012. const YAML::Node &raceNode = node["RaceGroups"];
  4013. for (const auto &raceit : raceNode) {
  4014. std::string raceName = raceit.first.as<std::string>(), raceName_constant = "RC2_" + raceName;
  4015. int64 constant;
  4016. if (!script_get_constant(raceName_constant.c_str(), &constant)) {
  4017. this->invalidWarning(raceNode[raceName], "Unknown monster race group %s, skipping.\n", raceName.c_str());
  4018. continue;
  4019. }
  4020. if (!CHK_RACE2(constant)) {
  4021. this->invalidWarning(raceNode[raceName], "Invalid monster race group %s, skipping.\n", raceName.c_str());
  4022. continue;
  4023. }
  4024. bool active;
  4025. if (!this->asBool(raceNode, raceName, active))
  4026. return 0;
  4027. if (active)
  4028. mob->race2.push_back(static_cast<e_race2>(constant));
  4029. else
  4030. util::vector_erase_if_exists(mob->race2, static_cast<e_race2>(constant));
  4031. }
  4032. }
  4033. if (this->nodeExists(node, "Element")) {
  4034. std::string ele;
  4035. if (!this->asString(node, "Element", ele))
  4036. return 0;
  4037. std::string ele_constant = "ELE_" + ele;
  4038. int64 constant;
  4039. if (!script_get_constant(ele_constant.c_str(), &constant)) {
  4040. this->invalidWarning(node["Element"], "Unknown monster element %s, defaulting to ELE_NEUTRAL.\n", ele.c_str());
  4041. constant = ELE_NEUTRAL;
  4042. }
  4043. if (!CHK_ELEMENT(constant)) {
  4044. this->invalidWarning(node["Element"], "Invalid monster element %s, defaulting to ELE_NEUTRAL.\n", ele.c_str());
  4045. constant = ELE_NEUTRAL;
  4046. }
  4047. mob->status.def_ele = static_cast<e_element>(constant);
  4048. } else {
  4049. if (!exists)
  4050. mob->status.def_ele = ELE_NEUTRAL;
  4051. }
  4052. if (this->nodeExists(node, "ElementLevel")) {
  4053. uint16 level;
  4054. if (!this->asUInt16(node, "ElementLevel", level))
  4055. return 0;
  4056. if (!CHK_ELEMENT_LEVEL(level)) {
  4057. this->invalidWarning(node["ElementLevel"], "Invalid monster element level %hu, defaulting to 1.\n", level);
  4058. level = 1;
  4059. }
  4060. mob->status.ele_lv = static_cast<uint8>(level);
  4061. } else {
  4062. if (!exists)
  4063. mob->status.ele_lv = 1;
  4064. }
  4065. if (this->nodeExists(node, "WalkSpeed")) {
  4066. uint16 speed;
  4067. if (!this->asUInt16(node, "WalkSpeed", speed))
  4068. return 0;
  4069. if (speed < MIN_WALK_SPEED || speed > MAX_WALK_SPEED) {
  4070. this->invalidWarning(node["WalkSpeed"], "Invalid monster walk speed %hu, capping...\n", speed);
  4071. speed = cap_value(speed, MIN_WALK_SPEED, MAX_WALK_SPEED);
  4072. }
  4073. mob->status.speed = speed;
  4074. } else {
  4075. if (!exists)
  4076. mob->status.speed = DEFAULT_WALK_SPEED;
  4077. }
  4078. if (this->nodeExists(node, "AttackDelay")) {
  4079. uint16 speed;
  4080. if (!this->asUInt16(node, "AttackDelay", speed))
  4081. return 0;
  4082. mob->status.adelay = cap_value(speed, battle_config.monster_max_aspd * 2, 4000);
  4083. } else {
  4084. if (!exists)
  4085. mob->status.adelay = 0;
  4086. }
  4087. if (this->nodeExists(node, "AttackMotion")) {
  4088. uint16 speed;
  4089. if (!this->asUInt16(node, "AttackMotion", speed))
  4090. return 0;
  4091. mob->status.amotion = cap_value(speed, battle_config.monster_max_aspd, 2000);
  4092. } else {
  4093. if (!exists)
  4094. mob->status.amotion = 0;
  4095. }
  4096. if (this->nodeExists(node, "DamageMotion")) {
  4097. uint16 speed;
  4098. if (!this->asUInt16(node, "DamageMotion", speed))
  4099. return 0;
  4100. if (battle_config.monster_damage_delay_rate != 100)
  4101. speed = speed * battle_config.monster_damage_delay_rate / 100;
  4102. mob->status.dmotion = speed;
  4103. } else {
  4104. if (!exists)
  4105. mob->status.dmotion = 0;
  4106. }
  4107. if (this->nodeExists(node, "DamageTaken")) {
  4108. uint16 damage;
  4109. if (!this->asUInt16Rate(node, "DamageTaken", damage, 100))
  4110. return 0;
  4111. mob->damagetaken = damage;
  4112. } else {
  4113. if (!exists)
  4114. mob->damagetaken = 100;
  4115. }
  4116. if (this->nodeExists(node, "Ai")) {
  4117. std::string ai;
  4118. if (!this->asString(node, "Ai", ai))
  4119. return 0;
  4120. std::string ai_constant = "MONSTER_TYPE_" + ai;
  4121. int64 constant;
  4122. if (!script_get_constant(ai_constant.c_str(), &constant)) {
  4123. this->invalidWarning(node["Ai"], "Unknown monster AI %s, defaulting to MONSTER_TYPE_06.\n", ai.c_str());
  4124. constant = MONSTER_TYPE_06;
  4125. }
  4126. if (constant < MD_NONE || constant > MD_MASK) {
  4127. this->invalidWarning(node["Ai"], "Invalid monster AI %s, defaulting to MONSTER_TYPE_06.\n", ai.c_str());
  4128. constant = MONSTER_TYPE_06;
  4129. }
  4130. mob->status.mode = static_cast<e_mode>(constant);
  4131. } else {
  4132. if (!exists)
  4133. mob->status.mode = static_cast<e_mode>(MONSTER_TYPE_06);
  4134. }
  4135. if (this->nodeExists(node, "Class")) {
  4136. std::string class_;
  4137. if (!this->asString(node, "Class", class_))
  4138. return 0;
  4139. std::string class_constant = "CLASS_" + class_;
  4140. int64 constant;
  4141. if (!script_get_constant(class_constant.c_str(), &constant)) {
  4142. this->invalidWarning(node["Class"], "Unknown monster class %s, defaulting to CLASS_NORMAL.\n", class_.c_str());
  4143. constant = CLASS_NORMAL;
  4144. }
  4145. if (constant < CLASS_NORMAL || constant > CLASS_EVENT) {
  4146. this->invalidWarning(node["Class"], "Invalid monster class %s, defaulting to CLASS_NORMAL.\n", class_.c_str());
  4147. constant = CLASS_NORMAL;
  4148. }
  4149. mob->status.class_ = static_cast<uint8>(constant);
  4150. } else {
  4151. if (!exists)
  4152. mob->status.class_ = CLASS_NORMAL;
  4153. }
  4154. if (this->nodeExists(node, "Modes")) {
  4155. const YAML::Node &modeNode = node["Modes"];
  4156. for (const auto &modeit : modeNode) {
  4157. std::string modeName = modeit.first.as<std::string>(), modeName_constant = "MD_" + modeName;
  4158. int64 constant;
  4159. if (!script_get_constant(modeName_constant.c_str(), &constant)) {
  4160. this->invalidWarning(modeNode[modeName], "Unknown monster mode %s, skipping.\n", modeName.c_str());
  4161. continue;
  4162. }
  4163. if (constant < MD_NONE || constant > MD_SKILLIMMUNE) {
  4164. this->invalidWarning(modeNode[modeName], "Invalid monster mode %s, skipping.\n", modeName.c_str());
  4165. continue;
  4166. }
  4167. bool active;
  4168. if (!this->asBool(modeNode, modeName, active))
  4169. return 0;
  4170. if (active)
  4171. mob->status.mode = static_cast<e_mode>(mob->status.mode | constant);
  4172. else
  4173. mob->status.mode = static_cast<e_mode>(mob->status.mode & ~constant);
  4174. }
  4175. }
  4176. if (this->nodeExists(node, "MvpDrops")) {
  4177. if (!this->parseDropNode("MvpDrops", node, MAX_MVP_DROP, mob->mvpitem))
  4178. return 0;
  4179. }
  4180. if (this->nodeExists(node, "Drops")) {
  4181. if (!this->parseDropNode("Drops", node, MAX_MOB_DROP, mob->dropitem))
  4182. return 0;
  4183. }
  4184. if (!exists)
  4185. this->put(mob_id, mob);
  4186. return true;
  4187. }
  4188. void MobDatabase::loadingFinished() {
  4189. for (auto &mobdata : *this) {
  4190. std::shared_ptr<s_mob_db> mob = mobdata.second;
  4191. switch (mob->status.class_) {
  4192. case CLASS_BOSS:
  4193. mob->status.mode = static_cast<e_mode>(mob->status.mode | (MD_DETECTOR | MD_STATUSIMMUNE | MD_KNOCKBACKIMMUNE));
  4194. break;
  4195. case CLASS_GUARDIAN:
  4196. mob->status.mode = static_cast<e_mode>(mob->status.mode | MD_STATUSIMMUNE);
  4197. break;
  4198. case CLASS_BATTLEFIELD:
  4199. mob->status.mode = static_cast<e_mode>(mob->status.mode | (MD_STATUSIMMUNE | MD_SKILLIMMUNE));
  4200. break;
  4201. case CLASS_EVENT:
  4202. mob->status.mode = static_cast<e_mode>(mob->status.mode | MD_FIXEDITEMDROP);
  4203. break;
  4204. }
  4205. if (battle_config.view_range_rate != 100)
  4206. mob->range2 = cap_value(mob->range2, 1, mob->range2 * battle_config.view_range_rate / 100);
  4207. if (battle_config.chase_range_rate != 100)
  4208. mob->range3 = cap_value(mob->range3, mob->range2, mob->range3 * battle_config.chase_range_rate / 100);
  4209. // Tests showed that chase range is effectively 2 cells larger than expected [Playtester]
  4210. mob->range3 += 2;
  4211. // If the attack animation is longer than the delay, the client crops the attack animation!
  4212. // On aegis there is no real visible effect of having a recharge-time less than amotion anyway.
  4213. mob->status.adelay = max(mob->status.adelay, mob->status.amotion);
  4214. mob->status.aspd_rate = 1000;
  4215. if (!battle_config.monster_active_enable)
  4216. mob->status.mode = static_cast<enum e_mode>(mob->status.mode & ~MD_AGGRESSIVE);
  4217. // Fill in remaining status data by using a dummy monster.
  4218. mob_data data;
  4219. data.bl.type = BL_MOB;
  4220. data.level = mob->lv;
  4221. memcpy(&data.status, &mob->status, sizeof(status_data));
  4222. status_calc_misc(&data.bl, &mob->status, mob->lv);
  4223. // Now that we know if it is a MVP or not, apply battle_config modifiers [Skotlex]
  4224. double maxhp = (double)mob->status.max_hp;
  4225. if (mob->get_bosstype() == BOSSTYPE_MVP) { // MVP
  4226. if (battle_config.mvp_hp_rate != 100)
  4227. maxhp = maxhp * (double)battle_config.mvp_hp_rate / 100.;
  4228. } else { // Normal mob
  4229. if (battle_config.monster_hp_rate != 100)
  4230. maxhp = maxhp * (double)battle_config.monster_hp_rate / 100.;
  4231. }
  4232. mob->status.max_hp = cap_value(static_cast<uint32>(maxhp), 1, UINT32_MAX);
  4233. mob->status.max_sp = cap_value(mob->status.max_sp, 1, UINT32_MAX);
  4234. mob->status.hp = mob->status.max_hp;
  4235. mob->status.sp = mob->status.max_sp;
  4236. }
  4237. }
  4238. MobDatabase mob_db;
  4239. /**
  4240. * Convert SQL data to YAML Node
  4241. * @param str: Array of parsed SQL data
  4242. * @return True on success or false otherwise
  4243. */
  4244. static bool mob_read_sqldb_sub(std::vector<std::string> str) {
  4245. YAML::Node node;
  4246. int32 index = -1;
  4247. node["Id"] = std::stoul(str[++index]);
  4248. node["AegisName"] = str[++index];
  4249. node["Name"] = str[++index];
  4250. if (!str[++index].empty())
  4251. node["JapaneseName"] = str[index];
  4252. if (!str[++index].empty() && std::stoi(str[index]) > 1)
  4253. node["Level"] = std::stoi(str[index]);
  4254. if (!str[++index].empty() && std::stoul(str[index]) > 1)
  4255. node["Hp"] = std::stoul(str[index]);
  4256. if (!str[++index].empty() && std::stoul(str[index]) > 1)
  4257. node["Sp"] = std::stoul(str[index]);
  4258. if (!str[++index].empty())
  4259. node["BaseExp"] = std::stoul(str[index]);
  4260. if (!str[++index].empty())
  4261. node["JobExp"] = std::stoul(str[index]);
  4262. if (!str[++index].empty())
  4263. node["MvpExp"] = std::stoul(str[index]);
  4264. if (!str[++index].empty())
  4265. node["Attack"] = std::stoi(str[index]);
  4266. if (!str[++index].empty())
  4267. node["Attack2"] = std::stoi(str[index]);
  4268. if (!str[++index].empty())
  4269. node["Defense"] = std::stoi(str[index]);
  4270. if (!str[++index].empty())
  4271. node["MagicDefense"] = std::stoi(str[index]);
  4272. if (!str[++index].empty() && std::stoi(str[index]) > 1)
  4273. node["Str"] = std::stoi(str[index]);
  4274. if (!str[++index].empty() && std::stoi(str[index]) > 1)
  4275. node["Agi"] = std::stoi(str[index]);
  4276. if (!str[++index].empty() && std::stoi(str[index]) > 1)
  4277. node["Vit"] = std::stoi(str[index]);
  4278. if (!str[++index].empty() && std::stoi(str[index]) > 1)
  4279. node["Int"] = std::stoi(str[index]);
  4280. if (!str[++index].empty() && std::stoi(str[index]) > 1)
  4281. node["Dex"] = std::stoi(str[index]);
  4282. if (!str[++index].empty() && std::stoi(str[index]) > 1)
  4283. node["Luk"] = std::stoi(str[index]);
  4284. if (!str[++index].empty())
  4285. node["AttackRange"] = std::stoi(str[index]);
  4286. if (!str[++index].empty())
  4287. node["SkillRange"] = std::stoi(str[index]);
  4288. if (!str[++index].empty())
  4289. node["ChaseRange"] = std::stoi(str[index]);
  4290. if (!str[++index].empty() && strcmp(str[index].c_str(), "Small") != 0)
  4291. node["Size"] = str[index];
  4292. if (!str[++index].empty() && strcmp(str[index].c_str(), "Formless") != 0)
  4293. node["Race"] = str[index];
  4294. for (uint16 i = 1; i < RC2_MAX; i++) {
  4295. if (!str[i + index].empty())
  4296. node["RaceGroups"][script_get_constant_str("RC2_", i) + 4] = std::stoi(str[i + index]) ? "true" : "false";
  4297. }
  4298. index += RC2_MAX - 1;
  4299. if (!str[++index].empty() && strcmp(str[index].c_str(), "Neutral") != 0)
  4300. node["Element"] = str[index];
  4301. if (!str[++index].empty() && std::stoi(str[index]) > 1)
  4302. node["ElementLevel"] = std::stoi(str[index]);
  4303. if (!str[++index].empty())
  4304. node["WalkSpeed"] = std::stoi(str[index]);
  4305. if (!str[++index].empty())
  4306. node["AttackDelay"] = std::stoi(str[index]);
  4307. if (!str[++index].empty())
  4308. node["AttackMotion"] = std::stoi(str[index]);
  4309. if (!str[++index].empty())
  4310. node["DamageMotion"] = std::stoi(str[index]);
  4311. if (!str[++index].empty())
  4312. node["DamageTaken"] = std::stoi(str[index]);
  4313. if (!str[++index].empty() && strcmp(str[index].c_str(), "06") != 0)
  4314. node["Ai"] = str[index];
  4315. if (!str[++index].empty() && strcmp(str[index].c_str(), "Normal") != 0)
  4316. node["Class"] = str[index];
  4317. YAML::Node modes;
  4318. if (!str[++index].empty())
  4319. modes["CanMove"] = std::stoi(str[index]) ? "true" : "false";
  4320. if (!str[++index].empty())
  4321. modes["Looter"] = std::stoi(str[index]) ? "true" : "false";
  4322. if (!str[++index].empty())
  4323. modes["Aggressive"] = std::stoi(str[index]) ? "true" : "false";
  4324. if (!str[++index].empty())
  4325. modes["Assist"] = std::stoi(str[index]) ? "true" : "false";
  4326. if (!str[++index].empty())
  4327. modes["CastSensorIdle"] = std::stoi(str[index]) ? "true" : "false";
  4328. if (!str[++index].empty())
  4329. modes["NoRandomWalk"] = std::stoi(str[index]) ? "true" : "false";
  4330. if (!str[++index].empty())
  4331. modes["NoCast"] = std::stoi(str[index]) ? "true" : "false";
  4332. if (!str[++index].empty())
  4333. modes["CanAttack"] = std::stoi(str[index]) ? "true" : "false";
  4334. if (!str[++index].empty())
  4335. modes["CastSensorChase"] = std::stoi(str[index]) ? "true" : "false";
  4336. if (!str[++index].empty())
  4337. modes["ChangeChase"] = std::stoi(str[index]) ? "true" : "false";
  4338. if (!str[++index].empty())
  4339. modes["Angry"] = std::stoi(str[index]) ? "true" : "false";
  4340. if (!str[++index].empty())
  4341. modes["ChangeTargetMelee"] = std::stoi(str[index]) ? "true" : "false";
  4342. if (!str[++index].empty())
  4343. modes["ChangeTargetChase"] = std::stoi(str[index]) ? "true" : "false";
  4344. if (!str[++index].empty())
  4345. modes["TargetWeak"] = std::stoi(str[index]) ? "true" : "false";
  4346. if (!str[++index].empty())
  4347. modes["RandomTarget"] = std::stoi(str[index]) ? "true" : "false";
  4348. if (!str[++index].empty())
  4349. modes["IgnoreMelee"] = std::stoi(str[index]) ? "true" : "false";
  4350. if (!str[++index].empty())
  4351. modes["IgnoreMagic"] = std::stoi(str[index]) ? "true" : "false";
  4352. if (!str[++index].empty())
  4353. modes["IgnoreRanged"] = std::stoi(str[index]) ? "true" : "false";
  4354. if (!str[++index].empty())
  4355. modes["Mvp"] = std::stoi(str[index]) ? "true" : "false";
  4356. if (!str[++index].empty())
  4357. modes["IgnoreMisc"] = std::stoi(str[index]) ? "true" : "false";
  4358. if (!str[++index].empty())
  4359. modes["KnockBackImmune"] = std::stoi(str[index]) ? "true" : "false";
  4360. if (!str[++index].empty())
  4361. modes["TeleportBlock"] = std::stoi(str[index]) ? "true" : "false";
  4362. if (!str[++index].empty())
  4363. modes["FixedItemDrop"] = std::stoi(str[index]) ? "true" : "false";
  4364. if (!str[++index].empty())
  4365. modes["Detector"] = std::stoi(str[index]) ? "true" : "false";
  4366. if (!str[++index].empty())
  4367. modes["StatusImmune"] = std::stoi(str[index]) ? "true" : "false";
  4368. if (!str[++index].empty())
  4369. modes["SkillImmune"] = std::stoi(str[index]) ? "true" : "false";
  4370. node["Modes"] = modes;
  4371. for (uint8 i = 0; i < MAX_MVP_DROP; i++) {
  4372. YAML::Node mvpdrops;
  4373. if (!str[++index].empty())
  4374. mvpdrops["Item"] = str[index];
  4375. if (!str[++index].empty())
  4376. mvpdrops["Rate"] = std::stoi(str[index]);
  4377. if (!str[++index].empty() && strcmp(str[index].c_str(), "None") != 0)
  4378. mvpdrops["RandomOptionGroup"] = str[index];
  4379. if (!str[++index].empty() && std::stoi(str[index]) >= 0)
  4380. mvpdrops["Index"] = std::stoi(str[index]);
  4381. if (!mvpdrops.IsNull())
  4382. node["MvpDrops"][i] = mvpdrops;
  4383. }
  4384. for (uint8 i = 0; i < MAX_MOB_DROP; i++) {
  4385. YAML::Node drops;
  4386. if (!str[++index].empty())
  4387. drops["Item"] = str[index];
  4388. if (!str[++index].empty())
  4389. drops["Rate"] = std::stoi(str[index]);
  4390. if (!str[++index].empty())
  4391. drops["StealProtected"] = std::stoi(str[index]) ? "true" : "false";
  4392. if (!str[++index].empty() && strcmp(str[index].c_str(), "None") != 0)
  4393. drops["RandomOptionGroup"] = str[index];
  4394. if (!str[++index].empty() && std::stoi(str[index]) >= 0)
  4395. drops["Index"] = std::stoi(str[index]);
  4396. if (!drops.IsNull())
  4397. node["Drops"][i] = drops;
  4398. }
  4399. return mob_db.parseBodyNode(node) > 0;
  4400. }
  4401. /**
  4402. * Read SQL mob_db table
  4403. */
  4404. static int mob_read_sqldb(void)
  4405. {
  4406. const char* mob_db_name[] = {
  4407. mob_table,
  4408. mob2_table
  4409. };
  4410. for( uint8 fi = 0; fi < ARRAYLENGTH(mob_db_name); ++fi ) {
  4411. // retrieve all rows from the mob database
  4412. if( SQL_ERROR == Sql_Query(mmysql_handle, "SELECT `id`,`name_aegis`,`name_english`,`name_japanese`,`level`,`hp`,`sp`,`base_exp`,`job_exp`,`mvp_exp`,`attack`,`attack2`,`defense`,`magic_defense`,`str`,`agi`,`vit`,`int`,`dex`,`luk`,`attack_range`,`skill_range`,`chase_range`,`size`,`race`,"
  4413. "`racegroup_goblin`,`racegroup_kobold`,`racegroup_orc`,`racegroup_golem`,`racegroup_guardian`,`racegroup_ninja`,`racegroup_gvg`,`racegroup_battlefield`,`racegroup_treasure`,`racegroup_biolab`,`racegroup_manuk`,`racegroup_splendide`,`racegroup_scaraba`,`racegroup_ogh_atk_def`,`racegroup_ogh_hidden`,`racegroup_bio5_swordman_thief`,`racegroup_bio5_acolyte_merchant`,`racegroup_bio5_mage_archer`,`racegroup_bio5_mvp`,`racegroup_clocktower`,`racegroup_thanatos`,`racegroup_faceworm`,`racegroup_hearthunter`,`racegroup_rockridge`,`racegroup_werner_lab`,`racegroup_temple_demon`,`racegroup_illusion_vampire`,"
  4414. "`element`,`element_level`,`walk_speed`,`attack_delay`,`attack_motion`,`damage_motion`,`damage_taken`,`ai`,`class`,"
  4415. "`mode_canmove`,`mode_looter`,`mode_aggressive`,`mode_assist`,`mode_castsensoridle`,`mode_norandomwalk`,`mode_nocast`,`mode_canattack`,`mode_castsensorchase`,`mode_changechase`,`mode_angry`,`mode_changetargetmelee`,`mode_changetargetchase`,`mode_targetweak`,`mode_randomtarget`,`mode_ignoremelee`,`mode_ignoremagic`,`mode_ignoreranged`,`mode_mvp`,`mode_ignoremisc`,`mode_knockbackimmune`,`mode_teleportblock`,`mode_fixeditemdrop`,`mode_detector`,`mode_statusimmune`,`mode_skillimmune`,"
  4416. "`mvpdrop1_item`,`mvpdrop1_rate`,`mvpdrop1_option`,`mvpdrop1_index`,`mvpdrop2_item`,`mvpdrop2_rate`,`mvpdrop2_option`,`mvpdrop2_index`,`mvpdrop3_item`,`mvpdrop3_rate`,`mvpdrop3_option`,`mvpdrop3_index`,"
  4417. "`drop1_item`,`drop1_rate`,`drop1_nosteal`,`drop1_option`,`drop1_index`,`drop2_item`,`drop2_rate`,`drop2_nosteal`,`drop2_option`,`drop2_index`,`drop3_item`,`drop3_rate`,`drop3_nosteal`,`drop3_option`,`drop3_index`,`drop4_item`,`drop4_rate`,`drop4_nosteal`,`drop4_option`,`drop4_index`,`drop5_item`,`drop5_rate`,`drop5_nosteal`,`drop5_option`,`drop5_index`,`drop6_item`,`drop6_rate`,`drop6_nosteal`,`drop6_option`,`drop6_index`,`drop7_item`,`drop7_rate`,`drop7_nosteal`,`drop7_option`,`drop7_index`,`drop8_item`,`drop8_rate`,`drop8_nosteal`,`drop8_option`,`drop8_index`,`drop9_item`,`drop9_rate`,`drop9_nosteal`,`drop9_option`,`drop9_index`,`drop10_item`,`drop10_rate`,`drop10_nosteal`,`drop10_option`,`drop10_index`"
  4418. " FROM `%s`", mob_db_name[fi]) ) {
  4419. Sql_ShowDebug(mmysql_handle);
  4420. continue;
  4421. }
  4422. uint32 total_columns = Sql_NumColumns(mmysql_handle);
  4423. uint64 total_rows = Sql_NumRows(mmysql_handle), rows = 0, count = 0;
  4424. // process rows one by one
  4425. while( SQL_SUCCESS == Sql_NextRow(mmysql_handle) ) {
  4426. ShowStatus("Loading [%" PRIu64 "/%" PRIu64 "] rows from '" CL_WHITE "%s" CL_RESET "'" CL_CLL "\r", ++rows, total_rows, mob_db_name[fi]);
  4427. std::vector<std::string> data = {};
  4428. for (uint32 i = 0; i < total_columns; i++) {
  4429. char *str;
  4430. Sql_GetData(mmysql_handle, i, &str, nullptr);
  4431. if (str == nullptr)
  4432. data.push_back("");
  4433. else
  4434. data.push_back(str);
  4435. }
  4436. if (!mob_read_sqldb_sub(data))
  4437. continue;
  4438. count++;
  4439. }
  4440. // free the query result
  4441. Sql_FreeResult(mmysql_handle);
  4442. ShowStatus("Done reading '" CL_WHITE "%" PRIu64 CL_RESET "' entries in '" CL_WHITE "%s" CL_RESET "'.\n", count, mob_db_name[fi]);
  4443. }
  4444. mob_db.loadingFinished();
  4445. return 0;
  4446. }
  4447. const std::string MobAvailDatabase::getDefaultLocation() {
  4448. return std::string(db_path) + "/" + DBIMPORT + "/mob_avail.yml";
  4449. }
  4450. /**
  4451. * Reads and parses an entry from the mob_avail.
  4452. * @param node: YAML node containing the entry.
  4453. * @return count of successfully parsed rows
  4454. */
  4455. uint64 MobAvailDatabase::parseBodyNode(const YAML::Node &node) {
  4456. std::string mob_name;
  4457. if (!this->asString(node, "Mob", mob_name))
  4458. return 0;
  4459. std::shared_ptr<s_mob_db> mob = mobdb_search_aegisname(mob_name.c_str());
  4460. if (mob == nullptr) {
  4461. this->invalidWarning(node["Mob"], "Unknown mob %s.\n", mob_name.c_str());
  4462. return 0;
  4463. }
  4464. if (this->nodeExists(node, "Sprite")) {
  4465. std::string sprite;
  4466. if (!this->asString(node, "Sprite", sprite))
  4467. return 0;
  4468. int64 constant;
  4469. if (script_get_constant(sprite.c_str(), &constant)) {
  4470. if (npcdb_checkid(constant) == 0 && pcdb_checkid(constant) == 0) {
  4471. this->invalidWarning(node["Sprite"], "Unknown sprite constant %s.\n", sprite.c_str());
  4472. return 0;
  4473. }
  4474. } else {
  4475. std::shared_ptr<s_mob_db> sprite_mob = mobdb_search_aegisname(sprite.c_str());
  4476. if (sprite_mob == nullptr) {
  4477. this->invalidWarning(node["Sprite"], "Unknown mob sprite constant %s.\n", sprite.c_str());
  4478. return 0;
  4479. }
  4480. constant = sprite_mob->vd.class_;
  4481. }
  4482. mob->vd.class_ = (unsigned short)constant;
  4483. } else {
  4484. this->invalidWarning(node["Sprite"], "Sprite is missing.\n");
  4485. return 0;
  4486. }
  4487. if (this->nodeExists(node, "Sex")) {
  4488. if (pcdb_checkid(mob->vd.class_) == 0) {
  4489. this->invalidWarning(node["Sex"], "Sex is only applicable to Job sprites.\n");
  4490. return 0;
  4491. }
  4492. std::string sex;
  4493. if (!this->asString(node, "Sex", sex))
  4494. return 0;
  4495. std::string sex_constant = "SEX_" + sex;
  4496. int64 constant;
  4497. if (!script_get_constant(sex_constant.c_str(), &constant)) {
  4498. this->invalidWarning(node["Sex"], "Unknown sex constant %s.\n", sex.c_str());
  4499. return 0;
  4500. }
  4501. if (constant < SEX_FEMALE || constant > SEX_MALE) {
  4502. this->invalidWarning(node["Sex"], "Sex %s is not valid.\n", sex.c_str());
  4503. return 0;
  4504. }
  4505. mob->vd.sex = (char)constant;
  4506. }
  4507. if (this->nodeExists(node, "HairStyle")) {
  4508. if (pcdb_checkid(mob->vd.class_) == 0) {
  4509. this->invalidWarning(node["HairStyle"], "HairStyle is only applicable to Job sprites.\n");
  4510. return 0;
  4511. }
  4512. uint16 hair_style;
  4513. if (!this->asUInt16(node, "HairStyle", hair_style))
  4514. return 0;
  4515. if (hair_style < MIN_HAIR_STYLE || hair_style > MAX_HAIR_STYLE) {
  4516. this->invalidWarning(node["HairStyle"], "HairStyle %d is out of range %d~%d. Setting to MIN_HAIR_STYLE.\n", hair_style, MIN_HAIR_STYLE, MAX_HAIR_STYLE);
  4517. hair_style = MIN_HAIR_STYLE;
  4518. }
  4519. mob->vd.hair_style = hair_style;
  4520. }
  4521. if (this->nodeExists(node, "HairColor")) {
  4522. if (pcdb_checkid(mob->vd.class_) == 0) {
  4523. this->invalidWarning(node["HairColor"], "HairColor is only applicable to Job sprites.\n");
  4524. return 0;
  4525. }
  4526. uint16 hair_color;
  4527. if (!this->asUInt16(node, "HairColor", hair_color))
  4528. return 0;
  4529. if (hair_color < MIN_HAIR_COLOR || hair_color > MAX_HAIR_COLOR) {
  4530. this->invalidWarning(node["HairColor"], "HairColor %d is out of range %d~%d. Setting to MIN_HAIR_COLOR.\n", hair_color, MIN_HAIR_COLOR, MAX_HAIR_COLOR);
  4531. hair_color = MIN_HAIR_COLOR;
  4532. }
  4533. mob->vd.hair_color = hair_color;
  4534. }
  4535. if (this->nodeExists(node, "ClothColor")) {
  4536. if (pcdb_checkid(mob->vd.class_) == 0) {
  4537. this->invalidWarning(node["ClothColor"], "ClothColor is only applicable to Job sprites.\n");
  4538. return 0;
  4539. }
  4540. uint32 cloth_color;
  4541. if (!this->asUInt32(node, "ClothColor", cloth_color))
  4542. return 0;
  4543. if (cloth_color < MIN_CLOTH_COLOR || cloth_color > MAX_CLOTH_COLOR) {
  4544. this->invalidWarning(node["ClothColor"], "ClothColor %d is out of range %d~%d. Setting to MIN_CLOTH_CLOR.\n", cloth_color, MIN_CLOTH_COLOR, MAX_CLOTH_COLOR);
  4545. cloth_color = MIN_CLOTH_COLOR;
  4546. }
  4547. mob->vd.cloth_color = cloth_color;
  4548. }
  4549. if (this->nodeExists(node, "Weapon")) {
  4550. if (pcdb_checkid(mob->vd.class_) == 0) {
  4551. this->invalidWarning(node["Weapon"], "Weapon is only applicable to Job sprites.\n");
  4552. return 0;
  4553. }
  4554. std::string weapon;
  4555. if (!this->asString(node, "Weapon", weapon))
  4556. return 0;
  4557. struct item_data *item = itemdb_search_aegisname(weapon.c_str());
  4558. if (item == nullptr) {
  4559. this->invalidWarning(node["Weapon"], "Weapon %s is not a valid item.\n", weapon.c_str());
  4560. return 0;
  4561. }
  4562. mob->vd.weapon = item->nameid;
  4563. }
  4564. if (this->nodeExists(node, "Shield")) {
  4565. if (pcdb_checkid(mob->vd.class_) == 0) {
  4566. this->invalidWarning(node["Shield"], "Shield is only applicable to Job sprites.\n");
  4567. return 0;
  4568. }
  4569. std::string shield;
  4570. if (!this->asString(node, "Shield", shield))
  4571. return 0;
  4572. struct item_data *item = itemdb_search_aegisname(shield.c_str());
  4573. if (item == nullptr) {
  4574. this->invalidWarning(node["Shield"], "Shield %s is not a valid item.\n", shield.c_str());
  4575. return 0;
  4576. }
  4577. mob->vd.shield = item->nameid;
  4578. }
  4579. if (this->nodeExists(node, "HeadTop")) {
  4580. if (pcdb_checkid(mob->vd.class_) == 0) {
  4581. this->invalidWarning(node["HeadTop"], "HeadTop is only applicable to Job sprites.\n");
  4582. return 0;
  4583. }
  4584. std::string head;
  4585. if (!this->asString(node, "HeadTop", head))
  4586. return 0;
  4587. struct item_data *item;
  4588. if ((item = itemdb_search_aegisname(head.c_str())) == nullptr) {
  4589. this->invalidWarning(node["HeadTop"], "HeadTop %s is not a valid item.\n", head.c_str());
  4590. return 0;
  4591. }
  4592. mob->vd.head_top = item->look;
  4593. }
  4594. if (this->nodeExists(node, "HeadMid")) {
  4595. if (pcdb_checkid(mob->vd.class_) == 0) {
  4596. this->invalidWarning(node["HeadMid"], "HeadMid is only applicable to Job sprites.\n");
  4597. return 0;
  4598. }
  4599. std::string head;
  4600. if (!this->asString(node, "HeadMid", head))
  4601. return 0;
  4602. struct item_data *item = itemdb_search_aegisname(head.c_str());
  4603. if (item == nullptr) {
  4604. this->invalidWarning(node["HeadMid"], "HeadMid %s is not a valid item.\n", head.c_str());
  4605. return 0;
  4606. }
  4607. mob->vd.head_mid = item->look;
  4608. }
  4609. if (this->nodeExists(node, "HeadLow")) {
  4610. if (pcdb_checkid(mob->vd.class_) == 0) {
  4611. this->invalidWarning(node["HeadLow"], "HeadLow is only applicable to Job sprites.\n");
  4612. return 0;
  4613. }
  4614. std::string head;
  4615. if (!this->asString(node, "HeadLow", head))
  4616. return 0;
  4617. struct item_data *item = itemdb_search_aegisname(head.c_str());
  4618. if (item == nullptr) {
  4619. this->invalidWarning(node["HeadLow"], "HeadLow %s is not a valid item.\n", head.c_str());
  4620. return 0;
  4621. }
  4622. mob->vd.head_bottom = item->look;
  4623. }
  4624. if (this->nodeExists(node, "PetEquip")) {
  4625. std::shared_ptr<s_pet_db> pet_db_ptr = pet_db.find(mob->vd.class_);
  4626. if (pet_db_ptr == nullptr) {
  4627. this->invalidWarning(node["PetEquip"], "PetEquip is only applicable to defined pets.\n");
  4628. return 0;
  4629. }
  4630. std::string equipment;
  4631. if (!this->asString(node, "PetEquip", equipment))
  4632. return 0;
  4633. struct item_data *item = itemdb_search_aegisname(equipment.c_str());
  4634. if (item == nullptr) {
  4635. this->invalidWarning(node["PetEquip"], "PetEquip %s is not a valid item.\n", equipment.c_str());
  4636. return 0;
  4637. }
  4638. mob->vd.head_bottom = item->nameid;
  4639. }
  4640. if (this->nodeExists(node, "Options")) {
  4641. const YAML::Node &optionNode = node["Options"];
  4642. for (const auto &it : optionNode) {
  4643. std::string option = it.first.as<std::string>(), option_constant = "OPTION_" + option;
  4644. int64 constant;
  4645. if (!script_get_constant(option_constant.c_str(), &constant)) {
  4646. this->invalidWarning(optionNode, "Unknown option constant %s, skipping.\n", option.c_str());
  4647. continue;
  4648. }
  4649. bool active;
  4650. if (!this->asBool(optionNode, option, active))
  4651. continue;
  4652. #ifdef NEW_CARTS
  4653. if (constant & OPTION_CART) {
  4654. this->invalidWarning(optionNode, "OPTION_CART was replace by SC_PUSH_CART, skipping.\n");
  4655. continue;
  4656. }
  4657. #endif
  4658. if (active)
  4659. mob->option |= constant;
  4660. else
  4661. mob->option &= ~constant;
  4662. }
  4663. mob->option &= ~(OPTION_HIDE | OPTION_CLOAK | OPTION_INVISIBLE | OPTION_CHASEWALK); // Remove hiding types
  4664. }
  4665. return 1;
  4666. }
  4667. MobAvailDatabase mob_avail_db;
  4668. /*==========================================
  4669. * Reading of random monster data
  4670. * MobGroup,MobID,DummyName,Rate
  4671. *------------------------------------------*/
  4672. static bool mob_readdb_group(char* str[], int columns, int current){
  4673. struct s_randomsummon_group *msummon = NULL;
  4674. int mob_id, group = 0;
  4675. unsigned short i = 0;
  4676. bool set_default = false;
  4677. if (ISDIGIT(str[0][0]) && ISDIGIT(str[0][1]))
  4678. group = atoi(str[0]);
  4679. else {
  4680. int64 group_tmp;
  4681. if (!script_get_constant(str[0], &group_tmp)) {
  4682. ShowError("mob_readdb_group: Invalid random monster group '%s'\n", str[0]);
  4683. return false;
  4684. }
  4685. group = static_cast<int>(group_tmp);
  4686. }
  4687. mob_id = atoi(str[1]);
  4688. if (mob_id != 0 && mob_db.find(mob_id) == nullptr) {
  4689. ShowError("mob_readdb_group: Invalid random monster group '%s'\n", str[0]);
  4690. return false;
  4691. }
  4692. else if (mob_id == 0){
  4693. mob_id = atoi(str[3]);
  4694. if (mob_db.find(mob_id) == nullptr) {
  4695. ShowError("mob_readdb_group: Invalid random monster group '%s'\n", str[0]);
  4696. return false;
  4697. }
  4698. set_default = true;
  4699. }
  4700. if (!(msummon = (struct s_randomsummon_group *)idb_get(mob_summon_db, group))) {
  4701. CREATE(msummon, struct s_randomsummon_group, 1);
  4702. CREATE(msummon->list, struct s_randomsummon_entry, (msummon->count = 1));
  4703. msummon->list[0].mob_id = mob_id;
  4704. msummon->list[0].rate = atoi(str[3]);
  4705. msummon->random_id = group;
  4706. idb_put(mob_summon_db, group, msummon);
  4707. }
  4708. else {
  4709. ARR_FIND(0, msummon->count, i, set_default || (i > 0 && msummon->list[i].mob_id == mob_id));
  4710. if (i >= msummon->count)
  4711. RECREATE(msummon->list, struct s_randomsummon_entry, ++msummon->count);
  4712. msummon->list[i].mob_id = mob_id;
  4713. msummon->list[i].rate = atoi(str[3]);
  4714. }
  4715. return true;
  4716. }
  4717. //processes one mob_chat_db entry [SnakeDrak]
  4718. //db struct: Line_ID,Color_Code,Dialog
  4719. static bool mob_parse_row_chatdb(char* fields[], int columns, int current)
  4720. {
  4721. char* msg;
  4722. struct mob_chat *ms;
  4723. int msg_id;
  4724. size_t len;
  4725. msg_id = atoi(fields[0]);
  4726. if (msg_id <= 0){
  4727. ShowError("mob_parse_row_chatdb: Invalid chat ID '%d' in line %d\n", msg_id, current);
  4728. return false;
  4729. }
  4730. ms = mob_chat(msg_id);
  4731. if( ms == NULL ){
  4732. try{
  4733. ms = &mob_chat_db[msg_id];
  4734. }catch( const std::bad_alloc& ){
  4735. ShowError( "mob_parse_row_chatdb: Memory allocation for chat ID '%d' failed.\n", msg_id );
  4736. return false;
  4737. }
  4738. }
  4739. //MSG ID
  4740. ms->msg_id=msg_id;
  4741. //Color
  4742. ms->color=strtoul(fields[1],NULL,0);
  4743. //Message
  4744. msg = fields[2];
  4745. len = strlen(msg);
  4746. while( len && ( msg[len-1]=='\r' || msg[len-1]=='\n' ) )
  4747. {// find EOL to strip
  4748. len--;
  4749. }
  4750. if(len>(CHAT_SIZE_MAX-1)){
  4751. ShowError("mob_parse_row_chatdb: Message too long! Line %d, id: %d\n", current, msg_id);
  4752. return false;
  4753. }
  4754. else if( !len ){
  4755. ShowWarning("mob_parse_row_chatdb: Empty message for id %d.\n", msg_id);
  4756. return false;
  4757. }
  4758. msg[len] = 0; // strip previously found EOL
  4759. safestrncpy(ms->msg, fields[2], CHAT_SIZE_MAX);
  4760. return true;
  4761. }
  4762. /*==========================================
  4763. * processes one mob_skill_db entry
  4764. *------------------------------------------*/
  4765. static bool mob_parse_row_mobskilldb(char** str, int columns, int current)
  4766. {
  4767. static const struct {
  4768. char str[32];
  4769. enum MobSkillState id;
  4770. } state[] = {
  4771. { "any", MSS_ANY }, //All states except Dead
  4772. { "idle", MSS_IDLE },
  4773. { "walk", MSS_WALK },
  4774. { "loot", MSS_LOOT },
  4775. { "dead", MSS_DEAD },
  4776. { "attack", MSS_BERSERK }, //Retaliating attack
  4777. { "angry", MSS_ANGRY }, //Preemptive attack (aggressive mobs)
  4778. { "chase", MSS_RUSH }, //Chase escaping target
  4779. { "follow", MSS_FOLLOW }, //Preemptive chase (aggressive mobs)
  4780. { "anytarget",MSS_ANYTARGET }, //Berserk+Angry+Rush+Follow
  4781. };
  4782. static const struct {
  4783. char str[32];
  4784. int id;
  4785. } cond1[] = {
  4786. // enum e_mob_skill_condition
  4787. { "always", MSC_ALWAYS },
  4788. { "myhpltmaxrate", MSC_MYHPLTMAXRATE },
  4789. { "myhpinrate", MSC_MYHPINRATE },
  4790. { "friendhpltmaxrate", MSC_FRIENDHPLTMAXRATE },
  4791. { "friendhpinrate", MSC_FRIENDHPINRATE },
  4792. { "mystatuson", MSC_MYSTATUSON },
  4793. { "mystatusoff", MSC_MYSTATUSOFF },
  4794. { "friendstatuson", MSC_FRIENDSTATUSON },
  4795. { "friendstatusoff", MSC_FRIENDSTATUSOFF },
  4796. { "attackpcgt", MSC_ATTACKPCGT },
  4797. { "attackpcge", MSC_ATTACKPCGE },
  4798. { "slavelt", MSC_SLAVELT },
  4799. { "slavele", MSC_SLAVELE },
  4800. { "closedattacked", MSC_CLOSEDATTACKED },
  4801. { "longrangeattacked", MSC_LONGRANGEATTACKED },
  4802. { "skillused", MSC_SKILLUSED },
  4803. { "afterskill", MSC_AFTERSKILL },
  4804. { "casttargeted", MSC_CASTTARGETED },
  4805. { "rudeattacked", MSC_RUDEATTACKED },
  4806. { "masterhpltmaxrate", MSC_MASTERHPLTMAXRATE },
  4807. { "masterattacked", MSC_MASTERATTACKED },
  4808. { "alchemist", MSC_ALCHEMIST },
  4809. { "onspawn", MSC_SPAWN },
  4810. }, cond2[] ={
  4811. { "anybad", -1 },
  4812. { "stone", SC_STONE },
  4813. { "freeze", SC_FREEZE },
  4814. { "stun", SC_STUN },
  4815. { "sleep", SC_SLEEP },
  4816. { "poison", SC_POISON },
  4817. { "curse", SC_CURSE },
  4818. { "silence", SC_SILENCE },
  4819. { "confusion", SC_CONFUSION },
  4820. { "blind", SC_BLIND },
  4821. { "hiding", SC_HIDING },
  4822. { "sight", SC_SIGHT },
  4823. }, target[] = {
  4824. // enum e_mob_skill_target
  4825. { "target", MST_TARGET },
  4826. { "randomtarget", MST_RANDOM },
  4827. { "self", MST_SELF },
  4828. { "friend", MST_FRIEND },
  4829. { "master", MST_MASTER },
  4830. { "around5", MST_AROUND5 },
  4831. { "around6", MST_AROUND6 },
  4832. { "around7", MST_AROUND7 },
  4833. { "around8", MST_AROUND8 },
  4834. { "around1", MST_AROUND1 },
  4835. { "around2", MST_AROUND2 },
  4836. { "around3", MST_AROUND3 },
  4837. { "around4", MST_AROUND4 },
  4838. { "around", MST_AROUND },
  4839. };
  4840. static int last_mob_id = 0; // ensures that only one error message per mob id is printed
  4841. int mob_id;
  4842. int j, tmp;
  4843. mob_id = atoi(str[0]);
  4844. std::shared_ptr<s_mob_db> mob = mob_db.find(mob_id);
  4845. if (mob_id > 0 && mob == nullptr)
  4846. {
  4847. if (mob_id != last_mob_id) {
  4848. ShowError("mob_parse_row_mobskilldb: Non existant Mob id %d\n", mob_id);
  4849. last_mob_id = mob_id;
  4850. }
  4851. return false;
  4852. }
  4853. else if (mob_id == 0)
  4854. return false;
  4855. // Looking for existing entry
  4856. std::shared_ptr<s_mob_skill_db> skill = util::umap_find(mob_skill_db, mob_id);
  4857. if (skill == nullptr)
  4858. skill = std::make_shared<s_mob_skill_db>();
  4859. if( strcmp(str[1],"clear") == 0 && skill->mob_id != 0 ) {
  4860. mob_skill_db.erase(skill->mob_id);
  4861. ShowInfo("Cleared skill for mob id '%d'\n", mob_id);
  4862. return true;
  4863. }
  4864. if (skill->skill.size() >= MAX_MOBSKILL) {
  4865. if (mob_id != last_mob_id) {
  4866. ShowError("mob_parse_row_mobskilldb: Too many skills for monster %d[%s]\n", mob_id, mob->sprite.c_str());
  4867. last_mob_id = mob_id;
  4868. }
  4869. return false;
  4870. }
  4871. std::shared_ptr<s_mob_skill> ms = std::make_shared<s_mob_skill>();
  4872. //State
  4873. ARR_FIND( 0, ARRAYLENGTH(state), j, strcmp(str[2],state[j].str) == 0 );
  4874. if( j < ARRAYLENGTH(state) )
  4875. ms->state = state[j].id;
  4876. else {
  4877. ShowError("mob_parse_row_mobskilldb: Unrecognized state '%s' in line %d\n", str[2], current);
  4878. return false;
  4879. }
  4880. //Skill ID
  4881. j = atoi(str[3]);
  4882. if (j <= 0 || j > MAX_SKILL_ID || !skill_get_index(j)) //fixed Lupus
  4883. {
  4884. if (mob_id < 0)
  4885. ShowError("mob_parse_row_mobskilldb: Invalid Skill ID (%d) for all mobs\n", j);
  4886. else
  4887. ShowError("mob_parse_row_mobskilldb: Invalid Skill ID (%d) for mob %d (%s)\n", j, mob_id, mob->sprite.c_str());
  4888. return false;
  4889. }
  4890. ms->skill_id = j;
  4891. //Skill lvl
  4892. j = atoi(str[4]) <= 0 ? 1 : atoi(str[4]);
  4893. ms->skill_lv = j > battle_config.mob_max_skilllvl ? battle_config.mob_max_skilllvl : j; //we strip max skill level
  4894. //Apply battle_config modifiers to rate (permillage) and delay [Skotlex]
  4895. tmp = atoi(str[5]);
  4896. if (battle_config.mob_skill_rate != 100)
  4897. tmp = tmp*battle_config.mob_skill_rate/100;
  4898. if (tmp > 10000)
  4899. ms->permillage = 10000;
  4900. else if (!tmp && battle_config.mob_skill_rate)
  4901. ms->permillage = 1;
  4902. else
  4903. ms->permillage = tmp;
  4904. ms->casttime = atoi(str[6]);
  4905. ms->delay = atoi(str[7]);
  4906. if (battle_config.mob_skill_delay != 100)
  4907. ms->delay = ms->delay*battle_config.mob_skill_delay/100;
  4908. if (ms->delay < 0 || ms->delay > MOB_MAX_DELAY) //time overflow?
  4909. ms->delay = MOB_MAX_DELAY;
  4910. ms->cancel = atoi(str[8]);
  4911. if( strcmp(str[8],"yes")==0 )
  4912. ms->cancel=1;
  4913. //Target
  4914. ARR_FIND( 0, ARRAYLENGTH(target), j, strcmp(str[9],target[j].str) == 0 );
  4915. if( j < ARRAYLENGTH(target) )
  4916. ms->target = target[j].id;
  4917. else {
  4918. ShowWarning("mob_parse_row_mobskilldb: Unrecognized target %s for %d\n", str[9], mob_id);
  4919. ms->target = MST_TARGET;
  4920. }
  4921. //Check that the target condition is right for the skill type. [Skotlex]
  4922. if (skill_get_casttype(ms->skill_id) == CAST_GROUND)
  4923. { //Ground skill.
  4924. if (ms->target > MST_AROUND)
  4925. {
  4926. ShowWarning("mob_parse_row_mobskilldb: Wrong mob skill target for ground skill %d (%s) for %s.\n",
  4927. ms->skill_id, skill_get_name(ms->skill_id),
  4928. mob_id < 0 ? "all mobs" : mob->sprite.c_str());
  4929. ms->target = MST_TARGET;
  4930. }
  4931. } else if (ms->target > MST_MASTER) {
  4932. ShowWarning("mob_parse_row_mobskilldb: Wrong mob skill target 'around' for non-ground skill %d (%s) for %s.\n",
  4933. ms->skill_id, skill_get_name(ms->skill_id),
  4934. mob_id < 0 ? "all mobs" : mob->sprite.c_str());
  4935. ms->target = MST_TARGET;
  4936. }
  4937. //Cond1
  4938. ARR_FIND( 0, ARRAYLENGTH(cond1), j, strcmp(str[10],cond1[j].str) == 0 );
  4939. if( j < ARRAYLENGTH(cond1) )
  4940. ms->cond1 = cond1[j].id;
  4941. else {
  4942. ShowWarning("mob_parse_row_mobskilldb: Unrecognized condition 1 %s for %d\n", str[10], mob_id);
  4943. ms->cond1 = -1;
  4944. }
  4945. //Cond2
  4946. // numeric value
  4947. ms->cond2 = atoi(str[11]);
  4948. // or special constant
  4949. ARR_FIND( 0, ARRAYLENGTH(cond2), j, strcmp(str[11],cond2[j].str) == 0 );
  4950. if( j < ARRAYLENGTH(cond2) )
  4951. ms->cond2 = cond2[j].id;
  4952. ms->val[0] = (int)strtol(str[12],NULL,0);
  4953. ms->val[1] = (int)strtol(str[13],NULL,0);
  4954. ms->val[2] = (int)strtol(str[14],NULL,0);
  4955. ms->val[3] = (int)strtol(str[15],NULL,0);
  4956. ms->val[4] = (int)strtol(str[16],NULL,0);
  4957. if(ms->skill_id == NPC_EMOTION && mob_id > 0 &&
  4958. ms->val[1] == mob->status.mode)
  4959. {
  4960. ms->val[1] = 0;
  4961. ms->val[4] = 1; //request to return mode to normal.
  4962. }
  4963. if(ms->skill_id == NPC_EMOTION_ON && mob_id > 0 && ms->val[1])
  4964. { //Adds a mode to the mob.
  4965. //Remove aggressive mode when the new mob type is passive.
  4966. if (!(ms->val[1]&MD_AGGRESSIVE))
  4967. ms->val[3] |= MD_AGGRESSIVE;
  4968. ms->val[2] |= ms->val[1]; //Add the new mode.
  4969. ms->val[1] = 0; //Do not "set" it.
  4970. }
  4971. if(*str[17])
  4972. ms->emotion = atoi(str[17]);
  4973. else
  4974. ms->emotion = -1;
  4975. if(str[18] != NULL && mob_chat(atoi(str[18]))!=NULL)
  4976. ms->msg_id = atoi(str[18]);
  4977. else
  4978. ms->msg_id = 0;
  4979. skill->skill.push_back(ms);
  4980. if (!skill->mob_id) { // Insert new entry
  4981. skill->mob_id = mob_id;
  4982. mob_skill_db.insert({ mob_id, skill });
  4983. }
  4984. return true;
  4985. }
  4986. /*==========================================
  4987. * mob_skill_db.txt reading
  4988. *------------------------------------------*/
  4989. static void mob_readskilldb(const char* basedir, bool silent) {
  4990. if( battle_config.mob_skill_rate == 0 ) {
  4991. ShowStatus("Mob skill use disabled. Not reading mob skills.\n");
  4992. return;
  4993. }
  4994. sv_readdb(basedir, "mob_skill_db.txt", ',', 19, 19, -1, &mob_parse_row_mobskilldb, silent);
  4995. }
  4996. /**
  4997. * mob_skill_db table reading [CalciumKid]
  4998. * not overly sure if this is all correct
  4999. * seems to work though...
  5000. */
  5001. static int mob_read_sqlskilldb(void)
  5002. {
  5003. const char* mob_skill_db_name[] = {
  5004. mob_skill_table,
  5005. mob_skill2_table };
  5006. int fi;
  5007. if( battle_config.mob_skill_rate == 0 ) {
  5008. ShowStatus("Mob skill use disabled. Not reading mob skills.\n");
  5009. return 0;
  5010. }
  5011. for( fi = 0; fi < ARRAYLENGTH(mob_skill_db_name); ++fi ) {
  5012. uint32 lines = 0, count = 0;
  5013. // retrieve all rows from the mob skill database
  5014. if( SQL_ERROR == Sql_Query(mmysql_handle, "SELECT * FROM `%s`", mob_skill_db_name[fi]) ) {
  5015. Sql_ShowDebug(mmysql_handle);
  5016. continue;
  5017. }
  5018. // process rows one by one
  5019. while( SQL_SUCCESS == Sql_NextRow(mmysql_handle) ) {
  5020. // wrap the result into a TXT-compatible format
  5021. char* str[19];
  5022. char dummy[255] = "";
  5023. int i;
  5024. ++lines;
  5025. for( i = 0; i < 19; ++i )
  5026. {
  5027. Sql_GetData(mmysql_handle, i, &str[i], NULL);
  5028. if( str[i] == NULL )
  5029. str[i] = dummy; // get rid of NULL columns
  5030. }
  5031. if (!mob_parse_row_mobskilldb(str, 19, count))
  5032. continue;
  5033. count++;
  5034. }
  5035. // free the query result
  5036. Sql_FreeResult(mmysql_handle);
  5037. ShowStatus("Done reading '" CL_WHITE "%u" CL_RESET "' entries in '" CL_WHITE "%s" CL_RESET "'.\n", count, mob_skill_db_name[fi]);
  5038. }
  5039. return 0;
  5040. }
  5041. /**
  5042. * Read mob_item_ratio.txt
  5043. */
  5044. static bool mob_readdb_itemratio(char* str[], int columns, int current)
  5045. {
  5046. t_itemid nameid;
  5047. int ratio, i;
  5048. struct s_mob_item_drop_ratio *item_ratio;
  5049. nameid = strtoul(str[0], nullptr, 10);
  5050. if (itemdb_exists(nameid) == NULL) {
  5051. ShowWarning("mob_readdb_itemratio: Invalid item id %u.\n", nameid);
  5052. return false;
  5053. }
  5054. ratio = atoi(str[1]);
  5055. if (!(item_ratio = (struct s_mob_item_drop_ratio *)uidb_get(mob_item_drop_ratio,nameid)))
  5056. CREATE(item_ratio, struct s_mob_item_drop_ratio, 1);
  5057. item_ratio->drop_ratio = ratio;
  5058. memset(item_ratio->mob_id, 0, sizeof(item_ratio->mob_id));
  5059. for (i = 0; i < columns-2; i++) {
  5060. uint16 mob_id = atoi(str[i+2]);
  5061. if (mob_db.find(mob_id) == nullptr)
  5062. ShowError("mob_readdb_itemratio: Invalid monster with ID %hu (Item:%u Col:%d).\n", mob_id, nameid, columns);
  5063. else
  5064. item_ratio->mob_id[i] = atoi(str[i+2]);
  5065. }
  5066. if (!item_ratio->nameid) {
  5067. item_ratio->nameid = nameid;
  5068. uidb_put(mob_item_drop_ratio, nameid, item_ratio);
  5069. }
  5070. return true;
  5071. }
  5072. /**
  5073. * Free drop ratio data
  5074. **/
  5075. static int mob_item_drop_ratio_free(DBKey key, DBData *data, va_list ap) {
  5076. struct s_mob_item_drop_ratio *item_ratio = (struct s_mob_item_drop_ratio *)db_data2ptr(data);
  5077. aFree(item_ratio);
  5078. return 0;
  5079. }
  5080. /**
  5081. * Adjust drop ratio for each monster
  5082. **/
  5083. static void mob_drop_ratio_adjust(void){
  5084. for( auto &pair : mob_db ){
  5085. std::shared_ptr<s_mob_db> mob = pair.second;
  5086. struct item_data *id;
  5087. t_itemid nameid;
  5088. int j, rate, rate_adjust = 0, mob_id = pair.first;
  5089. if( mob_is_clone( mob_id ) ){
  5090. continue;
  5091. }
  5092. for( j = 0; j < MAX_MVP_DROP_TOTAL; j++ ){
  5093. nameid = mob->mvpitem[j].nameid;
  5094. rate = mob->mvpitem[j].rate;
  5095. if( nameid == 0 || rate == 0 ){
  5096. continue;
  5097. }
  5098. rate_adjust = battle_config.item_rate_mvp;
  5099. // Adjust the rate if there is an entry in mob_item_ratio
  5100. item_dropratio_adjust( nameid, mob_id, &rate_adjust );
  5101. // Adjust rate with given algorithms
  5102. rate = mob_drop_adjust( rate, rate_adjust, battle_config.item_drop_mvp_min, battle_config.item_drop_mvp_max );
  5103. // calculate and store Max available drop chance of the MVP item
  5104. if( rate ){
  5105. id = itemdb_search( nameid );
  5106. // Item is not known anymore(should never happen)
  5107. if( !id ){
  5108. ShowWarning( "Monster \"%s\"(id:%u) is dropping an unknown item(id: %u)\n", mob->name.c_str(), mob_id, nameid );
  5109. mob->mvpitem[j].nameid = 0;
  5110. mob->mvpitem[j].rate = 0;
  5111. continue;
  5112. }
  5113. if( id->maxchance == -1 || ( id->maxchance < rate/10 + 1 ) ){
  5114. // item has bigger drop chance or sold in shops
  5115. id->maxchance = rate/10 + 1; // reduce MVP drop info to not spoil common drop rate
  5116. }
  5117. }
  5118. mob->mvpitem[j].rate = rate;
  5119. }
  5120. for( j = 0; j < MAX_MOB_DROP_TOTAL; j++ ){
  5121. unsigned short ratemin, ratemax;
  5122. bool is_treasurechest;
  5123. nameid = mob->dropitem[j].nameid;
  5124. rate = mob->dropitem[j].rate;
  5125. if( nameid == 0 || rate == 0 ){
  5126. continue;
  5127. }
  5128. id = itemdb_search( nameid );
  5129. // Item is not known anymore(should never happen)
  5130. if( !id ){
  5131. ShowWarning( "Monster \"%s\"(id:%hu) is dropping an unknown item(id: %u)\n", mob->name.c_str(), mob_id, nameid );
  5132. mob->dropitem[j].nameid = 0;
  5133. mob->dropitem[j].rate = 0;
  5134. continue;
  5135. }
  5136. if( battle_config.drop_rateincrease && rate < 5000 ){
  5137. rate++;
  5138. }
  5139. // Treasure box drop rates [Skotlex]
  5140. if (util::vector_exists(mob->race2, RC2_TREASURE)) {
  5141. is_treasurechest = true;
  5142. rate_adjust = battle_config.item_rate_treasure;
  5143. ratemin = battle_config.item_drop_treasure_min;
  5144. ratemax = battle_config.item_drop_treasure_max;
  5145. } else {
  5146. bool is_mvp = mob->get_bosstype() == BOSSTYPE_MVP;
  5147. bool is_boss = mob->get_bosstype() == BOSSTYPE_MINIBOSS;
  5148. is_treasurechest = false;
  5149. // Added suport to restrict normal drops of MVP's [Reddozen]
  5150. switch( id->type ){
  5151. case IT_HEALING:
  5152. rate_adjust = is_mvp ? battle_config.item_rate_heal_mvp : (is_boss ? battle_config.item_rate_heal_boss : battle_config.item_rate_heal);
  5153. ratemin = battle_config.item_drop_heal_min;
  5154. ratemax = battle_config.item_drop_heal_max;
  5155. break;
  5156. case IT_USABLE:
  5157. case IT_CASH:
  5158. rate_adjust = is_mvp ? battle_config.item_rate_use_mvp : (is_boss ? battle_config.item_rate_use_boss : battle_config.item_rate_use);
  5159. ratemin = battle_config.item_drop_use_min;
  5160. ratemax = battle_config.item_drop_use_max;
  5161. break;
  5162. case IT_WEAPON:
  5163. case IT_ARMOR:
  5164. case IT_PETARMOR:
  5165. rate_adjust = is_mvp ? battle_config.item_rate_equip_mvp : (is_boss ? battle_config.item_rate_equip_boss : battle_config.item_rate_equip);
  5166. ratemin = battle_config.item_drop_equip_min;
  5167. ratemax = battle_config.item_drop_equip_max;
  5168. break;
  5169. case IT_CARD:
  5170. rate_adjust = is_mvp ? battle_config.item_rate_card_mvp : (is_boss ? battle_config.item_rate_card_boss : battle_config.item_rate_card);
  5171. ratemin = battle_config.item_drop_card_min;
  5172. ratemax = battle_config.item_drop_card_max;
  5173. break;
  5174. default:
  5175. rate_adjust = is_mvp ? battle_config.item_rate_common_mvp : (is_boss ? battle_config.item_rate_common_boss : battle_config.item_rate_common);
  5176. ratemin = battle_config.item_drop_common_min;
  5177. ratemax = battle_config.item_drop_common_max;
  5178. break;
  5179. }
  5180. }
  5181. item_dropratio_adjust( nameid, mob_id, &rate_adjust );
  5182. rate = mob_drop_adjust( rate, rate_adjust, ratemin, ratemax );
  5183. // calculate and store Max available drop chance of the item
  5184. // but skip treasure chests.
  5185. if( rate && !is_treasurechest ){
  5186. unsigned short k;
  5187. if( id->maxchance == -1 || ( id->maxchance < rate ) ){
  5188. id->maxchance = rate; // item has bigger drop chance or sold in shops
  5189. }
  5190. for( k = 0; k < MAX_SEARCH; k++ ){
  5191. if( id->mob[k].chance <= rate ){
  5192. break;
  5193. }
  5194. }
  5195. if( k != MAX_SEARCH ){
  5196. if( id->mob[k].id != mob_id ){
  5197. memmove( &id->mob[k+1], &id->mob[k], (MAX_SEARCH-k-1)*sizeof(id->mob[0]) );
  5198. }
  5199. id->mob[k].chance = rate;
  5200. id->mob[k].id = mob_id;
  5201. }
  5202. }
  5203. mob->dropitem[j].rate = rate;
  5204. }
  5205. }
  5206. // Now that we are done we can delete the stored item ratios
  5207. mob_item_drop_ratio->clear( mob_item_drop_ratio, mob_item_drop_ratio_free );
  5208. }
  5209. /**
  5210. * Copy skill from DB to monster
  5211. * @param mob Monster DB entry
  5212. * @param skill Monster skill entries
  5213. **/
  5214. static void mob_skill_db_set_single_sub(std::shared_ptr<s_mob_db> mob, struct s_mob_skill_db *skill) {
  5215. nullpo_retv(skill);
  5216. if (mob == nullptr)
  5217. return;
  5218. size_t i = 0;
  5219. for (i = 0; mob->skill.size() < MAX_MOBSKILL && i < skill->skill.size(); i++) {
  5220. mob->skill.push_back(skill->skill[i]);
  5221. }
  5222. if (i < skill->skill.size())
  5223. ShowWarning("Monster '%s' (%d, src:%d) reaches max skill limit %d. Ignores '%zu' skills left.\n", mob->sprite.c_str(), mob->vd.class_, skill->mob_id, MAX_MOBSKILL, skill->skill.size() - i);
  5224. }
  5225. /**
  5226. * Check the skill & monster id before put the skills
  5227. * @param skill
  5228. **/
  5229. static void mob_skill_db_set_single(struct s_mob_skill_db *skill) {
  5230. nullpo_retv(skill);
  5231. // Specific monster
  5232. if (skill->mob_id >= 0) {
  5233. std::shared_ptr<s_mob_db> mob = mob_db.find(skill->mob_id);
  5234. if (mob != nullptr)
  5235. mob_skill_db_set_single_sub(mob, skill);
  5236. }
  5237. // Global skill
  5238. else {
  5239. uint16 id = skill->mob_id;
  5240. id *= -1;
  5241. for( auto &pair : mob_db ){
  5242. if ( mob_is_clone(pair.first) ){
  5243. continue;
  5244. }
  5245. if ( (!(id&1) && status_has_mode(&pair.second->status,MD_STATUSIMMUNE)) // Bosses
  5246. || (!(id&2) && !status_has_mode(&pair.second->status,MD_STATUSIMMUNE)) // Normal monsters
  5247. )
  5248. continue;
  5249. mob_skill_db_set_single_sub(pair.second, skill);
  5250. }
  5251. }
  5252. }
  5253. /**
  5254. * Free random summon data
  5255. **/
  5256. static int mob_summon_db_free(DBKey key, DBData *data, va_list ap) {
  5257. struct s_randomsummon_group *msummon = (struct s_randomsummon_group *)db_data2ptr(data);
  5258. if (msummon) {
  5259. if (msummon->list) {
  5260. aFree(msummon->list);
  5261. msummon->list = NULL;
  5262. msummon->count = 0;
  5263. }
  5264. aFree(msummon);
  5265. msummon = NULL;
  5266. }
  5267. return 0;
  5268. }
  5269. /**
  5270. * Set monster skills
  5271. **/
  5272. static void mob_skill_db_set(void) {
  5273. for (auto skill : mob_skill_db) {
  5274. mob_skill_db_set_single(skill.second.get());
  5275. }
  5276. //ShowStatus("Set skills to '%d' monsters.\n", db_size(mob_skill_db));
  5277. }
  5278. /**
  5279. * read all mob-related databases
  5280. */
  5281. static void mob_load(void)
  5282. {
  5283. const char* dbsubpath[] = {
  5284. "",
  5285. "/" DBIMPORT,
  5286. };
  5287. // First we parse all the possible monsters to add additional data in the second loop
  5288. if( db_use_sqldbs )
  5289. mob_read_sqldb();
  5290. else
  5291. mob_db.load();
  5292. for(int i = 0; i < ARRAYLENGTH(dbsubpath); i++){
  5293. int n1 = strlen(db_path)+strlen(dbsubpath[i])+1;
  5294. int n2 = strlen(db_path)+strlen(DBPATH)+strlen(dbsubpath[i])+1;
  5295. char* dbsubpath1 = (char*)aMalloc(n1+1);
  5296. char* dbsubpath2 = (char*)aMalloc(n2+1);
  5297. bool silent = i > 0;
  5298. if(i==0) {
  5299. safesnprintf(dbsubpath1,n1,"%s%s",db_path,dbsubpath[i]);
  5300. safesnprintf(dbsubpath2,n2,"%s/%s%s",db_path,DBPATH,dbsubpath[i]);
  5301. } else {
  5302. safesnprintf(dbsubpath1,n1,"%s%s",db_path,dbsubpath[i]);
  5303. safesnprintf(dbsubpath2,n1,"%s%s",db_path,dbsubpath[i]);
  5304. }
  5305. sv_readdb(dbsubpath1, "mob_chat_db.txt", '#', 3, 3, -1, &mob_parse_row_chatdb, silent);
  5306. if( db_use_sqldbs && i == 0 )
  5307. mob_read_sqlskilldb();
  5308. else
  5309. mob_readskilldb(dbsubpath2, silent);
  5310. sv_readdb(dbsubpath1, "mob_item_ratio.txt", ',', 2, 2+MAX_ITEMRATIO_MOBS, -1, &mob_readdb_itemratio, silent);
  5311. sv_readdb(dbsubpath2, "mob_random_db.txt", ',', 4, 4, -1, &mob_readdb_group, silent);
  5312. sv_readdb(dbsubpath2, "mob_branch.txt", ',', 4, 4, -1, &mob_readdb_group, silent);
  5313. sv_readdb(dbsubpath2, "mob_poring.txt", ',', 4, 4, -1, &mob_readdb_group, silent);
  5314. sv_readdb(dbsubpath2, "mob_boss.txt", ',', 4, 4, -1, &mob_readdb_group, silent);
  5315. sv_readdb(dbsubpath1, "mob_pouch.txt", ',', 4, 4, -1, &mob_readdb_group, silent);
  5316. sv_readdb(dbsubpath1, "mob_mission.txt", ',', 4, 4, -1, &mob_readdb_group, silent);
  5317. sv_readdb(dbsubpath1, "mob_classchange.txt", ',', 4, 4, -1, &mob_readdb_group, silent);
  5318. aFree(dbsubpath1);
  5319. aFree(dbsubpath2);
  5320. }
  5321. mob_avail_db.load();
  5322. mob_drop_ratio_adjust();
  5323. mob_skill_db_set();
  5324. }
  5325. /**
  5326. * Initialize monster data
  5327. */
  5328. void mob_db_load(bool is_reload){
  5329. if( !is_reload ) {
  5330. // on mobdbreload it's not neccessary to execute this
  5331. // item ers needs to be allocated only once
  5332. item_drop_ers = ers_new(sizeof(struct item_drop),"mob.cpp::item_drop_ers",ERS_OPT_CLEAN);
  5333. item_drop_list_ers = ers_new(sizeof(struct item_drop_list),"mob.cpp::item_drop_list_ers",ERS_OPT_NONE);
  5334. }
  5335. mob_item_drop_ratio = uidb_alloc(DB_OPT_BASE);
  5336. mob_summon_db = idb_alloc(DB_OPT_BASE);
  5337. mob_load();
  5338. }
  5339. /**
  5340. * Re-link monster drop data with item data
  5341. * Fixes the need of a @reloadmobdb after a @reloaditemdb
  5342. * @author Epoque
  5343. */
  5344. void mob_reload_itemmob_data(void) {
  5345. for( auto const &pair : mob_db ){
  5346. int d, k;
  5347. if( mob_is_clone( pair.first ) ){
  5348. continue;
  5349. }
  5350. for(d = 0; d < MAX_MOB_DROP_TOTAL; d++) {
  5351. struct item_data *id;
  5352. if( !pair.second->dropitem[d].nameid )
  5353. continue;
  5354. id = itemdb_search(pair.second->dropitem[d].nameid);
  5355. for (k = 0; k < MAX_SEARCH; k++) {
  5356. if (id->mob[k].chance <= pair.second->dropitem[d].rate)
  5357. break;
  5358. }
  5359. if (k == MAX_SEARCH)
  5360. continue;
  5361. if (id->mob[k].id != pair.first)
  5362. memmove(&id->mob[k+1], &id->mob[k], (MAX_SEARCH-k-1)*sizeof(id->mob[0]));
  5363. id->mob[k].chance = pair.second->dropitem[d].rate;
  5364. id->mob[k].id = pair.first;
  5365. }
  5366. }
  5367. }
  5368. /**
  5369. * Apply the proper view data on monsters during mob_db reload.
  5370. * @param md: Mob to adjust
  5371. * @param args: va_list of arguments
  5372. * @return 0
  5373. */
  5374. static int mob_reload_sub( struct mob_data *md, va_list args ){
  5375. // Slaves have to be killed
  5376. if( md->master_id != 0 ){
  5377. unit_remove_map( &md->bl, CLR_OUTSIGHT );
  5378. return 0;
  5379. }
  5380. // Relink the mob to the new database entry
  5381. md->db = mob_db.find(md->mob_id);
  5382. if( md->db == nullptr ){
  5383. ShowWarning( "mob_reload_sub: Monster %s (ID: %hu) does not exist anymore.\n", md->name, md->mob_id );
  5384. if( md->bl.prev != nullptr ){
  5385. ShowDebug( "mob_reload_sub: The monster was removed from map %s (%hu/%hu).\n", map_mapid2mapname( md->bl.m ), md->bl.x, md->bl.y );
  5386. }
  5387. unit_remove_map( &md->bl, CLR_OUTSIGHT );
  5388. return 0;
  5389. }
  5390. // Recalculate the monster status based on the new data
  5391. status_calc_mob(md, SCO_NONE);
  5392. // If the view data was not overwritten manually
  5393. if( !md->vd_changed ){
  5394. // Get the new view data from the mob database
  5395. md->vd = mob_get_viewdata(md->mob_id);
  5396. // If they are spawned right now
  5397. if( md->bl.prev != nullptr ){
  5398. // Respawn all mobs on client side so that they are displayed correctly(if their view id changed)
  5399. clif_clearunit_area(&md->bl, CLR_OUTSIGHT);
  5400. clif_spawn(&md->bl);
  5401. }
  5402. }
  5403. return 0;
  5404. }
  5405. /**
  5406. * Apply the proper view data on NPCs during mob_db reload.
  5407. * @param md: NPC to adjust
  5408. * @param args: va_list of arguments
  5409. * @return 0
  5410. */
  5411. static int mob_reload_sub_npc( struct npc_data *nd, va_list args ){
  5412. // If the view data points to a mob
  5413. if( mobdb_checkid(nd->class_) ){
  5414. struct view_data *vd = mob_get_viewdata(nd->class_);
  5415. if (vd) // Get the new view data from the mob database
  5416. memcpy(&nd->vd, vd, sizeof(struct view_data));
  5417. if (nd->bl.prev) // If they are spawned right now
  5418. unit_refresh(&nd->bl); // Respawn all NPCs on client side so that they are displayed correctly(if their view id changed)
  5419. }
  5420. return 0;
  5421. }
  5422. /**
  5423. * Reload monster data
  5424. */
  5425. void mob_reload(void) {
  5426. do_final_mob(true);
  5427. mob_db_load(true);
  5428. map_foreachmob(mob_reload_sub);
  5429. map_foreachnpc(mob_reload_sub_npc);
  5430. }
  5431. /**
  5432. * Clear spawn data for all monsters
  5433. */
  5434. void mob_clear_spawninfo()
  5435. { //Clears spawn related information for a script reload.
  5436. mob_spawn_data.clear();
  5437. }
  5438. /*==========================================
  5439. * Circumference initialization of mob
  5440. *------------------------------------------*/
  5441. void do_init_mob(void){
  5442. mob_db_load(false);
  5443. add_timer_func_list(mob_delayspawn,"mob_delayspawn");
  5444. add_timer_func_list(mob_delay_item_drop,"mob_delay_item_drop");
  5445. add_timer_func_list(mob_ai_hard,"mob_ai_hard");
  5446. add_timer_func_list(mob_ai_lazy,"mob_ai_lazy");
  5447. add_timer_func_list(mob_timer_delete,"mob_timer_delete");
  5448. add_timer_func_list(mob_spawn_guardian_sub,"mob_spawn_guardian_sub");
  5449. add_timer_func_list(mob_respawn,"mob_respawn");
  5450. add_timer_func_list(mvptomb_delayspawn,"mvptomb_delayspawn");
  5451. add_timer_interval(gettick()+MIN_MOBTHINKTIME,mob_ai_hard,0,0,MIN_MOBTHINKTIME);
  5452. add_timer_interval(gettick()+MIN_MOBTHINKTIME*10,mob_ai_lazy,0,0,MIN_MOBTHINKTIME*10);
  5453. }
  5454. /*==========================================
  5455. * Clean memory usage.
  5456. *------------------------------------------*/
  5457. void do_final_mob(bool is_reload){
  5458. mob_db.clear();
  5459. mob_chat_db.clear();
  5460. mob_skill_db.clear();
  5461. mob_item_drop_ratio->destroy(mob_item_drop_ratio,mob_item_drop_ratio_free);
  5462. mob_summon_db->destroy(mob_summon_db, mob_summon_db_free);
  5463. if( !is_reload ) {
  5464. ers_destroy(item_drop_ers);
  5465. ers_destroy(item_drop_list_ers);
  5466. }
  5467. }