mob.cpp 214 KB

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