npc.cpp 149 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923
  1. // Copyright (c) rAthena Dev Teams - Licensed under GNU GPL
  2. // For more information, see LICENCE in the main folder
  3. #include "npc.hpp"
  4. #include <errno.h>
  5. #include <map>
  6. #include <stdlib.h>
  7. #include <vector>
  8. #include "../common/cbasetypes.hpp"
  9. #include "../common/db.hpp"
  10. #include "../common/ers.hpp"
  11. #include "../common/malloc.hpp"
  12. #include "../common/nullpo.hpp"
  13. #include "../common/showmsg.hpp"
  14. #include "../common/strlib.hpp"
  15. #include "../common/timer.hpp"
  16. #include "../common/utils.hpp"
  17. #include "battle.hpp"
  18. #include "chat.hpp"
  19. #include "clif.hpp"
  20. #include "date.hpp" // days of week enum
  21. #include "guild.hpp"
  22. #include "instance.hpp"
  23. #include "intif.hpp"
  24. #include "log.hpp"
  25. #include "log.hpp"
  26. #include "map.hpp"
  27. #include "mob.hpp"
  28. #include "pc.hpp"
  29. #include "pet.hpp"
  30. #include "script.hpp" // script_config
  31. struct npc_data* fake_nd;
  32. // linked list of npc source files
  33. struct npc_src_list {
  34. struct npc_src_list* next;
  35. char name[4]; // dynamic array, the structure is allocated with extra bytes (string length)
  36. };
  37. static struct npc_src_list* npc_src_files = NULL;
  38. static int npc_id=START_NPC_NUM;
  39. static int npc_warp=0;
  40. static int npc_shop=0;
  41. static int npc_script=0;
  42. static int npc_mob=0;
  43. static int npc_delay_mob=0;
  44. static int npc_cache_mob=0;
  45. struct eri *npc_sc_display_ers;
  46. // Market Shop
  47. #if PACKETVER >= 20131223
  48. struct s_npc_market {
  49. struct npc_item_list *list;
  50. char exname[NPC_NAME_LENGTH+1];
  51. uint16 count;
  52. };
  53. static DBMap *NPCMarketDB; /// Stock persistency! Temporary market stocks from `market` table. struct s_npc_market, key: NPC exname
  54. static void npc_market_checkall(void);
  55. static void npc_market_fromsql(void);
  56. #define npc_market_delfromsql(exname,nameid) (npc_market_delfromsql_((exname), (nameid), false))
  57. #define npc_market_clearfromsql(exname) (npc_market_delfromsql_((exname), 0, true))
  58. #endif
  59. /// Returns a new npc id that isn't being used in id_db.
  60. /// Fatal error if nothing is available.
  61. int npc_get_new_npc_id(void) {
  62. if( npc_id >= START_NPC_NUM && !map_blid_exists(npc_id) )
  63. return npc_id++;// available
  64. else {// find next id
  65. int base_id = npc_id;
  66. while( base_id != ++npc_id ) {
  67. if( npc_id < START_NPC_NUM )
  68. npc_id = START_NPC_NUM;
  69. if( !map_blid_exists(npc_id) )
  70. return npc_id++;// available
  71. }
  72. // full loop, nothing available
  73. ShowFatalError("npc_get_new_npc_id: All ids are taken. Exiting...");
  74. exit(1);
  75. }
  76. }
  77. static DBMap* ev_db; // const char* event_name -> struct event_data*
  78. static DBMap* npcname_db; // const char* npc_name -> struct npc_data*
  79. struct event_data {
  80. struct npc_data *nd;
  81. int pos;
  82. };
  83. static struct eri *timer_event_ers; //For the npc timer data. [Skotlex]
  84. /* hello */
  85. static char *npc_last_path;
  86. static char *npc_last_ref;
  87. struct npc_path_data {
  88. char* path;
  89. unsigned short references;
  90. };
  91. struct npc_path_data *npc_last_npd;
  92. static DBMap *npc_path_db;
  93. //For holding the view data of npc classes. [Skotlex]
  94. static struct view_data npc_viewdb[MAX_NPC_CLASS];
  95. static struct view_data npc_viewdb2[MAX_NPC_CLASS2_END-MAX_NPC_CLASS2_START];
  96. struct script_event_s{
  97. struct event_data *event;
  98. const char *event_name;
  99. };
  100. // Holds pointers to the commonly executed scripts for speedup. [Skotlex]
  101. std::map<enum npce_event, std::vector<struct script_event_s>> script_event;
  102. /**
  103. * Returns the viewdata for normal NPC classes.
  104. * @param class_: NPC class ID
  105. * @return viewdata or nullptr if the ID is invalid
  106. */
  107. struct view_data* npc_get_viewdata(int class_) {
  108. if( class_ == JT_INVISIBLE )
  109. return &npc_viewdb[0];
  110. if (npcdb_checkid(class_)){
  111. if( class_ > MAX_NPC_CLASS2_START ){
  112. return &npc_viewdb2[class_-MAX_NPC_CLASS2_START];
  113. }else{
  114. return &npc_viewdb[class_];
  115. }
  116. }
  117. return nullptr;
  118. }
  119. int npc_isnear_sub(struct block_list* bl, va_list args) {
  120. struct npc_data *nd = (struct npc_data*)bl;
  121. if (nd->sc.option & (OPTION_HIDE|OPTION_INVISIBLE))
  122. return 0;
  123. int skill_id = va_arg(args, int);
  124. if (skill_id > 0) { //If skill_id > 0 that means is used for INF2_DISABLENEARNPC [Cydh]
  125. std::shared_ptr<s_skill_db> skill = skill_db.find(skill_id);
  126. if (skill && skill->unit_nonearnpc_type) {
  127. if (skill->unit_nonearnpc_type&SKILL_NONEAR_WARPPORTAL && nd->subtype == NPCTYPE_WARP)
  128. return 1;
  129. if (skill->unit_nonearnpc_type&SKILL_NONEAR_SHOP && nd->subtype == NPCTYPE_SHOP)
  130. return 1;
  131. if (skill->unit_nonearnpc_type&SKILL_NONEAR_NPC && nd->subtype == NPCTYPE_SCRIPT)
  132. return 1;
  133. if (skill->unit_nonearnpc_type&SKILL_NONEAR_TOMB && nd->subtype == NPCTYPE_TOMB)
  134. return 1;
  135. }
  136. }
  137. return 0;
  138. }
  139. bool npc_isnear(struct block_list * bl) {
  140. if( battle_config.min_npc_vendchat_distance > 0 &&
  141. map_foreachinallrange(npc_isnear_sub,bl, battle_config.min_npc_vendchat_distance, BL_NPC, 0) )
  142. return true;
  143. return false;
  144. }
  145. int npc_ontouch_event(struct map_session_data *sd, struct npc_data *nd)
  146. {
  147. char name[EVENT_NAME_LENGTH];
  148. if (pc_isdead(sd)) // Dead player don't trigger 'OnTouch_'
  149. return 0;
  150. if( nd->touching_id )
  151. return 0; // Attached a player already. Can't trigger on anyone else.
  152. // pc_ishiding moved in npc_event for now.
  153. // If OnTouch_ event exists hiding player doesn't click the npc.
  154. // if( pc_ishiding(sd) )
  155. // return 1; // Can't trigger 'OnTouch_'.
  156. auto it = std::find(sd->npc_ontouch_.begin(), sd->npc_ontouch_.end(), nd->bl.id);
  157. if (it != sd->npc_ontouch_.end())
  158. return 0;
  159. safesnprintf(name, ARRAYLENGTH(name), "%s::%s", nd->exname, script_config.ontouch_event_name);
  160. return npc_event(sd,name,1);
  161. }
  162. int npc_ontouch2_event(struct map_session_data *sd, struct npc_data *nd)
  163. {
  164. char name[EVENT_NAME_LENGTH];
  165. auto it = std::find(sd->areanpc.begin(), sd->areanpc.end(), nd->bl.id);
  166. if (it != sd->areanpc.end())
  167. return 0;
  168. safesnprintf(name, ARRAYLENGTH(name), "%s::%s", nd->exname, script_config.ontouch2_event_name);
  169. return npc_event(sd,name,2);
  170. }
  171. /*==========================================
  172. * Sub-function of npc_enable, runs OnTouch event when enabled
  173. *------------------------------------------*/
  174. int npc_enable_sub(struct block_list *bl, va_list ap)
  175. {
  176. struct npc_data *nd;
  177. nullpo_ret(bl);
  178. nullpo_ret(nd=va_arg(ap,struct npc_data *));
  179. if(bl->type == BL_PC)
  180. {
  181. TBL_PC *sd = (TBL_PC*)bl;
  182. if (nd->sc.option&(OPTION_INVISIBLE|OPTION_CLOAK))
  183. return 1;
  184. switch (nd->subtype) {
  185. case NPCTYPE_WARP:
  186. if ((!nd->trigger_on_hidden && (pc_ishiding(sd) || (sd->sc.count && sd->sc.data[SC_CAMOUFLAGE]))) || pc_isdead(sd))
  187. return 1;
  188. if (!pc_job_can_entermap((enum e_job)sd->status.class_, map_mapindex2mapid(nd->u.warp.mapindex), sd->group_level))
  189. return 1;
  190. if (sd->count_rewarp > 10) {
  191. ShowWarning("Prevented infinite warp loop for player (%d:%d). Please fix NPC: '%s', path: '%s'\n", sd->status.account_id, sd->status.char_id, nd->exname, nd->path);
  192. sd->count_rewarp = 0;
  193. return 1;
  194. }
  195. pc_setpos(sd, nd->u.warp.mapindex, nd->u.warp.x, nd->u.warp.y, CLR_OUTSIGHT);
  196. break;
  197. default:
  198. // note : disablenpc doesn't reset the previous trigger status on official
  199. if( npc_ontouch_event(sd,nd) > 0 && npc_ontouch2_event(sd,nd) > 0 )
  200. { // failed to run OnTouch event, so just click the npc
  201. if (sd->npc_id != 0)
  202. return 0;
  203. pc_stop_walking(sd,1);
  204. npc_click(sd,nd);
  205. }
  206. break;
  207. }
  208. }
  209. return 0;
  210. }
  211. bool npc_is_cloaked(struct npc_data* nd, struct map_session_data* sd) {
  212. bool npc_cloaked = (nd->sc.option & OPTION_CLOAK) ? true : false;
  213. if (std::find(sd->cloaked_npc.begin(), sd->cloaked_npc.end(), nd->bl.id) != sd->cloaked_npc.end())
  214. return (!npc_cloaked);
  215. return npc_cloaked;
  216. }
  217. static int npc_cloaked_sub(struct block_list *bl, va_list ap)
  218. {
  219. struct map_session_data* sd;
  220. nullpo_ret(bl);
  221. nullpo_ret(sd = (struct map_session_data *)bl);
  222. int id = va_arg(ap, int);
  223. auto it = std::find(sd->cloaked_npc.begin(), sd->cloaked_npc.end(), id);
  224. if (it != sd->cloaked_npc.end())
  225. sd->cloaked_npc.erase(it);
  226. return 1;
  227. }
  228. /*==========================================
  229. * Disable / Enable NPC
  230. *------------------------------------------*/
  231. bool npc_enable_target(const char* name, uint32 char_id, int flag)
  232. {
  233. struct npc_data* nd = npc_name2id(name);
  234. if (!nd) {
  235. ShowError("npc_enable: Attempted to %s a non-existing NPC '%s' (flag=%d).\n", (flag&11) ? "show" : "hide", name, flag);
  236. return false;
  237. }
  238. if (char_id > 0 && (flag & 24)) {
  239. map_session_data *sd = map_charid2sd(char_id);
  240. if (!sd) {
  241. ShowError("npc_enable: Attempted to %s a NPC '%s' on an invalid target %d.\n", (flag & 8) ? "show" : "hide", name, char_id);
  242. return false;
  243. }
  244. unsigned int option = nd->sc.option;
  245. if (flag&8)
  246. nd->sc.option &= ~OPTION_CLOAK;
  247. else
  248. nd->sc.option |= OPTION_CLOAK;
  249. auto it = std::find(sd->cloaked_npc.begin(), sd->cloaked_npc.end(), nd->bl.id);
  250. if (it == sd->cloaked_npc.end() && option != nd->sc.option)
  251. sd->cloaked_npc.push_back(nd->bl.id);
  252. else if (it != sd->cloaked_npc.end() && option == nd->sc.option)
  253. sd->cloaked_npc.erase(it);
  254. if (nd->class_ != JT_WARPNPC && nd->class_ != JT_GUILD_FLAG)
  255. clif_changeoption_target(&nd->bl, &sd->bl);
  256. else {
  257. if (nd->sc.option&(OPTION_HIDE|OPTION_INVISIBLE|OPTION_CLOAK))
  258. clif_clearunit_single(nd->bl.id, CLR_OUTSIGHT, sd->fd);
  259. else
  260. clif_spawn(&nd->bl);
  261. }
  262. nd->sc.option = option;
  263. }
  264. else {
  265. if (flag&1) {
  266. nd->sc.option &= ~OPTION_INVISIBLE;
  267. clif_spawn(&nd->bl);
  268. }
  269. else if (flag&2)
  270. nd->sc.option &= ~OPTION_HIDE;
  271. else if (flag&4)
  272. nd->sc.option |= OPTION_HIDE;
  273. else if (flag&8)
  274. nd->sc.option &= ~OPTION_CLOAK;
  275. else if (flag&16)
  276. nd->sc.option |= OPTION_CLOAK;
  277. else { //Can't change the view_data to invisible class because the view_data for all npcs is shared! [Skotlex]
  278. nd->sc.option |= OPTION_INVISIBLE;
  279. clif_clearunit_area(&nd->bl,CLR_OUTSIGHT); // Hack to trick maya purple card [Xazax]
  280. }
  281. if (nd->class_ != JT_WARPNPC && nd->class_ != JT_GUILD_FLAG) //Client won't display option changes for these classes [Toms]
  282. clif_changeoption(&nd->bl);
  283. else {
  284. if (nd->sc.option&(OPTION_HIDE|OPTION_INVISIBLE|OPTION_CLOAK))
  285. clif_clearunit_area(&nd->bl,CLR_OUTSIGHT);
  286. else
  287. clif_spawn(&nd->bl);
  288. }
  289. map_foreachinmap(npc_cloaked_sub, nd->bl.m, BL_PC, nd->bl.id); // Because npc option has been updated we remove the npc id from sd->cloaked_npc
  290. }
  291. if (flag&11) { // check if player standing on a OnTouchArea
  292. int xs = -1, ys = -1;
  293. switch (nd->subtype) {
  294. case NPCTYPE_SCRIPT:
  295. xs = nd->u.scr.xs;
  296. ys = nd->u.scr.ys;
  297. break;
  298. case NPCTYPE_WARP:
  299. xs = nd->u.warp.xs;
  300. ys = nd->u.warp.ys;
  301. break;
  302. }
  303. if (xs >= 0 || ys >= 0)
  304. map_foreachinallarea( npc_enable_sub, nd->bl.m, nd->bl.x-xs, nd->bl.y-ys, nd->bl.x+xs, nd->bl.y+ys, BL_PC, nd );
  305. }
  306. return true;
  307. }
  308. /*==========================================
  309. * NPC lookup (get npc_data through npcname)
  310. *------------------------------------------*/
  311. struct npc_data* npc_name2id(const char* name)
  312. {
  313. return (struct npc_data *) strdb_get(npcname_db, name);
  314. }
  315. /**
  316. * For the Secure NPC Timeout option (check src/config/secure.hpp)
  317. * @author RR
  318. **/
  319. #ifdef SECURE_NPCTIMEOUT
  320. /**
  321. * Timer to check for idle time and timeout the dialog if necessary
  322. **/
  323. TIMER_FUNC(npc_secure_timeout_timer){
  324. struct map_session_data* sd = NULL;
  325. unsigned int timeout = NPC_SECURE_TIMEOUT_NEXT;
  326. t_tick cur_tick = gettick(); //ensure we are on last tick
  327. if ((sd = map_id2sd(id)) == NULL || !sd->npc_id || sd->state.ignoretimeout) {
  328. if (sd)
  329. sd->npc_idle_timer = INVALID_TIMER;
  330. return 0; // Not logged in anymore OR no longer attached to a NPC OR using 'ignoretimeout' script command
  331. }
  332. switch( sd->npc_idle_type ) {
  333. case NPCT_INPUT:
  334. timeout = NPC_SECURE_TIMEOUT_INPUT;
  335. break;
  336. case NPCT_MENU:
  337. timeout = NPC_SECURE_TIMEOUT_MENU;
  338. break;
  339. //case NPCT_WAIT: var starts with this value
  340. }
  341. if( DIFF_TICK(cur_tick,sd->npc_idle_tick) > (timeout*1000) ) {
  342. pc_close_npc(sd,1);
  343. } else if(sd->st && (sd->st->state == END || sd->st->state == CLOSE)){
  344. sd->npc_idle_timer = INVALID_TIMER; //stop timer the script is already ending
  345. } else { //Create a new instance of ourselves to continue
  346. sd->npc_idle_timer = add_timer(cur_tick + (SECURE_NPCTIMEOUT_INTERVAL*1000),npc_secure_timeout_timer,sd->bl.id,0);
  347. }
  348. return 0;
  349. }
  350. #endif
  351. /*==========================================
  352. * Dequeue event and add timer for execution (100ms)
  353. *------------------------------------------*/
  354. int npc_event_dequeue(struct map_session_data* sd,bool free_script_stack)
  355. {
  356. nullpo_ret(sd);
  357. if(sd->npc_id)
  358. { //Current script is aborted.
  359. if(sd->state.using_fake_npc){
  360. clif_clearunit_single(sd->npc_id, CLR_OUTSIGHT, sd->fd);
  361. sd->state.using_fake_npc = 0;
  362. }
  363. if (free_script_stack&&sd->st) {
  364. script_free_state(sd->st);
  365. sd->st = NULL;
  366. }
  367. sd->npc_id = 0;
  368. }
  369. if (!sd->eventqueue[0][0])
  370. return 0; //Nothing to dequeue
  371. if (!pc_addeventtimer(sd,100,sd->eventqueue[0]))
  372. { //Failed to dequeue, couldn't set a timer.
  373. ShowWarning("npc_event_dequeue: event timer is full !\n");
  374. return 0;
  375. }
  376. //Event dequeued successfully, shift other elements.
  377. memmove(sd->eventqueue[0], sd->eventqueue[1], (MAX_EVENTQUEUE-1)*sizeof(sd->eventqueue[0]));
  378. sd->eventqueue[MAX_EVENTQUEUE-1][0]=0;
  379. return 1;
  380. }
  381. /*==========================================
  382. * exports a npc event label
  383. * called from npc_parse_script
  384. *------------------------------------------*/
  385. static int npc_event_export(struct npc_data *nd, int i)
  386. {
  387. char* lname = nd->u.scr.label_list[i].name;
  388. int pos = nd->u.scr.label_list[i].pos;
  389. if ((lname[0] == 'O' || lname[0] == 'o') && (lname[1] == 'N' || lname[1] == 'n')) {
  390. struct event_data *ev;
  391. char buf[EVENT_NAME_LENGTH];
  392. if (nd->bl.m > -1 && map_getmapdata(nd->bl.m)->instance_id > 0) { // Block script events in instances
  393. int j;
  394. for (j = 0; j < NPCE_MAX; j++) {
  395. if (strcmpi(npc_get_script_event_name(j), lname) == 0) {
  396. ShowWarning("npc_event_export: attempting to duplicate a script event in an instance (%s::%s), ignoring\n", nd->name, lname);
  397. return 0;
  398. }
  399. }
  400. }
  401. // NPC:<name> the prefix uses 4 characters
  402. if( !strncasecmp( lname, script_config.onwhisper_event_name, NAME_LENGTH ) && strlen(nd->exname) > ( NAME_LENGTH - 4 ) ){
  403. // The client only allows that many character so that NPC could not be whispered by unmodified clients
  404. ShowWarning( "Whisper event in npc '" CL_WHITE "%s" CL_RESET "' was ignored, because it's name is too long.\n", nd->exname );
  405. return 0;
  406. }
  407. snprintf(buf, ARRAYLENGTH(buf), "%s::%s", nd->exname, lname);
  408. // generate the data and insert it
  409. CREATE(ev, struct event_data, 1);
  410. ev->nd = nd;
  411. ev->pos = pos;
  412. if (strdb_put(ev_db, buf, ev)) // There was already another event of the same name?
  413. return 1;
  414. }
  415. return 0;
  416. }
  417. int npc_event_sub(struct map_session_data* sd, struct event_data* ev, const char* eventname); //[Lance]
  418. /**
  419. * Exec name (NPC events) on player or global
  420. * Do on all NPC when called with foreach
  421. * @see DBApply
  422. */
  423. int npc_event_doall_sub(DBKey key, DBData *data, va_list ap)
  424. {
  425. const char* p = key.str;
  426. struct event_data* ev;
  427. int* c;
  428. const char* name;
  429. int rid;
  430. nullpo_ret(ev = (struct event_data*)db_data2ptr(data));
  431. nullpo_ret(c = va_arg(ap, int *));
  432. nullpo_ret(name = va_arg(ap, const char *));
  433. rid = va_arg(ap, int);
  434. p = strchr(p, ':'); // match only the event name
  435. if( p && strcmpi(name, p) == 0 /* && !ev->nd->src_id */ ) // Do not run on duplicates. [Paradox924X]
  436. {
  437. if(rid) // a player may only have 1 script running at the same time
  438. npc_event_sub(map_id2sd(rid),ev,key.str);
  439. else
  440. run_script(ev->nd->u.scr.script,ev->pos,rid,ev->nd->bl.id);
  441. (*c)++;
  442. }
  443. return 0;
  444. }
  445. /**
  446. * @see DBApply
  447. */
  448. static int npc_event_do_sub(DBKey key, DBData *data, va_list ap)
  449. {
  450. const char* p = key.str;
  451. struct event_data* ev;
  452. int* c, rid;
  453. const char* name;
  454. nullpo_ret(ev = (struct event_data*)db_data2ptr(data));
  455. nullpo_ret(c = va_arg(ap, int *));
  456. nullpo_ret(name = va_arg(ap, const char *));
  457. rid = va_arg(ap, int);
  458. if( p && strcmpi(name, p) == 0 )
  459. {
  460. run_script(ev->nd->u.scr.script,ev->pos,rid,ev->nd->bl.id);
  461. (*c)++;
  462. }
  463. return 0;
  464. }
  465. int npc_event_do_id(const char* name, int rid) {
  466. int c = 0;
  467. if( name[0] == ':' && name[1] == ':' )
  468. ev_db->foreach(ev_db,npc_event_doall_sub,&c,name,0,rid);
  469. else
  470. ev_db->foreach(ev_db,npc_event_do_sub,&c,name,rid);
  471. return c;
  472. }
  473. // runs the specified event (supports both single-npc and global events)
  474. int npc_event_do(const char* name) {
  475. return npc_event_do_id(name, 0);
  476. }
  477. // runs the specified event (global only)
  478. int npc_event_doall(const char* name)
  479. {
  480. return npc_event_doall_id(name, 0);
  481. }
  482. // runs the specified event(global only) and reports call count
  483. void npc_event_runall( const char* eventname ){
  484. ShowStatus( "Event '" CL_WHITE "%s" CL_RESET "' executed with '" CL_WHITE "%d" CL_RESET "' NPCs.\n", eventname, npc_event_doall( eventname ) );
  485. }
  486. // runs the specified event, with a RID attached (global only)
  487. int npc_event_doall_id(const char* name, int rid)
  488. {
  489. int c = 0;
  490. char buf[EVENT_NAME_LENGTH];
  491. safesnprintf(buf, sizeof(buf), "::%s", name);
  492. ev_db->foreach(ev_db,npc_event_doall_sub,&c,buf,rid);
  493. return c;
  494. }
  495. /*==========================================
  496. * Clock event execution
  497. * OnMinute/OnClock/OnHour/OnDay/OnDDHHMM
  498. *------------------------------------------*/
  499. TIMER_FUNC(npc_event_do_clock){
  500. static struct tm ev_tm_b; // tracks previous execution time
  501. time_t timer;
  502. struct tm* t;
  503. char buf[EVENT_NAME_LENGTH];
  504. int c = 0;
  505. timer = time(NULL);
  506. t = localtime(&timer);
  507. if (t->tm_min != ev_tm_b.tm_min ) {
  508. const char* day = NULL;
  509. safesnprintf(buf,EVENT_NAME_LENGTH,"%s%02d",script_config.timer_minute_event_name,t->tm_min);
  510. c += npc_event_doall(buf);
  511. safesnprintf(buf,EVENT_NAME_LENGTH,"%s%02d%02d",script_config.timer_clock_event_name,t->tm_hour,t->tm_min);
  512. c += npc_event_doall(buf);
  513. switch (t->tm_wday) {
  514. case SUNDAY: day = script_config.timer_sunday_event_name; break;
  515. case MONDAY: day = script_config.timer_monday_event_name; break;
  516. case TUESDAY: day = script_config.timer_tuesday_event_name; break;
  517. case WEDNESDAY: day = script_config.timer_wednesday_event_name; break;
  518. case THURSDAY: day = script_config.timer_thursday_event_name; break;
  519. case FRIDAY: day = script_config.timer_friday_event_name; break;
  520. case SATURDAY: day = script_config.timer_saturday_event_name; break;
  521. }
  522. if( day != NULL ){
  523. safesnprintf(buf,EVENT_NAME_LENGTH,"%s%02d%02d",day,t->tm_hour,t->tm_min);
  524. c += npc_event_doall(buf);
  525. }
  526. }
  527. if (t->tm_hour != ev_tm_b.tm_hour) {
  528. safesnprintf(buf,EVENT_NAME_LENGTH,"%s%02d",script_config.timer_hour_event_name,t->tm_hour);
  529. c += npc_event_doall(buf);
  530. }
  531. if (t->tm_mday != ev_tm_b.tm_mday) {
  532. safesnprintf(buf,EVENT_NAME_LENGTH,"%s%02d%02d",script_config.timer_day_event_name,t->tm_mon+1,t->tm_mday);
  533. c += npc_event_doall(buf);
  534. }
  535. memcpy(&ev_tm_b,t,sizeof(ev_tm_b));
  536. return c;
  537. }
  538. /*==========================================
  539. * OnInit Event execution (the start of the event and watch)
  540. *------------------------------------------*/
  541. void npc_event_do_oninit(void)
  542. {
  543. npc_event_runall(script_config.init_event_name);
  544. add_timer_interval(gettick()+100,npc_event_do_clock,0,0,1000);
  545. }
  546. /*==========================================
  547. * Incorporation of the label for the timer event
  548. * called from npc_parse_script
  549. *------------------------------------------*/
  550. int npc_timerevent_export(struct npc_data *nd, int i)
  551. {
  552. int t = 0, k = 0;
  553. char *lname = nd->u.scr.label_list[i].name;
  554. int pos = nd->u.scr.label_list[i].pos;
  555. size_t len = strlen(script_config.timer_event_name);
  556. // Check if the label name starts with OnTimer(default) and then parse the seconds right after it
  557. if ( !strncmp(lname,script_config.timer_event_name,len) && sscanf( (lname += len), "%11d%n", &t, &k) == 1 && lname[k] == '\0') {
  558. // Timer event
  559. struct npc_timerevent_list *te = nd->u.scr.timer_event;
  560. int j, k2 = nd->u.scr.timeramount;
  561. if (te == NULL)
  562. te = (struct npc_timerevent_list *)aMalloc(sizeof(struct npc_timerevent_list));
  563. else
  564. te = (struct npc_timerevent_list *)aRealloc( te, sizeof(struct npc_timerevent_list) * (k2+1) );
  565. for (j = 0; j < k2; j++) {
  566. if (te[j].timer > t) {
  567. memmove(te+j+1, te+j, sizeof(struct npc_timerevent_list)*(k2-j));
  568. break;
  569. }
  570. }
  571. te[j].timer = t;
  572. te[j].pos = pos;
  573. nd->u.scr.timer_event = te;
  574. nd->u.scr.timeramount++;
  575. }
  576. return 0;
  577. }
  578. struct timer_event_data {
  579. int rid; //Attached player for this timer.
  580. int next; //timer index (starts with 0, then goes up to nd->u.scr.timeramount)
  581. int time; //holds total time elapsed for the script from when timer was started to when last time the event triggered.
  582. };
  583. /*==========================================
  584. * triger 'OnTimerXXXX' events
  585. *------------------------------------------*/
  586. TIMER_FUNC(npc_timerevent){
  587. int old_rid;
  588. t_tick old_timer;
  589. t_tick old_tick;
  590. struct npc_data* nd=(struct npc_data *)map_id2bl(id);
  591. struct npc_timerevent_list *te;
  592. struct timer_event_data *ted = (struct timer_event_data*)data;
  593. struct map_session_data *sd=NULL;
  594. if( nd == NULL )
  595. {
  596. ShowError("npc_timerevent: NPC not found??\n");
  597. return 0;
  598. }
  599. if( ted->rid && !(sd = map_id2sd(ted->rid)) )
  600. {
  601. ShowError("npc_timerevent: Attached player not found.\n");
  602. ers_free(timer_event_ers, ted);
  603. return 0;
  604. }
  605. // These stuffs might need to be restored.
  606. old_rid = nd->u.scr.rid;
  607. old_tick = nd->u.scr.timertick;
  608. old_timer = nd->u.scr.timer;
  609. // Set the values of the timer
  610. nd->u.scr.rid = sd?sd->bl.id:0; //attached rid
  611. nd->u.scr.timertick = tick; //current time tick
  612. nd->u.scr.timer = ted->time; //total time from beginning to now
  613. // Locate the event
  614. te = nd->u.scr.timer_event + ted->next;
  615. // Arrange for the next event
  616. ted->next++;
  617. if( nd->u.scr.timeramount > ted->next )
  618. {
  619. int next;
  620. next = nd->u.scr.timer_event[ ted->next ].timer - nd->u.scr.timer_event[ ted->next - 1 ].timer;
  621. ted->time += next;
  622. if( sd )
  623. sd->npc_timer_id = add_timer(tick+next,npc_timerevent,id,(intptr_t)ted);
  624. else
  625. nd->u.scr.timerid = add_timer(tick+next,npc_timerevent,id,(intptr_t)ted);
  626. }
  627. else
  628. {
  629. if( sd )
  630. sd->npc_timer_id = INVALID_TIMER;
  631. else
  632. nd->u.scr.timerid = INVALID_TIMER;
  633. ers_free(timer_event_ers, ted);
  634. }
  635. // Run the script
  636. run_script(nd->u.scr.script,te->pos,nd->u.scr.rid,nd->bl.id);
  637. nd->u.scr.rid = old_rid; // Attached-rid should be restored anyway.
  638. if( sd )
  639. { // Restore previous data, only if this timer is a player-attached one.
  640. nd->u.scr.timer = old_timer;
  641. nd->u.scr.timertick = old_tick;
  642. }
  643. return 0;
  644. }
  645. /*==========================================
  646. * Start/Resume NPC timer
  647. *------------------------------------------*/
  648. int npc_timerevent_start(struct npc_data* nd, int rid)
  649. {
  650. int j;
  651. t_tick tick = gettick();
  652. struct map_session_data *sd = NULL; //Player to whom script is attached.
  653. nullpo_ret(nd);
  654. // Check if there is an OnTimer Event
  655. ARR_FIND( 0, nd->u.scr.timeramount, j, nd->u.scr.timer_event[j].timer > nd->u.scr.timer );
  656. if( nd->u.scr.rid > 0 && !(sd = map_id2sd(nd->u.scr.rid)) )
  657. { // Failed to attach timer to this player.
  658. ShowError("npc_timerevent_start: Attached player not found!\n");
  659. return 1;
  660. }
  661. // Check if timer is already started.
  662. if( sd )
  663. {
  664. if( sd->npc_timer_id != INVALID_TIMER )
  665. return 0;
  666. }
  667. else if( nd->u.scr.timerid != INVALID_TIMER || nd->u.scr.timertick )
  668. return 0;
  669. if (j < nd->u.scr.timeramount)
  670. {
  671. t_tick next;
  672. struct timer_event_data *ted;
  673. // Arrange for the next event
  674. ted = ers_alloc(timer_event_ers, struct timer_event_data);
  675. ted->next = j; // Set event index
  676. ted->time = nd->u.scr.timer_event[j].timer;
  677. next = nd->u.scr.timer_event[j].timer - nd->u.scr.timer;
  678. if( sd )
  679. {
  680. ted->rid = sd->bl.id; // Attach only the player if attachplayerrid was used.
  681. sd->npc_timer_id = add_timer(tick+next,npc_timerevent,nd->bl.id,(intptr_t)ted);
  682. }
  683. else
  684. {
  685. ted->rid = 0;
  686. nd->u.scr.timertick = tick; // Set when timer is started
  687. nd->u.scr.timerid = add_timer(tick+next,npc_timerevent,nd->bl.id,(intptr_t)ted);
  688. }
  689. }
  690. else if (!sd)
  691. {
  692. nd->u.scr.timertick = tick;
  693. }
  694. return 0;
  695. }
  696. /*==========================================
  697. * Stop NPC timer
  698. *------------------------------------------*/
  699. int npc_timerevent_stop(struct npc_data* nd)
  700. {
  701. struct map_session_data *sd = NULL;
  702. int *tid;
  703. nullpo_ret(nd);
  704. if( nd->u.scr.rid && !(sd = map_id2sd(nd->u.scr.rid)) )
  705. {
  706. ShowError("npc_timerevent_stop: Attached player not found!\n");
  707. return 1;
  708. }
  709. tid = sd?&sd->npc_timer_id:&nd->u.scr.timerid;
  710. if( *tid == INVALID_TIMER && (sd || !nd->u.scr.timertick) ) // Nothing to stop
  711. return 0;
  712. // Delete timer
  713. if ( *tid != INVALID_TIMER )
  714. {
  715. const struct TimerData *td = NULL;
  716. td = get_timer(*tid);
  717. if( td && td->data )
  718. ers_free(timer_event_ers, (void*)td->data);
  719. delete_timer(*tid,npc_timerevent);
  720. *tid = INVALID_TIMER;
  721. }
  722. if( !sd && nd->u.scr.timertick )
  723. {
  724. nd->u.scr.timer += DIFF_TICK(gettick(),nd->u.scr.timertick); // Set 'timer' to the time that has passed since the beginning of the timers
  725. nd->u.scr.timertick = 0; // Set 'tick' to zero so that we know it's off.
  726. }
  727. return 0;
  728. }
  729. /*==========================================
  730. * Aborts a running NPC timer that is attached to a player.
  731. *------------------------------------------*/
  732. void npc_timerevent_quit(struct map_session_data* sd)
  733. {
  734. const struct TimerData *td;
  735. struct npc_data* nd;
  736. struct timer_event_data *ted;
  737. // Check timer existance
  738. if( sd->npc_timer_id == INVALID_TIMER )
  739. return;
  740. if( !(td = get_timer(sd->npc_timer_id)) )
  741. {
  742. sd->npc_timer_id = INVALID_TIMER;
  743. return;
  744. }
  745. // Delete timer
  746. nd = (struct npc_data *)map_id2bl(td->id);
  747. ted = (struct timer_event_data*)td->data;
  748. delete_timer(sd->npc_timer_id, npc_timerevent);
  749. sd->npc_timer_id = INVALID_TIMER;
  750. // Execute OnTimerQuit
  751. if( nd && nd->bl.type == BL_NPC )
  752. {
  753. char buf[EVENT_NAME_LENGTH];
  754. struct event_data *ev;
  755. snprintf(buf, ARRAYLENGTH(buf), "%s::%s", nd->exname, script_config.timer_quit_event_name);
  756. ev = (struct event_data*)strdb_get(ev_db, buf);
  757. if( ev && ev->nd != nd )
  758. {
  759. ShowWarning("npc_timerevent_quit: Unable to execute \"%s\", two NPCs have the same event name [%s]!\n",script_config.timer_quit_event_name,buf);
  760. ev = NULL;
  761. }
  762. if( ev )
  763. {
  764. int old_rid;
  765. t_tick old_timer;
  766. t_tick old_tick;
  767. //Set timer related info.
  768. old_rid = (nd->u.scr.rid == sd->bl.id ? 0 : nd->u.scr.rid); // Detach rid if the last attached player logged off.
  769. old_tick = nd->u.scr.timertick;
  770. old_timer = nd->u.scr.timer;
  771. nd->u.scr.rid = sd->bl.id;
  772. nd->u.scr.timertick = gettick();
  773. nd->u.scr.timer = ted->time;
  774. //Execute label
  775. run_script(nd->u.scr.script,ev->pos,sd->bl.id,nd->bl.id);
  776. //Restore previous data.
  777. nd->u.scr.rid = old_rid;
  778. nd->u.scr.timer = old_timer;
  779. nd->u.scr.timertick = old_tick;
  780. }
  781. }
  782. ers_free(timer_event_ers, ted);
  783. }
  784. /*==========================================
  785. * Get the tick value of an NPC timer
  786. * If it's stopped, return stopped time
  787. *------------------------------------------*/
  788. t_tick npc_gettimerevent_tick(struct npc_data* nd)
  789. {
  790. t_tick tick;
  791. nullpo_ret(nd);
  792. // TODO: Get player attached timer's tick. Now we can just get it by using 'getnpctimer' inside OnTimer event.
  793. tick = nd->u.scr.timer; // The last time it's active(start, stop or event trigger)
  794. if( nd->u.scr.timertick ) // It's a running timer
  795. tick += DIFF_TICK(gettick(), nd->u.scr.timertick);
  796. return tick;
  797. }
  798. /*==========================================
  799. * Set tick for running and stopped timer
  800. *------------------------------------------*/
  801. int npc_settimerevent_tick(struct npc_data* nd, int newtimer)
  802. {
  803. bool flag;
  804. int old_rid;
  805. //struct map_session_data *sd = NULL;
  806. nullpo_ret(nd);
  807. // TODO: Set player attached timer's tick.
  808. old_rid = nd->u.scr.rid;
  809. nd->u.scr.rid = 0;
  810. // Check if timer is started
  811. flag = (nd->u.scr.timerid != INVALID_TIMER || nd->u.scr.timertick);
  812. if( flag ) npc_timerevent_stop(nd);
  813. nd->u.scr.timer = newtimer;
  814. if( flag ) npc_timerevent_start(nd, -1);
  815. nd->u.scr.rid = old_rid;
  816. return 0;
  817. }
  818. int npc_event_sub(struct map_session_data* sd, struct event_data* ev, const char* eventname)
  819. {
  820. if ( sd->npc_id != 0 )
  821. {
  822. //Enqueue the event trigger.
  823. int i;
  824. ARR_FIND( 0, MAX_EVENTQUEUE, i, sd->eventqueue[i][0] == '\0' );
  825. if( i < MAX_EVENTQUEUE )
  826. {
  827. safestrncpy(sd->eventqueue[i],eventname,EVENT_NAME_LENGTH); //Event enqueued.
  828. return 0;
  829. }
  830. ShowWarning("npc_event: player's event queue is full, can't add event '%s' !\n", eventname);
  831. return 1;
  832. }
  833. if( ev->nd->sc.option&OPTION_INVISIBLE )
  834. {
  835. //Disabled npc, shouldn't trigger event.
  836. npc_event_dequeue(sd);
  837. return 2;
  838. }
  839. run_script(ev->nd->u.scr.script,ev->pos,sd->bl.id,ev->nd->bl.id);
  840. return 0;
  841. }
  842. /*==========================================
  843. * NPC processing event type
  844. *------------------------------------------*/
  845. int npc_event(struct map_session_data* sd, const char* eventname, int ontouch)
  846. {
  847. struct event_data* ev = (struct event_data*)strdb_get(ev_db, eventname);
  848. struct npc_data *nd;
  849. nullpo_ret(sd);
  850. if( ev == NULL || (nd = ev->nd) == NULL )
  851. {
  852. if( !ontouch )
  853. ShowError("npc_event: event not found [%s]\n", eventname);
  854. return ontouch;
  855. }
  856. if (ontouch == 1) { // OnTouch_
  857. if (pc_ishiding(sd))
  858. return 0;
  859. nd->touching_id = sd->bl.id;
  860. auto it = std::find(sd->npc_ontouch_.begin(), sd->npc_ontouch_.end(), nd->bl.id);
  861. if (it == sd->npc_ontouch_.end())
  862. sd->npc_ontouch_.push_back(nd->bl.id);
  863. } else if (ontouch == 2) { // OnTouch
  864. auto it = std::find(sd->areanpc.begin(), sd->areanpc.end(), nd->bl.id);
  865. if (it == sd->areanpc.end())
  866. sd->areanpc.push_back(nd->bl.id);
  867. }
  868. npc_event_sub(sd,ev,eventname); // Don't return this value so npc_enable_sub doesn't attempt to "click" the NPC if OnTouch fails.
  869. return 0;
  870. }
  871. /*==========================================
  872. * Sub chk then execute area event type
  873. *------------------------------------------*/
  874. int npc_touch_areanpc_sub(struct block_list *bl, va_list ap)
  875. {
  876. struct map_session_data *sd;
  877. int pc_id;
  878. char *name;
  879. nullpo_ret(bl);
  880. nullpo_ret((sd = map_id2sd(bl->id)));
  881. pc_id = va_arg(ap,int);
  882. name = va_arg(ap,char*);
  883. if( sd->state.warping )
  884. return 0;
  885. if( pc_ishiding(sd) )
  886. return 0;
  887. if( pc_isdead(sd) )
  888. return 0;
  889. if( pc_id == sd->bl.id )
  890. return 0;
  891. npc_event(sd,name,1);
  892. return 1;
  893. }
  894. /*==========================================
  895. * Chk if sd is still touching his assigned npc.
  896. * If not, it unsets it and searches for another player in range.
  897. *------------------------------------------*/
  898. int npc_touchnext_areanpc(struct map_session_data* sd, bool leavemap)
  899. {
  900. if (sd->npc_ontouch_.empty())
  901. return 0;
  902. bool found = false;
  903. sd->npc_ontouch_.erase(std::remove_if(sd->npc_ontouch_.begin(), sd->npc_ontouch_.end(), [&] (const int &current_npc_id) {
  904. struct npc_data *nd = map_id2nd(current_npc_id);
  905. if (!nd) {
  906. return true;
  907. } else {
  908. int16 xs = nd->u.scr.xs;
  909. int16 ys = nd->u.scr.ys;
  910. // note : hiding doesn't reset the previous trigger status
  911. // player must leave the area to reset nd->touching_id on official
  912. if (sd->bl.m != nd->bl.m || sd->bl.x < nd->bl.x - xs || sd->bl.x > nd->bl.x + xs || sd->bl.y < nd->bl.y - ys || sd->bl.y > nd->bl.y + ys || leavemap) {
  913. char name[EVENT_NAME_LENGTH];
  914. if (nd->touching_id && nd->touching_id == sd->bl.id) {// empty when reload script
  915. found = true;
  916. nd->touching_id = 0;
  917. safesnprintf(name, ARRAYLENGTH(name), "%s::%s", nd->exname, script_config.ontouch_event_name);
  918. map_forcountinarea(npc_touch_areanpc_sub,nd->bl.m,nd->bl.x - xs,nd->bl.y - ys,nd->bl.x + xs,nd->bl.y + ys,1,BL_PC,sd->bl.id,name);
  919. }
  920. return true;
  921. }
  922. }
  923. return false;
  924. }), sd->npc_ontouch_.end());
  925. return found;
  926. }
  927. /*==========================================
  928. * Exec OnTouch for player if in range of area event
  929. *------------------------------------------*/
  930. int npc_touch_areanpc(struct map_session_data* sd, int16 m, int16 x, int16 y)
  931. {
  932. int xs, ys, i, f = 1;
  933. nullpo_retr(1, sd);
  934. // Remove NPCs that are no longer within the OnTouch area
  935. for (i = 0; i < sd->areanpc.size(); i++) {
  936. struct npc_data *nd = map_id2nd(sd->areanpc[i]);
  937. if (!nd || nd->subtype != NPCTYPE_SCRIPT ||
  938. !(nd->bl.m == m && x >= nd->bl.x - nd->u.scr.xs && x <= nd->bl.x + nd->u.scr.xs && y >= nd->bl.y - nd->u.scr.ys && y <= nd->bl.y + nd->u.scr.ys))
  939. sd->areanpc.erase(sd->areanpc.begin() + i);
  940. }
  941. if (sd->state.block_action & PCBLOCK_NPCCLICK)
  942. return 0;
  943. struct map_data *mapdata = map_getmapdata(m);
  944. for (i = 0; i < mapdata->npc_num_area; i++) {
  945. if (mapdata->npc[i]->sc.option&OPTION_INVISIBLE) {
  946. f = 0; // a npc was found, but it is disabled; don't print warning
  947. continue;
  948. }
  949. switch(mapdata->npc[i]->subtype) {
  950. case NPCTYPE_WARP:
  951. xs = mapdata->npc[i]->u.warp.xs;
  952. ys = mapdata->npc[i]->u.warp.ys;
  953. break;
  954. case NPCTYPE_SCRIPT:
  955. xs = mapdata->npc[i]->u.scr.xs;
  956. ys = mapdata->npc[i]->u.scr.ys;
  957. break;
  958. default:
  959. continue;
  960. }
  961. if (x >= mapdata->npc[i]->bl.x - xs && x <= mapdata->npc[i]->bl.x + xs && y >= mapdata->npc[i]->bl.y - ys && y <= mapdata->npc[i]->bl.y + ys) {
  962. f = 0;
  963. if (npc_is_cloaked(mapdata->npc[i], sd))
  964. continue;
  965. switch (mapdata->npc[i]->subtype) {
  966. case NPCTYPE_WARP:
  967. if ((!mapdata->npc[i]->trigger_on_hidden && (pc_ishiding(sd) || (sd->sc.count && sd->sc.data[SC_CAMOUFLAGE]))) || pc_isdead(sd))
  968. break; // hidden or dead chars cannot use warps
  969. if (!pc_job_can_entermap((enum e_job)sd->status.class_, map_mapindex2mapid(mapdata->npc[i]->u.warp.mapindex), sd->group_level))
  970. break;
  971. if (sd->count_rewarp > 10) {
  972. ShowWarning("Prevented infinite warp loop for player (%d:%d). Please fix NPC: '%s', path: '%s'\n", sd->status.account_id, sd->status.char_id, mapdata->npc[i]->exname, mapdata->npc[i]->path);
  973. sd->count_rewarp = 0;
  974. break;
  975. }
  976. pc_setpos(sd, mapdata->npc[i]->u.warp.mapindex, mapdata->npc[i]->u.warp.x, mapdata->npc[i]->u.warp.y, CLR_OUTSIGHT);
  977. return 0;
  978. case NPCTYPE_SCRIPT:
  979. // warp type sorted first, no need to check if they override any other OnTouch areas.
  980. if (npc_ontouch_event(sd, mapdata->npc[i]) > 0 && npc_ontouch2_event(sd, mapdata->npc[i]) > 0) { // failed to run OnTouch event, so just click the npc
  981. auto it = std::find(sd->areanpc.begin(), sd->areanpc.end(), mapdata->npc[i]->bl.id);
  982. if (it == sd->areanpc.end())
  983. sd->areanpc.push_back(mapdata->npc[i]->bl.id);
  984. npc_click(sd, mapdata->npc[i]);
  985. }
  986. break;
  987. }
  988. }
  989. }
  990. if (f == 1) {
  991. ShowError("npc_touch_areanpc : stray NPC cell/NPC not found in the block on coordinates '%s',%d,%d\n", mapdata->name, x, y);
  992. return 1;
  993. }
  994. return 0;
  995. }
  996. // OnTouch NPC or Warp for Mobs
  997. // Return 1 if Warped
  998. int npc_touch_areanpc2(struct mob_data *md)
  999. {
  1000. int i, x = md->bl.x, y = md->bl.y, id;
  1001. char eventname[EVENT_NAME_LENGTH];
  1002. struct event_data* ev;
  1003. int xs, ys;
  1004. struct map_data *mapdata = map_getmapdata(md->bl.m);
  1005. for( i = 0; i < mapdata->npc_num_area; i++ )
  1006. {
  1007. if( mapdata->npc[i]->sc.option&(OPTION_INVISIBLE|OPTION_CLOAK) )
  1008. continue;
  1009. switch( mapdata->npc[i]->subtype )
  1010. {
  1011. case NPCTYPE_WARP:
  1012. if( !( battle_config.mob_warp&1 ) )
  1013. continue;
  1014. xs = mapdata->npc[i]->u.warp.xs;
  1015. ys = mapdata->npc[i]->u.warp.ys;
  1016. break;
  1017. case NPCTYPE_SCRIPT:
  1018. xs = mapdata->npc[i]->u.scr.xs;
  1019. ys = mapdata->npc[i]->u.scr.ys;
  1020. break;
  1021. default:
  1022. continue; // Keep Searching
  1023. }
  1024. if( x >= mapdata->npc[i]->bl.x-xs && x <= mapdata->npc[i]->bl.x+xs && y >= mapdata->npc[i]->bl.y-ys && y <= mapdata->npc[i]->bl.y+ys )
  1025. { // In the npc touch area
  1026. switch( mapdata->npc[i]->subtype )
  1027. {
  1028. case NPCTYPE_WARP: {
  1029. int16 warp_m = map_mapindex2mapid(mapdata->npc[i]->u.warp.mapindex);
  1030. if( warp_m < 0 )
  1031. break; // Cannot Warp between map servers
  1032. if( unit_warp(&md->bl, warp_m, mapdata->npc[i]->u.warp.x, mapdata->npc[i]->u.warp.y, CLR_OUTSIGHT) == 0 )
  1033. return 1; // Warped
  1034. }
  1035. break;
  1036. case NPCTYPE_SCRIPT:
  1037. if( mapdata->npc[i]->bl.id == md->areanpc_id )
  1038. break; // Already touch this NPC
  1039. safesnprintf(eventname, ARRAYLENGTH(eventname), "%s::%s", mapdata->npc[i]->exname, script_config.ontouchnpc_event_name);
  1040. if( (ev = (struct event_data*)strdb_get(ev_db, eventname)) == NULL || ev->nd == NULL )
  1041. break; // No OnTouchNPC Event
  1042. md->areanpc_id = mapdata->npc[i]->bl.id;
  1043. id = md->bl.id; // Stores Unique ID
  1044. run_script(ev->nd->u.scr.script, ev->pos, md->bl.id, ev->nd->bl.id);
  1045. if( map_id2md(id) == NULL ) return 1; // Not Warped, but killed
  1046. break;
  1047. }
  1048. return 0;
  1049. }
  1050. }
  1051. return 0;
  1052. }
  1053. /**
  1054. * Checks if there are any NPC on-touch objects on the given range.
  1055. * @param flag : Flag determines the type of object to check for
  1056. * &1: NPC Warps
  1057. * &2: NPCs with on-touch events.
  1058. * @param m : mapindex
  1059. * @param x : x coord
  1060. * @param y : y coord
  1061. * @param range : range to check
  1062. * @return 0: no npc on target cells, x: npc_id
  1063. */
  1064. int npc_check_areanpc(int flag, int16 m, int16 x, int16 y, int16 range)
  1065. {
  1066. int i;
  1067. int x0,y0,x1,y1;
  1068. int xs,ys;
  1069. if (range < 0) return 0;
  1070. struct map_data *mapdata = map_getmapdata(m);
  1071. x0 = i16max(x-range, 0);
  1072. y0 = i16max(y-range, 0);
  1073. x1 = i16min(x+range, mapdata->xs-1);
  1074. y1 = i16min(y+range, mapdata->ys-1);
  1075. //First check for npc_cells on the range given
  1076. i = 0;
  1077. for (ys = y0; ys <= y1 && !i; ys++) {
  1078. for(xs = x0; xs <= x1 && !i; xs++){
  1079. if (map_getcell(m,xs,ys,CELL_CHKNPC))
  1080. i = 1;
  1081. }
  1082. }
  1083. if (!i) return 0; //No NPC_CELLs.
  1084. //Now check for the actual NPC on said range.
  1085. for (i = 0; i < mapdata->npc_num_area; i++)
  1086. {
  1087. if (mapdata->npc[i]->sc.option&OPTION_INVISIBLE)
  1088. continue;
  1089. switch(mapdata->npc[i]->subtype)
  1090. {
  1091. case NPCTYPE_WARP:
  1092. if (!(flag&1))
  1093. continue;
  1094. xs=mapdata->npc[i]->u.warp.xs;
  1095. ys=mapdata->npc[i]->u.warp.ys;
  1096. break;
  1097. case NPCTYPE_SCRIPT:
  1098. if (!(flag&2))
  1099. continue;
  1100. xs=mapdata->npc[i]->u.scr.xs;
  1101. ys=mapdata->npc[i]->u.scr.ys;
  1102. break;
  1103. default:
  1104. continue;
  1105. }
  1106. if( x1 >= mapdata->npc[i]->bl.x-xs && x0 <= mapdata->npc[i]->bl.x+xs
  1107. && y1 >= mapdata->npc[i]->bl.y-ys && y0 <= mapdata->npc[i]->bl.y+ys )
  1108. break; // found a npc
  1109. }
  1110. if (i == mapdata->npc_num_area)
  1111. return 0;
  1112. return (mapdata->npc[i]->bl.id);
  1113. }
  1114. /*==========================================
  1115. * Chk if player not too far to access the npc.
  1116. * Returns npc_data (success) or NULL (fail).
  1117. *------------------------------------------*/
  1118. struct npc_data* npc_checknear(struct map_session_data* sd, struct block_list* bl)
  1119. {
  1120. struct npc_data *nd;
  1121. nullpo_retr(NULL, sd);
  1122. if(bl == NULL) return NULL;
  1123. if(bl->type != BL_NPC) return NULL;
  1124. nd = (TBL_NPC*)bl;
  1125. if(sd->state.using_fake_npc && sd->npc_id == bl->id)
  1126. return nd;
  1127. if (nd->class_<0) //Class-less npc, enable click from anywhere.
  1128. return nd;
  1129. if (bl->m!=sd->bl.m ||
  1130. bl->x<sd->bl.x-AREA_SIZE-1 || bl->x>sd->bl.x+AREA_SIZE+1 ||
  1131. bl->y<sd->bl.y-AREA_SIZE-1 || bl->y>sd->bl.y+AREA_SIZE+1)
  1132. return NULL;
  1133. return nd;
  1134. }
  1135. /*==========================================
  1136. * Make NPC talk in global chat (like npctalk)
  1137. *------------------------------------------*/
  1138. int npc_globalmessage(const char* name, const char* mes)
  1139. {
  1140. struct npc_data* nd = npc_name2id(name);
  1141. char temp[100];
  1142. if (!nd)
  1143. return 0;
  1144. snprintf(temp, sizeof(temp), "%s", mes);
  1145. clif_GlobalMessage(&nd->bl,temp,ALL_CLIENT);
  1146. return 0;
  1147. }
  1148. // MvP tomb [GreenBox]
  1149. void run_tomb(struct map_session_data* sd, struct npc_data* nd)
  1150. {
  1151. char buffer[200];
  1152. char time[10];
  1153. strftime(time, sizeof(time), "%H:%M", localtime(&nd->u.tomb.kill_time));
  1154. // TODO: Find exact color?
  1155. snprintf(buffer, sizeof(buffer), msg_txt(sd,657), nd->u.tomb.md->db->name);
  1156. clif_scriptmes(sd, nd->bl.id, buffer);
  1157. clif_scriptmes(sd, nd->bl.id, msg_txt(sd,658));
  1158. snprintf(buffer, sizeof(buffer), msg_txt(sd,659), time);
  1159. clif_scriptmes(sd, nd->bl.id, buffer);
  1160. clif_scriptmes(sd, nd->bl.id, msg_txt(sd,660));
  1161. snprintf(buffer, sizeof(buffer), msg_txt(sd,661), nd->u.tomb.killer_name[0] ? nd->u.tomb.killer_name : "Unknown");
  1162. clif_scriptmes(sd, nd->bl.id, buffer);
  1163. clif_scriptclose(sd, nd->bl.id);
  1164. }
  1165. /*==========================================
  1166. * NPC 1st call when clicking on npc
  1167. * Do specific action for NPC type (openshop, run scripts...)
  1168. *------------------------------------------*/
  1169. int npc_click(struct map_session_data* sd, struct npc_data* nd)
  1170. {
  1171. nullpo_retr(1, sd);
  1172. if (sd->npc_id != 0) {
  1173. ShowError("npc_click: npc_id != 0\n");
  1174. return 1;
  1175. }
  1176. if(!nd) return 1;
  1177. if ((nd = npc_checknear(sd,&nd->bl)) == NULL)
  1178. return 1;
  1179. //Hidden/Disabled npc.
  1180. if (nd->class_ < 0 || nd->sc.option&(OPTION_INVISIBLE|OPTION_HIDE))
  1181. return 1;
  1182. if (sd->state.block_action & PCBLOCK_NPCCLICK) {
  1183. clif_msg(sd, WORK_IN_PROGRESS);
  1184. return 1;
  1185. }
  1186. switch(nd->subtype) {
  1187. case NPCTYPE_SHOP:
  1188. clif_npcbuysell(sd,nd->bl.id);
  1189. break;
  1190. case NPCTYPE_CASHSHOP:
  1191. case NPCTYPE_ITEMSHOP:
  1192. case NPCTYPE_POINTSHOP:
  1193. clif_cashshop_show(sd,nd);
  1194. break;
  1195. case NPCTYPE_MARKETSHOP:
  1196. #if PACKETVER >= 20131223
  1197. {
  1198. unsigned short i;
  1199. for (i = 0; i < nd->u.shop.count; i++) {
  1200. if (nd->u.shop.shop_item[i].qty)
  1201. break;
  1202. }
  1203. if (i == nd->u.shop.count) {
  1204. clif_messagecolor(&sd->bl, color_table[COLOR_RED], msg_txt(sd, 534), false, SELF);
  1205. return false;
  1206. }
  1207. sd->npc_shopid = nd->bl.id;
  1208. clif_npc_market_open(sd, nd);
  1209. }
  1210. #endif
  1211. break;
  1212. case NPCTYPE_SCRIPT:
  1213. run_script(nd->u.scr.script,0,sd->bl.id,nd->bl.id);
  1214. break;
  1215. case NPCTYPE_TOMB:
  1216. run_tomb(sd,nd);
  1217. break;
  1218. }
  1219. return 0;
  1220. }
  1221. /*==========================================
  1222. *
  1223. *------------------------------------------*/
  1224. bool npc_scriptcont(struct map_session_data* sd, int id, bool closing){
  1225. struct block_list *target = map_id2bl(id);
  1226. nullpo_retr(true, sd);
  1227. if( id != sd->npc_id ){
  1228. TBL_NPC* nd_sd = (TBL_NPC*)map_id2bl(sd->npc_id);
  1229. TBL_NPC* nd = BL_CAST(BL_NPC, target);
  1230. ShowDebug("npc_scriptcont: %s (sd->npc_id=%d) is not %s (id=%d).\n",
  1231. nd_sd?(char*)nd_sd->name:"'Unknown NPC'", (int)sd->npc_id,
  1232. nd?(char*)nd->name:"'Unknown NPC'", (int)id);
  1233. return true;
  1234. }
  1235. if(id != fake_nd->bl.id) { // Not item script
  1236. if ((npc_checknear(sd, target)) == NULL) {
  1237. ShowWarning("npc_scriptcont: failed npc_checknear test.\n");
  1238. return true;
  1239. }
  1240. }
  1241. #ifdef SECURE_NPCTIMEOUT
  1242. sd->npc_idle_tick = gettick(); //Update the last NPC iteration
  1243. #endif
  1244. /**
  1245. * WPE can get to this point with a progressbar; we deny it.
  1246. **/
  1247. if( sd->progressbar.npc_id && DIFF_TICK(sd->progressbar.timeout,gettick()) > 0 )
  1248. return true;
  1249. if( sd->st == nullptr ){
  1250. return true;
  1251. }
  1252. if( closing ){
  1253. switch( sd->st->state ){
  1254. // close
  1255. case CLOSE:
  1256. sd->st->state = END;
  1257. break;
  1258. // close2
  1259. case STOP:
  1260. sd->st->state = RUN;
  1261. break;
  1262. default:
  1263. sd->st->state = END;
  1264. ShowError( "npc_scriptcont: unexpected state '%d' for closing call. (AID: %u CID: %u)\n", sd->st->state, sd->status.account_id, sd->status.char_id );
  1265. break;
  1266. }
  1267. }else{
  1268. switch( sd->st->state ){
  1269. // next
  1270. // progressbar
  1271. case STOP:
  1272. sd->st->state = RUN;
  1273. break;
  1274. // input
  1275. // menu
  1276. // select
  1277. case RERUNLINE:
  1278. // keep state as it is
  1279. break;
  1280. default:
  1281. sd->st->state = END;
  1282. ShowError( "npc_scriptcont: unexpected state '%d' for continue call. (AID: %u CID: %u)\n", sd->st->state, sd->status.account_id, sd->status.char_id );
  1283. break;
  1284. }
  1285. }
  1286. // Call this even, if it was set to end, because it will free the script state
  1287. run_script_main(sd->st);
  1288. return false;
  1289. }
  1290. /**
  1291. * Open the shop Buy or Sell list
  1292. * @param sd: Player data
  1293. * @param id: NPC ID
  1294. * @param type: 0 - Buy, 1 - Sell
  1295. * @return 0 on success or 1 on failure
  1296. */
  1297. int npc_buysellsel(struct map_session_data* sd, int id, int type)
  1298. {
  1299. struct npc_data *nd;
  1300. nullpo_retr(1, sd);
  1301. if ((nd = npc_checknear(sd,map_id2bl(id))) == NULL)
  1302. return 1;
  1303. if (nd->subtype != NPCTYPE_SHOP) {
  1304. ShowError("no such shop npc : %d\n",id);
  1305. if (sd->npc_id == id)
  1306. sd->npc_id=0;
  1307. return 1;
  1308. }
  1309. if (nd->sc.option & OPTION_INVISIBLE) // can't buy if npc is not visible (hack?)
  1310. return 1;
  1311. sd->npc_shopid = id;
  1312. if (type == 0) {
  1313. clif_buylist(sd,nd);
  1314. } else {
  1315. clif_selllist(sd);
  1316. }
  1317. return 0;
  1318. }
  1319. /** Payment Process for NPCTYPE_CASHSHOP, NPCTYPE_ITEMSHOP, and NPCTYPE_POINTSHOP
  1320. * @param nd NPC Shop data
  1321. * @param price Price must be paid
  1322. * @param points Amount of secondary points that player requested
  1323. * @param sd Player data
  1324. * @return e_CASHSHOP_ACK
  1325. **/
  1326. static enum e_CASHSHOP_ACK npc_cashshop_process_payment(struct npc_data *nd, int price, int points, struct map_session_data *sd) {
  1327. int cost[2] = { 0, 0 };
  1328. npc_shop_currency_type(sd, nd, cost, false);
  1329. switch(nd->subtype) {
  1330. case NPCTYPE_CASHSHOP:
  1331. if (cost[1] < points || cost[0] < (price - points))
  1332. return ERROR_TYPE_MONEY;
  1333. if (pc_paycash(sd, price, points, LOG_TYPE_NPC) <= 0) {
  1334. return ERROR_TYPE_MONEY;
  1335. }
  1336. break;
  1337. case NPCTYPE_ITEMSHOP:
  1338. {
  1339. struct item_data *id = itemdb_exists(nd->u.shop.itemshop_nameid);
  1340. int delete_amount = price, i;
  1341. if (!id) { // Item Data is checked at script parsing but in case of item_db reload, check again.
  1342. ShowWarning("Failed to find sellitem %hu for itemshop NPC '%s' (%s, %d, %d)!\n", nd->u.shop.itemshop_nameid, nd->exname, map_mapid2mapname(nd->bl.m), nd->bl.x, nd->bl.y);
  1343. return ERROR_TYPE_PURCHASE_FAIL;
  1344. }
  1345. if (cost[1] < points || cost[0] < (price - points)) {
  1346. char output[CHAT_SIZE_MAX];
  1347. memset(output, '\0', sizeof(output));
  1348. sprintf(output, msg_txt(sd, 712), id->jname, id->nameid); // You do not have enough %s (%hu).
  1349. clif_messagecolor(&sd->bl, color_table[COLOR_RED], output, false, SELF);
  1350. return ERROR_TYPE_PURCHASE_FAIL;
  1351. }
  1352. for (i = 0; i < MAX_INVENTORY && delete_amount > 0; i++) {
  1353. struct item *it;
  1354. int amount = 0;
  1355. if (sd->inventory.u.items_inventory[i].nameid == 0 || sd->inventory_data[i] == NULL || !(it = &sd->inventory.u.items_inventory[i]) || it->nameid != nd->u.shop.itemshop_nameid)
  1356. continue;
  1357. if (!pc_can_sell_item(sd, it, nd->subtype))
  1358. continue;
  1359. amount = it->amount;
  1360. if (amount > delete_amount)
  1361. amount = delete_amount;
  1362. if (pc_delitem(sd, i, amount, 0, 0, LOG_TYPE_NPC)) {
  1363. ShowWarning("Failed to delete item %hu from '%s' at itemshop NPC '%s' (%s, %d, %d)!\n", nd->u.shop.itemshop_nameid, sd->status.name, nd->exname, map_mapid2mapname(nd->bl.m), nd->bl.x, nd->bl.y);
  1364. return ERROR_TYPE_PURCHASE_FAIL;
  1365. }
  1366. delete_amount -= amount;
  1367. }
  1368. if (delete_amount > 0) {
  1369. ShowError("Item %hu is not enough as payment at itemshop NPC '%s' (%s, %d, %d, AID=%d, CID=%d)!\n", nd->u.shop.itemshop_nameid, nd->exname, map_mapid2mapname(nd->bl.m), nd->bl.x, nd->bl.y, sd->status.account_id, sd->status.char_id);
  1370. return ERROR_TYPE_PURCHASE_FAIL;
  1371. }
  1372. }
  1373. break;
  1374. case NPCTYPE_POINTSHOP:
  1375. {
  1376. char output[CHAT_SIZE_MAX];
  1377. memset(output, '\0', sizeof(output));
  1378. if (cost[1] < points || cost[0] < (price - points)) {
  1379. sprintf(output, msg_txt(sd, 713), nd->u.shop.pointshop_str); // You do not have enough '%s'.
  1380. clif_messagecolor(&sd->bl, color_table[COLOR_RED], output, false, SELF);
  1381. return ERROR_TYPE_PURCHASE_FAIL;
  1382. }
  1383. pc_setreg2(sd, nd->u.shop.pointshop_str, cost[0] - (price - points));
  1384. sprintf(output, msg_txt(sd, 716), nd->u.shop.pointshop_str, cost[0] - (price - points)); // Your '%s' is now: %d
  1385. clif_messagecolor(&sd->bl, color_table[COLOR_LIGHT_GREEN], output, false, SELF);
  1386. }
  1387. break;
  1388. }
  1389. return ERROR_TYPE_NONE;
  1390. }
  1391. /**
  1392. * Cash Shop Buy List for clients 2010-11-16 and newer
  1393. * @param sd: Player data
  1394. * @param points: Secondary point
  1395. * @param count: Amount of items to purchase
  1396. * @param item_list: List of items to purchase
  1397. * @return clif_cashshop_ack value to display
  1398. */
  1399. int npc_cashshop_buylist(struct map_session_data *sd, int points, int count, unsigned short* item_list)
  1400. {
  1401. int i, j, amount, new_, w, vt;
  1402. unsigned short nameid;
  1403. struct npc_data *nd = (struct npc_data *)map_id2bl(sd->npc_shopid);
  1404. enum e_CASHSHOP_ACK res;
  1405. item_data *id;
  1406. if( !nd || ( nd->subtype != NPCTYPE_CASHSHOP && nd->subtype != NPCTYPE_ITEMSHOP && nd->subtype != NPCTYPE_POINTSHOP ) )
  1407. return ERROR_TYPE_NPC;
  1408. if( sd->state.trading )
  1409. return ERROR_TYPE_EXCHANGE;
  1410. new_ = 0;
  1411. w = 0;
  1412. vt = 0; // Global Value
  1413. // Validating Process ----------------------------------------------------
  1414. for( i = 0; i < count; i++ )
  1415. {
  1416. nameid = item_list[i*2+1];
  1417. amount = item_list[i*2+0];
  1418. id = itemdb_exists(nameid);
  1419. if( !id || amount <= 0 )
  1420. return ERROR_TYPE_ITEM_ID;
  1421. ARR_FIND(0,nd->u.shop.count,j,nd->u.shop.shop_item[j].nameid == nameid || itemdb_viewid(nd->u.shop.shop_item[j].nameid) == nameid);
  1422. if( j == nd->u.shop.count || nd->u.shop.shop_item[j].value <= 0 )
  1423. return ERROR_TYPE_ITEM_ID;
  1424. nameid = item_list[i*2+1] = nd->u.shop.shop_item[j].nameid; //item_avail replacement
  1425. if( !itemdb_isstackable2(id) && amount > 1 )
  1426. {
  1427. ShowWarning("Player %s (%d:%d) sent a hexed packet trying to buy %d of nonstackable item %hu!\n", sd->status.name, sd->status.account_id, sd->status.char_id, amount, nameid);
  1428. amount = item_list[i*2+0] = 1;
  1429. }
  1430. switch( pc_checkadditem(sd,nameid,amount) )
  1431. {
  1432. case CHKADDITEM_NEW:
  1433. new_ += id->inventorySlotNeeded(amount);
  1434. break;
  1435. case CHKADDITEM_OVERAMOUNT:
  1436. return ERROR_TYPE_INVENTORY_WEIGHT;
  1437. }
  1438. vt += nd->u.shop.shop_item[j].value * amount;
  1439. w += itemdb_weight(nameid) * amount;
  1440. }
  1441. if( w + sd->weight > sd->max_weight )
  1442. return ERROR_TYPE_INVENTORY_WEIGHT;
  1443. if( pc_inventoryblank(sd) < new_ )
  1444. return ERROR_TYPE_INVENTORY_WEIGHT;
  1445. if( points > vt ) points = vt;
  1446. if ((res = npc_cashshop_process_payment(nd, vt, points, sd)) != ERROR_TYPE_NONE)
  1447. return res;
  1448. // Delivery Process ----------------------------------------------------
  1449. for( i = 0; i < count; i++ ) {
  1450. nameid = item_list[i*2+1];
  1451. amount = item_list[i*2+0];
  1452. if( !pet_create_egg(sd,nameid) ) {
  1453. struct item item_tmp;
  1454. unsigned short get_amt = amount;
  1455. memset(&item_tmp, 0, sizeof(item_tmp));
  1456. item_tmp.nameid = nameid;
  1457. item_tmp.identify = 1;
  1458. if ((itemdb_search(nameid))->flag.guid)
  1459. get_amt = 1;
  1460. for (j = 0; j < amount; j += get_amt)
  1461. pc_additem(sd,&item_tmp,get_amt,LOG_TYPE_NPC);
  1462. }
  1463. }
  1464. return ERROR_TYPE_NONE;
  1465. }
  1466. /**
  1467. * Returns the shop currency type
  1468. * @param sd: Player data
  1469. * @param nd: NPC data
  1470. * @param cost: Reference to cost variable
  1471. * @param display: Display cost type to player?
  1472. */
  1473. void npc_shop_currency_type(struct map_session_data *sd, struct npc_data *nd, int cost[2], bool display)
  1474. {
  1475. nullpo_retv(sd);
  1476. if (!nd) { // Assume it's Cash Shop through the button
  1477. cost[0] = sd->cashPoints;
  1478. cost[1] = sd->kafraPoints;
  1479. return;
  1480. }
  1481. switch(nd->subtype) {
  1482. case NPCTYPE_CASHSHOP:
  1483. cost[0] = sd->cashPoints;
  1484. cost[1] = sd->kafraPoints;
  1485. break;
  1486. case NPCTYPE_ITEMSHOP:
  1487. {
  1488. int total = 0, i;
  1489. struct item_data *id = itemdb_exists(nd->u.shop.itemshop_nameid);
  1490. if (id) { // Item Data is checked at script parsing but in case of item_db reload, check again.
  1491. if (display) {
  1492. char output[CHAT_SIZE_MAX];
  1493. memset(output, '\0', sizeof(output));
  1494. sprintf(output, msg_txt(sd, 714), id->jname, id->nameid); // Item Shop List: %s (%hu)
  1495. clif_broadcast(&sd->bl, output, strlen(output) + 1, BC_BLUE,SELF);
  1496. }
  1497. for (i = 0; i < MAX_INVENTORY; i++) {
  1498. if (sd->inventory.u.items_inventory[i].amount > 0 && sd->inventory.u.items_inventory[i].nameid == id->nameid && pc_can_sell_item(sd, &sd->inventory.u.items_inventory[i], nd->subtype))
  1499. total += sd->inventory.u.items_inventory[i].amount;
  1500. }
  1501. }
  1502. cost[0] = total;
  1503. }
  1504. break;
  1505. case NPCTYPE_POINTSHOP:
  1506. if (display) {
  1507. char output[CHAT_SIZE_MAX];
  1508. memset(output, '\0', sizeof(output));
  1509. sprintf(output, msg_txt(sd, 715), nd->u.shop.pointshop_str); // Point Shop List: '%s'
  1510. clif_broadcast(&sd->bl, output, strlen(output) + 1, BC_BLUE,SELF);
  1511. }
  1512. cost[0] = static_cast<int>(pc_readreg2(sd, nd->u.shop.pointshop_str));
  1513. break;
  1514. }
  1515. }
  1516. /**
  1517. * Cash Shop Buy List for clients 2010-11-15 and older
  1518. * @param sd: Player data
  1519. * @param nameid: Item to purchase
  1520. * @param amount: Amount of items to purchase
  1521. * @param points: Cost of total items
  1522. * @return clif_cashshop_ack value to display
  1523. */
  1524. int npc_cashshop_buy(struct map_session_data *sd, unsigned short nameid, int amount, int points)
  1525. {
  1526. struct npc_data *nd = (struct npc_data *)map_id2bl(sd->npc_shopid);
  1527. struct item_data *item;
  1528. int i, price, w;
  1529. enum e_CASHSHOP_ACK res;
  1530. if( amount <= 0 )
  1531. return ERROR_TYPE_ITEM_ID;
  1532. if( points < 0 )
  1533. return ERROR_TYPE_MONEY;
  1534. if( !nd || (nd->subtype != NPCTYPE_CASHSHOP && nd->subtype != NPCTYPE_ITEMSHOP && nd->subtype != NPCTYPE_POINTSHOP) )
  1535. return ERROR_TYPE_NPC;
  1536. if( sd->state.trading )
  1537. return ERROR_TYPE_EXCHANGE;
  1538. if( (item = itemdb_exists(nameid)) == NULL )
  1539. return ERROR_TYPE_ITEM_ID; // Invalid Item
  1540. ARR_FIND(0, nd->u.shop.count, i, nd->u.shop.shop_item[i].nameid == nameid || itemdb_viewid(nd->u.shop.shop_item[i].nameid) == nameid);
  1541. if( i == nd->u.shop.count )
  1542. return ERROR_TYPE_ITEM_ID;
  1543. if( nd->u.shop.shop_item[i].value <= 0 )
  1544. return ERROR_TYPE_ITEM_ID;
  1545. nameid = nd->u.shop.shop_item[i].nameid; //item_avail replacement
  1546. if(!itemdb_isstackable2(item) && amount > 1)
  1547. {
  1548. ShowWarning("Player %s (%d:%d) sent a hexed packet trying to buy %d of nonstackable item %hu!\n",
  1549. sd->status.name, sd->status.account_id, sd->status.char_id, amount, nameid);
  1550. amount = 1;
  1551. }
  1552. switch( pc_checkadditem(sd, nameid, amount) )
  1553. {
  1554. case CHKADDITEM_NEW:
  1555. if( pc_inventoryblank(sd) < item->inventorySlotNeeded(amount) )
  1556. return ERROR_TYPE_INVENTORY_WEIGHT;
  1557. break;
  1558. case CHKADDITEM_OVERAMOUNT:
  1559. return ERROR_TYPE_INVENTORY_WEIGHT;
  1560. }
  1561. w = item->weight * amount;
  1562. if( w + sd->weight > sd->max_weight )
  1563. return ERROR_TYPE_INVENTORY_WEIGHT;
  1564. if( (double)nd->u.shop.shop_item[i].value * amount > INT_MAX )
  1565. {
  1566. ShowWarning("npc_cashshop_buy: Item '%s' (%hu) price overflow attempt!\n", item->name, nameid);
  1567. ShowDebug("(NPC:'%s' (%s,%d,%d), player:'%s' (%d/%d), value:%d, amount:%d)\n",
  1568. nd->exname, map_mapid2mapname(nd->bl.m), nd->bl.x, nd->bl.y, sd->status.name, sd->status.account_id, sd->status.char_id, nd->u.shop.shop_item[i].value, amount);
  1569. return ERROR_TYPE_ITEM_ID;
  1570. }
  1571. price = nd->u.shop.shop_item[i].value * amount;
  1572. if( points > price )
  1573. points = price;
  1574. if ((res = npc_cashshop_process_payment(nd, price, points, sd)) != ERROR_TYPE_NONE)
  1575. return res;
  1576. if( !pet_create_egg(sd, nameid) ) {
  1577. struct item item_tmp;
  1578. unsigned short get_amt = amount, j;
  1579. memset(&item_tmp, 0, sizeof(item_tmp));
  1580. item_tmp.nameid = nameid;
  1581. item_tmp.identify = 1;
  1582. if (item->flag.guid)
  1583. get_amt = 1;
  1584. for (j = 0; j < amount; j += get_amt)
  1585. pc_additem(sd,&item_tmp, get_amt, LOG_TYPE_NPC);
  1586. }
  1587. return ERROR_TYPE_NONE;
  1588. }
  1589. /**
  1590. * NPC buylist for script-controlled shops
  1591. * @param sd: Player who bought
  1592. * @param n: Number of items
  1593. * @param item_list: List of items
  1594. * @param nd: Attached NPC
  1595. */
  1596. static int npc_buylist_sub(struct map_session_data* sd, uint16 n, struct s_npc_buy_list *item_list, struct npc_data* nd) {
  1597. char npc_ev[EVENT_NAME_LENGTH];
  1598. int i, key_nameid = 0, key_amount = 0;
  1599. // discard old contents
  1600. script_cleararray_pc( sd, "@bought_nameid" );
  1601. script_cleararray_pc( sd, "@bought_quantity" );
  1602. // save list of bought items
  1603. for (i = 0; i < n; i++) {
  1604. script_setarray_pc( sd, "@bought_nameid", i, item_list[i].nameid, &key_nameid );
  1605. script_setarray_pc( sd, "@bought_quantity", i, item_list[i].qty, &key_amount );
  1606. }
  1607. // invoke event
  1608. snprintf(npc_ev, ARRAYLENGTH(npc_ev), "%s::%s", nd->exname, script_config.onbuy_event_name);
  1609. npc_event(sd, npc_ev, 0);
  1610. return 0;
  1611. }
  1612. /**
  1613. * Shop buylist that the player is attempting to purchase
  1614. * @param sd: Player who attempt to buy
  1615. * @param n: Number of items
  1616. * @param item_list: List of items
  1617. * @return result code for clif_parse_NpcBuyListSend/clif_npc_market_purchase_ack
  1618. */
  1619. uint8 npc_buylist(struct map_session_data* sd, uint16 n, struct s_npc_buy_list *item_list) {
  1620. struct npc_data* nd;
  1621. struct npc_item_list *shop = NULL;
  1622. double z;
  1623. int i,j,k,w,skill,new_;
  1624. uint8 market_index[MAX_INVENTORY];
  1625. nullpo_retr(3, sd);
  1626. nullpo_retr(3, item_list);
  1627. nd = npc_checknear(sd,map_id2bl(sd->npc_shopid));
  1628. if( nd == NULL )
  1629. return 3;
  1630. if( nd->subtype != NPCTYPE_SHOP && nd->subtype != NPCTYPE_MARKETSHOP )
  1631. return 3;
  1632. if (!item_list || !n)
  1633. return 3;
  1634. z = 0;
  1635. w = 0;
  1636. new_ = 0;
  1637. shop = nd->u.shop.shop_item;
  1638. memset(market_index, 0, sizeof(market_index));
  1639. // process entries in buy list, one by one
  1640. for( i = 0; i < n; ++i ) {
  1641. unsigned short nameid, amount;
  1642. int value;
  1643. item_data *id;
  1644. // find this entry in the shop's sell list
  1645. ARR_FIND( 0, nd->u.shop.count, j,
  1646. item_list[i].nameid == shop[j].nameid || //Normal items
  1647. item_list[i].nameid == itemdb_viewid(shop[j].nameid) //item_avail replacement
  1648. );
  1649. if( j == nd->u.shop.count )
  1650. return 3; // no such item in shop
  1651. #if PACKETVER >= 20131223
  1652. if (nd->subtype == NPCTYPE_MARKETSHOP) {
  1653. if (item_list[i].qty > shop[j].qty)
  1654. return 3;
  1655. market_index[i] = j;
  1656. }
  1657. #endif
  1658. amount = item_list[i].qty;
  1659. nameid = item_list[i].nameid = shop[j].nameid; //item_avail replacement
  1660. value = shop[j].value;
  1661. id = itemdb_exists(nameid);
  1662. if( !id )
  1663. return 3; // item no longer in itemdb
  1664. if( !itemdb_isstackable2(id) && amount > 1 ) { //Exploit? You can't buy more than 1 of equipment types o.O
  1665. ShowWarning("Player %s (%d:%d) sent a hexed packet trying to buy %d of nonstackable item %hu!\n",
  1666. sd->status.name, sd->status.account_id, sd->status.char_id, amount, nameid);
  1667. amount = item_list[i].qty = 1;
  1668. }
  1669. if( nd->master_nd ) { // Script-controlled shops decide by themselves, what can be bought and for what price.
  1670. continue;
  1671. }
  1672. switch( pc_checkadditem(sd,nameid,amount) ) {
  1673. case CHKADDITEM_EXIST:
  1674. break;
  1675. case CHKADDITEM_NEW:
  1676. new_ += id->inventorySlotNeeded(amount);
  1677. break;
  1678. case CHKADDITEM_OVERAMOUNT:
  1679. return 2;
  1680. }
  1681. if (npc_shop_discount(nd))
  1682. value = pc_modifybuyvalue(sd,value);
  1683. z += (double)value * amount;
  1684. w += itemdb_weight(nameid) * amount;
  1685. }
  1686. if (nd->master_nd) //Script-based shops.
  1687. return npc_buylist_sub(sd,n,item_list,nd->master_nd);
  1688. if (z > (double)sd->status.zeny)
  1689. return 1; // Not enough Zeny
  1690. if( w + sd->weight > sd->max_weight )
  1691. return 2; // Too heavy
  1692. if( pc_inventoryblank(sd) < new_ )
  1693. return 3; // Not enough space to store items
  1694. pc_payzeny(sd, (int)z, LOG_TYPE_NPC, NULL);
  1695. for( i = 0; i < n; ++i ) {
  1696. unsigned short nameid = item_list[i].nameid;
  1697. unsigned short amount = item_list[i].qty;
  1698. #if PACKETVER >= 20131223
  1699. if (nd->subtype == NPCTYPE_MARKETSHOP) {
  1700. j = market_index[i];
  1701. if (amount > shop[j].qty)
  1702. return 1;
  1703. shop[j].qty -= amount;
  1704. npc_market_tosql(nd->exname, &shop[j]);
  1705. }
  1706. #endif
  1707. if (itemdb_type(nameid) == IT_PETEGG)
  1708. pet_create_egg(sd, nameid);
  1709. else {
  1710. unsigned short get_amt = amount;
  1711. if ((itemdb_search(nameid))->flag.guid)
  1712. get_amt = 1;
  1713. for (k = 0; k < amount; k += get_amt) {
  1714. struct item item_tmp;
  1715. memset(&item_tmp, 0, sizeof(item_tmp));
  1716. item_tmp.nameid = nameid;
  1717. item_tmp.identify = 1;
  1718. pc_additem(sd,&item_tmp,get_amt,LOG_TYPE_NPC);
  1719. }
  1720. }
  1721. }
  1722. // custom merchant shop exp bonus
  1723. if( battle_config.shop_exp > 0 && z > 0 && (skill = pc_checkskill(sd,MC_DISCOUNT)) > 0 ) {
  1724. uint16 sk_idx = skill_get_index(MC_DISCOUNT);
  1725. if( sd->status.skill[sk_idx].flag >= SKILL_FLAG_REPLACED_LV_0 )
  1726. skill = sd->status.skill[sk_idx].flag - SKILL_FLAG_REPLACED_LV_0;
  1727. if( skill > 0 ) {
  1728. z = z * (double)skill * (double)battle_config.shop_exp/10000.;
  1729. if( z < 1 )
  1730. z = 1;
  1731. pc_gainexp(sd,NULL,0,(int)z, 0);
  1732. }
  1733. }
  1734. return 0;
  1735. }
  1736. /// npc_selllist for script-controlled shops
  1737. static int npc_selllist_sub(struct map_session_data* sd, int n, unsigned short* item_list, struct npc_data* nd)
  1738. {
  1739. char npc_ev[EVENT_NAME_LENGTH];
  1740. char card_slot[NAME_LENGTH];
  1741. char option_id[NAME_LENGTH], option_val[NAME_LENGTH], option_param[NAME_LENGTH];
  1742. int i, j;
  1743. int key_nameid = 0;
  1744. int key_amount = 0;
  1745. int key_refine = 0;
  1746. int key_attribute = 0;
  1747. int key_identify = 0;
  1748. int key_card[MAX_SLOTS];
  1749. int key_option_id[MAX_ITEM_RDM_OPT], key_option_val[MAX_ITEM_RDM_OPT], key_option_param[MAX_ITEM_RDM_OPT];
  1750. // discard old contents
  1751. script_cleararray_pc( sd, "@sold_nameid" );
  1752. script_cleararray_pc( sd, "@sold_quantity" );
  1753. script_cleararray_pc( sd, "@sold_refine" );
  1754. script_cleararray_pc( sd, "@sold_attribute" );
  1755. script_cleararray_pc( sd, "@sold_identify" );
  1756. for( j = 0; j < MAX_SLOTS; j++ )
  1757. {// clear each of the card slot entries
  1758. key_card[j] = 0;
  1759. snprintf(card_slot, sizeof(card_slot), "@sold_card%d", j + 1);
  1760. script_cleararray_pc( sd, card_slot );
  1761. }
  1762. for (j = 0; j < MAX_ITEM_RDM_OPT; j++) { // Clear each of the item option entries
  1763. key_option_id[j] = key_option_val[j] = key_option_param[j] = 0;
  1764. snprintf(option_id, sizeof(option_id), "@sold_option_id%d", j + 1);
  1765. script_cleararray_pc( sd, option_id );
  1766. snprintf(option_val, sizeof(option_val), "@sold_option_val%d", j + 1);
  1767. script_cleararray_pc( sd, option_val );
  1768. snprintf(option_param, sizeof(option_param), "@sold_option_param%d", j + 1);
  1769. script_cleararray_pc( sd, option_param );
  1770. }
  1771. // save list of to be sold items
  1772. for( i = 0; i < n; i++ )
  1773. {
  1774. int idx = item_list[i * 2] - 2;
  1775. script_setarray_pc( sd, "@sold_nameid", i, sd->inventory.u.items_inventory[idx].nameid, &key_nameid );
  1776. script_setarray_pc( sd, "@sold_quantity", i, item_list[i*2+1], &key_amount );
  1777. if( itemdb_isequip(sd->inventory.u.items_inventory[idx].nameid) )
  1778. {// process equipment based information into the arrays
  1779. script_setarray_pc( sd, "@sold_refine", i, sd->inventory.u.items_inventory[idx].refine, &key_refine );
  1780. script_setarray_pc( sd, "@sold_attribute", i, sd->inventory.u.items_inventory[idx].attribute, &key_attribute );
  1781. script_setarray_pc( sd, "@sold_identify", i, sd->inventory.u.items_inventory[idx].identify, &key_identify );
  1782. for( j = 0; j < MAX_SLOTS; j++ )
  1783. {// store each of the cards from the equipment in the array
  1784. snprintf(card_slot, sizeof(card_slot), "@sold_card%d", j + 1);
  1785. script_setarray_pc( sd, card_slot, i, sd->inventory.u.items_inventory[idx].card[j], &key_card[j] );
  1786. }
  1787. for (j = 0; j < MAX_ITEM_RDM_OPT; j++) { // Store each of the item options in the array
  1788. snprintf(option_id, sizeof(option_id), "@sold_option_id%d", j + 1);
  1789. script_setarray_pc( sd, option_id, i, sd->inventory.u.items_inventory[idx].option[j].id, &key_option_id[j] );
  1790. snprintf(option_val, sizeof(option_val), "@sold_option_val%d", j + 1);
  1791. script_setarray_pc( sd, option_val, i, sd->inventory.u.items_inventory[idx].option[j].value, &key_option_val[j] );
  1792. snprintf(option_param, sizeof(option_param), "@sold_option_param%d", j + 1);
  1793. script_setarray_pc( sd, option_param, i, sd->inventory.u.items_inventory[idx].option[j].param, &key_option_param[j] );
  1794. }
  1795. }
  1796. }
  1797. // invoke event
  1798. snprintf(npc_ev, ARRAYLENGTH(npc_ev), "%s::%s", nd->exname, script_config.onsell_event_name);
  1799. npc_event(sd, npc_ev, 0);
  1800. return 0;
  1801. }
  1802. /// Player item selling to npc shop.
  1803. ///
  1804. /// @param item_list 'n' pairs <index,amount>
  1805. /// @return result code for clif_parse_NpcSellListSend
  1806. uint8 npc_selllist(struct map_session_data* sd, int n, unsigned short *item_list)
  1807. {
  1808. double z;
  1809. int i,skill;
  1810. struct npc_data *nd;
  1811. nullpo_retr(1, sd);
  1812. nullpo_retr(1, item_list);
  1813. if( ( nd = npc_checknear(sd, map_id2bl(sd->npc_shopid)) ) == NULL || nd->subtype != NPCTYPE_SHOP )
  1814. {
  1815. return 1;
  1816. }
  1817. z = 0;
  1818. // verify the sell list
  1819. for( i = 0; i < n; i++ )
  1820. {
  1821. unsigned short nameid;
  1822. int amount, idx, value;
  1823. idx = item_list[i*2]-2;
  1824. amount = item_list[i*2+1];
  1825. if( idx >= MAX_INVENTORY || idx < 0 || amount < 0 )
  1826. {
  1827. return 1;
  1828. }
  1829. nameid = sd->inventory.u.items_inventory[idx].nameid;
  1830. if( !nameid || !sd->inventory_data[idx] || sd->inventory.u.items_inventory[idx].amount < amount )
  1831. {
  1832. return 1;
  1833. }
  1834. if( nd->master_nd )
  1835. {// Script-controlled shops decide by themselves, what can be sold and at what price.
  1836. continue;
  1837. }
  1838. if (!pc_can_sell_item(sd, &sd->inventory.u.items_inventory[idx], nd->subtype)) {
  1839. return 1; // In official server, this illegal attempt the player will be disconnected
  1840. }
  1841. value = pc_modifysellvalue(sd, sd->inventory_data[idx]->value_sell);
  1842. z+= (double)value*amount;
  1843. }
  1844. if( nd->master_nd )
  1845. {// Script-controlled shops
  1846. return npc_selllist_sub(sd, n, item_list, nd->master_nd);
  1847. }
  1848. // delete items
  1849. for( i = 0; i < n; i++ )
  1850. {
  1851. int amount, idx;
  1852. idx = item_list[i*2]-2;
  1853. amount = item_list[i*2+1];
  1854. // Forged packet, we do not care if he loses items
  1855. if( sd->inventory_data[idx] == nullptr ){
  1856. return 1;
  1857. }
  1858. if( sd->inventory_data[idx]->type == IT_PETEGG && sd->inventory.u.items_inventory[idx].card[0] == CARD0_PET )
  1859. {
  1860. if( pet_db_search(sd->inventory.u.items_inventory[idx].nameid, PET_EGG) )
  1861. {
  1862. intif_delete_petdata(MakeDWord(sd->inventory.u.items_inventory[idx].card[1], sd->inventory.u.items_inventory[idx].card[2]));
  1863. }
  1864. }
  1865. pc_delitem(sd, idx, amount, 0, 6, LOG_TYPE_NPC);
  1866. }
  1867. if( z > MAX_ZENY )
  1868. z = MAX_ZENY;
  1869. pc_getzeny(sd, (int)z, LOG_TYPE_NPC, NULL);
  1870. // custom merchant shop exp bonus
  1871. if( battle_config.shop_exp > 0 && z > 0 && ( skill = pc_checkskill(sd,MC_OVERCHARGE) ) > 0)
  1872. {
  1873. uint16 sk_idx = skill_get_index(MC_OVERCHARGE);
  1874. if( sd->status.skill[sk_idx].flag >= SKILL_FLAG_REPLACED_LV_0 )
  1875. skill = sd->status.skill[sk_idx].flag - SKILL_FLAG_REPLACED_LV_0;
  1876. if( skill > 0 )
  1877. {
  1878. z = z * (double)skill * (double)battle_config.shop_exp/10000.;
  1879. if( z < 1 )
  1880. z = 1;
  1881. pc_gainexp(sd, NULL, 0, (int)z, 0);
  1882. }
  1883. }
  1884. return 0;
  1885. }
  1886. //Atempt to remove an npc from a map
  1887. //This doesn't remove it from map_db
  1888. int npc_remove_map(struct npc_data* nd)
  1889. {
  1890. int16 i;
  1891. nullpo_retr(1, nd);
  1892. if(nd->bl.prev == NULL || nd->bl.m < 0)
  1893. return 1; //Not assigned to a map.
  1894. struct map_data *mapdata = map_getmapdata(nd->bl.m);
  1895. if (nd->subtype == NPCTYPE_SCRIPT)
  1896. skill_clear_unitgroup(&nd->bl);
  1897. clif_clearunit_area(&nd->bl,CLR_RESPAWN);
  1898. npc_unsetcells(nd);
  1899. map_delblock(&nd->bl);
  1900. //Remove npc from map[].npc list. [Skotlex]
  1901. ARR_FIND( 0, mapdata->npc_num, i, mapdata->npc[i] == nd );
  1902. if( i == mapdata->npc_num ) return 2; //failed to find it?
  1903. mapdata->npc_num--;
  1904. if (i >= mapdata->npc_num_area)
  1905. mapdata->npc[i] = mapdata->npc[ mapdata->npc_num ];
  1906. else if (i >= mapdata->npc_num_warp) {
  1907. mapdata->npc_num_area--;
  1908. mapdata->npc[i] = mapdata->npc[ mapdata->npc_num_area ];
  1909. mapdata->npc[ mapdata->npc_num_area ] = mapdata->npc[ mapdata->npc_num ];
  1910. }
  1911. else {
  1912. mapdata->npc_num_warp--;
  1913. mapdata->npc_num_area--;
  1914. mapdata->npc[i] = mapdata->npc[ mapdata->npc_num_warp ];
  1915. mapdata->npc[ mapdata->npc_num_warp ] = mapdata->npc[ mapdata->npc_num_area ];
  1916. mapdata->npc[ mapdata->npc_num_area ] = mapdata->npc[ mapdata->npc_num ];
  1917. }
  1918. mapdata->npc[ mapdata->npc_num ] = NULL;
  1919. return 0;
  1920. }
  1921. /**
  1922. * @see DBApply
  1923. */
  1924. static int npc_unload_ev(DBKey key, DBData *data, va_list ap)
  1925. {
  1926. struct event_data* ev = (struct event_data*)db_data2ptr(data);
  1927. char* npcname = va_arg(ap, char *);
  1928. if(strcmp(ev->nd->exname,npcname)==0){
  1929. db_remove(ev_db, key);
  1930. return 1;
  1931. }
  1932. return 0;
  1933. }
  1934. //Chk if npc matches src_id, then unload.
  1935. //Sub-function used to find duplicates.
  1936. static int npc_unload_dup_sub(struct npc_data* nd, va_list args)
  1937. {
  1938. int src_id;
  1939. src_id = va_arg(args, int);
  1940. if (nd->src_id == src_id)
  1941. npc_unload(nd, true);
  1942. return 0;
  1943. }
  1944. //Removes all npcs that are duplicates of the passed one. [Skotlex]
  1945. void npc_unload_duplicates(struct npc_data* nd)
  1946. {
  1947. map_foreachnpc(npc_unload_dup_sub,nd->bl.id);
  1948. }
  1949. //Removes an npc from map and db.
  1950. //Single is to free name (for duplicates).
  1951. int npc_unload(struct npc_data* nd, bool single) {
  1952. nullpo_ret(nd);
  1953. status_change_clear(&nd->bl, 1);
  1954. npc_remove_map(nd);
  1955. map_deliddb(&nd->bl);
  1956. if( single )
  1957. strdb_remove(npcname_db, nd->exname);
  1958. if (nd->chat_id) // remove npc chatroom object and kick users
  1959. chat_deletenpcchat(nd);
  1960. #ifdef PCRE_SUPPORT
  1961. npc_chat_finalize(nd); // deallocate npc PCRE data structures
  1962. #endif
  1963. if( single && nd->path ) {
  1964. struct npc_path_data* npd = NULL;
  1965. if( nd->path ) {
  1966. npd = (struct npc_path_data*)strdb_get(npc_path_db, nd->path);
  1967. }
  1968. if( npd && --npd->references == 0 ) {
  1969. strdb_remove(npc_path_db, nd->path);/* remove from db */
  1970. aFree(nd->path);/* remove now that no other instances exist */
  1971. if (npd == npc_last_npd) {
  1972. npc_last_npd = NULL;
  1973. npc_last_ref = NULL;
  1974. npc_last_path = NULL;
  1975. }
  1976. }
  1977. }
  1978. if( single && nd->bl.m != -1 )
  1979. map_remove_questinfo(nd->bl.m, nd);
  1980. if( (nd->subtype == NPCTYPE_SHOP || nd->subtype == NPCTYPE_CASHSHOP || nd->subtype == NPCTYPE_ITEMSHOP || nd->subtype == NPCTYPE_POINTSHOP || nd->subtype == NPCTYPE_MARKETSHOP) && nd->src_id == 0) //src check for duplicate shops [Orcao]
  1981. aFree(nd->u.shop.shop_item);
  1982. else if( nd->subtype == NPCTYPE_SCRIPT ) {
  1983. struct s_mapiterator* iter;
  1984. struct block_list* bl;
  1985. if( single )
  1986. ev_db->foreach(ev_db,npc_unload_ev,nd->exname); //Clean up all events related
  1987. iter = mapit_geteachpc();
  1988. for( bl = (struct block_list*)mapit_first(iter); mapit_exists(iter); bl = (struct block_list*)mapit_next(iter) ) {
  1989. struct map_session_data *sd = ((TBL_PC*)bl);
  1990. if( sd && sd->npc_timer_id != INVALID_TIMER ) {
  1991. const struct TimerData *td = get_timer(sd->npc_timer_id);
  1992. if( td && td->id != nd->bl.id )
  1993. continue;
  1994. if( td && td->data )
  1995. ers_free(timer_event_ers, (void*)td->data);
  1996. delete_timer(sd->npc_timer_id, npc_timerevent);
  1997. sd->npc_timer_id = INVALID_TIMER;
  1998. }
  1999. }
  2000. mapit_free(iter);
  2001. if (nd->u.scr.timerid != INVALID_TIMER) {
  2002. const struct TimerData *td;
  2003. td = get_timer(nd->u.scr.timerid);
  2004. if (td && td->data)
  2005. ers_free(timer_event_ers, (void*)td->data);
  2006. delete_timer(nd->u.scr.timerid, npc_timerevent);
  2007. }
  2008. if (nd->u.scr.timer_event)
  2009. aFree(nd->u.scr.timer_event);
  2010. if (nd->src_id == 0) {
  2011. if(nd->u.scr.script) {
  2012. script_free_code(nd->u.scr.script);
  2013. nd->u.scr.script = NULL;
  2014. }
  2015. if (nd->u.scr.label_list) {
  2016. aFree(nd->u.scr.label_list);
  2017. nd->u.scr.label_list = NULL;
  2018. nd->u.scr.label_list_num = 0;
  2019. }
  2020. }
  2021. if( nd->u.scr.guild_id )
  2022. guild_flag_remove(nd);
  2023. if( nd->sc_display_count ){
  2024. unsigned char i;
  2025. for( i = 0; i < nd->sc_display_count; i++ )
  2026. ers_free(npc_sc_display_ers, nd->sc_display[i]);
  2027. nd->sc_display_count = 0;
  2028. aFree(nd->sc_display);
  2029. nd->sc_display = NULL;
  2030. }
  2031. }
  2032. script_stop_sleeptimers(nd->bl.id);
  2033. aFree(nd);
  2034. return 0;
  2035. }
  2036. //
  2037. // NPC Source Files
  2038. //
  2039. /// Clears the npc source file list
  2040. static void npc_clearsrcfile(void)
  2041. {
  2042. struct npc_src_list* file = npc_src_files;
  2043. while( file != NULL ) {
  2044. struct npc_src_list* file_tofree = file;
  2045. file = file->next;
  2046. aFree(file_tofree);
  2047. }
  2048. npc_src_files = NULL;
  2049. }
  2050. /**
  2051. * Adds a npc source file (or removes all)
  2052. * @param name : file to add
  2053. * @param loadscript : flag to parse the script immediately after adding the src file
  2054. * @return 0=error, 1=sucess
  2055. */
  2056. int npc_addsrcfile(const char* name, bool loadscript)
  2057. {
  2058. struct npc_src_list* file;
  2059. struct npc_src_list* file_prev = NULL;
  2060. if( strcmpi(name, "clear") == 0 )
  2061. {
  2062. npc_clearsrcfile();
  2063. return 1;
  2064. }
  2065. //Check if this is not a file
  2066. if(check_filepath(name)!=2){
  2067. ShowError("npc_addsrcfile: Can't find source file \"%s\"\n", name );
  2068. return 0;
  2069. }
  2070. // prevent multiple insert of source files
  2071. file = npc_src_files;
  2072. while( file != NULL )
  2073. {
  2074. if( strcmp(name, file->name) == 0 )
  2075. return 0;// found the file, no need to insert it again
  2076. file_prev = file;
  2077. file = file->next;
  2078. }
  2079. file = (struct npc_src_list*)aMalloc(sizeof(struct npc_src_list) + strlen(name));
  2080. file->next = NULL;
  2081. safestrncpy(file->name, name, strlen(name) + 1);
  2082. if( file_prev == NULL )
  2083. npc_src_files = file;
  2084. else
  2085. file_prev->next = file;
  2086. if (loadscript)
  2087. return npc_parsesrcfile(file->name, true);
  2088. return 1;
  2089. }
  2090. /// Removes a npc source file (or all)
  2091. void npc_delsrcfile(const char* name)
  2092. {
  2093. struct npc_src_list* file = npc_src_files;
  2094. struct npc_src_list* file_prev = NULL;
  2095. if( strcmpi(name, "all") == 0 )
  2096. {
  2097. npc_clearsrcfile();
  2098. return;
  2099. }
  2100. while( file != NULL )
  2101. {
  2102. if( strcmp(file->name, name) == 0 )
  2103. {
  2104. if( npc_src_files == file )
  2105. npc_src_files = file->next;
  2106. else
  2107. file_prev->next = file->next;
  2108. aFree(file);
  2109. break;
  2110. }
  2111. file_prev = file;
  2112. file = file->next;
  2113. }
  2114. }
  2115. /// Parses and sets the name and exname of a npc.
  2116. /// Assumes that m, x and y are already set in nd.
  2117. static void npc_parsename(struct npc_data* nd, const char* name, const char* start, const char* buffer, const char* filepath)
  2118. {
  2119. const char* p;
  2120. struct npc_data* dnd;// duplicate npc
  2121. char newname[NPC_NAME_LENGTH+1];
  2122. // parse name
  2123. p = strstr(name,"::");
  2124. if( p ) { // <Display name>::<Unique name>
  2125. size_t len = p-name;
  2126. if( len > NPC_NAME_LENGTH ) {
  2127. ShowWarning("npc_parsename: Display name of '%s' is too long (len=%u) in file '%s', line'%d'. Truncating to %u characters.\n", name, (unsigned int)len, filepath, strline(buffer,start-buffer), NPC_NAME_LENGTH);
  2128. safestrncpy(nd->name, name, sizeof(nd->name));
  2129. } else {
  2130. memcpy(nd->name, name, len);
  2131. memset(nd->name+len, 0, sizeof(nd->name)-len);
  2132. }
  2133. len = strlen(p+2);
  2134. if( len > NPC_NAME_LENGTH )
  2135. ShowWarning("npc_parsename: Unique name of '%s' is too long (len=%u) in file '%s', line'%d'. Truncating to %u characters.\n", name, (unsigned int)len, filepath, strline(buffer,start-buffer), NPC_NAME_LENGTH);
  2136. safestrncpy(nd->exname, p+2, sizeof(nd->exname));
  2137. } else {// <Display name>
  2138. size_t len = strlen(name);
  2139. if( len > NPC_NAME_LENGTH )
  2140. ShowWarning("npc_parsename: Name '%s' is too long (len=%u) in file '%s', line'%d'. Truncating to %u characters.\n", name, (unsigned int)len, filepath, strline(buffer,start-buffer), NPC_NAME_LENGTH);
  2141. safestrncpy(nd->name, name, sizeof(nd->name));
  2142. safestrncpy(nd->exname, name, sizeof(nd->exname));
  2143. }
  2144. if( *nd->exname == '\0' || strstr(nd->exname,"::") != NULL ) {// invalid
  2145. snprintf(newname, ARRAYLENGTH(newname), "0_%d_%d_%d", nd->bl.m, nd->bl.x, nd->bl.y);
  2146. ShowWarning("npc_parsename: Invalid unique name in file '%s', line'%d'. Renaming '%s' to '%s'.\n", filepath, strline(buffer,start-buffer), nd->exname, newname);
  2147. safestrncpy(nd->exname, newname, sizeof(nd->exname));
  2148. }
  2149. if( (dnd=npc_name2id(nd->exname)) != NULL ) {// duplicate unique name, generate new one
  2150. char this_mapname[MAP_NAME_LENGTH_EXT];
  2151. char other_mapname[MAP_NAME_LENGTH_EXT];
  2152. int i = 0;
  2153. do {
  2154. ++i;
  2155. snprintf(newname, ARRAYLENGTH(newname), "%d_%d_%d_%d", i, nd->bl.m, nd->bl.x, nd->bl.y);
  2156. } while( npc_name2id(newname) != NULL );
  2157. strcpy(this_mapname, (nd->bl.m==-1?"(not on a map)":mapindex_id2name(map_getmapdata(nd->bl.m)->index)));
  2158. strcpy(other_mapname, (dnd->bl.m==-1?"(not on a map)":mapindex_id2name(map_getmapdata(dnd->bl.m)->index)));
  2159. ShowWarning("npc_parsename: Duplicate unique name in file '%s', line'%d'. Renaming '%s' to '%s'.\n", filepath, strline(buffer,start-buffer), nd->exname, newname);
  2160. ShowDebug("this npc:\n display name '%s'\n unique name '%s'\n map=%s, x=%d, y=%d\n", nd->name, nd->exname, this_mapname, nd->bl.x, nd->bl.y);
  2161. ShowDebug("other npc in '%s' :\n display name '%s'\n unique name '%s'\n map=%s, x=%d, y=%d\n",dnd->path, dnd->name, dnd->exname, other_mapname, dnd->bl.x, dnd->bl.y);
  2162. safestrncpy(nd->exname, newname, sizeof(nd->exname));
  2163. }
  2164. if( npc_last_path != filepath ) {
  2165. struct npc_path_data * npd = NULL;
  2166. if( !(npd = (struct npc_path_data *)strdb_get(npc_path_db,filepath) ) ) {
  2167. CREATE(npd, struct npc_path_data, 1);
  2168. strdb_put(npc_path_db, filepath, npd);
  2169. CREATE(npd->path, char, strlen(filepath)+1);
  2170. safestrncpy(npd->path, filepath, strlen(filepath)+1);
  2171. npd->references = 0;
  2172. }
  2173. nd->path = npd->path;
  2174. npd->references++;
  2175. npc_last_npd = npd;
  2176. npc_last_ref = npd->path;
  2177. npc_last_path = (char*) filepath;
  2178. } else {
  2179. nd->path = npc_last_ref;
  2180. if( npc_last_npd )
  2181. npc_last_npd->references++;
  2182. }
  2183. }
  2184. /**
  2185. * Parses NPC view.
  2186. * Support for using Constants in place of NPC View IDs.
  2187. */
  2188. int npc_parseview(const char* w4, const char* start, const char* buffer, const char* filepath) {
  2189. int i = 0;
  2190. char viewid[1024]; // Max size of name from const.txt, see read_constdb.
  2191. // Extract view ID / constant
  2192. while (w4[i] != '\0') {
  2193. if (ISSPACE(w4[i]) || w4[i] == '/' || w4[i] == ',')
  2194. break;
  2195. i++;
  2196. }
  2197. safestrncpy(viewid, w4, i+=1);
  2198. char *pid;
  2199. int val = strtol(viewid, &pid, 0);
  2200. // Check if view id is not an ID (only numbers).
  2201. if (pid != nullptr && *pid != '\0') {
  2202. int64 val_tmp;
  2203. // Check if constant exists and get its value.
  2204. if(!script_get_constant(viewid, &val_tmp)) {
  2205. ShowWarning("npc_parseview: Invalid NPC constant '%s' specified in file '%s', line'%d'. Defaulting to INVISIBLE. \n", viewid, filepath, strline(buffer,start-buffer));
  2206. val = JT_INVISIBLE;
  2207. } else
  2208. val = static_cast<int>(val_tmp);
  2209. }
  2210. return val;
  2211. }
  2212. /**
  2213. * Create a bare NPC object.
  2214. * @param m: Map ID
  2215. * @param x: X location
  2216. * @param y: Y location
  2217. * @return npc_data
  2218. */
  2219. struct npc_data *npc_create_npc(int16 m, int16 x, int16 y){
  2220. struct npc_data *nd = nullptr;
  2221. CREATE(nd, struct npc_data, 1);
  2222. nd->bl.id = npc_get_new_npc_id();
  2223. nd->bl.prev = nd->bl.next = nullptr;
  2224. nd->bl.m = m;
  2225. nd->bl.x = x;
  2226. nd->bl.y = y;
  2227. nd->sc_display = nullptr;
  2228. nd->sc_display_count = 0;
  2229. nd->progressbar.timeout = 0;
  2230. nd->vd = npc_viewdb[0]; // Default to JT_INVISIBLE
  2231. return nd;
  2232. }
  2233. /**
  2234. * Add then display an npc warp on map
  2235. * @param name : warp unique name
  2236. * @param from_mapid : mapid to warp from
  2237. * @param from_x : x coordinate of warp
  2238. * @param from_y : y coordinate of warp
  2239. * @param xs : x lenght of warp (for trigger activation)
  2240. * @param ys : y lenght of warp (for trigger activation)
  2241. * @param to_mapindex : mapid to warp to
  2242. * @param to_x : x coordinate to warp to
  2243. * @param to_y : y coordinate to warp to
  2244. * @return NULL:failed creation, npc_data* new warp
  2245. */
  2246. struct npc_data* npc_add_warp(char* name, short from_mapid, short from_x, short from_y, short xs, short ys, unsigned short to_mapindex, short to_x, short to_y)
  2247. {
  2248. int i, flag = 0;
  2249. struct npc_data *nd;
  2250. nd = npc_create_npc(from_mapid, from_x, from_y);
  2251. safestrncpy(nd->exname, name, ARRAYLENGTH(nd->exname));
  2252. if (npc_name2id(nd->exname) != NULL)
  2253. flag = 1;
  2254. if (flag == 1)
  2255. snprintf(nd->exname, ARRAYLENGTH(nd->exname), "warp_%d_%d_%d", from_mapid, from_x, from_y);
  2256. for( i = 0; npc_name2id(nd->exname) != NULL; ++i )
  2257. snprintf(nd->exname, ARRAYLENGTH(nd->exname), "warp%d_%d_%d_%d", i, from_mapid, from_x, from_y);
  2258. safestrncpy(nd->name, nd->exname, ARRAYLENGTH(nd->name));
  2259. if( battle_config.warp_point_debug )
  2260. nd->class_ = JT_GUILD_FLAG;
  2261. else
  2262. nd->class_ = JT_WARPNPC;
  2263. nd->speed = 200;
  2264. nd->u.warp.mapindex = to_mapindex;
  2265. nd->u.warp.x = to_x;
  2266. nd->u.warp.y = to_y;
  2267. nd->u.warp.xs = xs;
  2268. nd->u.warp.ys = ys;
  2269. nd->bl.type = BL_NPC;
  2270. nd->subtype = NPCTYPE_WARP;
  2271. nd->trigger_on_hidden = false;
  2272. map_addnpc(from_mapid, nd);
  2273. npc_setcells(nd);
  2274. if(map_addblock(&nd->bl))
  2275. return NULL;
  2276. status_set_viewdata(&nd->bl, nd->class_);
  2277. status_change_init(&nd->bl);
  2278. unit_dataset(&nd->bl);
  2279. if( map_getmapdata(nd->bl.m)->users )
  2280. clif_spawn(&nd->bl);
  2281. strdb_put(npcname_db, nd->exname, nd);
  2282. return nd;
  2283. }
  2284. /**
  2285. * Parses a warp npc.
  2286. * Line definition <from mapname>,<fromX>,<fromY>,<facing>%TAB%warp%TAB%<warp name>%TAB%<spanx>,<spany>,<to mapname>,<toX>,<toY>
  2287. * @param w1 : word 1 before tab (<from map name>,<fromX>,<fromY>,<facing>)
  2288. * @param w2 : word 2 before tab (warp), keyword that sent us in this parsing
  2289. * @param w3 : word 3 before tab (<warp name>)
  2290. * @param w4 : word 4 before tab (<spanx>,<spany>,<to mapname>,<toX>,<toY>)
  2291. * @param start : index to start parsing
  2292. * @param buffer : lines to parses
  2293. * @param filepath : filename with path wich we are parsing
  2294. * @return new index for next parsing
  2295. */
  2296. static const char* npc_parse_warp(char* w1, char* w2, char* w3, char* w4, const char* start, const char* buffer, const char* filepath)
  2297. {
  2298. int m;
  2299. short x, y, xs, ys, to_x, to_y;
  2300. unsigned short i;
  2301. char mapname[MAP_NAME_LENGTH_EXT], to_mapname[MAP_NAME_LENGTH_EXT];
  2302. struct npc_data *nd;
  2303. // w1=<from map name>,<fromX>,<fromY>,<facing>
  2304. // w4=<spanx>,<spany>,<to map name>,<toX>,<toY>
  2305. if( sscanf(w1, "%15[^,],%6hd,%6hd", mapname, &x, &y) != 3
  2306. || sscanf(w4, "%6hd,%6hd,%15[^,],%6hd,%6hd", &xs, &ys, to_mapname, &to_x, &to_y) != 5 )
  2307. {
  2308. ShowError("npc_parse_warp: Invalid warp definition in file '%s', line '%d'.\n * w1=%s\n * w2=%s\n * w3=%s\n * w4=%s\n", filepath, strline(buffer,start-buffer), w1, w2, w3, w4);
  2309. return strchr(start,'\n');// skip and continue
  2310. }
  2311. m = map_mapname2mapid(mapname);
  2312. i = mapindex_name2id(to_mapname);
  2313. if( i == 0 )
  2314. {
  2315. ShowError("npc_parse_warp: Unknown destination map in file '%s', line '%d' : %s\n * w1=%s\n * w2=%s\n * w3=%s\n * w4=%s\n", filepath, strline(buffer,start-buffer), to_mapname, w1, w2, w3, w4);
  2316. return strchr(start,'\n');// skip and continue
  2317. }
  2318. struct map_data *mapdata = map_getmapdata(m);
  2319. if( m != -1 && ( x < 0 || x >= mapdata->xs || y < 0 || y >= mapdata->ys ) ) {
  2320. ShowWarning("npc_parse_warp: coordinates %d/%d are out of bounds in map %s(%dx%d), in file '%s', line '%d'\n", x, y, mapdata->name, mapdata->xs, mapdata->ys,filepath,strline(buffer,start-buffer));
  2321. }
  2322. nd = npc_create_npc(m, x, y);
  2323. npc_parsename(nd, w3, start, buffer, filepath);
  2324. if (!battle_config.warp_point_debug)
  2325. nd->class_ = JT_WARPNPC;
  2326. else
  2327. nd->class_ = JT_GUILD_FLAG;
  2328. nd->speed = 200;
  2329. nd->u.warp.mapindex = i;
  2330. nd->u.warp.x = to_x;
  2331. nd->u.warp.y = to_y;
  2332. nd->u.warp.xs = xs;
  2333. nd->u.warp.ys = ys;
  2334. npc_warp++;
  2335. nd->bl.type = BL_NPC;
  2336. nd->subtype = NPCTYPE_WARP;
  2337. if (strcasecmp("warp2", w2) == 0)
  2338. nd->trigger_on_hidden = true;
  2339. else
  2340. nd->trigger_on_hidden = false;
  2341. map_addnpc(m, nd);
  2342. npc_setcells(nd);
  2343. if(map_addblock(&nd->bl)) //couldn't add on map
  2344. return strchr(start,'\n');
  2345. status_set_viewdata(&nd->bl, nd->class_);
  2346. status_change_init(&nd->bl);
  2347. unit_dataset(&nd->bl);
  2348. if( map_getmapdata(nd->bl.m)->users )
  2349. clif_spawn(&nd->bl);
  2350. strdb_put(npcname_db, nd->exname, nd);
  2351. return strchr(start,'\n');// continue
  2352. }
  2353. /**
  2354. * Parses a shop/cashshop npc.
  2355. * Line definition :
  2356. * <map name>,<x>,<y>,<facing>%TAB%shop%TAB%<NPC Name>%TAB%<sprite id>,<itemid>:<price>{,<itemid>:<price>...}
  2357. * <map name>,<x>,<y>,<facing>%TAB%cashshop%TAB%<NPC Name>%TAB%<sprite id>,<itemid>:<price>{,<itemid>:<price>...}
  2358. * <map name>,<x>,<y>,<facing>%TAB%itemshop%TAB%<NPC Name>%TAB%<sprite id>,<costitemid>{:<discount>},<itemid>:<price>{,<itemid>:<price>...}
  2359. * <map name>,<x>,<y>,<facing>%TAB%pointshop%TAB%<NPC Name>%TAB%<sprite id>,<costvariable>{:<discount>},<itemid>:<price>{,<itemid>:<price>...}
  2360. * <map name>,<x>,<y>,<facing>%TAB%marketshop%TAB%<NPC Name>%TAB%<sprite id>,<itemid>:<price>:<quantity>{,<itemid>:<price>:<quantity>...}
  2361. * @param w1 : word 1 before tab (<from map name>,<x>,<y>,<facing>)
  2362. * @param w2 : word 2 before tab (shop|cashshop|itemshop|pointshop|marketshop), keyword that sent us in this parsing
  2363. * @param w3 : word 3 before tab (<NPC Name>)
  2364. * @param w4 : word 4 before tab (<sprited id>,<shop definition...>)
  2365. * @param start : index to start parsing
  2366. * @param buffer : lines to parses
  2367. * @param filepath : filename with path wich we are parsing
  2368. * @return new index for next parsing
  2369. */
  2370. static const char* npc_parse_shop(char* w1, char* w2, char* w3, char* w4, const char* start, const char* buffer, const char* filepath)
  2371. {
  2372. char *p, point_str[32];
  2373. int m, is_discount = 0;
  2374. uint16 dir;
  2375. short x, y;
  2376. unsigned short nameid = 0;
  2377. struct npc_data *nd;
  2378. enum npc_subtype type;
  2379. if( strcmp(w1,"-") == 0 )
  2380. {// 'floating' shop?
  2381. x = y = dir = 0;
  2382. m = -1;
  2383. }
  2384. else
  2385. {// w1=<map name>,<x>,<y>,<facing>
  2386. char mapname[MAP_NAME_LENGTH_EXT];
  2387. if( sscanf(w1, "%15[^,],%6hd,%6hd,%4hd", mapname, &x, &y, &dir) != 4
  2388. || strchr(w4, ',') == NULL )
  2389. {
  2390. ShowError("npc_parse_shop: Invalid shop definition in file '%s', line '%d'.\n * w1=%s\n * w2=%s\n * w3=%s\n * w4=%s\n", filepath, strline(buffer,start-buffer), w1, w2, w3, w4);
  2391. return strchr(start,'\n');// skip and continue
  2392. }
  2393. m = map_mapname2mapid(mapname);
  2394. }
  2395. struct map_data *mapdata = map_getmapdata(m);
  2396. if( m != -1 && ( x < 0 || x >= mapdata->xs || y < 0 || y >= mapdata->ys ) ) {
  2397. ShowWarning("npc_parse_shop: coordinates %d/%d are out of bounds in map %s(%dx%d), in file '%s', line '%d'\n", x, y, mapdata->name, mapdata->xs, mapdata->ys,filepath,strline(buffer,start-buffer));
  2398. }
  2399. if( !strcasecmp(w2,"cashshop") )
  2400. type = NPCTYPE_CASHSHOP;
  2401. else if( !strcasecmp(w2,"itemshop") )
  2402. type = NPCTYPE_ITEMSHOP;
  2403. else if( !strcasecmp(w2,"pointshop") )
  2404. type = NPCTYPE_POINTSHOP;
  2405. else if( !strcasecmp(w2, "marketshop") )
  2406. type = NPCTYPE_MARKETSHOP;
  2407. else
  2408. type = NPCTYPE_SHOP;
  2409. p = strchr(w4,',');
  2410. memset(point_str,'\0',sizeof(point_str));
  2411. switch(type) {
  2412. case NPCTYPE_ITEMSHOP: {
  2413. if (sscanf(p,",%5hu:%11d,",&nameid,&is_discount) < 1) {
  2414. ShowError("npc_parse_shop: Invalid item cost definition in file '%s', line '%d'. Ignoring the rest of the line...\n * w1=%s\n * w2=%s\n * w3=%s\n * w4=%s\n", filepath, strline(buffer,start-buffer), w1, w2, w3, w4);
  2415. return strchr(start,'\n'); // skip and continue
  2416. }
  2417. if (itemdb_exists(nameid) == NULL) {
  2418. ShowWarning("npc_parse_shop: Invalid item ID cost in file '%s', line '%d' (id '%hu').\n", filepath, strline(buffer,start-buffer), nameid);
  2419. return strchr(start,'\n'); // skip and continue
  2420. }
  2421. p = strchr(p+1,',');
  2422. break;
  2423. }
  2424. case NPCTYPE_POINTSHOP: {
  2425. if (sscanf(p, ",%32[^,:]:%11d,",point_str,&is_discount) < 1) {
  2426. ShowError("npc_parse_shop: Invalid item cost definition in file '%s', line '%d'. Ignoring the rest of the line...\n * w1=%s\n * w2=%s\n * w3=%s\n * w4=%s\n", filepath, strline(buffer,start-buffer), w1, w2, w3, w4);
  2427. return strchr(start,'\n'); // skip and continue
  2428. }
  2429. switch(point_str[0]) {
  2430. case '$':
  2431. case '.':
  2432. case '\'':
  2433. ShowWarning("npc_parse_shop: Invalid item cost variable type (must be permanent character or account based) in file '%s', line '%d'. Ignoring the rest of the line...\n * w1=%s\n * w2=%s\n * w3=%s\n * w4=%s\n", filepath, strline(buffer,start-buffer), w1, w2, w3, w4);
  2434. return strchr(start,'\n'); // skip and continue
  2435. break;
  2436. }
  2437. if (point_str[strlen(point_str) - 1] == '$') {
  2438. ShowWarning("npc_parse_shop: Invalid item cost variable type (must be integer) in file '%s', line '%d'. Ignoring the rest of the line...\n * w1=%s\n * w2=%s\n * w3=%s\n * w4=%s\n", filepath, strline(buffer,start-buffer), w1, w2, w3, w4);
  2439. return strchr(start,'\n'); // skip and continue
  2440. }
  2441. p = strchr(p+1,',');
  2442. break;
  2443. }
  2444. case NPCTYPE_MARKETSHOP:
  2445. #if PACKETVER < 20131223
  2446. ShowError("npc_parse_shop: (MARKETSHOP) Feature is disabled, need client 20131223 or newer. Ignoring file '%s', line '%d\n * w1=%s\n * w2=%s\n * w3=%s\n * w4=%s\n", filepath, strline(buffer, start - buffer), w1, w2, w3, w4);
  2447. return strchr(start, '\n'); // skip and continue
  2448. #else
  2449. is_discount = 0;
  2450. break;
  2451. #endif
  2452. default:
  2453. if( sscanf( p, ",%32[^,:]:%11d,", point_str, &is_discount ) == 2 ){
  2454. is_discount = 1;
  2455. }else{
  2456. if( !strcasecmp( point_str, "yes" ) ){
  2457. is_discount = 1;
  2458. }else if( !strcasecmp( point_str, "no" ) ){
  2459. is_discount = 0;
  2460. }else{
  2461. ShowError( "npc_parse_shop: unknown discount setting %s\n", point_str );
  2462. return strchr( start, '\n' ); // skip and continue
  2463. }
  2464. p = strchr( p + 1, ',' );
  2465. }
  2466. break;
  2467. }
  2468. nd = npc_create_npc(m, x, y);
  2469. nd->u.shop.count = 0;
  2470. while ( p ) {
  2471. unsigned short nameid2, qty = 0;
  2472. int value;
  2473. struct item_data* id;
  2474. bool skip = false;
  2475. if( p == NULL )
  2476. break;
  2477. switch(type) {
  2478. case NPCTYPE_MARKETSHOP:
  2479. #if PACKETVER >= 20131223
  2480. if (sscanf(p, ",%6hu:%11d:%6hu", &nameid2, &value, &qty) != 3) {
  2481. ShowError("npc_parse_shop: (MARKETSHOP) Invalid item definition in file '%s', line '%d'. Ignoring the rest of the line...\n * w1=%s\n * w2=%s\n * w3=%s\n * w4=%s\n", filepath, strline(buffer, start - buffer), w1, w2, w3, w4);
  2482. skip = true;
  2483. }
  2484. #endif
  2485. break;
  2486. default:
  2487. if (sscanf(p, ",%6hu:%11d", &nameid2, &value) != 2) {
  2488. ShowError("npc_parse_shop: Invalid item definition in file '%s', line '%d'. Ignoring the rest of the line...\n * w1=%s\n * w2=%s\n * w3=%s\n * w4=%s\n", filepath, strline(buffer, start - buffer), w1, w2, w3, w4);
  2489. skip = true;
  2490. }
  2491. break;
  2492. }
  2493. if (skip)
  2494. break;
  2495. if( (id = itemdb_exists(nameid2)) == NULL ) {
  2496. ShowWarning("npc_parse_shop: Invalid sell item in file '%s', line '%d' (id '%hu').\n", filepath, strline(buffer,start-buffer), nameid2);
  2497. p = strchr(p+1,',');
  2498. continue;
  2499. }
  2500. if( value < 0 ) {
  2501. if (type == NPCTYPE_SHOP || type == NPCTYPE_MARKETSHOP) value = id->value_buy;
  2502. else value = 0; // Cashshop doesn't have a "buy price" in the item_db
  2503. }
  2504. if (value == 0 && (type == NPCTYPE_SHOP || type == NPCTYPE_MARKETSHOP)) { // NPC selling items for free!
  2505. ShowWarning("npc_parse_shop: Item %s [%hu] is being sold for FREE in file '%s', line '%d'.\n",
  2506. id->name, nameid2, filepath, strline(buffer,start-buffer));
  2507. }
  2508. if( type == NPCTYPE_SHOP && value*0.75 < id->value_sell*1.24 ) { // Exploit possible: you can buy and sell back with profit
  2509. ShowWarning("npc_parse_shop: Item %s [%hu] discounted buying price (%d->%d) is less than overcharged selling price (%d->%d) at file '%s', line '%d'.\n",
  2510. id->name, nameid2, value, (int)(value*0.75), id->value_sell, (int)(id->value_sell*1.24), filepath, strline(buffer,start-buffer));
  2511. }
  2512. if (type == NPCTYPE_MARKETSHOP && (!qty || qty > UINT16_MAX)) {
  2513. ShowWarning("npc_parse_shop: Item %s [%hu] is stocked with invalid value %d, changed to 1. File '%s', line '%d'.\n",
  2514. id->name, nameid2, qty, filepath, strline(buffer,start-buffer));
  2515. qty = 1;
  2516. }
  2517. //for logs filters, atcommands and iteminfo script command
  2518. if( id->maxchance == 0 )
  2519. id->maxchance = -1; // -1 would show that the item's sold in NPC Shop
  2520. #if PACKETVER >= 20131223
  2521. if (nd->u.shop.count && type == NPCTYPE_MARKETSHOP) {
  2522. uint16 i;
  2523. // Duplicate entry? Replace the value
  2524. ARR_FIND(0, nd->u.shop.count, i, nd->u.shop.shop_item[i].nameid == nameid);
  2525. if (i != nd->u.shop.count) {
  2526. nd->u.shop.shop_item[i].qty = qty;
  2527. nd->u.shop.shop_item[i].value = value;
  2528. p = strchr(p+1,',');
  2529. continue;
  2530. }
  2531. }
  2532. #endif
  2533. RECREATE(nd->u.shop.shop_item, struct npc_item_list,nd->u.shop.count+1);
  2534. nd->u.shop.shop_item[nd->u.shop.count].nameid = nameid2;
  2535. nd->u.shop.shop_item[nd->u.shop.count].value = value;
  2536. #if PACKETVER >= 20131223
  2537. nd->u.shop.shop_item[nd->u.shop.count].flag = 0;
  2538. if (type == NPCTYPE_MARKETSHOP)
  2539. nd->u.shop.shop_item[nd->u.shop.count].qty = qty;
  2540. #endif
  2541. nd->u.shop.count++;
  2542. p = strchr(p+1,',');
  2543. }
  2544. if( nd->u.shop.count == 0 ) {
  2545. ShowWarning("npc_parse_shop: Ignoring empty shop in file '%s', line '%d'.\n", filepath, strline(buffer,start-buffer));
  2546. aFree(nd);
  2547. return strchr(start,'\n');// continue
  2548. }
  2549. if( type == NPCTYPE_ITEMSHOP ){
  2550. // Item shop currency
  2551. nd->u.shop.itemshop_nameid = nameid;
  2552. }else if( type == NPCTYPE_POINTSHOP ){
  2553. // Point shop currency
  2554. safestrncpy( nd->u.shop.pointshop_str, point_str, strlen( point_str ) + 1 );
  2555. }
  2556. nd->u.shop.discount = is_discount > 0;
  2557. npc_parsename(nd, w3, start, buffer, filepath);
  2558. nd->class_ = m == -1 ? JT_FAKENPC : npc_parseview(w4, start, buffer, filepath);
  2559. nd->speed = 200;
  2560. ++npc_shop;
  2561. nd->bl.type = BL_NPC;
  2562. nd->subtype = type;
  2563. #if PACKETVER >= 20131223
  2564. // Insert market data to table
  2565. if (nd->subtype == NPCTYPE_MARKETSHOP) {
  2566. uint16 i;
  2567. for (i = 0; i < nd->u.shop.count; i++)
  2568. npc_market_tosql(nd->exname, &nd->u.shop.shop_item[i]);
  2569. }
  2570. #endif
  2571. if( m >= 0 )
  2572. {// normal shop npc
  2573. map_addnpc(m,nd);
  2574. if(map_addblock(&nd->bl))
  2575. return strchr(start,'\n');
  2576. status_change_init(&nd->bl);
  2577. unit_dataset(&nd->bl);
  2578. nd->ud.dir = (uint8)dir;
  2579. if( nd->class_ != JT_FAKENPC ){
  2580. status_set_viewdata(&nd->bl, nd->class_);
  2581. if( map_getmapdata(nd->bl.m)->users )
  2582. clif_spawn(&nd->bl);
  2583. }
  2584. } else
  2585. {// 'floating' shop?
  2586. map_addiddb(&nd->bl);
  2587. }
  2588. strdb_put(npcname_db, nd->exname, nd);
  2589. return strchr(start,'\n');// continue
  2590. }
  2591. /** [Cydh]
  2592. * Check if the shop is affected by discount or not
  2593. * @param type Type of NPC shop (enum npc_subtype)
  2594. * @param discount Discount flag of NPC shop
  2595. * @return bool 'true' is discountable, 'false' otherwise
  2596. */
  2597. bool npc_shop_discount( struct npc_data* nd ){
  2598. switch( nd->subtype ){
  2599. case NPCTYPE_ITEMSHOP:
  2600. return nd->u.shop.discount || ( battle_config.discount_item_point_shop&1 );
  2601. case NPCTYPE_POINTSHOP:
  2602. return nd->u.shop.discount || ( battle_config.discount_item_point_shop&2 );
  2603. default:
  2604. return nd->u.shop.discount;
  2605. }
  2606. }
  2607. /**
  2608. * NPC other label
  2609. * Not sure, seem to add label in a chainlink
  2610. * @see DBApply
  2611. */
  2612. int npc_convertlabel_db(DBKey key, DBData *data, va_list ap)
  2613. {
  2614. const char* lname = (const char*)key.str;
  2615. int lpos = db_data2i(data);
  2616. struct npc_label_list** label_list;
  2617. int* label_list_num;
  2618. const char* filepath;
  2619. struct npc_label_list* label;
  2620. const char *p;
  2621. int len;
  2622. nullpo_ret(label_list = va_arg(ap,struct npc_label_list**));
  2623. nullpo_ret(label_list_num = va_arg(ap,int*));
  2624. nullpo_ret(filepath = va_arg(ap,const char*));
  2625. // In case of labels not terminated with ':', for user defined function support
  2626. p = lname;
  2627. while( ISALNUM(*p) || *p == '_' )
  2628. ++p;
  2629. len = p-lname;
  2630. // here we check if the label fit into the buffer
  2631. if( len > NAME_LENGTH )
  2632. {
  2633. ShowError("npc_parse_script: label name longer than %d chars! '%s'\n (%s)", NAME_LENGTH, lname, filepath);
  2634. return 0;
  2635. }
  2636. if( *label_list == NULL )
  2637. {
  2638. *label_list = (struct npc_label_list *) aCalloc (1, sizeof(struct npc_label_list));
  2639. *label_list_num = 0;
  2640. } else
  2641. *label_list = (struct npc_label_list *) aRealloc (*label_list, sizeof(struct npc_label_list)*(*label_list_num+1));
  2642. label = *label_list+*label_list_num;
  2643. safestrncpy(label->name, lname, sizeof(label->name));
  2644. label->pos = lpos;
  2645. ++(*label_list_num);
  2646. return 0;
  2647. }
  2648. // Skip the contents of a script.
  2649. static const char* npc_skip_script(const char* start, const char* buffer, const char* filepath)
  2650. {
  2651. const char* p;
  2652. int curly_count;
  2653. if( start == NULL )
  2654. return NULL;// nothing to skip
  2655. // initial bracket (assumes the previous part is ok)
  2656. p = strchr(start,'{');
  2657. if( p == NULL )
  2658. {
  2659. ShowError("npc_skip_script: Missing left curly in file '%s', line'%d'.", filepath, strline(buffer,start-buffer));
  2660. return NULL;// can't continue
  2661. }
  2662. // skip everything
  2663. for( curly_count = 1; curly_count > 0 ; )
  2664. {
  2665. p = skip_space(p+1) ;
  2666. if( *p == '}' )
  2667. {// right curly
  2668. --curly_count;
  2669. }
  2670. else if( *p == '{' )
  2671. {// left curly
  2672. ++curly_count;
  2673. }
  2674. else if( *p == '"' )
  2675. {// string
  2676. for( ++p; *p != '"' ; ++p )
  2677. {
  2678. if( *p == '\\' && (unsigned char)p[-1] <= 0x7e )
  2679. ++p;// escape sequence (not part of a multibyte character)
  2680. else if( *p == '\0' )
  2681. {
  2682. script_error(buffer, filepath, 0, "Unexpected end of string.", p);
  2683. return NULL;// can't continue
  2684. }
  2685. else if( *p == '\n' )
  2686. {
  2687. script_error(buffer, filepath, 0, "Unexpected newline at string.", p);
  2688. return NULL;// can't continue
  2689. }
  2690. }
  2691. }
  2692. else if( *p == '\0' )
  2693. {// end of buffer
  2694. ShowError("Missing %d right curlys at file '%s', line '%d'.\n", curly_count, filepath, strline(buffer,p-buffer));
  2695. return NULL;// can't continue
  2696. }
  2697. }
  2698. return p+1;// return after the last '}'
  2699. }
  2700. /**
  2701. * Parses a npc script.
  2702. * Line definition :
  2703. * <map name>,<x>,<y>,<facing>%TAB%script%TAB%<NPC Name>%TAB%<sprite id>,{<code>}
  2704. * <map name>,<x>,<y>,<facing>%TAB%script%TAB%<NPC Name>%TAB%<sprite id>,<triggerX>,<triggerY>,{<code>} * @TODO missing cashshop line definition
  2705. * @param w1 : word 1 before tab (<from map name>,<x>,<y>,<facing>)
  2706. * @param w2 : word 2 before tab (script), keyword that sent us in this parsing
  2707. * @param w3 : word 3 before tab (<NPC Name>)
  2708. * @param w4 : word 4 before tab (<sprited id>,<code>)
  2709. * @param start : index to start parsing
  2710. * @param buffer : lines to parses
  2711. * @param filepath : filename with path wich we are parsing
  2712. * @return new index for next parsing
  2713. */
  2714. static const char* npc_parse_script(char* w1, char* w2, char* w3, char* w4, const char* start, const char* buffer, const char* filepath, bool runOnInit) {
  2715. int16 dir = 0;
  2716. short m, x, y, xs = 0, ys = 0; // [Valaris] thanks to fov
  2717. struct script_code *script;
  2718. int i;
  2719. const char* end;
  2720. const char* script_start;
  2721. struct npc_label_list* label_list;
  2722. int label_list_num;
  2723. struct npc_data* nd;
  2724. if( strcmp(w1, "-") == 0 )
  2725. {// floating npc
  2726. x = 0;
  2727. y = 0;
  2728. m = -1;
  2729. }
  2730. else
  2731. {// npc in a map
  2732. char mapname[MAP_NAME_LENGTH_EXT];
  2733. if( sscanf(w1, "%15[^,],%6hd,%6hd,%4hd", mapname, &x, &y, &dir) != 4 )
  2734. {
  2735. ShowError("npc_parse_script: Invalid placement format for a script in file '%s', line '%d'. Skipping the rest of file...\n * w1=%s\n * w2=%s\n * w3=%s\n * w4=%s\n", filepath, strline(buffer,start-buffer), w1, w2, w3, w4);
  2736. return NULL;// unknown format, don't continue
  2737. }
  2738. m = map_mapname2mapid(mapname);
  2739. }
  2740. script_start = strstr(start,",{");
  2741. end = strchr(start,'\n');
  2742. if( strstr(w4,",{") == NULL || script_start == NULL || (end != NULL && script_start > end) )
  2743. {
  2744. ShowError("npc_parse_script: Missing left curly ',{' in file '%s', line '%d'. Skipping the rest of the file.\n * w1=%s\n * w2=%s\n * w3=%s\n * w4=%s\n", filepath, strline(buffer,start-buffer), w1, w2, w3, w4);
  2745. return NULL;// can't continue
  2746. }
  2747. ++script_start;
  2748. end = npc_skip_script(script_start, buffer, filepath);
  2749. if( end == NULL )
  2750. return NULL;// (simple) parse error, don't continue
  2751. script = parse_script(script_start, filepath, strline(buffer,script_start-buffer), SCRIPT_USE_LABEL_DB);
  2752. label_list = NULL;
  2753. label_list_num = 0;
  2754. if( script )
  2755. {
  2756. DBMap* label_db = script_get_label_db();
  2757. label_db->foreach(label_db, npc_convertlabel_db, &label_list, &label_list_num, filepath);
  2758. db_clear(label_db); // not needed anymore, so clear the db
  2759. }
  2760. nd = npc_create_npc(m, x, y);
  2761. if( sscanf(w4, "%*[^,],%6hd,%6hd", &xs, &ys) == 2 )
  2762. {// OnTouch area defined
  2763. nd->u.scr.xs = xs;
  2764. nd->u.scr.ys = ys;
  2765. }
  2766. else
  2767. {// no OnTouch area
  2768. nd->u.scr.xs = -1;
  2769. nd->u.scr.ys = -1;
  2770. }
  2771. npc_parsename(nd, w3, start, buffer, filepath);
  2772. nd->class_ = m == -1 ? JT_FAKENPC : npc_parseview(w4, start, buffer, filepath);
  2773. nd->speed = 200;
  2774. nd->u.scr.script = script;
  2775. nd->u.scr.label_list = label_list;
  2776. nd->u.scr.label_list_num = label_list_num;
  2777. ++npc_script;
  2778. nd->bl.type = BL_NPC;
  2779. nd->subtype = NPCTYPE_SCRIPT;
  2780. if( m >= 0 )
  2781. {
  2782. map_addnpc(m, nd);
  2783. status_change_init(&nd->bl);
  2784. unit_dataset(&nd->bl);
  2785. nd->ud.dir = (uint8)dir;
  2786. npc_setcells(nd);
  2787. if(map_addblock(&nd->bl))
  2788. return NULL;
  2789. if( nd->class_ != JT_FAKENPC )
  2790. {
  2791. status_set_viewdata(&nd->bl, nd->class_);
  2792. if( map_getmapdata(nd->bl.m)->users )
  2793. clif_spawn(&nd->bl);
  2794. }
  2795. }
  2796. else
  2797. {
  2798. // we skip map_addnpc, but still add it to the list of ID's
  2799. map_addiddb(&nd->bl);
  2800. }
  2801. strdb_put(npcname_db, nd->exname, nd);
  2802. //-----------------------------------------
  2803. // Loop through labels to export them as necessary
  2804. for (i = 0; i < nd->u.scr.label_list_num; i++) {
  2805. if (npc_event_export(nd, i)) {
  2806. ShowWarning("npc_parse_script : duplicate event %s::%s (%s)\n",
  2807. nd->exname, nd->u.scr.label_list[i].name, filepath);
  2808. }
  2809. npc_timerevent_export(nd, i);
  2810. }
  2811. nd->u.scr.timerid = INVALID_TIMER;
  2812. if( runOnInit ) {
  2813. char evname[EVENT_NAME_LENGTH];
  2814. struct event_data *ev;
  2815. snprintf(evname, ARRAYLENGTH(evname), "%s::%s", nd->exname, script_config.init_event_name);
  2816. if( ( ev = (struct event_data*)strdb_get(ev_db, evname) ) ) {
  2817. //Execute OnInit
  2818. run_script(nd->u.scr.script,ev->pos,0,nd->bl.id);
  2819. }
  2820. }
  2821. return end;
  2822. }
  2823. /// Duplicate a warp, shop, cashshop or script. [Orcao]
  2824. /// warp: <map name>,<x>,<y>,<facing>%TAB%duplicate(<name of target>)%TAB%<NPC Name>%TAB%<spanx>,<spany>
  2825. /// shop/cashshop/npc: -%TAB%duplicate(<name of target>)%TAB%<NPC Name>%TAB%<sprite id>
  2826. /// shop/cashshop/npc: <map name>,<x>,<y>,<facing>%TAB%duplicate(<name of target>)%TAB%<NPC Name>%TAB%<sprite id>
  2827. /// npc: -%TAB%duplicate(<name of target>)%TAB%<NPC Name>%TAB%<sprite id>,<triggerX>,<triggerY>
  2828. /// npc: <map name>,<x>,<y>,<facing>%TAB%duplicate(<name of target>)%TAB%<NPC Name>%TAB%<sprite id>,<triggerX>,<triggerY>
  2829. const char* npc_parse_duplicate(char* w1, char* w2, char* w3, char* w4, const char* start, const char* buffer, const char* filepath)
  2830. {
  2831. short x, y, m, xs = -1, ys = -1;
  2832. int16 dir;
  2833. char srcname[128];
  2834. int i;
  2835. const char* end;
  2836. size_t length;
  2837. int src_id;
  2838. int type;
  2839. struct npc_data* nd;
  2840. struct npc_data* dnd;
  2841. end = strchr(start,'\n');
  2842. length = strlen(w2);
  2843. // get the npc being duplicated
  2844. if( w2[length-1] != ')' || length <= 11 || length-11 >= sizeof(srcname) )
  2845. {// does not match 'duplicate(%127s)', name is empty or too long
  2846. ShowError("npc_parse_script: bad duplicate name in file '%s', line '%d' : %s\n", filepath, strline(buffer,start-buffer), w2);
  2847. return end;// next line, try to continue
  2848. }
  2849. safestrncpy(srcname, w2+10, length-10);
  2850. dnd = npc_name2id(srcname);
  2851. if( dnd == NULL) {
  2852. ShowError("npc_parse_script: original npc not found for duplicate in file '%s', line '%d' : %s\n", filepath, strline(buffer,start-buffer), srcname);
  2853. return end;// next line, try to continue
  2854. }
  2855. src_id = dnd->src_id ? dnd->src_id : dnd->bl.id;
  2856. type = dnd->subtype;
  2857. // get placement
  2858. if ((type == NPCTYPE_SHOP || type == NPCTYPE_CASHSHOP || type == NPCTYPE_ITEMSHOP || type == NPCTYPE_POINTSHOP || type == NPCTYPE_SCRIPT || type == NPCTYPE_MARKETSHOP) && strcmp(w1, "-") == 0) {// floating shop/chashshop/itemshop/pointshop/script
  2859. x = y = dir = 0;
  2860. m = -1;
  2861. } else {
  2862. char mapname[MAP_NAME_LENGTH_EXT];
  2863. if( sscanf(w1, "%15[^,],%6hd,%6hd,%4hd", mapname, &x, &y, &dir) != 4 ) { // <map name>,<x>,<y>,<facing>
  2864. ShowError("npc_parse_duplicate: Invalid placement format for duplicate in file '%s', line '%d'. Skipping line...\n * w1=%s\n * w2=%s\n * w3=%s\n * w4=%s\n", filepath, strline(buffer,start-buffer), w1, w2, w3, w4);
  2865. return end;// next line, try to continue
  2866. }
  2867. m = map_mapname2mapid(mapname);
  2868. }
  2869. struct map_data *mapdata = map_getmapdata(m);
  2870. if( m != -1 && ( x < 0 || x >= mapdata->xs || y < 0 || y >= mapdata->ys ) ) {
  2871. ShowError("npc_parse_duplicate: coordinates %d/%d are out of bounds in map %s(%dx%d), in file '%s', line '%d'\n", x, y, mapdata->name, mapdata->xs, mapdata->ys,filepath,strline(buffer,start-buffer));
  2872. }
  2873. if( type == NPCTYPE_WARP && sscanf(w4, "%6hd,%6hd", &xs, &ys) == 2 );// <spanx>,<spany>
  2874. else if( type == NPCTYPE_SCRIPT && sscanf(w4, "%*[^,],%6hd,%6hd", &xs, &ys) == 2);// <sprite id>,<triggerX>,<triggerY>
  2875. else if( type == NPCTYPE_WARP ) {
  2876. ShowError("npc_parse_duplicate: Invalid span format for duplicate warp in file '%s', line '%d'. Skipping line...\n * w1=%s\n * w2=%s\n * w3=%s\n * w4=%s\n", filepath, strline(buffer,start-buffer), w1, w2, w3, w4);
  2877. return end;// next line, try to continue
  2878. }
  2879. nd = npc_create_npc(m, x, y);
  2880. npc_parsename(nd, w3, start, buffer, filepath);
  2881. nd->class_ = m == -1 ? JT_FAKENPC : npc_parseview(w4, start, buffer, filepath);
  2882. nd->speed = 200;
  2883. nd->src_id = src_id;
  2884. nd->bl.type = BL_NPC;
  2885. nd->subtype = (enum npc_subtype)type;
  2886. switch( type ) {
  2887. case NPCTYPE_SCRIPT:
  2888. ++npc_script;
  2889. nd->u.scr.xs = xs;
  2890. nd->u.scr.ys = ys;
  2891. nd->u.scr.script = dnd->u.scr.script;
  2892. nd->u.scr.label_list = dnd->u.scr.label_list;
  2893. nd->u.scr.label_list_num = dnd->u.scr.label_list_num;
  2894. break;
  2895. case NPCTYPE_SHOP:
  2896. case NPCTYPE_CASHSHOP:
  2897. case NPCTYPE_ITEMSHOP:
  2898. case NPCTYPE_POINTSHOP:
  2899. case NPCTYPE_MARKETSHOP:
  2900. ++npc_shop;
  2901. nd->u.shop.shop_item = dnd->u.shop.shop_item;
  2902. nd->u.shop.count = dnd->u.shop.count;
  2903. break;
  2904. case NPCTYPE_WARP:
  2905. ++npc_warp;
  2906. if( !battle_config.warp_point_debug )
  2907. nd->class_ = JT_WARPNPC;
  2908. else
  2909. nd->class_ = JT_GUILD_FLAG;
  2910. nd->u.warp.xs = xs;
  2911. nd->u.warp.ys = ys;
  2912. nd->u.warp.mapindex = dnd->u.warp.mapindex;
  2913. nd->u.warp.x = dnd->u.warp.x;
  2914. nd->u.warp.y = dnd->u.warp.y;
  2915. nd->trigger_on_hidden = dnd->trigger_on_hidden;
  2916. break;
  2917. }
  2918. //Add the npc to its location
  2919. if( m >= 0 ) {
  2920. map_addnpc(m, nd);
  2921. status_change_init(&nd->bl);
  2922. unit_dataset(&nd->bl);
  2923. nd->ud.dir = (uint8)dir;
  2924. npc_setcells(nd);
  2925. if(map_addblock(&nd->bl))
  2926. return end;
  2927. if( nd->class_ != JT_FAKENPC ) {
  2928. status_set_viewdata(&nd->bl, nd->class_);
  2929. if( map_getmapdata(nd->bl.m)->users )
  2930. clif_spawn(&nd->bl);
  2931. }
  2932. } else {
  2933. // we skip map_addnpc, but still add it to the list of ID's
  2934. map_addiddb(&nd->bl);
  2935. }
  2936. strdb_put(npcname_db, nd->exname, nd);
  2937. if( type != NPCTYPE_SCRIPT )
  2938. return end;
  2939. //-----------------------------------------
  2940. // Loop through labels to export them as necessary
  2941. for (i = 0; i < nd->u.scr.label_list_num; i++) {
  2942. if (npc_event_export(nd, i)) {
  2943. ShowWarning("npc_parse_duplicate : duplicate event %s::%s (%s)\n",
  2944. nd->exname, nd->u.scr.label_list[i].name, filepath);
  2945. }
  2946. npc_timerevent_export(nd, i);
  2947. }
  2948. if(!strcmp(filepath,"INSTANCING")) //Instance NPCs will use this for commands
  2949. nd->instance_id = mapdata->instance_id;
  2950. nd->u.scr.timerid = INVALID_TIMER;
  2951. return end;
  2952. }
  2953. int npc_duplicate4instance(struct npc_data *snd, int16 m) {
  2954. char newname[NPC_NAME_LENGTH+1];
  2955. struct map_data *mapdata = map_getmapdata(m);
  2956. if( mapdata->instance_id == 0 )
  2957. return 1;
  2958. snprintf(newname, ARRAYLENGTH(newname), "dup_%d_%d", mapdata->instance_id, snd->bl.id);
  2959. if( npc_name2id(newname) != NULL ) { // Name already in use
  2960. ShowError("npc_duplicate4instance: the npcname (%s) is already in use while trying to duplicate npc %s in instance %d.\n", newname, snd->exname, mapdata->instance_id);
  2961. return 1;
  2962. }
  2963. if( snd->subtype == NPCTYPE_WARP ) { // Adjust destination, if instanced
  2964. struct npc_data *wnd = NULL; // New NPC
  2965. struct instance_data *im = &instance_data[mapdata->instance_id];
  2966. int dm = map_mapindex2mapid(snd->u.warp.mapindex), imap = 0, i;
  2967. if( dm < 0 ) return 1;
  2968. for(i = 0; i < im->cnt_map; i++)
  2969. if(im->map[i]->m && map_mapname2mapid(map_getmapdata(im->map[i]->src_m)->name) == dm) {
  2970. imap = map_mapname2mapid(map_getmapdata(im->map[i]->m)->name);
  2971. break; // Instance map matches destination, update to instance map
  2972. }
  2973. if(!imap)
  2974. imap = map_mapname2mapid(map_getmapdata(dm)->name);
  2975. if( imap == -1 ) {
  2976. ShowError("npc_duplicate4instance: warp (%s) leading to instanced map (%s), but instance map is not attached to current instance.\n", map_mapid2mapname(dm), snd->exname);
  2977. return 1;
  2978. }
  2979. wnd = npc_create_npc(m, snd->bl.x, snd->bl.y);
  2980. safestrncpy(wnd->name, "", ARRAYLENGTH(wnd->name));
  2981. safestrncpy(wnd->exname, newname, ARRAYLENGTH(wnd->exname));
  2982. wnd->class_ = JT_WARPNPC;
  2983. wnd->speed = 200;
  2984. wnd->u.warp.mapindex = map_id2index(imap);
  2985. wnd->u.warp.x = snd->u.warp.x;
  2986. wnd->u.warp.y = snd->u.warp.y;
  2987. wnd->u.warp.xs = snd->u.warp.xs;
  2988. wnd->u.warp.ys = snd->u.warp.ys;
  2989. wnd->bl.type = BL_NPC;
  2990. wnd->subtype = NPCTYPE_WARP;
  2991. wnd->trigger_on_hidden = snd->trigger_on_hidden;
  2992. wnd->src_id = snd->src_id ? snd->src_id : snd->bl.id;
  2993. map_addnpc(m, wnd);
  2994. npc_setcells(wnd);
  2995. if(map_addblock(&wnd->bl))
  2996. return 1;
  2997. status_set_viewdata(&wnd->bl, wnd->class_);
  2998. status_change_init(&wnd->bl);
  2999. unit_dataset(&wnd->bl);
  3000. if( map_getmapdata(wnd->bl.m)->users )
  3001. clif_spawn(&wnd->bl);
  3002. strdb_put(npcname_db, wnd->exname, wnd);
  3003. } else {
  3004. static char w1[128], w2[128], w3[128], w4[128];
  3005. const char* stat_buf = "- call from instancing subsystem -\n";
  3006. snprintf(w1, sizeof(w1), "%s,%d,%d,%d", mapdata->name, snd->bl.x, snd->bl.y, snd->ud.dir);
  3007. snprintf(w2, sizeof(w2), "duplicate(%s)", snd->exname);
  3008. snprintf(w3, sizeof(w3), "%s::%s", snd->name, newname);
  3009. if( snd->u.scr.xs >= 0 && snd->u.scr.ys >= 0 )
  3010. snprintf(w4, sizeof(w4), "%d,%d,%d", snd->class_, snd->u.scr.xs, snd->u.scr.ys); // Touch Area
  3011. else
  3012. snprintf(w4, sizeof(w4), "%d", snd->class_);
  3013. npc_parse_duplicate(w1, w2, w3, w4, stat_buf, stat_buf, "INSTANCING");
  3014. }
  3015. return 0;
  3016. }
  3017. int npc_instanceinit(struct npc_data* nd)
  3018. {
  3019. struct event_data *ev;
  3020. char evname[EVENT_NAME_LENGTH];
  3021. snprintf(evname, ARRAYLENGTH(evname), "%s::%s", nd->exname, script_config.instance_init_event_name);
  3022. if( ( ev = (struct event_data*)strdb_get(ev_db, evname) ) )
  3023. run_script(nd->u.scr.script,ev->pos,0,nd->bl.id);
  3024. return 0;
  3025. }
  3026. int npc_instancedestroy(struct npc_data* nd)
  3027. {
  3028. struct event_data *ev;
  3029. char evname[EVENT_NAME_LENGTH];
  3030. snprintf(evname, ARRAYLENGTH(evname), "%s::%s", nd->exname, script_config.instance_destroy_event_name);
  3031. if( ( ev = (struct event_data*)strdb_get(ev_db, evname) ) )
  3032. run_script(nd->u.scr.script,ev->pos,0,nd->bl.id);
  3033. return 0;
  3034. }
  3035. #if PACKETVER >= 20131223
  3036. /**
  3037. * Saves persistent NPC Market Data into SQL
  3038. * @param exname NPC exname
  3039. * @param nameid Item ID
  3040. * @param qty Stock
  3041. **/
  3042. void npc_market_tosql(const char *exname, struct npc_item_list *list) {
  3043. SqlStmt* stmt = SqlStmt_Malloc(mmysql_handle);
  3044. if (SQL_ERROR == SqlStmt_Prepare(stmt, "REPLACE INTO `%s` (`name`,`nameid`,`price`,`amount`,`flag`) VALUES ('%s','%hu','%d','%hu','%" PRIu8 "')",
  3045. market_table, exname, list->nameid, list->value, list->qty, list->flag) ||
  3046. SQL_ERROR == SqlStmt_Execute(stmt))
  3047. SqlStmt_ShowDebug(stmt);
  3048. SqlStmt_Free(stmt);
  3049. }
  3050. /**
  3051. * Removes persistent NPC Market Data from SQL
  3052. * @param exname NPC exname
  3053. * @param nameid Item ID
  3054. * @param clear True: will removes all records related with the NPC
  3055. **/
  3056. void npc_market_delfromsql_(const char *exname, unsigned short nameid, bool clear) {
  3057. SqlStmt* stmt = SqlStmt_Malloc(mmysql_handle);
  3058. if (clear) {
  3059. if( SQL_ERROR == SqlStmt_Prepare(stmt, "DELETE FROM `%s` WHERE `name`='%s'", market_table, exname) ||
  3060. SQL_ERROR == SqlStmt_Execute(stmt))
  3061. SqlStmt_ShowDebug(stmt);
  3062. } else {
  3063. if (SQL_ERROR == SqlStmt_Prepare(stmt, "DELETE FROM `%s` WHERE `name`='%s' AND `nameid`='%d' LIMIT 1", market_table, exname, nameid) ||
  3064. SQL_ERROR == SqlStmt_Execute(stmt))
  3065. SqlStmt_ShowDebug(stmt);
  3066. }
  3067. SqlStmt_Free(stmt);
  3068. }
  3069. /**
  3070. * Check NPC Market Shop for each entry
  3071. **/
  3072. static int npc_market_checkall_sub(DBKey key, DBData *data, va_list ap) {
  3073. struct s_npc_market *market = (struct s_npc_market *)db_data2ptr(data);
  3074. struct npc_data *nd = NULL;
  3075. uint16 i;
  3076. if (!market)
  3077. return 1;
  3078. nd = npc_name2id(market->exname);
  3079. if (!nd) {
  3080. ShowInfo("npc_market_checkall_sub: NPC '%s' not found, removing...\n", market->exname);
  3081. npc_market_clearfromsql(market->exname);
  3082. return 1;
  3083. }
  3084. else if (nd->subtype != NPCTYPE_MARKETSHOP || !nd->u.shop.shop_item || !nd->u.shop.count ) {
  3085. ShowError("npc_market_checkall_sub: NPC '%s' is not proper for market, removing...\n", nd->exname);
  3086. npc_market_clearfromsql(nd->exname);
  3087. return 1;
  3088. }
  3089. if (!market->count || !market->list)
  3090. return 1;
  3091. for (i = 0; i < market->count; i++) {
  3092. struct npc_item_list *list = &market->list[i];
  3093. uint16 j;
  3094. if (!list->nameid || !itemdb_exists(list->nameid)) {
  3095. ShowError("npc_market_checkall_sub: NPC '%s' sells invalid item '%hu', deleting...\n", nd->exname, list->nameid);
  3096. npc_market_delfromsql(nd->exname, list->nameid);
  3097. continue;
  3098. }
  3099. // Reloading stock from `market` table
  3100. ARR_FIND(0, nd->u.shop.count, j, nd->u.shop.shop_item[j].nameid == list->nameid);
  3101. if (j != nd->u.shop.count) {
  3102. nd->u.shop.shop_item[j].value = list->value;
  3103. nd->u.shop.shop_item[j].qty = list->qty;
  3104. nd->u.shop.shop_item[j].flag = list->flag;
  3105. npc_market_tosql(nd->exname, &nd->u.shop.shop_item[j]);
  3106. continue;
  3107. }
  3108. if (list->flag&1) { // Item added by npcshopitem/npcshopadditem, add new entry
  3109. RECREATE(nd->u.shop.shop_item, struct npc_item_list, nd->u.shop.count+1);
  3110. nd->u.shop.shop_item[j].nameid = list->nameid;
  3111. nd->u.shop.shop_item[j].value = list->value;
  3112. nd->u.shop.shop_item[j].qty = list->qty;
  3113. nd->u.shop.shop_item[j].flag = list->flag;
  3114. nd->u.shop.count++;
  3115. npc_market_tosql(nd->exname, &nd->u.shop.shop_item[j]);
  3116. }
  3117. else { // Removing "out-of-date" entry
  3118. ShowError("npc_market_checkall_sub: NPC '%s' does not sell item %hu (qty %hu), deleting...\n", nd->exname, list->nameid, list->qty);
  3119. npc_market_delfromsql(nd->exname, list->nameid);
  3120. }
  3121. }
  3122. return 0;
  3123. }
  3124. /**
  3125. * Clear NPC market single entry
  3126. **/
  3127. static int npc_market_free(DBKey key, DBData *data, va_list ap) {
  3128. struct s_npc_market *market = (struct s_npc_market *)db_data2ptr(data);
  3129. if (!market)
  3130. return 0;
  3131. if (market->list) {
  3132. aFree(market->list);
  3133. market->list = NULL;
  3134. }
  3135. aFree(market);
  3136. return 1;
  3137. }
  3138. /**
  3139. * Check all existing NPC Market Shop after first loading map-server or after reloading scripts.
  3140. * Overwrite stocks from NPC by using stock entries from `market` table.
  3141. **/
  3142. static void npc_market_checkall(void) {
  3143. if (!db_size(NPCMarketDB))
  3144. return;
  3145. else {
  3146. ShowInfo("Checking '" CL_WHITE "%d" CL_RESET "' NPC Markets...\n", db_size(NPCMarketDB));
  3147. NPCMarketDB->foreach(NPCMarketDB, npc_market_checkall_sub);
  3148. ShowStatus("Done checking '" CL_WHITE "%d" CL_RESET "' NPC Markets.\n", db_size(NPCMarketDB));
  3149. NPCMarketDB->clear(NPCMarketDB, npc_market_free);
  3150. }
  3151. }
  3152. /**
  3153. * Loads persistent NPC Market Data from SQL, use the records after NPCs init'd to reuse the stock values.
  3154. **/
  3155. static void npc_market_fromsql(void) {
  3156. uint32 count = 0;
  3157. if (SQL_ERROR == Sql_Query(mmysql_handle, "SELECT `name`,`nameid`,`price`,`amount`,`flag` FROM `%s` ORDER BY `name`", market_table)) {
  3158. Sql_ShowDebug(mmysql_handle);
  3159. return;
  3160. }
  3161. while (SQL_SUCCESS == Sql_NextRow(mmysql_handle)) {
  3162. char *data;
  3163. struct s_npc_market *market;
  3164. struct npc_item_list list;
  3165. Sql_GetData(mmysql_handle, 0, &data, NULL);
  3166. if (!(market = (struct s_npc_market *)strdb_get(NPCMarketDB,data))) {
  3167. CREATE(market, struct s_npc_market, 1);
  3168. market->count = 0;
  3169. safestrncpy(market->exname, data, NPC_NAME_LENGTH);
  3170. strdb_put(NPCMarketDB, market->exname, market);
  3171. }
  3172. Sql_GetData(mmysql_handle, 1, &data, NULL); list.nameid = atoi(data);
  3173. Sql_GetData(mmysql_handle, 2, &data, NULL); list.value = atoi(data);
  3174. Sql_GetData(mmysql_handle, 3, &data, NULL); list.qty = atoi(data);
  3175. Sql_GetData(mmysql_handle, 4, &data, NULL); list.flag = atoi(data);
  3176. RECREATE(market->list, struct npc_item_list, market->count+1);
  3177. market->list[market->count++] = list;
  3178. count++;
  3179. }
  3180. Sql_FreeResult(mmysql_handle);
  3181. ShowStatus("Done loading '" CL_WHITE "%d" CL_RESET "' entries for '" CL_WHITE "%d" CL_RESET "' NPC Markets from '" CL_WHITE "%s" CL_RESET "' table.\n", count, db_size(NPCMarketDB), market_table);
  3182. }
  3183. #endif
  3184. //Set mapcell CELL_NPC to trigger event later
  3185. void npc_setcells(struct npc_data* nd)
  3186. {
  3187. int16 m = nd->bl.m, x = nd->bl.x, y = nd->bl.y, xs, ys;
  3188. int i,j;
  3189. switch(nd->subtype)
  3190. {
  3191. case NPCTYPE_WARP:
  3192. xs = nd->u.warp.xs;
  3193. ys = nd->u.warp.ys;
  3194. break;
  3195. case NPCTYPE_SCRIPT:
  3196. xs = nd->u.scr.xs;
  3197. ys = nd->u.scr.ys;
  3198. break;
  3199. default:
  3200. return; // Other types doesn't have touch area
  3201. }
  3202. if (m < 0 || xs < 0 || ys < 0) //invalid range or map
  3203. return;
  3204. for (i = y-ys; i <= y+ys; i++) {
  3205. for (j = x-xs; j <= x+xs; j++) {
  3206. if (map_getcell(m, j, i, CELL_CHKNOPASS))
  3207. continue;
  3208. map_setcell(m, j, i, CELL_NPC, true);
  3209. }
  3210. }
  3211. }
  3212. int npc_unsetcells_sub(struct block_list* bl, va_list ap)
  3213. {
  3214. struct npc_data *nd = (struct npc_data*)bl;
  3215. int id = va_arg(ap,int);
  3216. if (nd->bl.id == id) return 0;
  3217. npc_setcells(nd);
  3218. return 1;
  3219. }
  3220. void npc_unsetcells(struct npc_data* nd)
  3221. {
  3222. int16 m = nd->bl.m, x = nd->bl.x, y = nd->bl.y, xs, ys;
  3223. int i,j, x0, x1, y0, y1;
  3224. if (nd->subtype == NPCTYPE_WARP) {
  3225. xs = nd->u.warp.xs;
  3226. ys = nd->u.warp.ys;
  3227. } else {
  3228. xs = nd->u.scr.xs;
  3229. ys = nd->u.scr.ys;
  3230. }
  3231. if (m < 0 || xs < 0 || ys < 0)
  3232. return;
  3233. struct map_data *mapdata = map_getmapdata(m);
  3234. //Locate max range on which we can locate npc cells
  3235. //FIXME: does this really do what it's supposed to do? [ultramage]
  3236. for(x0 = x-xs; x0 > 0 && map_getcell(m, x0, y, CELL_CHKNPC); x0--);
  3237. for(x1 = x+xs; x1 < mapdata->xs-1 && map_getcell(m, x1, y, CELL_CHKNPC); x1++);
  3238. for(y0 = y-ys; y0 > 0 && map_getcell(m, x, y0, CELL_CHKNPC); y0--);
  3239. for(y1 = y+ys; y1 < mapdata->ys-1 && map_getcell(m, x, y1, CELL_CHKNPC); y1++);
  3240. //Erase this npc's cells
  3241. for (i = y-ys; i <= y+ys; i++)
  3242. for (j = x-xs; j <= x+xs; j++)
  3243. map_setcell(m, j, i, CELL_NPC, false);
  3244. //Re-deploy NPC cells for other nearby npcs.
  3245. map_foreachinallarea( npc_unsetcells_sub, m, x0, y0, x1, y1, BL_NPC, nd->bl.id );
  3246. }
  3247. bool npc_movenpc(struct npc_data* nd, int16 x, int16 y)
  3248. {
  3249. if (nd->bl.m < 0 || nd->bl.prev == NULL)
  3250. return false; //Not on a map.
  3251. struct map_data *mapdata = map_getmapdata(nd->bl.m);
  3252. x = cap_value(x, 0, mapdata->xs-1);
  3253. y = cap_value(y, 0, mapdata->ys-1);
  3254. map_foreachinallrange(clif_outsight, &nd->bl, AREA_SIZE, BL_PC, &nd->bl);
  3255. map_moveblock(&nd->bl, x, y, gettick());
  3256. map_foreachinallrange(clif_insight, &nd->bl, AREA_SIZE, BL_PC, &nd->bl);
  3257. return true;
  3258. }
  3259. /// Changes the display name of the npc.
  3260. ///
  3261. /// @param nd Target npc
  3262. /// @param newname New display name
  3263. void npc_setdisplayname(struct npc_data* nd, const char* newname)
  3264. {
  3265. nullpo_retv(nd);
  3266. safestrncpy(nd->name, newname, sizeof(nd->name));
  3267. if( map_getmapdata(nd->bl.m)->users )
  3268. clif_name_area(&nd->bl);
  3269. }
  3270. /// Changes the display class of the npc.
  3271. ///
  3272. /// @param nd Target npc
  3273. /// @param class_ New display class
  3274. void npc_setclass(struct npc_data* nd, short class_)
  3275. {
  3276. nullpo_retv(nd);
  3277. if( nd->class_ == class_ )
  3278. return;
  3279. nd->class_ = class_;
  3280. status_set_viewdata(&nd->bl, class_);
  3281. unit_refresh(&nd->bl);
  3282. }
  3283. // @commands (script based)
  3284. int npc_do_atcmd_event(struct map_session_data* sd, const char* command, const char* message, const char* eventname)
  3285. {
  3286. struct event_data* ev = (struct event_data*)strdb_get(ev_db, eventname);
  3287. struct npc_data *nd;
  3288. struct script_state *st;
  3289. int i = 0, j = 0, k = 0;
  3290. char *temp;
  3291. nullpo_ret(sd);
  3292. if( ev == NULL || (nd = ev->nd) == NULL ) {
  3293. ShowError("npc_event: event not found [%s]\n", eventname);
  3294. return 0;
  3295. }
  3296. if( sd->npc_id != 0 ) { // Enqueue the event trigger.
  3297. int l;
  3298. ARR_FIND( 0, MAX_EVENTQUEUE, l, sd->eventqueue[l][0] == '\0' );
  3299. if( l < MAX_EVENTQUEUE ) {
  3300. safestrncpy(sd->eventqueue[l],eventname,EVENT_NAME_LENGTH); //Event enqueued.
  3301. return 0;
  3302. }
  3303. ShowWarning("npc_event: player's event queue is full, can't add event '%s' !\n", eventname);
  3304. return 1;
  3305. }
  3306. if( ev->nd->sc.option&OPTION_INVISIBLE ) { // Disabled npc, shouldn't trigger event.
  3307. npc_event_dequeue(sd);
  3308. return 2;
  3309. }
  3310. st = script_alloc_state(ev->nd->u.scr.script, ev->pos, sd->bl.id, ev->nd->bl.id);
  3311. setd_sub_str( st, NULL, ".@atcmd_command$", 0, command, NULL );
  3312. // split atcmd parameters based on spaces
  3313. temp = (char*)aMalloc(strlen(message) + 1);
  3314. for( i = 0; i < ( strlen( message ) + 1 ) && k < 127; i ++ ) {
  3315. if( message[i] == ' ' || message[i] == '\0' ) {
  3316. if( message[ ( i - 1 ) ] == ' ' ) {
  3317. continue; // To prevent "@atcmd [space][space]" and .@atcmd_numparameters return 1 without any parameter.
  3318. }
  3319. temp[k] = '\0';
  3320. k = 0;
  3321. if( temp[0] != '\0' ) {
  3322. setd_sub_str( st, NULL, ".@atcmd_parameters$", j++, temp, NULL );
  3323. }
  3324. } else {
  3325. temp[k] = message[i];
  3326. k++;
  3327. }
  3328. }
  3329. setd_sub_num( st, NULL, ".@atcmd_numparameters", 0, j, NULL );
  3330. aFree(temp);
  3331. run_script_main(st);
  3332. return 0;
  3333. }
  3334. /// Parses a function.
  3335. /// function%TAB%script%TAB%<function name>%TAB%{<code>}
  3336. static const char* npc_parse_function(char* w1, char* w2, char* w3, char* w4, const char* start, const char* buffer, const char* filepath)
  3337. {
  3338. DBMap* func_db;
  3339. DBData old_data;
  3340. struct script_code *script;
  3341. const char* end;
  3342. const char* script_start;
  3343. script_start = strstr(start,"\t{");
  3344. end = strchr(start,'\n');
  3345. if (*w4 != '{' || script_start == NULL || (end != NULL && script_start > end)) {
  3346. ShowError("npc_parse_function: Missing left curly '%%TAB%%{' in file '%s', line '%d'. Skipping the rest of the file.\n * w1=%s\n * w2=%s\n * w3=%s\n * w4=%s\n", filepath, strline(buffer,start-buffer), w1, w2, w3, w4);
  3347. return NULL;// can't continue
  3348. }
  3349. ++script_start;
  3350. end = npc_skip_script(script_start,buffer,filepath);
  3351. if( end == NULL )
  3352. return NULL;// (simple) parse error, don't continue
  3353. script = parse_script(script_start, filepath, strline(buffer,start-buffer), SCRIPT_RETURN_EMPTY_SCRIPT);
  3354. if( script == NULL )// parse error, continue
  3355. return end;
  3356. func_db = script_get_userfunc_db();
  3357. if (func_db->put(func_db, db_str2key(w3), db_ptr2data(script), &old_data)) {
  3358. struct script_code *oldscript = (struct script_code*)db_data2ptr(&old_data);
  3359. ShowInfo("npc_parse_function: Overwriting user function [%s] (%s:%d)\n", w3, filepath, strline(buffer,start-buffer));
  3360. script_stop_scriptinstances(oldscript);
  3361. script_free_vars(oldscript->local.vars);
  3362. aFree(oldscript->script_buf);
  3363. aFree(oldscript);
  3364. }
  3365. return end;
  3366. }
  3367. /*==========================================
  3368. * Parse Mob 1 - Parse mob list into each map
  3369. * Parse Mob 2 - Actually Spawns Mob
  3370. * [Wizputer]
  3371. *------------------------------------------*/
  3372. void npc_parse_mob2(struct spawn_data* mob)
  3373. {
  3374. int i;
  3375. for( i = mob->active; i < mob->num; ++i )
  3376. {
  3377. struct mob_data* md = mob_spawn_dataset(mob);
  3378. md->spawn = mob;
  3379. md->spawn->active++;
  3380. mob_spawn(md);
  3381. }
  3382. }
  3383. static const char* npc_parse_mob(char* w1, char* w2, char* w3, char* w4, const char* start, const char* buffer, const char* filepath)
  3384. {
  3385. int num, mob_id, mob_lv = -1, size = -1, w1count;
  3386. short m, x = 0, y = 0, xs = -1, ys = -1;
  3387. char mapname[MAP_NAME_LENGTH_EXT], mobname[NAME_LENGTH];
  3388. struct spawn_data mob, *data;
  3389. int ai = AI_NONE; // mob_ai
  3390. memset(&mob, 0, sizeof(struct spawn_data));
  3391. mob.state.boss = !strcmpi(w2,"boss_monster");
  3392. // w1=<map name>{,<x>,<y>,<xs>{,<ys>}}
  3393. // w3=<mob name>{,<mob level>}
  3394. // w4=<mob id>,<amount>{,<delay1>{,<delay2>{,<event>{,<mob size>{,<mob ai>}}}}}
  3395. if( ( w1count = sscanf(w1, "%15[^,],%6hd,%6hd,%6hd,%6hd", mapname, &x, &y, &xs, &ys) ) < 1
  3396. || sscanf(w3, "%23[^,],%11d", mobname, &mob_lv) < 1
  3397. || sscanf(w4, "%11d,%11d,%11u,%11u,%77[^,],%11d,%11d[^\t\r\n]", &mob_id, &num, &mob.delay1, &mob.delay2, mob.eventname, &size, &ai) < 2 )
  3398. {
  3399. ShowError("npc_parse_mob: Invalid mob definition in file '%s', line '%d'.\n * w1=%s\n * w2=%s\n * w3=%s\n * w4=%s\n", filepath, strline(buffer,start-buffer), w1, w2, w3, w4);
  3400. return strchr(start,'\n');// skip and continue
  3401. }
  3402. if( mapindex_name2id(mapname) == 0 )
  3403. {
  3404. ShowError("npc_parse_mob: Unknown map '%s' in file '%s', line '%d'.\n", mapname, filepath, strline(buffer,start-buffer));
  3405. return strchr(start,'\n');// skip and continue
  3406. }
  3407. m = map_mapname2mapid(mapname);
  3408. if( m < 0 )//Not loaded on this map-server instance.
  3409. return strchr(start,'\n');// skip and continue
  3410. mob.m = (unsigned short)m;
  3411. struct map_data *mapdata = map_getmapdata(m);
  3412. if( x < 0 || x >= mapdata->xs || y < 0 || y >= mapdata->ys )
  3413. {
  3414. ShowError("npc_parse_mob: Spawn coordinates out of range: %s (%d,%d), map size is (%d,%d) - %s %s (file '%s', line '%d').\n", mapdata->name, x, y, (mapdata->xs-1), (mapdata->ys-1), w1, w3, filepath, strline(buffer,start-buffer));
  3415. return strchr(start,'\n');// skip and continue
  3416. }
  3417. // check monster ID if exists!
  3418. if( mobdb_checkid(mob_id) == 0 )
  3419. {
  3420. ShowError("npc_parse_mob: Unknown mob ID %d (file '%s', line '%d').\n", mob_id, filepath, strline(buffer,start-buffer));
  3421. return strchr(start,'\n');// skip and continue
  3422. }
  3423. if( num < 1 || num > 1000 )
  3424. {
  3425. ShowError("npc_parse_mob: Invalid number of monsters %d, must be inside the range [1,1000] (file '%s', line '%d').\n", num, filepath, strline(buffer,start-buffer));
  3426. return strchr(start,'\n');// skip and continue
  3427. }
  3428. if( mob.state.size > SZ_BIG && size != -1 )
  3429. {
  3430. ShowError("npc_parse_mob: Invalid size number %d for mob ID %d (file '%s', line '%d').\n", mob.state.size, mob_id, filepath, strline(buffer, start - buffer));
  3431. return strchr(start, '\n');
  3432. }
  3433. if( (mob.state.ai < AI_NONE || mob.state.ai >= AI_MAX) && ai != -1 )
  3434. {
  3435. ShowError("npc_parse_mob: Invalid ai %d for mob ID %d (file '%s', line '%d').\n", mob.state.ai, mob_id, filepath, strline(buffer, start - buffer));
  3436. return strchr(start, '\n');
  3437. }
  3438. if( (mob_lv == 0 || mob_lv > MAX_LEVEL) && mob_lv != -1 )
  3439. {
  3440. ShowError("npc_parse_mob: Invalid level %d for mob ID %d (file '%s', line '%d').\n", mob_lv, mob_id, filepath, strline(buffer, start - buffer));
  3441. return strchr(start, '\n');
  3442. }
  3443. mob.num = (unsigned short)num;
  3444. mob.active = 0;
  3445. mob.id = (short) mob_id;
  3446. mob.x = (unsigned short)x;
  3447. mob.y = (unsigned short)y;
  3448. mob.xs = (signed short)xs;
  3449. mob.ys = (signed short)ys;
  3450. if (mob_lv > 0 && mob_lv <= MAX_LEVEL)
  3451. mob.level = mob_lv;
  3452. if (size > SZ_SMALL && size <= SZ_BIG)
  3453. mob.state.size = size;
  3454. if (ai > AI_NONE && ai <= AI_MAX)
  3455. mob.state.ai = static_cast<enum mob_ai>(ai);
  3456. if (mob.xs < 0) {
  3457. if (w1count > 3) {
  3458. ShowWarning("npc_parse_mob: Negative x-span %hd for mob ID %d (file '%s', line '%d').\n", mob.xs, mob_id, filepath, strline(buffer, start - buffer));
  3459. }
  3460. mob.xs = 0;
  3461. }
  3462. if (mob.ys < 0) {
  3463. if (w1count > 4) {
  3464. ShowWarning("npc_parse_mob: Negative y-span %hd for mob ID %d (file '%s', line '%d').\n", mob.ys, mob_id, filepath, strline(buffer, start - buffer));
  3465. }
  3466. mob.ys = 0;
  3467. }
  3468. if (mob.num > 1 && battle_config.mob_count_rate != 100) {
  3469. if ((mob.num = mob.num * battle_config.mob_count_rate / 100) < 1)
  3470. mob.num = 1;
  3471. }
  3472. if (battle_config.force_random_spawn || (mob.x == 0 && mob.y == 0))
  3473. { //Force a random spawn anywhere on the map.
  3474. mob.x = mob.y = 0;
  3475. mob.xs = mob.ys = -1;
  3476. }
  3477. if(mob.delay1>0xfffffff || mob.delay2>0xfffffff) {
  3478. ShowError("npc_parse_mob: Invalid spawn delays %u %u (file '%s', line '%d').\n", mob.delay1, mob.delay2, filepath, strline(buffer,start-buffer));
  3479. return strchr(start,'\n');// skip and continue
  3480. }
  3481. //Use db names instead of the spawn file ones.
  3482. if(battle_config.override_mob_names==1)
  3483. strcpy(mob.name,"--en--");
  3484. else if (battle_config.override_mob_names==2)
  3485. strcpy(mob.name,"--ja--");
  3486. else
  3487. safestrncpy(mob.name, mobname, sizeof(mob.name));
  3488. //Verify dataset.
  3489. if( !mob_parse_dataset(&mob) )
  3490. {
  3491. ShowError("npc_parse_mob: Invalid dataset for monster ID %d (file '%s', line '%d').\n", mob_id, filepath, strline(buffer,start-buffer));
  3492. return strchr(start,'\n');// skip and continue
  3493. }
  3494. //Update mob spawn lookup database
  3495. struct spawn_info spawn = { mapdata->index, mob.num };
  3496. mob_add_spawn(mob_id, spawn);
  3497. //Now that all has been validated. We allocate the actual memory that the re-spawn data will use.
  3498. data = (struct spawn_data*)aMalloc(sizeof(struct spawn_data));
  3499. memcpy(data, &mob, sizeof(struct spawn_data));
  3500. // spawn / cache the new mobs
  3501. if( battle_config.dynamic_mobs && map_addmobtolist(data->m, data) >= 0 )
  3502. {
  3503. data->state.dynamic = true;
  3504. npc_cache_mob += data->num;
  3505. // check if target map has players
  3506. // (usually shouldn't occur when map server is just starting,
  3507. // but not the case when we do @reloadscript
  3508. if( map_getmapdata(data->m)->users > 0 )
  3509. npc_parse_mob2(data);
  3510. }
  3511. else
  3512. {
  3513. data->state.dynamic = false;
  3514. npc_parse_mob2(data);
  3515. npc_delay_mob += data->num;
  3516. }
  3517. npc_mob++;
  3518. return strchr(start,'\n');// continue
  3519. }
  3520. /*==========================================
  3521. * Set or disable mapflag on map
  3522. * eg : bat_c01 mapflag battleground 2
  3523. * also chking if mapflag conflict with another
  3524. *------------------------------------------*/
  3525. static const char* npc_parse_mapflag(char* w1, char* w2, char* w3, char* w4, const char* start, const char* buffer, const char* filepath)
  3526. {
  3527. int16 m;
  3528. char mapname[MAP_NAME_LENGTH_EXT];
  3529. bool state = true;
  3530. enum e_mapflag mapflag;
  3531. // w1=<mapname>
  3532. if (sscanf(w1, "%15[^,]", mapname) != 1) {
  3533. ShowError("npc_parse_mapflag: Invalid mapflag definition in file '%s', line '%d'.\n * w1=%s\n * w2=%s\n * w3=%s\n * w4=%s\n", filepath, strline(buffer,start-buffer), w1, w2, w3, w4);
  3534. return strchr(start,'\n');// skip and continue
  3535. }
  3536. m = map_mapname2mapid(mapname);
  3537. if (m < 0) {
  3538. ShowWarning("npc_parse_mapflag: Unknown map '%s' in file '%s', line '%d'.\n * w1=%s\n * w2=%s\n * w3=%s\n * w4=%s\n", mapname, filepath, strline(buffer,start-buffer), w1, w2, w3, w4);
  3539. return strchr(start,'\n');// skip and continue
  3540. }
  3541. if (w4 && !strcmpi(w4, "off"))
  3542. state = false; //Disable mapflag rather than enable it. [Skotlex]
  3543. mapflag = map_getmapflag_by_name(w3);
  3544. switch( mapflag ){
  3545. case MF_INVALID:
  3546. ShowError("npc_parse_mapflag: unrecognized mapflag '%s' (file '%s', line '%d').\n", w3, filepath, strline(buffer,start-buffer));
  3547. break;
  3548. case MF_NOSAVE: {
  3549. char savemap[MAP_NAME_LENGTH_EXT];
  3550. union u_mapflag_args args = {};
  3551. if (state && !strcmpi(w4, "SavePoint")) {
  3552. args.nosave.map = 0;
  3553. args.nosave.x = -1;
  3554. args.nosave.y = -1;
  3555. } else if (state && sscanf(w4, "%15[^,],%6hd,%6hd", savemap, &args.nosave.x, &args.nosave.y) == 3) {
  3556. args.nosave.map = mapindex_name2id(savemap);
  3557. if (!args.nosave.map) {
  3558. ShowWarning("npc_parse_mapflag: Specified save point map '%s' for mapflag 'nosave' not found (file '%s', line '%d'), using 'SavePoint'.\n * w1=%s\n * w2=%s\n * w3=%s\n * w4=%s\n", savemap, filepath, strline(buffer,start-buffer), w1, w2, w3, w4);
  3559. args.nosave.x = -1;
  3560. args.nosave.y = -1;
  3561. }
  3562. }
  3563. map_setmapflag_sub(m, MF_NOSAVE, state, &args);
  3564. break;
  3565. }
  3566. case MF_PVP_NIGHTMAREDROP: {
  3567. char drop_arg1[16], drop_arg2[16];
  3568. union u_mapflag_args args = {};
  3569. if (sscanf(w4, "%15[^,],%15[^,],%11d", drop_arg1, drop_arg2, &args.nightmaredrop.drop_per) == 3) {
  3570. if (!strcmpi(drop_arg1, "random"))
  3571. args.nightmaredrop.drop_id = -1;
  3572. else if (itemdb_exists((args.nightmaredrop.drop_id = atoi(drop_arg1))) == NULL) {
  3573. args.nightmaredrop.drop_id = 0;
  3574. ShowWarning("npc_parse_mapflag: Invalid item ID '%d' supplied for mapflag 'pvp_nightmaredrop' (file '%s', line '%d'), removing.\n * w1=%s\n * w2=%s\n * w3=%s\n * w4=%s\n", args.nightmaredrop.drop_id, filepath, strline(buffer, start - buffer), w1, w2, w3, w4);
  3575. break;
  3576. }
  3577. if (!strcmpi(drop_arg2, "inventory"))
  3578. args.nightmaredrop.drop_type = NMDT_INVENTORY;
  3579. else if (!strcmpi(drop_arg2, "equip"))
  3580. args.nightmaredrop.drop_type = NMDT_EQUIP;
  3581. else if (!strcmpi(drop_arg2, "all"))
  3582. args.nightmaredrop.drop_type = NMDT_ALL;
  3583. if (args.nightmaredrop.drop_id != 0)
  3584. map_setmapflag_sub(m, MF_PVP_NIGHTMAREDROP, true, &args);
  3585. } else if (!state)
  3586. map_setmapflag(m, MF_PVP_NIGHTMAREDROP, false);
  3587. break;
  3588. }
  3589. case MF_BATTLEGROUND:
  3590. if (state) {
  3591. union u_mapflag_args args = {};
  3592. if (sscanf(w4, "%11d", &args.flag_val) < 1)
  3593. args.flag_val = 1; // Default value
  3594. map_setmapflag_sub(m, MF_BATTLEGROUND, true, &args);
  3595. } else
  3596. map_setmapflag(m, MF_BATTLEGROUND, false);
  3597. break;
  3598. case MF_NOCOMMAND:
  3599. if (state) {
  3600. union u_mapflag_args args = {};
  3601. if (sscanf(w4, "%11d", &args.flag_val) < 1)
  3602. args.flag_val = 100; // No level specified, block everyone.
  3603. map_setmapflag_sub(m, MF_NOCOMMAND, true, &args);
  3604. } else
  3605. map_setmapflag(m, MF_NOCOMMAND, false);
  3606. break;
  3607. case MF_RESTRICTED:
  3608. if (state) {
  3609. union u_mapflag_args args = {};
  3610. if (sscanf(w4, "%11d", &args.flag_val) == 1)
  3611. map_setmapflag_sub(m, MF_RESTRICTED, true, &args);
  3612. else // Could not be read, no value defined; don't remove as other restrictions may be set on the map
  3613. ShowWarning("npc_parse_mapflag: Zone value not set for the restricted mapflag! Skipped flag from %s (file '%s', line '%d').\n", map_mapid2mapname(m), filepath, strline(buffer,start-buffer));
  3614. } else
  3615. map_setmapflag(m, MF_RESTRICTED, false);
  3616. break;
  3617. case MF_JEXP:
  3618. case MF_BEXP: {
  3619. union u_mapflag_args args = {};
  3620. if (sscanf(w4, "%11d", &args.flag_val) < 1)
  3621. args.flag_val = 0;
  3622. map_setmapflag_sub(m, mapflag, state, &args);
  3623. }
  3624. break;
  3625. case MF_SKILL_DAMAGE: {
  3626. char skill_name[SKILL_NAME_LENGTH];
  3627. char caster_constant[NAME_LENGTH];
  3628. union u_mapflag_args args = {};
  3629. memset(skill_name, 0, sizeof(skill_name));
  3630. if (!state)
  3631. map_setmapflag_sub(m, MF_SKILL_DAMAGE, false, &args);
  3632. else {
  3633. if (sscanf(w4, "%30[^,],%23[^,],%11d,%11d,%11d,%11d[^\n]", skill_name, caster_constant, &args.skill_damage.rate[SKILLDMG_PC], &args.skill_damage.rate[SKILLDMG_MOB], &args.skill_damage.rate[SKILLDMG_BOSS], &args.skill_damage.rate[SKILLDMG_OTHER]) >= 3) {
  3634. if (ISDIGIT(caster_constant[0]))
  3635. args.skill_damage.caster = atoi(caster_constant);
  3636. else {
  3637. int64 val_tmp;
  3638. if (!script_get_constant(caster_constant, &val_tmp)) {
  3639. ShowError( "npc_parse_mapflag: Unknown constant '%s'. Skipping (file '%s', line '%d').\n", caster_constant, filepath, strline(buffer, start - buffer) );
  3640. break;
  3641. }
  3642. args.skill_damage.caster = static_cast<uint16>(val_tmp);
  3643. }
  3644. if (args.skill_damage.caster == 0)
  3645. args.skill_damage.caster = BL_ALL;
  3646. for (int i = SKILLDMG_PC; i < SKILLDMG_MAX; i++)
  3647. args.skill_damage.rate[i] = cap_value(args.skill_damage.rate[i], -100, 100000);
  3648. trim(skill_name);
  3649. if (strcmp(skill_name, "all") == 0) // Adjust damage for all skills
  3650. map_setmapflag_sub(m, MF_SKILL_DAMAGE, true, &args);
  3651. else if (skill_name2id(skill_name) <= 0)
  3652. ShowWarning("npc_parse_mapflag: Invalid skill name '%s' for Skill Damage mapflag. Skipping (file '%s', line '%d').\n", skill_name, filepath, strline(buffer, start - buffer));
  3653. else { // Adjusted damage for specified skill
  3654. args.flag_val = 1;
  3655. map_setmapflag_sub(m, MF_SKILL_DAMAGE, true, &args);
  3656. map_skill_damage_add(map_getmapdata(m), skill_name2id(skill_name), &args);
  3657. }
  3658. }
  3659. }
  3660. break;
  3661. }
  3662. case MF_SKILL_DURATION: {
  3663. union u_mapflag_args args = {};
  3664. if (!state)
  3665. map_setmapflag_sub(m, MF_SKILL_DURATION, false, &args);
  3666. else {
  3667. char skill_name[SKILL_NAME_LENGTH];
  3668. if (sscanf(w4, "%30[^,],%5hu[^\n]", skill_name, &args.skill_duration.per) == 2) {
  3669. args.skill_duration.skill_id = skill_name2id(skill_name);
  3670. if (!args.skill_duration.skill_id)
  3671. ShowError("npc_parse_mapflag: skill_duration: Invalid skill name '%s' for Skill Duration mapflag. Skipping (file '%s', line '%d')\n", skill_name, filepath, strline(buffer, start - buffer));
  3672. else {
  3673. args.skill_duration.per = cap_value(args.skill_duration.per, 0, UINT16_MAX);
  3674. map_setmapflag_sub(m, MF_SKILL_DURATION, true, &args);
  3675. }
  3676. }
  3677. }
  3678. break;
  3679. }
  3680. // All others do not need special treatment
  3681. default:
  3682. map_setmapflag(m, mapflag, state);
  3683. break;
  3684. }
  3685. return strchr(start,'\n');// continue
  3686. }
  3687. /**
  3688. * Read file and create npc/func/mapflag/monster... accordingly.
  3689. * @param filepath : Relative path of file from map-serv bin
  3690. * @param runOnInit : should we exec OnInit when it's done ?
  3691. * @return 0:error, 1:success
  3692. */
  3693. int npc_parsesrcfile(const char* filepath, bool runOnInit)
  3694. {
  3695. int16 m, x, y;
  3696. int lines = 0;
  3697. FILE* fp;
  3698. size_t len;
  3699. char* buffer;
  3700. const char* p;
  3701. if(check_filepath(filepath)!=2) { //this is not a file
  3702. ShowDebug("npc_parsesrcfile: Path doesn't seem to be a file skipping it : '%s'.\n", filepath);
  3703. return 0;
  3704. }
  3705. // read whole file to buffer
  3706. fp = fopen(filepath, "rb");
  3707. if( fp == NULL )
  3708. {
  3709. ShowError("npc_parsesrcfile: File not found '%s'.\n", filepath);
  3710. return 0;
  3711. }
  3712. fseek(fp, 0, SEEK_END);
  3713. len = ftell(fp);
  3714. buffer = (char*)aMalloc(len+1);
  3715. fseek(fp, 0, SEEK_SET);
  3716. len = fread(buffer, 1, len, fp);
  3717. buffer[len] = '\0';
  3718. if( ferror(fp) )
  3719. {
  3720. ShowError("npc_parsesrcfile: Failed to read file '%s' - %s\n", filepath, strerror(errno));
  3721. aFree(buffer);
  3722. fclose(fp);
  3723. return 0;
  3724. }
  3725. fclose(fp);
  3726. if ((unsigned char)buffer[0] == 0xEF && (unsigned char)buffer[1] == 0xBB && (unsigned char)buffer[2] == 0xBF) {
  3727. // UTF-8 BOM. This is most likely an error on the user's part, because:
  3728. // - BOM is discouraged in UTF-8, and the only place where you see it is Notepad and such.
  3729. // - It's unlikely that the user wants to use UTF-8 data here, since we don't really support it, nor does the client by default.
  3730. // - If the user really wants to use UTF-8 (instead of latin1, EUC-KR, SJIS, etc), then they can still do it <without BOM>.
  3731. // More info at http://unicode.org/faq/utf_bom.html#bom5 and http://en.wikipedia.org/wiki/Byte_order_mark#UTF-8
  3732. ShowError("npc_parsesrcfile: Detected unsupported UTF-8 BOM in file '%s'. Stopping (please consider using another character set).\n", filepath);
  3733. aFree(buffer);
  3734. return 0;
  3735. }
  3736. // parse buffer
  3737. for( p = skip_space(buffer); p && *p ; p = skip_space(p) )
  3738. {
  3739. int pos[9];
  3740. char w1[2048], w2[2048], w3[2048], w4[2048];
  3741. int i, count;
  3742. lines++;
  3743. // w1<TAB>w2<TAB>w3<TAB>w4
  3744. count = sv_parse(p, len+buffer-p, 0, '\t', pos, ARRAYLENGTH(pos), (e_svopt)(SV_TERMINATE_LF|SV_TERMINATE_CRLF));
  3745. if( count < 0 )
  3746. {
  3747. ShowError("npc_parsesrcfile: Parse error in file '%s', line '%d'. Stopping...\n", filepath, strline(buffer,p-buffer));
  3748. break;
  3749. }
  3750. // fill w1
  3751. if( pos[3]-pos[2] > ARRAYLENGTH(w1)-1 )
  3752. ShowWarning("npc_parsesrcfile: w1 truncated, too much data (%d) in file '%s', line '%d'.\n", pos[3]-pos[2], filepath, strline(buffer,p-buffer));
  3753. i = min(pos[3]-pos[2], ARRAYLENGTH(w1)-1);
  3754. memcpy(w1, p+pos[2], i*sizeof(char));
  3755. w1[i] = '\0';
  3756. // fill w2
  3757. if( pos[5]-pos[4] > ARRAYLENGTH(w2)-1 )
  3758. ShowWarning("npc_parsesrcfile: w2 truncated, too much data (%d) in file '%s', line '%d'.\n", pos[5]-pos[4], filepath, strline(buffer,p-buffer));
  3759. i = min(pos[5]-pos[4], ARRAYLENGTH(w2)-1);
  3760. memcpy(w2, p+pos[4], i*sizeof(char));
  3761. w2[i] = '\0';
  3762. // fill w3
  3763. if( pos[7]-pos[6] > ARRAYLENGTH(w3)-1 )
  3764. ShowWarning("npc_parsesrcfile: w3 truncated, too much data (%d) in file '%s', line '%d'.\n", pos[7]-pos[6], filepath, strline(buffer,p-buffer));
  3765. i = min(pos[7]-pos[6], ARRAYLENGTH(w3)-1);
  3766. memcpy(w3, p+pos[6], i*sizeof(char));
  3767. w3[i] = '\0';
  3768. // fill w4 (to end of line)
  3769. if( pos[1]-pos[8] > ARRAYLENGTH(w4)-1 )
  3770. ShowWarning("npc_parsesrcfile: w4 truncated, too much data (%d) in file '%s', line '%d'.\n", pos[1]-pos[8], filepath, strline(buffer,p-buffer));
  3771. if( pos[8] != -1 )
  3772. {
  3773. i = min(pos[1]-pos[8], ARRAYLENGTH(w4)-1);
  3774. memcpy(w4, p+pos[8], i*sizeof(char));
  3775. w4[i] = '\0';
  3776. }
  3777. else
  3778. w4[0] = '\0';
  3779. if( count < 3 )
  3780. {// Unknown syntax
  3781. ShowError("npc_parsesrcfile: Unknown syntax in file '%s', line '%d'. Stopping...\n * w1=%s\n * w2=%s\n * w3=%s\n * w4=%s\n", filepath, strline(buffer,p-buffer), w1, w2, w3, w4);
  3782. break;
  3783. }
  3784. if( strcmp(w1,"-") !=0 && strcasecmp(w1,"function") != 0 )
  3785. {// w1 = <map name>,<x>,<y>,<facing>
  3786. char mapname[MAP_NAME_LENGTH_EXT];
  3787. int count2;
  3788. count2 = sscanf(w1,"%15[^,],%6hd,%6hd[^,]",mapname,&x,&y);
  3789. if ( count2 < 1 ) {
  3790. ShowError("npc_parsesrcfile: Invalid script definition in file '%s', line '%d'. Skipping line...\n * w1=%s\n * w2=%s\n * w3=%s\n * w4=%s\n", filepath, strline(buffer,p-buffer), w1, w2, w3, w4);
  3791. if (strcasecmp(w2,"script") == 0 && count > 3) {
  3792. if ((p = npc_skip_script(p,buffer,filepath)) == NULL)
  3793. break;
  3794. }
  3795. p = strchr(p,'\n');// next line
  3796. continue;
  3797. }else if( count2 < 3 ){
  3798. // If we were not able to parse any x and y coordinates(usually used by mapflags)
  3799. x = y = 0;
  3800. }
  3801. if( !mapindex_name2id(mapname) )
  3802. {// Incorrect map, we must skip the script info...
  3803. ShowError("npc_parsesrcfile: Unknown map '%s' in file '%s', line '%d'. Skipping line...\n", mapname, filepath, strline(buffer,p-buffer));
  3804. if( strcasecmp(w2,"script") == 0 && count > 3 )
  3805. {
  3806. if((p = npc_skip_script(p,buffer,filepath)) == NULL)
  3807. {
  3808. break;
  3809. }
  3810. }
  3811. p = strchr(p,'\n');// next line
  3812. continue;
  3813. }
  3814. m = map_mapname2mapid(mapname);
  3815. if( m < 0 )
  3816. {// "mapname" is not assigned to this server, we must skip the script info...
  3817. if( strcasecmp(w2,"script") == 0 && count > 3 )
  3818. {
  3819. if((p = npc_skip_script(p,buffer,filepath)) == NULL)
  3820. {
  3821. break;
  3822. }
  3823. }
  3824. p = strchr(p,'\n');// next line
  3825. continue;
  3826. }
  3827. struct map_data *mapdata = map_getmapdata(m);
  3828. if (x < 0 || x >= mapdata->xs || y < 0 || y >= mapdata->ys) {
  3829. ShowError("npc_parsesrcfile: Unknown coordinates ('%d', '%d') for map '%s' in file '%s', line '%d'. Skipping line...\n", x, y, mapname, filepath, strline(buffer,p-buffer));
  3830. if( strcasecmp(w2,"script") == 0 && count > 3 )
  3831. {
  3832. if((p = npc_skip_script(p,buffer,filepath)) == NULL)
  3833. {
  3834. break;
  3835. }
  3836. }
  3837. p = strchr(p,'\n');// next line
  3838. continue;
  3839. }
  3840. }
  3841. if((strcasecmp(w2,"warp") == 0 || strcasecmp(w2,"warp2") == 0) && count > 3)
  3842. p = npc_parse_warp(w1,w2,w3,w4, p, buffer, filepath);
  3843. else if( (!strcasecmp(w2,"shop") || !strcasecmp(w2,"cashshop") || !strcasecmp(w2,"itemshop") || !strcasecmp(w2,"pointshop") || !strcasecmp(w2,"marketshop") ) && count > 3 )
  3844. p = npc_parse_shop(w1,w2,w3,w4, p, buffer, filepath);
  3845. else if( strcasecmp(w2,"script") == 0 && count > 3 ) {
  3846. if( strcasecmp(w1,"function") == 0 )
  3847. p = npc_parse_function(w1, w2, w3, w4, p, buffer, filepath);
  3848. else
  3849. p = npc_parse_script(w1,w2,w3,w4, p, buffer, filepath,runOnInit);
  3850. }
  3851. else if( (i=0, sscanf(w2,"duplicate%n",&i), (i > 0 && w2[i] == '(')) && count > 3 )
  3852. p = npc_parse_duplicate(w1,w2,w3,w4, p, buffer, filepath);
  3853. else if( (strcmpi(w2,"monster") == 0 || strcmpi(w2,"boss_monster") == 0) && count > 3 )
  3854. p = npc_parse_mob(w1, w2, w3, w4, p, buffer, filepath);
  3855. else if( strcmpi(w2,"mapflag") == 0 && count >= 3 )
  3856. p = npc_parse_mapflag(w1, w2, trim(w3), trim(w4), p, buffer, filepath);
  3857. else {
  3858. ShowError("npc_parsesrcfile: Unable to parse, probably a missing or extra TAB in file '%s', line '%d'. Skipping line...\n * w1=%s\n * w2=%s\n * w3=%s\n * w4=%s\n", filepath, strline(buffer,p-buffer), w1, w2, w3, w4);
  3859. p = strchr(p,'\n');// skip and continue
  3860. }
  3861. }
  3862. aFree(buffer);
  3863. return 1;
  3864. }
  3865. int npc_script_event(struct map_session_data* sd, enum npce_event type){
  3866. if (type == NPCE_MAX)
  3867. return 0;
  3868. if (!sd) {
  3869. ShowError("npc_script_event: NULL sd. Event Type %d\n", type);
  3870. return 0;
  3871. }
  3872. std::vector<struct script_event_s>& vector = script_event[type];
  3873. for( struct script_event_s& evt : vector ){
  3874. npc_event_sub( sd, evt.event, evt.event_name );
  3875. }
  3876. return vector.size();
  3877. }
  3878. const char *npc_get_script_event_name(int npce_index)
  3879. {
  3880. switch (npce_index) {
  3881. case NPCE_LOGIN:
  3882. return script_config.login_event_name;
  3883. case NPCE_LOGOUT:
  3884. return script_config.logout_event_name;
  3885. case NPCE_LOADMAP:
  3886. return script_config.loadmap_event_name;
  3887. case NPCE_BASELVUP:
  3888. return script_config.baselvup_event_name;
  3889. case NPCE_JOBLVUP:
  3890. return script_config.joblvup_event_name;
  3891. case NPCE_DIE:
  3892. return script_config.die_event_name;
  3893. case NPCE_KILLPC:
  3894. return script_config.kill_pc_event_name;
  3895. case NPCE_KILLNPC:
  3896. return script_config.kill_mob_event_name;
  3897. case NPCE_STATCALC:
  3898. return script_config.stat_calc_event_name;
  3899. default:
  3900. ShowError("npc_get_script_event_name: npce_index is outside the array limits: %d (max: %d).\n", npce_index, NPCE_MAX);
  3901. return NULL;
  3902. }
  3903. }
  3904. void npc_read_event_script(void)
  3905. {
  3906. int i;
  3907. script_event.clear();
  3908. for (i = 0; i < NPCE_MAX; i++)
  3909. {
  3910. DBIterator* iter;
  3911. DBKey key;
  3912. DBData *data;
  3913. char name[EVENT_NAME_LENGTH];
  3914. safesnprintf(name,EVENT_NAME_LENGTH,"::%s", npc_get_script_event_name(i));
  3915. iter = db_iterator(ev_db);
  3916. for( data = iter->first(iter,&key); iter->exists(iter); data = iter->next(iter,&key) )
  3917. {
  3918. const char* p = key.str;
  3919. struct event_data* ed = (struct event_data*)db_data2ptr(data);
  3920. if( (p=strchr(p,':')) && strcmpi(name,p)==0 ){
  3921. struct script_event_s evt;
  3922. evt.event = ed;
  3923. evt.event_name = key.str;
  3924. script_event[static_cast<enum npce_event>(i)].push_back(evt);
  3925. }
  3926. }
  3927. dbi_destroy(iter);
  3928. }
  3929. if (battle_config.etc_log) {
  3930. //Print summary.
  3931. for (i = 0; i < NPCE_MAX; i++)
  3932. ShowInfo("%" PRIuPTR " '%s' events.\n", script_event[static_cast<enum npce_event>(i)].size(), npc_get_script_event_name(i));
  3933. }
  3934. }
  3935. void npc_clear_pathlist(void) {
  3936. struct npc_path_data *npd = NULL;
  3937. DBIterator *path_list = db_iterator(npc_path_db);
  3938. /* free all npc_path_data filepaths */
  3939. for( npd = (struct npc_path_data *)dbi_first(path_list); dbi_exists(path_list); npd = (struct npc_path_data *)dbi_next(path_list) ) {
  3940. if( npd->path )
  3941. aFree(npd->path);
  3942. }
  3943. dbi_destroy(path_list);
  3944. }
  3945. //Clear then reload npcs files
  3946. int npc_reload(void) {
  3947. struct npc_src_list *nsl;
  3948. int npc_new_min = npc_id;
  3949. struct s_mapiterator* iter;
  3950. struct block_list* bl;
  3951. /* clear guild flag cache */
  3952. guild_flags_clear();
  3953. npc_clear_pathlist();
  3954. db_clear(npc_path_db);
  3955. db_clear(npcname_db);
  3956. db_clear(ev_db);
  3957. //Remove all npcs/mobs. [Skotlex]
  3958. #if PACKETVER >= 20131223
  3959. npc_market_fromsql();
  3960. #endif
  3961. iter = mapit_geteachiddb();
  3962. for( bl = (struct block_list*)mapit_first(iter); mapit_exists(iter); bl = (struct block_list*)mapit_next(iter) ) {
  3963. switch(bl->type) {
  3964. case BL_NPC:
  3965. if( bl->id != fake_nd->bl.id )// don't remove fake_nd
  3966. npc_unload((struct npc_data *)bl, false);
  3967. break;
  3968. case BL_MOB:
  3969. unit_free(bl,CLR_OUTSIGHT);
  3970. break;
  3971. }
  3972. }
  3973. mapit_free(iter);
  3974. // dynamic check by [random]
  3975. if( battle_config.dynamic_mobs ){
  3976. for (int i = 0; i < map_num; i++) {
  3977. for( int16 j = 0; j < MAX_MOB_LIST_PER_MAP; j++ ){
  3978. struct map_data *mapdata = map_getmapdata(i);
  3979. if (mapdata->moblist[j] != NULL) {
  3980. aFree(mapdata->moblist[j]);
  3981. mapdata->moblist[j] = NULL;
  3982. }
  3983. if( mapdata->mob_delete_timer != INVALID_TIMER )
  3984. { // Mobs were removed anyway,so delete the timer [Inkfish]
  3985. delete_timer(mapdata->mob_delete_timer, map_removemobs_timer);
  3986. mapdata->mob_delete_timer = INVALID_TIMER;
  3987. }
  3988. if( mapdata->npc_num > 0 ){
  3989. ShowWarning( "npc_reload: %d npcs weren't removed at map %s!\n", mapdata->npc_num, mapdata->name );
  3990. }
  3991. }
  3992. }
  3993. }
  3994. // clear mob spawn lookup index
  3995. mob_clear_spawninfo();
  3996. npc_warp = npc_shop = npc_script = 0;
  3997. npc_mob = npc_cache_mob = npc_delay_mob = 0;
  3998. // reset mapflags
  3999. map_flags_init();
  4000. //TODO: the following code is copy-pasted from do_init_npc(); clean it up
  4001. // Reloading npcs now
  4002. for (nsl = npc_src_files; nsl; nsl = nsl->next) {
  4003. ShowStatus("Loading NPC file: %s" CL_CLL "\r", nsl->name);
  4004. npc_parsesrcfile(nsl->name,false);
  4005. }
  4006. ShowInfo ("Done loading '" CL_WHITE "%d" CL_RESET "' NPCs:" CL_CLL "\n"
  4007. "\t-'" CL_WHITE "%d" CL_RESET "' Warps\n"
  4008. "\t-'" CL_WHITE "%d" CL_RESET "' Shops\n"
  4009. "\t-'" CL_WHITE "%d" CL_RESET "' Scripts\n"
  4010. "\t-'" CL_WHITE "%d" CL_RESET "' Spawn sets\n"
  4011. "\t-'" CL_WHITE "%d" CL_RESET "' Mobs Cached\n"
  4012. "\t-'" CL_WHITE "%d" CL_RESET "' Mobs Not Cached\n",
  4013. npc_id - npc_new_min, npc_warp, npc_shop, npc_script, npc_mob, npc_cache_mob, npc_delay_mob);
  4014. //Re-read the NPC Script Events cache.
  4015. npc_read_event_script();
  4016. /* refresh guild castle flags on both woe setups */
  4017. npc_event_doall( script_config.agit_init_event_name );
  4018. npc_event_doall( script_config.agit_init2_event_name );
  4019. npc_event_doall( script_config.agit_init3_event_name );
  4020. //Execute the OnInit event for freshly loaded npcs. [Skotlex]
  4021. npc_event_runall(script_config.init_event_name);
  4022. map_data_copyall();
  4023. do_reload_instance();
  4024. // Execute rest of the startup events if connected to char-server. [Lance]
  4025. if(!CheckForCharServer()){
  4026. npc_event_runall(script_config.inter_init_event_name);
  4027. }
  4028. #if PACKETVER >= 20131223
  4029. npc_market_checkall();
  4030. #endif
  4031. return 0;
  4032. }
  4033. //Unload all npc in the given file
  4034. bool npc_unloadfile( const char* path ) {
  4035. DBIterator * iter = db_iterator(npcname_db);
  4036. struct npc_data* nd = NULL;
  4037. bool found = false;
  4038. for( nd = (struct npc_data*)dbi_first(iter); dbi_exists(iter); nd = (struct npc_data*)dbi_next(iter) ) {
  4039. if( nd->path && strcasecmp(nd->path,path) == 0 ) {
  4040. found = true;
  4041. npc_unload_duplicates(nd);/* unload any npcs which could duplicate this but be in a different file */
  4042. npc_unload(nd, true);
  4043. }
  4044. }
  4045. dbi_destroy(iter);
  4046. if( found ) /* refresh event cache */
  4047. npc_read_event_script();
  4048. npc_delsrcfile(path);
  4049. return found;
  4050. }
  4051. void do_clear_npc(void) {
  4052. db_clear(npcname_db);
  4053. db_clear(ev_db);
  4054. }
  4055. /*==========================================
  4056. * Destructor
  4057. *------------------------------------------*/
  4058. void do_final_npc(void) {
  4059. npc_clear_pathlist();
  4060. script_event.clear();
  4061. ev_db->destroy(ev_db, NULL);
  4062. npcname_db->destroy(npcname_db, NULL);
  4063. npc_path_db->destroy(npc_path_db, NULL);
  4064. #if PACKETVER >= 20131223
  4065. NPCMarketDB->destroy(NPCMarketDB, npc_market_free);
  4066. #endif
  4067. ers_destroy(timer_event_ers);
  4068. ers_destroy(npc_sc_display_ers);
  4069. npc_clearsrcfile();
  4070. }
  4071. static void npc_debug_warps_sub(struct npc_data* nd)
  4072. {
  4073. int16 m;
  4074. if (nd->bl.type != BL_NPC || nd->subtype != NPCTYPE_WARP || nd->bl.m < 0)
  4075. return;
  4076. m = map_mapindex2mapid(nd->u.warp.mapindex);
  4077. if (m < 0) return; //Warps to another map, nothing to do about it.
  4078. if (nd->u.warp.x == 0 && nd->u.warp.y == 0) return; // random warp
  4079. struct map_data *mapdata = map_getmapdata(m);
  4080. struct map_data *mapdata_nd = map_getmapdata(nd->bl.m);
  4081. if (map_getcell(m, nd->u.warp.x, nd->u.warp.y, CELL_CHKNPC)) {
  4082. ShowWarning("Warp %s at %s(%d,%d) warps directly on top of an area npc at %s(%d,%d)\n",
  4083. nd->name,
  4084. mapdata_nd->name, nd->bl.x, nd->bl.y,
  4085. mapdata->name, nd->u.warp.x, nd->u.warp.y
  4086. );
  4087. }
  4088. if (map_getcell(m, nd->u.warp.x, nd->u.warp.y, CELL_CHKNOPASS)) {
  4089. ShowWarning("Warp %s at %s(%d,%d) warps to a non-walkable tile at %s(%d,%d)\n",
  4090. nd->name,
  4091. mapdata_nd->name, nd->bl.x, nd->bl.y,
  4092. mapdata->name, nd->u.warp.x, nd->u.warp.y
  4093. );
  4094. }
  4095. }
  4096. static void npc_debug_warps(void){
  4097. for (int i = 0; i < map_num; i++) {
  4098. struct map_data *mapdata = map_getmapdata(i);
  4099. for( int i = 0; i < mapdata->npc_num; i++ ){
  4100. npc_debug_warps_sub(mapdata->npc[i]);
  4101. }
  4102. }
  4103. }
  4104. /*==========================================
  4105. * npc initialization
  4106. *------------------------------------------*/
  4107. void do_init_npc(void){
  4108. struct npc_src_list *file;
  4109. int i;
  4110. //Stock view data for normal npcs.
  4111. memset(&npc_viewdb, 0, sizeof(npc_viewdb));
  4112. npc_viewdb[0].class_ = JT_INVISIBLE; //Invisible class is stored here.
  4113. for( i = 1; i < MAX_NPC_CLASS; i++ )
  4114. npc_viewdb[i].class_ = i;
  4115. for( i = MAX_NPC_CLASS2_START; i < MAX_NPC_CLASS2_END; i++ )
  4116. npc_viewdb2[i - MAX_NPC_CLASS2_START].class_ = i;
  4117. ev_db = strdb_alloc((DBOptions)(DB_OPT_DUP_KEY|DB_OPT_RELEASE_DATA), EVENT_NAME_LENGTH);
  4118. npcname_db = strdb_alloc(DB_OPT_BASE, NPC_NAME_LENGTH+1);
  4119. npc_path_db = strdb_alloc((DBOptions)(DB_OPT_BASE|DB_OPT_DUP_KEY|DB_OPT_RELEASE_DATA),80);
  4120. #if PACKETVER >= 20131223
  4121. NPCMarketDB = strdb_alloc(DB_OPT_BASE, NPC_NAME_LENGTH+1);
  4122. npc_market_fromsql();
  4123. #endif
  4124. timer_event_ers = ers_new(sizeof(struct timer_event_data),"npc.cpp::timer_event_ers",ERS_OPT_NONE);
  4125. npc_sc_display_ers = ers_new(sizeof(struct sc_display_entry), "npc.cpp:npc_sc_display_ers", ERS_OPT_NONE);
  4126. // process all npc files
  4127. ShowStatus("Loading NPCs...\r");
  4128. for( file = npc_src_files; file != NULL; file = file->next ) {
  4129. ShowStatus("Loading NPC file: %s" CL_CLL "\r", file->name);
  4130. npc_parsesrcfile(file->name,false);
  4131. }
  4132. ShowInfo ("Done loading '" CL_WHITE "%d" CL_RESET "' NPCs:" CL_CLL "\n"
  4133. "\t-'" CL_WHITE "%d" CL_RESET "' Warps\n"
  4134. "\t-'" CL_WHITE "%d" CL_RESET "' Shops\n"
  4135. "\t-'" CL_WHITE "%d" CL_RESET "' Scripts\n"
  4136. "\t-'" CL_WHITE "%d" CL_RESET "' Spawn sets\n"
  4137. "\t-'" CL_WHITE "%d" CL_RESET "' Mobs Cached\n"
  4138. "\t-'" CL_WHITE "%d" CL_RESET "' Mobs Not Cached\n",
  4139. npc_id - START_NPC_NUM, npc_warp, npc_shop, npc_script, npc_mob, npc_cache_mob, npc_delay_mob);
  4140. // set up the events cache
  4141. npc_read_event_script();
  4142. #if PACKETVER >= 20131223
  4143. npc_market_checkall();
  4144. #endif
  4145. //Debug function to locate all endless loop warps.
  4146. if (battle_config.warp_point_debug)
  4147. npc_debug_warps();
  4148. add_timer_func_list(npc_event_do_clock,"npc_event_do_clock");
  4149. add_timer_func_list(npc_timerevent,"npc_timerevent");
  4150. // Init dummy NPC
  4151. fake_nd = (struct npc_data *)aCalloc(1,sizeof(struct npc_data));
  4152. fake_nd->bl.m = -1;
  4153. fake_nd->bl.id = npc_get_new_npc_id();
  4154. fake_nd->class_ = JT_FAKENPC;
  4155. fake_nd->speed = 200;
  4156. strcpy(fake_nd->name,"FAKE_NPC");
  4157. memcpy(fake_nd->exname, fake_nd->name, 9);
  4158. npc_script++;
  4159. fake_nd->bl.type = BL_NPC;
  4160. fake_nd->subtype = NPCTYPE_SCRIPT;
  4161. strdb_put(npcname_db, fake_nd->exname, fake_nd);
  4162. fake_nd->u.scr.timerid = INVALID_TIMER;
  4163. map_addiddb(&fake_nd->bl);
  4164. // End of initialization
  4165. }