mob.cpp 194 KB

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