npc.c 101 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618
  1. // Copyright (c) Athena Dev Teams - Licensed under GNU GPL
  2. // For more information, see LICENCE in the main folder
  3. #include "../common/cbasetypes.h"
  4. #include "../common/timer.h"
  5. #include "../common/nullpo.h"
  6. #include "../common/malloc.h"
  7. #include "../common/showmsg.h"
  8. #include "../common/strlib.h"
  9. #include "../common/utils.h"
  10. #include "../common/ers.h"
  11. #include "../common/db.h"
  12. #include "../common/socket.h"
  13. #include "map.h"
  14. #include "log.h"
  15. #include "clif.h"
  16. #include "intif.h"
  17. #include "pc.h"
  18. #include "status.h"
  19. #include "itemdb.h"
  20. #include "script.h"
  21. #include "mob.h"
  22. #include "pet.h"
  23. #include "instance.h"
  24. #include "battle.h"
  25. #include "skill.h"
  26. #include "unit.h"
  27. #include "npc.h"
  28. #include "chat.h"
  29. #include <stdio.h>
  30. #include <stdlib.h>
  31. #include <string.h>
  32. #include <math.h>
  33. #include <time.h>
  34. #include <errno.h>
  35. struct npc_data* fake_nd;
  36. // linked list of npc source files
  37. struct npc_src_list {
  38. struct npc_src_list* next;
  39. char name[4]; // dynamic array, the structure is allocated with extra bytes (string length)
  40. };
  41. static struct npc_src_list* npc_src_files = NULL;
  42. static int npc_id=START_NPC_NUM;
  43. static int npc_warp=0;
  44. static int npc_shop=0;
  45. static int npc_script=0;
  46. static int npc_mob=0;
  47. static int npc_delay_mob=0;
  48. static int npc_cache_mob=0;
  49. /// Returns a new npc id that isn't being used in id_db.
  50. /// Fatal error if nothing is available.
  51. int npc_get_new_npc_id(void)
  52. {
  53. if( npc_id >= START_NPC_NUM && map_id2bl(npc_id) == NULL )
  54. return npc_id++;// available
  55. {// find next id
  56. int base_id = npc_id;
  57. while( base_id != ++npc_id )
  58. {
  59. if( npc_id < START_NPC_NUM )
  60. npc_id = START_NPC_NUM;
  61. if( map_id2bl(npc_id) == NULL )
  62. return npc_id++;// available
  63. }
  64. // full loop, nothing available
  65. ShowFatalError("npc_get_new_npc_id: All ids are taken. Exiting...");
  66. exit(1);
  67. }
  68. }
  69. static DBMap* ev_db; // const char* event_name -> struct event_data*
  70. static DBMap* npcname_db; // const char* npc_name -> struct npc_data*
  71. struct event_data {
  72. struct npc_data *nd;
  73. int pos;
  74. };
  75. static struct eri *timer_event_ers; //For the npc timer data. [Skotlex]
  76. //For holding the view data of npc classes. [Skotlex]
  77. static struct view_data npc_viewdb[MAX_NPC_CLASS];
  78. static struct script_event_s
  79. { //Holds pointers to the commonly executed scripts for speedup. [Skotlex]
  80. struct event_data *event[UCHAR_MAX];
  81. const char *event_name[UCHAR_MAX];
  82. uint8 event_count;
  83. } script_event[NPCE_MAX];
  84. struct view_data* npc_get_viewdata(int class_)
  85. { //Returns the viewdata for normal npc classes.
  86. if( class_ == INVISIBLE_CLASS )
  87. return &npc_viewdb[0];
  88. if (npcdb_checkid(class_) || class_ == WARP_CLASS)
  89. return &npc_viewdb[class_];
  90. return NULL;
  91. }
  92. int npc_ontouch_event(struct map_session_data *sd, struct npc_data *nd)
  93. {
  94. char name[EVENT_NAME_LENGTH];
  95. if( nd->touching_id )
  96. return 0; // Attached a player already. Can't trigger on anyone else.
  97. if( pc_ishiding(sd) )
  98. return 1; // Can't trigger 'OnTouch_'. try 'OnTouch' later.
  99. snprintf(name, ARRAYLENGTH(name), "%s::%s", nd->exname, script_config.ontouch_name);
  100. return npc_event(sd,name,1);
  101. }
  102. int npc_ontouch2_event(struct map_session_data *sd, struct npc_data *nd)
  103. {
  104. char name[EVENT_NAME_LENGTH];
  105. if( sd->areanpc_id == nd->bl.id )
  106. return 0;
  107. snprintf(name, ARRAYLENGTH(name), "%s::%s", nd->exname, script_config.ontouch2_name);
  108. return npc_event(sd,name,2);
  109. }
  110. /*==========================================
  111. * NPCの無効化/有効化
  112. * npc_enable
  113. * npc_enable_sub 有効時にOnTouchイベントを実行
  114. *------------------------------------------*/
  115. int npc_enable_sub(struct block_list *bl, va_list ap)
  116. {
  117. struct npc_data *nd;
  118. nullpo_ret(bl);
  119. nullpo_ret(nd=va_arg(ap,struct npc_data *));
  120. if(bl->type == BL_PC)
  121. {
  122. TBL_PC *sd = (TBL_PC*)bl;
  123. if (nd->sc.option&OPTION_INVISIBLE)
  124. return 1;
  125. if( npc_ontouch_event(sd,nd) > 0 && npc_ontouch2_event(sd,nd) > 0 )
  126. { // failed to run OnTouch event, so just click the npc
  127. if (sd->npc_id != 0)
  128. return 0;
  129. pc_stop_walking(sd,1);
  130. npc_click(sd,nd);
  131. }
  132. }
  133. return 0;
  134. }
  135. int npc_enable(const char* name, int flag)
  136. {
  137. struct npc_data* nd = npc_name2id(name);
  138. if (nd==NULL)
  139. {
  140. ShowError("npc_enable: Attempted to %s a non-existing NPC '%s' (flag=%d).\n", (flag&3) ? "show" : "hide", name, flag);
  141. return 0;
  142. }
  143. if (flag&1) {
  144. nd->sc.option&=~OPTION_INVISIBLE;
  145. clif_spawn(&nd->bl);
  146. } else if (flag&2)
  147. nd->sc.option&=~OPTION_HIDE;
  148. else if (flag&4)
  149. nd->sc.option|= OPTION_HIDE;
  150. else { //Can't change the view_data to invisible class because the view_data for all npcs is shared! [Skotlex]
  151. nd->sc.option|= OPTION_INVISIBLE;
  152. clif_clearunit_area(&nd->bl,CLR_OUTSIGHT); // Hack to trick maya purple card [Xazax]
  153. }
  154. if (nd->class_ == WARP_CLASS || nd->class_ == FLAG_CLASS)
  155. { //Client won't display option changes for these classes [Toms]
  156. if (nd->sc.option&(OPTION_HIDE|OPTION_INVISIBLE))
  157. clif_clearunit_area(&nd->bl, CLR_OUTSIGHT);
  158. else
  159. clif_spawn(&nd->bl);
  160. } else
  161. clif_changeoption(&nd->bl);
  162. if( flag&3 && (nd->u.scr.xs >= 0 || nd->u.scr.ys >= 0) )
  163. map_foreachinarea( npc_enable_sub, nd->bl.m, nd->bl.x-nd->u.scr.xs, nd->bl.y-nd->u.scr.ys, nd->bl.x+nd->u.scr.xs, nd->bl.y+nd->u.scr.ys, BL_PC, nd );
  164. return 0;
  165. }
  166. /*==========================================
  167. * NPCを名前で探す
  168. *------------------------------------------*/
  169. struct npc_data* npc_name2id(const char* name)
  170. {
  171. return (struct npc_data *) strdb_get(npcname_db, name);
  172. }
  173. /**
  174. * For the Secure NPC Timeout option (check config/Secure.h) [RR]
  175. **/
  176. #if SECURE_NPCTIMEOUT
  177. /**
  178. * Timer to check for idle time and timeout the dialog if necessary
  179. **/
  180. int npc_rr_secure_timeout_timer(int tid, unsigned int tick, int id, intptr_t data) {
  181. struct map_session_data* sd = NULL;
  182. if( (sd = map_id2sd(id)) == NULL || !sd->npc_id ) {
  183. if( sd ) sd->npc_idle_timer = INVALID_TIMER;
  184. return 0;//Not logged in anymore OR no longer attached to a npc
  185. }
  186. if( DIFF_TICK(tick,sd->npc_idle_tick) > (SECURE_NPCTIMEOUT*1000) ) {
  187. /**
  188. * If we still have the NPC script attached, tell it to stop.
  189. **/
  190. if( sd->st )
  191. sd->st->state = END;
  192. /**
  193. * This guy's been idle for longer than allowed, close him.
  194. **/
  195. clif_scriptclose(sd,sd->npc_id);
  196. sd->npc_idle_timer = INVALID_TIMER;
  197. } else //Create a new instance of ourselves to continue
  198. sd->npc_idle_timer = add_timer(gettick() + (SECURE_NPCTIMEOUT_INTERVAL*1000),npc_rr_secure_timeout_timer,sd->bl.id,0);
  199. return 0;
  200. }
  201. #endif
  202. /*==========================================
  203. * イベントキューのイベント処理
  204. *------------------------------------------*/
  205. int npc_event_dequeue(struct map_session_data* sd)
  206. {
  207. nullpo_ret(sd);
  208. if(sd->npc_id)
  209. { //Current script is aborted.
  210. if(sd->state.using_fake_npc){
  211. clif_clearunit_single(sd->npc_id, CLR_OUTSIGHT, sd->fd);
  212. sd->state.using_fake_npc = 0;
  213. }
  214. if (sd->st) {
  215. script_free_state(sd->st);
  216. sd->st = NULL;
  217. }
  218. sd->npc_id = 0;
  219. }
  220. if (!sd->eventqueue[0][0])
  221. return 0; //Nothing to dequeue
  222. if (!pc_addeventtimer(sd,100,sd->eventqueue[0]))
  223. { //Failed to dequeue, couldn't set a timer.
  224. ShowWarning("npc_event_dequeue: event timer is full !\n");
  225. return 0;
  226. }
  227. //Event dequeued successfully, shift other elements.
  228. memmove(sd->eventqueue[0], sd->eventqueue[1], (MAX_EVENTQUEUE-1)*sizeof(sd->eventqueue[0]));
  229. sd->eventqueue[MAX_EVENTQUEUE-1][0]=0;
  230. return 1;
  231. }
  232. /*==========================================
  233. * exports a npc event label
  234. * called from npc_parse_script
  235. *------------------------------------------*/
  236. static int npc_event_export(struct npc_data *nd, int i)
  237. {
  238. char* lname = nd->u.scr.label_list[i].name;
  239. int pos = nd->u.scr.label_list[i].pos;
  240. if ((lname[0] == 'O' || lname[0] == 'o') && (lname[1] == 'N' || lname[1] == 'n')) {
  241. struct event_data *ev;
  242. char buf[EVENT_NAME_LENGTH];
  243. snprintf(buf, ARRAYLENGTH(buf), "%s::%s", nd->exname, lname);
  244. // generate the data and insert it
  245. CREATE(ev, struct event_data, 1);
  246. ev->nd = nd;
  247. ev->pos = pos;
  248. if (strdb_put(ev_db, buf, ev)) // There was already another event of the same name?
  249. return 1;
  250. }
  251. return 0;
  252. }
  253. int npc_event_sub(struct map_session_data* sd, struct event_data* ev, const char* eventname); //[Lance]
  254. /**
  255. * 全てのNPCのOn*イベント実行
  256. * @see DBApply
  257. */
  258. int npc_event_doall_sub(DBKey key, DBData *data, va_list ap)
  259. {
  260. const char* p = key.str;
  261. struct event_data* ev;
  262. int* c;
  263. const char* name;
  264. int rid;
  265. nullpo_ret(ev = db_data2ptr(data));
  266. nullpo_ret(c = va_arg(ap, int *));
  267. nullpo_ret(name = va_arg(ap, const char *));
  268. rid = va_arg(ap, int);
  269. p = strchr(p, ':'); // match only the event name
  270. if( p && strcmpi(name, p) == 0 /* && !ev->nd->src_id */ ) // Do not run on duplicates. [Paradox924X]
  271. {
  272. if(rid) // a player may only have 1 script running at the same time
  273. npc_event_sub(map_id2sd(rid),ev,key.str);
  274. else
  275. run_script(ev->nd->u.scr.script,ev->pos,rid,ev->nd->bl.id);
  276. (*c)++;
  277. }
  278. return 0;
  279. }
  280. /**
  281. * @see DBApply
  282. */
  283. static int npc_event_do_sub(DBKey key, DBData *data, va_list ap)
  284. {
  285. const char* p = key.str;
  286. struct event_data* ev;
  287. int* c;
  288. const char* name;
  289. nullpo_ret(ev = db_data2ptr(data));
  290. nullpo_ret(c = va_arg(ap, int *));
  291. nullpo_ret(name = va_arg(ap, const char *));
  292. if( p && strcmpi(name, p) == 0 )
  293. {
  294. run_script(ev->nd->u.scr.script,ev->pos,0,ev->nd->bl.id);
  295. (*c)++;
  296. }
  297. return 0;
  298. }
  299. // runs the specified event (supports both single-npc and global events)
  300. int npc_event_do(const char* name)
  301. {
  302. int c = 0;
  303. if( name[0] == ':' && name[1] == ':' )
  304. ev_db->foreach(ev_db,npc_event_doall_sub,&c,name,0);
  305. else
  306. ev_db->foreach(ev_db,npc_event_do_sub,&c,name);
  307. return c;
  308. }
  309. // runs the specified event (global only)
  310. int npc_event_doall(const char* name)
  311. {
  312. return npc_event_doall_id(name, 0);
  313. }
  314. // runs the specified event, with a RID attached (global only)
  315. int npc_event_doall_id(const char* name, int rid)
  316. {
  317. int c = 0;
  318. char buf[64];
  319. safesnprintf(buf, sizeof(buf), "::%s", name);
  320. ev_db->foreach(ev_db,npc_event_doall_sub,&c,buf,rid);
  321. return c;
  322. }
  323. /// Checks whether or not the event name is used as transport for
  324. /// special flags.
  325. bool npc_event_isspecial(const char* eventname)
  326. {
  327. return (bool)( eventname && ISDIGIT(eventname[0]) && !strstr(eventname, "::") );
  328. }
  329. /*==========================================
  330. * 時計イベント実行
  331. *------------------------------------------*/
  332. int npc_event_do_clock(int tid, unsigned int tick, int id, intptr_t data)
  333. {
  334. static struct tm ev_tm_b; // tracks previous execution time
  335. time_t timer;
  336. struct tm* t;
  337. char buf[64];
  338. char* day;
  339. int c = 0;
  340. timer = time(NULL);
  341. t = localtime(&timer);
  342. switch (t->tm_wday) {
  343. case 0: day = "Sun"; break;
  344. case 1: day = "Mon"; break;
  345. case 2: day = "Tue"; break;
  346. case 3: day = "Wed"; break;
  347. case 4: day = "Thu"; break;
  348. case 5: day = "Fri"; break;
  349. case 6: day = "Sat"; break;
  350. default:day = ""; break;
  351. }
  352. if (t->tm_min != ev_tm_b.tm_min ) {
  353. sprintf(buf,"OnMinute%02d",t->tm_min);
  354. c+=npc_event_doall(buf);
  355. sprintf(buf,"OnClock%02d%02d",t->tm_hour,t->tm_min);
  356. c+=npc_event_doall(buf);
  357. sprintf(buf,"On%s%02d%02d",day,t->tm_hour,t->tm_min);
  358. c+=npc_event_doall(buf);
  359. }
  360. if (t->tm_hour!= ev_tm_b.tm_hour) {
  361. sprintf(buf,"OnHour%02d",t->tm_hour);
  362. c+=npc_event_doall(buf);
  363. }
  364. if (t->tm_mday!= ev_tm_b.tm_mday) {
  365. sprintf(buf,"OnDay%02d%02d",t->tm_mon+1,t->tm_mday);
  366. c+=npc_event_doall(buf);
  367. }
  368. memcpy(&ev_tm_b,t,sizeof(ev_tm_b));
  369. return c;
  370. }
  371. /*==========================================
  372. * OnInitイベント実行(&時計イベント開始)
  373. *------------------------------------------*/
  374. void npc_event_do_oninit(void)
  375. {
  376. ShowStatus("Event '"CL_WHITE"OnInit"CL_RESET"' executed with '"CL_WHITE"%d"CL_RESET"' NPCs."CL_CLL"\n", npc_event_doall("OnInit"));
  377. add_timer_interval(gettick()+100,npc_event_do_clock,0,0,1000);
  378. }
  379. /*==========================================
  380. * タイマーイベント用ラベルの取り込み
  381. * called from npc_parse_script
  382. *------------------------------------------*/
  383. int npc_timerevent_export(struct npc_data *nd, int i)
  384. {
  385. int t = 0, k = 0;
  386. char *lname = nd->u.scr.label_list[i].name;
  387. int pos = nd->u.scr.label_list[i].pos;
  388. if (sscanf(lname, "OnTimer%d%n", &t, &k) == 1 && lname[k] == '\0') {
  389. // タイマーイベント
  390. struct npc_timerevent_list *te = nd->u.scr.timer_event;
  391. int j, k = nd->u.scr.timeramount;
  392. if (te == NULL)
  393. te = (struct npc_timerevent_list *)aMalloc(sizeof(struct npc_timerevent_list));
  394. else
  395. te = (struct npc_timerevent_list *)aRealloc( te, sizeof(struct npc_timerevent_list) * (k+1) );
  396. for (j = 0; j < k; j++) {
  397. if (te[j].timer > t) {
  398. memmove(te+j+1, te+j, sizeof(struct npc_timerevent_list)*(k-j));
  399. break;
  400. }
  401. }
  402. te[j].timer = t;
  403. te[j].pos = pos;
  404. nd->u.scr.timer_event = te;
  405. nd->u.scr.timeramount++;
  406. }
  407. return 0;
  408. }
  409. struct timer_event_data {
  410. int rid; //Attached player for this timer.
  411. int next; //timer index (starts with 0, then goes up to nd->u.scr.timeramount)
  412. int time; //holds total time elapsed for the script from when timer was started to when last time the event triggered.
  413. };
  414. /*==========================================
  415. * triger 'OnTimerXXXX' events
  416. *------------------------------------------*/
  417. int npc_timerevent(int tid, unsigned int tick, int id, intptr_t data)
  418. {
  419. int next;
  420. int old_rid, old_timer;
  421. unsigned int old_tick;
  422. struct npc_data* nd=(struct npc_data *)map_id2bl(id);
  423. struct npc_timerevent_list *te;
  424. struct timer_event_data *ted = (struct timer_event_data*)data;
  425. struct map_session_data *sd=NULL;
  426. if( nd == NULL )
  427. {
  428. ShowError("npc_timerevent: NPC not found??\n");
  429. return 0;
  430. }
  431. if( ted->rid && !(sd = map_id2sd(ted->rid)) )
  432. {
  433. ShowError("npc_timerevent: Attached player not found.\n");
  434. ers_free(timer_event_ers, ted);
  435. return 0;
  436. }
  437. // These stuffs might need to be restored.
  438. old_rid = nd->u.scr.rid;
  439. old_tick = nd->u.scr.timertick;
  440. old_timer = nd->u.scr.timer;
  441. // Set the values of the timer
  442. nd->u.scr.rid = sd?sd->bl.id:0; //attached rid
  443. nd->u.scr.timertick = tick; //current time tick
  444. nd->u.scr.timer = ted->time; //total time from beginning to now
  445. // Locate the event
  446. te = nd->u.scr.timer_event + ted->next;
  447. // Arrange for the next event
  448. ted->next++;
  449. if( nd->u.scr.timeramount > ted->next )
  450. {
  451. next = nd->u.scr.timer_event[ ted->next ].timer - nd->u.scr.timer_event[ ted->next - 1 ].timer;
  452. ted->time += next;
  453. if( sd )
  454. sd->npc_timer_id = add_timer(tick+next,npc_timerevent,id,(intptr_t)ted);
  455. else
  456. nd->u.scr.timerid = add_timer(tick+next,npc_timerevent,id,(intptr_t)ted);
  457. }
  458. else
  459. {
  460. if( sd )
  461. sd->npc_timer_id = INVALID_TIMER;
  462. else
  463. {
  464. nd->u.scr.timerid = INVALID_TIMER;
  465. nd->u.scr.timertick = 0; // NPC timer stopped
  466. }
  467. ers_free(timer_event_ers, ted);
  468. }
  469. // Run the script
  470. run_script(nd->u.scr.script,te->pos,nd->u.scr.rid,nd->bl.id);
  471. nd->u.scr.rid = old_rid; // Attached-rid should be restored anyway.
  472. if( sd )
  473. { // Restore previous data, only if this timer is a player-attached one.
  474. nd->u.scr.timer = old_timer;
  475. nd->u.scr.timertick = old_tick;
  476. }
  477. return 0;
  478. }
  479. /*==========================================
  480. * Start/Resume NPC timer
  481. *------------------------------------------*/
  482. int npc_timerevent_start(struct npc_data* nd, int rid)
  483. {
  484. int j, next;
  485. unsigned int tick = gettick();
  486. struct map_session_data *sd = NULL; //Player to whom script is attached.
  487. struct timer_event_data *ted;
  488. nullpo_ret(nd);
  489. // No need to start because of no events
  490. if( nd->u.scr.timeramount == 0 )
  491. return 0;
  492. // Check if there is an OnTimer Event
  493. ARR_FIND( 0, nd->u.scr.timeramount, j, nd->u.scr.timer_event[j].timer > nd->u.scr.timer );
  494. if( j >= nd->u.scr.timeramount ) // No need to start because of no events left to trigger
  495. return 0;
  496. if( nd->u.scr.rid > 0 && !(sd = map_id2sd(nd->u.scr.rid)) )
  497. { // Failed to attach timer to this player.
  498. ShowError("npc_timerevent_start: Attached player not found!\n");
  499. return 1;
  500. }
  501. // Check if timer is already started.
  502. if( sd )
  503. {
  504. if( sd->npc_timer_id != INVALID_TIMER )
  505. return 0;
  506. }
  507. else if( nd->u.scr.timerid != INVALID_TIMER )
  508. return 0;
  509. // Arrange for the next event
  510. ted = ers_alloc(timer_event_ers, struct timer_event_data);
  511. ted->next = j; // Set event index
  512. ted->time = nd->u.scr.timer_event[j].timer;
  513. next = nd->u.scr.timer_event[j].timer - nd->u.scr.timer;
  514. if( sd )
  515. {
  516. ted->rid = sd->bl.id; // Attach only the player if attachplayerrid was used.
  517. sd->npc_timer_id = add_timer(tick+next,npc_timerevent,nd->bl.id,(intptr_t)ted);
  518. }
  519. else
  520. {
  521. ted->rid = 0;
  522. nd->u.scr.timertick = tick; // Set when timer is started
  523. nd->u.scr.timerid = add_timer(tick+next,npc_timerevent,nd->bl.id,(intptr_t)ted);
  524. }
  525. return 0;
  526. }
  527. /*==========================================
  528. * Stop NPC timer
  529. *------------------------------------------*/
  530. int npc_timerevent_stop(struct npc_data* nd)
  531. {
  532. struct map_session_data *sd = NULL;
  533. const struct TimerData *td = NULL;
  534. int *tid;
  535. nullpo_ret(nd);
  536. if( nd->u.scr.rid && !(sd = map_id2sd(nd->u.scr.rid)) )
  537. {
  538. ShowError("npc_timerevent_stop: Attached player not found!\n");
  539. return 1;
  540. }
  541. tid = sd?&sd->npc_timer_id:&nd->u.scr.timerid;
  542. if( *tid == INVALID_TIMER ) // Nothing to stop
  543. return 0;
  544. // Delete timer
  545. td = get_timer(*tid);
  546. if( td && td->data )
  547. ers_free(timer_event_ers, (void*)td->data);
  548. delete_timer(*tid,npc_timerevent);
  549. *tid = INVALID_TIMER;
  550. if( !sd )
  551. {
  552. 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
  553. nd->u.scr.timertick = 0; // Set 'tick' to zero so that we know it's off.
  554. }
  555. return 0;
  556. }
  557. /*==========================================
  558. * Aborts a running NPC timer that is attached to a player.
  559. *------------------------------------------*/
  560. void npc_timerevent_quit(struct map_session_data* sd)
  561. {
  562. const struct TimerData *td;
  563. struct npc_data* nd;
  564. struct timer_event_data *ted;
  565. // Check timer existance
  566. if( sd->npc_timer_id == INVALID_TIMER )
  567. return;
  568. if( !(td = get_timer(sd->npc_timer_id)) )
  569. {
  570. sd->npc_timer_id = INVALID_TIMER;
  571. return;
  572. }
  573. // Delete timer
  574. nd = (struct npc_data *)map_id2bl(td->id);
  575. ted = (struct timer_event_data*)td->data;
  576. delete_timer(sd->npc_timer_id, npc_timerevent);
  577. sd->npc_timer_id = INVALID_TIMER;
  578. // Execute OnTimerQuit
  579. if( nd && nd->bl.type == BL_NPC )
  580. {
  581. char buf[EVENT_NAME_LENGTH];
  582. struct event_data *ev;
  583. snprintf(buf, ARRAYLENGTH(buf), "%s::OnTimerQuit", nd->exname);
  584. ev = (struct event_data*)strdb_get(ev_db, buf);
  585. if( ev && ev->nd != nd )
  586. {
  587. ShowWarning("npc_timerevent_quit: Unable to execute \"OnTimerQuit\", two NPCs have the same event name [%s]!\n",buf);
  588. ev = NULL;
  589. }
  590. if( ev )
  591. {
  592. int old_rid,old_timer;
  593. unsigned int old_tick;
  594. //Set timer related info.
  595. old_rid = (nd->u.scr.rid == sd->bl.id ? 0 : nd->u.scr.rid); // Detach rid if the last attached player logged off.
  596. old_tick = nd->u.scr.timertick;
  597. old_timer = nd->u.scr.timer;
  598. nd->u.scr.rid = sd->bl.id;
  599. nd->u.scr.timertick = gettick();
  600. nd->u.scr.timer = ted->time;
  601. //Execute label
  602. run_script(nd->u.scr.script,ev->pos,sd->bl.id,nd->bl.id);
  603. //Restore previous data.
  604. nd->u.scr.rid = old_rid;
  605. nd->u.scr.timer = old_timer;
  606. nd->u.scr.timertick = old_tick;
  607. }
  608. }
  609. ers_free(timer_event_ers, ted);
  610. }
  611. /*==========================================
  612. * Get the tick value of an NPC timer
  613. * If it's stopped, return stopped time
  614. *------------------------------------------*/
  615. int npc_gettimerevent_tick(struct npc_data* nd)
  616. {
  617. int tick;
  618. nullpo_ret(nd);
  619. // TODO: Get player attached timer's tick. Now we can just get it by using 'getnpctimer' inside OnTimer event.
  620. tick = nd->u.scr.timer; // The last time it's active(start, stop or event trigger)
  621. if( nd->u.scr.timertick ) // It's a running timer
  622. tick += DIFF_TICK(gettick(), nd->u.scr.timertick);
  623. return tick;
  624. }
  625. /*==========================================
  626. * Set tick for running and stopped timer
  627. *------------------------------------------*/
  628. int npc_settimerevent_tick(struct npc_data* nd, int newtimer)
  629. {
  630. bool flag;
  631. int old_rid;
  632. //struct map_session_data *sd = NULL;
  633. nullpo_ret(nd);
  634. // TODO: Set player attached timer's tick.
  635. old_rid = nd->u.scr.rid;
  636. nd->u.scr.rid = 0;
  637. // Check if timer is started
  638. flag = (nd->u.scr.timerid != INVALID_TIMER);
  639. if( flag ) npc_timerevent_stop(nd);
  640. nd->u.scr.timer = newtimer;
  641. if( flag ) npc_timerevent_start(nd, -1);
  642. nd->u.scr.rid = old_rid;
  643. return 0;
  644. }
  645. int npc_event_sub(struct map_session_data* sd, struct event_data* ev, const char* eventname)
  646. {
  647. if ( sd->npc_id != 0 )
  648. {
  649. //Enqueue the event trigger.
  650. int i;
  651. ARR_FIND( 0, MAX_EVENTQUEUE, i, sd->eventqueue[i][0] == '\0' );
  652. if( i < MAX_EVENTQUEUE )
  653. {
  654. safestrncpy(sd->eventqueue[i],eventname,50); //Event enqueued.
  655. return 0;
  656. }
  657. ShowWarning("npc_event: player's event queue is full, can't add event '%s' !\n", eventname);
  658. return 1;
  659. }
  660. if( ev->nd->sc.option&OPTION_INVISIBLE )
  661. {
  662. //Disabled npc, shouldn't trigger event.
  663. npc_event_dequeue(sd);
  664. return 2;
  665. }
  666. run_script(ev->nd->u.scr.script,ev->pos,sd->bl.id,ev->nd->bl.id);
  667. return 0;
  668. }
  669. /*==========================================
  670. * イベント型のNPC処理
  671. *------------------------------------------*/
  672. int npc_event(struct map_session_data* sd, const char* eventname, int ontouch)
  673. {
  674. struct event_data* ev = (struct event_data*)strdb_get(ev_db, eventname);
  675. struct npc_data *nd;
  676. nullpo_ret(sd);
  677. if( ev == NULL || (nd = ev->nd) == NULL )
  678. {
  679. if( !ontouch )
  680. ShowError("npc_event: event not found [%s]\n", eventname);
  681. return ontouch;
  682. }
  683. switch(ontouch)
  684. {
  685. case 1:
  686. nd->touching_id = sd->bl.id;
  687. sd->touching_id = nd->bl.id;
  688. break;
  689. case 2:
  690. sd->areanpc_id = nd->bl.id;
  691. break;
  692. }
  693. return npc_event_sub(sd,ev,eventname);
  694. }
  695. int npc_touch_areanpc_sub(struct block_list *bl, va_list ap)
  696. {
  697. struct map_session_data *sd;
  698. int pc_id,npc_id;
  699. char *name;
  700. nullpo_ret(bl);
  701. nullpo_ret((sd = map_id2sd(bl->id)));
  702. pc_id = va_arg(ap,int);
  703. npc_id = va_arg(ap,int);
  704. name = va_arg(ap,char*);
  705. if( pc_ishiding(sd) )
  706. return 0;
  707. if( pc_id == sd->bl.id )
  708. return 0;
  709. npc_event(sd,name,1);
  710. return 1;
  711. }
  712. int npc_touchnext_areanpc(struct map_session_data* sd, bool leavemap)
  713. {
  714. struct npc_data *nd = map_id2nd(sd->touching_id);
  715. short xs, ys;
  716. if( !nd || nd->touching_id != sd->bl.id )
  717. return 1;
  718. xs = nd->u.scr.xs;
  719. ys = nd->u.scr.ys;
  720. if( sd->bl.m != nd->bl.m ||
  721. sd->bl.x < nd->bl.x - xs || sd->bl.x > nd->bl.x + xs ||
  722. sd->bl.y < nd->bl.y - ys || sd->bl.y > nd->bl.y + ys ||
  723. pc_ishiding(sd) || leavemap )
  724. {
  725. char name[EVENT_NAME_LENGTH];
  726. nd->touching_id = sd->touching_id = 0;
  727. snprintf(name, ARRAYLENGTH(name), "%s::%s", nd->exname, script_config.ontouch_name);
  728. 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,nd->bl.id,name);
  729. }
  730. return 0;
  731. }
  732. /*==========================================
  733. * 接触型のNPC処理
  734. *------------------------------------------*/
  735. int npc_touch_areanpc(struct map_session_data* sd, int m, int x, int y)
  736. {
  737. int xs,ys;
  738. int f = 1;
  739. int i;
  740. nullpo_retr(1, sd);
  741. // Why not enqueue it? [Inkfish]
  742. //if(sd->npc_id)
  743. // return 1;
  744. for(i=0;i<map[m].npc_num;i++)
  745. {
  746. if (map[m].npc[i]->sc.option&OPTION_INVISIBLE) {
  747. f=0; // a npc was found, but it is disabled; don't print warning
  748. continue;
  749. }
  750. switch(map[m].npc[i]->subtype) {
  751. case WARP:
  752. xs=map[m].npc[i]->u.warp.xs;
  753. ys=map[m].npc[i]->u.warp.ys;
  754. break;
  755. case SCRIPT:
  756. xs=map[m].npc[i]->u.scr.xs;
  757. ys=map[m].npc[i]->u.scr.ys;
  758. break;
  759. default:
  760. continue;
  761. }
  762. if( x >= map[m].npc[i]->bl.x-xs && x <= map[m].npc[i]->bl.x+xs
  763. && y >= map[m].npc[i]->bl.y-ys && y <= map[m].npc[i]->bl.y+ys )
  764. break;
  765. }
  766. if( i == map[m].npc_num )
  767. {
  768. if( f == 1 ) // no npc found
  769. ShowError("npc_touch_areanpc : stray NPC cell/NPC not found in the block on coordinates '%s',%d,%d\n", map[m].name, x, y);
  770. return 1;
  771. }
  772. switch(map[m].npc[i]->subtype) {
  773. case WARP:
  774. if( pc_ishiding(sd) )
  775. break; // hidden chars cannot use warps
  776. pc_setpos(sd,map[m].npc[i]->u.warp.mapindex,map[m].npc[i]->u.warp.x,map[m].npc[i]->u.warp.y,CLR_OUTSIGHT);
  777. break;
  778. case SCRIPT:
  779. if( npc_ontouch_event(sd,map[m].npc[i]) > 0 && npc_ontouch2_event(sd,map[m].npc[i]) > 0 )
  780. { // failed to run OnTouch event, so just click the npc
  781. struct unit_data *ud = unit_bl2ud(&sd->bl);
  782. if( ud && ud->walkpath.path_pos < ud->walkpath.path_len )
  783. { // Since walktimer always == INVALID_TIMER at this time, we stop walking manually. [Inkfish]
  784. clif_fixpos(&sd->bl);
  785. ud->walkpath.path_pos = ud->walkpath.path_len;
  786. }
  787. sd->areanpc_id = map[m].npc[i]->bl.id;
  788. npc_click(sd,map[m].npc[i]);
  789. }
  790. break;
  791. }
  792. return 0;
  793. }
  794. // OnTouch NPC or Warp for Mobs
  795. // Return 1 if Warped
  796. int npc_touch_areanpc2(struct mob_data *md)
  797. {
  798. int i, m = md->bl.m, x = md->bl.x, y = md->bl.y, id;
  799. char eventname[EVENT_NAME_LENGTH];
  800. struct event_data* ev;
  801. int xs, ys;
  802. for( i = 0; i < map[m].npc_num; i++ )
  803. {
  804. if( map[m].npc[i]->sc.option&OPTION_INVISIBLE )
  805. continue;
  806. switch( map[m].npc[i]->subtype )
  807. {
  808. case WARP:
  809. if( !( battle_config.mob_warp&1 ) )
  810. continue;
  811. xs = map[m].npc[i]->u.warp.xs;
  812. ys = map[m].npc[i]->u.warp.ys;
  813. break;
  814. case SCRIPT:
  815. xs = map[m].npc[i]->u.scr.xs;
  816. ys = map[m].npc[i]->u.scr.ys;
  817. break;
  818. default:
  819. continue; // Keep Searching
  820. }
  821. if( x >= map[m].npc[i]->bl.x-xs && x <= map[m].npc[i]->bl.x+xs && y >= map[m].npc[i]->bl.y-ys && y <= map[m].npc[i]->bl.y+ys )
  822. { // In the npc touch area
  823. switch( map[m].npc[i]->subtype )
  824. {
  825. case WARP:
  826. xs = map_mapindex2mapid(map[m].npc[i]->u.warp.mapindex);
  827. if( m < 0 )
  828. break; // Cannot Warp between map servers
  829. if( unit_warp(&md->bl, xs, map[m].npc[i]->u.warp.x, map[m].npc[i]->u.warp.y, CLR_OUTSIGHT) == 0 )
  830. return 1; // Warped
  831. break;
  832. case SCRIPT:
  833. if( map[m].npc[i]->bl.id == md->areanpc_id )
  834. break; // Already touch this NPC
  835. snprintf(eventname, ARRAYLENGTH(eventname), "%s::OnTouchNPC", map[m].npc[i]->exname);
  836. if( (ev = (struct event_data*)strdb_get(ev_db, eventname)) == NULL || ev->nd == NULL )
  837. break; // No OnTouchNPC Event
  838. md->areanpc_id = map[m].npc[i]->bl.id;
  839. id = md->bl.id; // Stores Unique ID
  840. run_script(ev->nd->u.scr.script, ev->pos, md->bl.id, ev->nd->bl.id);
  841. if( map_id2md(id) == NULL ) return 1; // Not Warped, but killed
  842. break;
  843. }
  844. return 0;
  845. }
  846. }
  847. return 0;
  848. }
  849. //Checks if there are any NPC on-touch objects on the given range.
  850. //Flag determines the type of object to check for:
  851. //&1: NPC Warps
  852. //&2: NPCs with on-touch events.
  853. int npc_check_areanpc(int flag, int m, int x, int y, int range)
  854. {
  855. int i;
  856. int x0,y0,x1,y1;
  857. int xs,ys;
  858. if (range < 0) return 0;
  859. x0 = max(x-range, 0);
  860. y0 = max(y-range, 0);
  861. x1 = min(x+range, map[m].xs-1);
  862. y1 = min(y+range, map[m].ys-1);
  863. //First check for npc_cells on the range given
  864. i = 0;
  865. for (ys = y0; ys <= y1 && !i; ys++) {
  866. for(xs = x0; xs <= x1 && !i; xs++){
  867. if (map_getcell(m,xs,ys,CELL_CHKNPC))
  868. i = 1;
  869. }
  870. }
  871. if (!i) return 0; //No NPC_CELLs.
  872. //Now check for the actual NPC on said range.
  873. for(i=0;i<map[m].npc_num;i++)
  874. {
  875. if (map[m].npc[i]->sc.option&OPTION_INVISIBLE)
  876. continue;
  877. switch(map[m].npc[i]->subtype)
  878. {
  879. case WARP:
  880. if (!(flag&1))
  881. continue;
  882. xs=map[m].npc[i]->u.warp.xs;
  883. ys=map[m].npc[i]->u.warp.ys;
  884. break;
  885. case SCRIPT:
  886. if (!(flag&2))
  887. continue;
  888. xs=map[m].npc[i]->u.scr.xs;
  889. ys=map[m].npc[i]->u.scr.ys;
  890. break;
  891. default:
  892. continue;
  893. }
  894. if( x1 >= map[m].npc[i]->bl.x-xs && x0 <= map[m].npc[i]->bl.x+xs
  895. && y1 >= map[m].npc[i]->bl.y-ys && y0 <= map[m].npc[i]->bl.y+ys )
  896. break; // found a npc
  897. }
  898. if (i==map[m].npc_num)
  899. return 0;
  900. return (map[m].npc[i]->bl.id);
  901. }
  902. struct npc_data* npc_checknear(struct map_session_data* sd, struct block_list* bl)
  903. {
  904. struct npc_data *nd;
  905. nullpo_retr(NULL, sd);
  906. if(bl == NULL) return NULL;
  907. if(bl->type != BL_NPC) return NULL;
  908. nd = (TBL_NPC*)bl;
  909. if(sd->state.using_fake_npc && sd->npc_id == bl->id)
  910. return nd;
  911. if (nd->class_<0) //Class-less npc, enable click from anywhere.
  912. return nd;
  913. if (bl->m!=sd->bl.m ||
  914. bl->x<sd->bl.x-AREA_SIZE-1 || bl->x>sd->bl.x+AREA_SIZE+1 ||
  915. bl->y<sd->bl.y-AREA_SIZE-1 || bl->y>sd->bl.y+AREA_SIZE+1)
  916. return NULL;
  917. return nd;
  918. }
  919. /*==========================================
  920. * NPCのオープンチャット発言
  921. *------------------------------------------*/
  922. int npc_globalmessage(const char* name, const char* mes)
  923. {
  924. struct npc_data* nd = npc_name2id(name);
  925. char temp[100];
  926. if (!nd)
  927. return 0;
  928. snprintf(temp, sizeof(temp), "%s : %s", name, mes);
  929. clif_GlobalMessage(&nd->bl,temp);
  930. return 0;
  931. }
  932. /*==========================================
  933. * クリック時のNPC処理
  934. *------------------------------------------*/
  935. int npc_click(struct map_session_data* sd, struct npc_data* nd)
  936. {
  937. nullpo_retr(1, sd);
  938. if (sd->npc_id != 0) {
  939. ShowError("npc_click: npc_id != 0\n");
  940. return 1;
  941. }
  942. if(!nd) return 1;
  943. if ((nd = npc_checknear(sd,&nd->bl)) == NULL)
  944. return 1;
  945. //Hidden/Disabled npc.
  946. if (nd->class_ < 0 || nd->sc.option&(OPTION_INVISIBLE|OPTION_HIDE))
  947. return 1;
  948. switch(nd->subtype) {
  949. case SHOP:
  950. clif_npcbuysell(sd,nd->bl.id);
  951. break;
  952. case CASHSHOP:
  953. clif_cashshop_show(sd,nd);
  954. break;
  955. case SCRIPT:
  956. run_script(nd->u.scr.script,0,sd->bl.id,nd->bl.id);
  957. break;
  958. }
  959. return 0;
  960. }
  961. /*==========================================
  962. *
  963. *------------------------------------------*/
  964. int npc_scriptcont(struct map_session_data* sd, int id)
  965. {
  966. nullpo_retr(1, sd);
  967. if( id != sd->npc_id ){
  968. TBL_NPC* nd_sd=(TBL_NPC*)map_id2bl(sd->npc_id);
  969. TBL_NPC* nd=(TBL_NPC*)map_id2bl(id);
  970. ShowDebug("npc_scriptcont: %s (sd->npc_id=%d) is not %s (id=%d).\n",
  971. nd_sd?(char*)nd_sd->name:"'Unknown NPC'", (int)sd->npc_id,
  972. nd?(char*)nd->name:"'Unknown NPC'", (int)id);
  973. return 1;
  974. }
  975. if(id != fake_nd->bl.id) { // Not item script
  976. if ((npc_checknear(sd,map_id2bl(id))) == NULL){
  977. ShowWarning("npc_scriptcont: failed npc_checknear test.\n");
  978. return 1;
  979. }
  980. }
  981. /**
  982. * For the Secure NPC Timeout option (check config/Secure.h) [RR]
  983. **/
  984. #if SECURE_NPCTIMEOUT
  985. /**
  986. * Update the last NPC iteration
  987. **/
  988. sd->npc_idle_tick = gettick();
  989. #endif
  990. /**
  991. * WPE can get to this point with a progressbar; we deny it.
  992. **/
  993. if( sd->progressbar.npc_id && DIFF_TICK(sd->progressbar.timeout,gettick()) > 0 )
  994. return 1;
  995. run_script_main(sd->st);
  996. return 0;
  997. }
  998. /*==========================================
  999. *
  1000. *------------------------------------------*/
  1001. int npc_buysellsel(struct map_session_data* sd, int id, int type)
  1002. {
  1003. struct npc_data *nd;
  1004. nullpo_retr(1, sd);
  1005. if ((nd = npc_checknear(sd,map_id2bl(id))) == NULL)
  1006. return 1;
  1007. if (nd->subtype!=SHOP) {
  1008. ShowError("no such shop npc : %d\n",id);
  1009. if (sd->npc_id == id)
  1010. sd->npc_id=0;
  1011. return 1;
  1012. }
  1013. if (nd->sc.option&OPTION_INVISIBLE) // 無効化されている
  1014. return 1;
  1015. if( nd->class_ < 0 && !sd->state.callshop )
  1016. {// not called through a script and is not a visible NPC so an invalid call
  1017. return 1;
  1018. }
  1019. // reset the callshop state for future calls
  1020. sd->state.callshop = 0;
  1021. sd->npc_shopid = id;
  1022. if (type==0) {
  1023. clif_buylist(sd,nd);
  1024. } else {
  1025. clif_selllist(sd);
  1026. }
  1027. return 0;
  1028. }
  1029. /*==========================================
  1030. * Cash Shop Buy List
  1031. *------------------------------------------*/
  1032. int npc_cashshop_buylist(struct map_session_data *sd, int points, int count, unsigned short* item_list)
  1033. {
  1034. int i, j, nameid, amount, new_, w, vt;
  1035. struct npc_data *nd = (struct npc_data *)map_id2bl(sd->npc_shopid);
  1036. if( !nd || nd->subtype != CASHSHOP )
  1037. return 1;
  1038. if( sd->state.trading )
  1039. return 4;
  1040. new_ = 0;
  1041. w = 0;
  1042. vt = 0; // Global Value
  1043. // Validating Process ----------------------------------------------------
  1044. for( i = 0; i < count; i++ )
  1045. {
  1046. nameid = item_list[i*2+1];
  1047. amount = item_list[i*2+0];
  1048. if( !itemdb_exists(nameid) || amount <= 0 )
  1049. return 5;
  1050. ARR_FIND(0,nd->u.shop.count,j,nd->u.shop.shop_item[j].nameid == nameid);
  1051. if( j == nd->u.shop.count || nd->u.shop.shop_item[j].value <= 0 )
  1052. return 5;
  1053. if( !itemdb_isstackable(nameid) && amount > 1 )
  1054. {
  1055. ShowWarning("Player %s (%d:%d) sent a hexed packet trying to buy %d of nonstackable item %d!\n", sd->status.name, sd->status.account_id, sd->status.char_id, amount, nameid);
  1056. amount = item_list[i*2+0] = 1;
  1057. }
  1058. switch( pc_checkadditem(sd,nameid,amount) )
  1059. {
  1060. case ADDITEM_NEW:
  1061. new_++;
  1062. break;
  1063. case ADDITEM_OVERAMOUNT:
  1064. return 3;
  1065. }
  1066. vt += nd->u.shop.shop_item[j].value * amount;
  1067. w += itemdb_weight(nameid) * amount;
  1068. }
  1069. if( w + sd->weight > sd->max_weight )
  1070. return 3;
  1071. if( pc_inventoryblank(sd) < new_ )
  1072. return 3;
  1073. if( points > vt ) points = vt;
  1074. // Payment Process ----------------------------------------------------
  1075. if( sd->kafraPoints < points || sd->cashPoints < (vt - points) )
  1076. return 6;
  1077. pc_paycash(sd,vt,points);
  1078. // Delivery Process ----------------------------------------------------
  1079. for( i = 0; i < count; i++ )
  1080. {
  1081. struct item item_tmp;
  1082. nameid = item_list[i*2+1];
  1083. amount = item_list[i*2+0];
  1084. memset(&item_tmp,0,sizeof(item_tmp));
  1085. if( !pet_create_egg(sd,nameid) )
  1086. {
  1087. item_tmp.nameid = nameid;
  1088. item_tmp.identify = 1;
  1089. pc_additem(sd,&item_tmp,amount,LOG_TYPE_NPC);
  1090. }
  1091. }
  1092. return 0;
  1093. }
  1094. //npc_buylist for script-controlled shops.
  1095. static int npc_buylist_sub(struct map_session_data* sd, int n, unsigned short* item_list, struct npc_data* nd)
  1096. {
  1097. char npc_ev[EVENT_NAME_LENGTH];
  1098. int i;
  1099. int key_nameid = 0;
  1100. int key_amount = 0;
  1101. // discard old contents
  1102. script_cleararray_pc(sd, "@bought_nameid", (void*)0);
  1103. script_cleararray_pc(sd, "@bought_quantity", (void*)0);
  1104. // save list of bought items
  1105. for( i = 0; i < n; i++ )
  1106. {
  1107. script_setarray_pc(sd, "@bought_nameid", i, (void*)(intptr_t)item_list[i*2+1], &key_nameid);
  1108. script_setarray_pc(sd, "@bought_quantity", i, (void*)(intptr_t)item_list[i*2], &key_amount);
  1109. }
  1110. // invoke event
  1111. snprintf(npc_ev, ARRAYLENGTH(npc_ev), "%s::OnBuyItem", nd->exname);
  1112. npc_event(sd, npc_ev, 0);
  1113. return 0;
  1114. }
  1115. /*==========================================
  1116. * Cash Shop Buy
  1117. *------------------------------------------*/
  1118. int npc_cashshop_buy(struct map_session_data *sd, int nameid, int amount, int points)
  1119. {
  1120. struct npc_data *nd = (struct npc_data *)map_id2bl(sd->npc_shopid);
  1121. struct item_data *item;
  1122. int i, price, w;
  1123. if( amount <= 0 )
  1124. return 5;
  1125. if( points < 0 )
  1126. return 6;
  1127. if( !nd || nd->subtype != CASHSHOP )
  1128. return 1;
  1129. if( sd->state.trading )
  1130. return 4;
  1131. if( (item = itemdb_exists(nameid)) == NULL )
  1132. return 5; // Invalid Item
  1133. ARR_FIND(0, nd->u.shop.count, i, nd->u.shop.shop_item[i].nameid == nameid);
  1134. if( i == nd->u.shop.count )
  1135. return 5;
  1136. if( nd->u.shop.shop_item[i].value <= 0 )
  1137. return 5;
  1138. if(!itemdb_isstackable(nameid) && amount > 1)
  1139. {
  1140. ShowWarning("Player %s (%d:%d) sent a hexed packet trying to buy %d of nonstackable item %d!\n",
  1141. sd->status.name, sd->status.account_id, sd->status.char_id, amount, nameid);
  1142. amount = 1;
  1143. }
  1144. switch( pc_checkadditem(sd, nameid, amount) )
  1145. {
  1146. case ADDITEM_NEW:
  1147. if( pc_inventoryblank(sd) == 0 )
  1148. return 3;
  1149. break;
  1150. case ADDITEM_OVERAMOUNT:
  1151. return 3;
  1152. }
  1153. w = item->weight * amount;
  1154. if( w + sd->weight > sd->max_weight )
  1155. return 3;
  1156. if( (double)nd->u.shop.shop_item[i].value * amount > INT_MAX )
  1157. {
  1158. ShowWarning("npc_cashshop_buy: Item '%s' (%d) price overflow attempt!\n", item->name, nameid);
  1159. ShowDebug("(NPC:'%s' (%s,%d,%d), player:'%s' (%d/%d), value:%d, amount:%d)\n", nd->exname, map[nd->bl.m].name, 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);
  1160. return 5;
  1161. }
  1162. price = nd->u.shop.shop_item[i].value * amount;
  1163. if( points > price )
  1164. points = price;
  1165. if( (sd->kafraPoints < points) || (sd->cashPoints < price - points) )
  1166. return 6;
  1167. pc_paycash(sd, price, points);
  1168. if( !pet_create_egg(sd, nameid) )
  1169. {
  1170. struct item item_tmp;
  1171. memset(&item_tmp, 0, sizeof(struct item));
  1172. item_tmp.nameid = nameid;
  1173. item_tmp.identify = 1;
  1174. pc_additem(sd,&item_tmp, amount, LOG_TYPE_NPC);
  1175. }
  1176. return 0;
  1177. }
  1178. /// Player item purchase from npc shop.
  1179. ///
  1180. /// @param item_list 'n' pairs <amount,itemid>
  1181. /// @return result code for clif_parse_NpcBuyListSend
  1182. int npc_buylist(struct map_session_data* sd, int n, unsigned short* item_list)
  1183. {
  1184. struct npc_data* nd;
  1185. double z;
  1186. int i,j,w,skill,new_;
  1187. nullpo_retr(3, sd);
  1188. nullpo_retr(3, item_list);
  1189. nd = npc_checknear(sd,map_id2bl(sd->npc_shopid));
  1190. if( nd == NULL )
  1191. return 3;
  1192. if( nd->subtype != SHOP )
  1193. return 3;
  1194. z = 0;
  1195. w = 0;
  1196. new_ = 0;
  1197. // process entries in buy list, one by one
  1198. for( i = 0; i < n; ++i )
  1199. {
  1200. int nameid, amount, value;
  1201. // find this entry in the shop's sell list
  1202. ARR_FIND( 0, nd->u.shop.count, j,
  1203. item_list[i*2+1] == nd->u.shop.shop_item[j].nameid || //Normal items
  1204. item_list[i*2+1] == itemdb_viewid(nd->u.shop.shop_item[j].nameid) //item_avail replacement
  1205. );
  1206. if( j == nd->u.shop.count )
  1207. return 3; // no such item in shop
  1208. amount = item_list[i*2+0];
  1209. nameid = item_list[i*2+1] = nd->u.shop.shop_item[j].nameid; //item_avail replacement
  1210. value = nd->u.shop.shop_item[j].value;
  1211. if( !itemdb_exists(nameid) )
  1212. return 3; // item no longer in itemdb
  1213. if( !itemdb_isstackable(nameid) && amount > 1 )
  1214. { //Exploit? You can't buy more than 1 of equipment types o.O
  1215. ShowWarning("Player %s (%d:%d) sent a hexed packet trying to buy %d of nonstackable item %d!\n",
  1216. sd->status.name, sd->status.account_id, sd->status.char_id, amount, nameid);
  1217. amount = item_list[i*2+0] = 1;
  1218. }
  1219. if( nd->master_nd )
  1220. {// Script-controlled shops decide by themselves, what can be bought and for what price.
  1221. continue;
  1222. }
  1223. switch( pc_checkadditem(sd,nameid,amount) )
  1224. {
  1225. case ADDITEM_EXIST:
  1226. break;
  1227. case ADDITEM_NEW:
  1228. new_++;
  1229. break;
  1230. case ADDITEM_OVERAMOUNT:
  1231. return 2;
  1232. }
  1233. value = pc_modifybuyvalue(sd,value);
  1234. z += (double)value * amount;
  1235. w += itemdb_weight(nameid) * amount;
  1236. }
  1237. if( nd->master_nd != NULL ) //Script-based shops.
  1238. return npc_buylist_sub(sd,n,item_list,nd->master_nd);
  1239. if( z > (double)sd->status.zeny )
  1240. return 1; // Not enough Zeny
  1241. if( w + sd->weight > sd->max_weight )
  1242. return 2; // Too heavy
  1243. if( pc_inventoryblank(sd) < new_ )
  1244. return 3; // Not enough space to store items
  1245. //Logs (S)hopping Zeny [Lupus]
  1246. log_zeny(sd, LOG_TYPE_NPC, sd, -(int)z);
  1247. //Logs
  1248. pc_payzeny(sd,(int)z);
  1249. for( i = 0; i < n; ++i )
  1250. {
  1251. int nameid = item_list[i*2+1];
  1252. int amount = item_list[i*2+0];
  1253. struct item item_tmp;
  1254. memset(&item_tmp,0,sizeof(item_tmp));
  1255. item_tmp.nameid = nameid;
  1256. item_tmp.identify = 1;
  1257. pc_additem(sd,&item_tmp,amount,LOG_TYPE_NPC);
  1258. }
  1259. // custom merchant shop exp bonus
  1260. if( battle_config.shop_exp > 0 && z > 0 && (skill = pc_checkskill(sd,MC_DISCOUNT)) > 0 )
  1261. {
  1262. if( sd->status.skill[MC_DISCOUNT].flag >= SKILL_FLAG_REPLACED_LV_0 )
  1263. skill = sd->status.skill[MC_DISCOUNT].flag - SKILL_FLAG_REPLACED_LV_0;
  1264. if( skill > 0 )
  1265. {
  1266. z = z * (double)skill * (double)battle_config.shop_exp/10000.;
  1267. if( z < 1 )
  1268. z = 1;
  1269. pc_gainexp(sd,NULL,0,(int)z, false);
  1270. }
  1271. }
  1272. return 0;
  1273. }
  1274. /// npc_selllist for script-controlled shops
  1275. static int npc_selllist_sub(struct map_session_data* sd, int n, unsigned short* item_list, struct npc_data* nd)
  1276. {
  1277. char npc_ev[EVENT_NAME_LENGTH];
  1278. char card_slot[NAME_LENGTH];
  1279. int i, j, idx;
  1280. int key_nameid = 0;
  1281. int key_amount = 0;
  1282. int key_refine = 0;
  1283. int key_attribute = 0;
  1284. int key_identify = 0;
  1285. int key_card = 0;
  1286. // discard old contents
  1287. script_cleararray_pc(sd, "@sold_nameid", (void*)0);
  1288. script_cleararray_pc(sd, "@sold_quantity", (void*)0);
  1289. script_cleararray_pc(sd, "@sold_refine", (void*)0);
  1290. script_cleararray_pc(sd, "@sold_attribute", (void*)0);
  1291. script_cleararray_pc(sd, "@sold_identify", (void*)0);
  1292. for( j = 0; MAX_SLOTS > j; j++ )
  1293. {// clear each of the card slot entries
  1294. snprintf(card_slot, sizeof(card_slot), "@sold_card%d", j + 1);
  1295. script_cleararray_pc(sd, card_slot, (void*)0);
  1296. }
  1297. // save list of to be sold items
  1298. for( i = 0; i < n; i++ )
  1299. {
  1300. idx = item_list[i*2]-2;
  1301. script_setarray_pc(sd, "@sold_nameid", i, (void*)(intptr_t)sd->status.inventory[idx].nameid, &key_nameid);
  1302. script_setarray_pc(sd, "@sold_quantity", i, (void*)(intptr_t)item_list[i*2+1], &key_amount);
  1303. if( itemdb_isequip(sd->status.inventory[idx].nameid) )
  1304. {// process equipment based information into the arrays
  1305. script_setarray_pc(sd, "@sold_refine", i, (void*)(intptr_t)sd->status.inventory[idx].refine, &key_refine);
  1306. script_setarray_pc(sd, "@sold_attribute", i, (void*)(intptr_t)sd->status.inventory[idx].attribute, &key_attribute);
  1307. script_setarray_pc(sd, "@sold_identify", i, (void*)(intptr_t)sd->status.inventory[idx].identify, &key_identify);
  1308. for( j = 0; MAX_SLOTS > j; j++ )
  1309. {// store each of the cards from the equipment in the array
  1310. snprintf(card_slot, sizeof(card_slot), "@sold_card%d", j + 1);
  1311. script_setarray_pc(sd, card_slot, i, (void*)(intptr_t)sd->status.inventory[idx].card[j], &key_card);
  1312. }
  1313. }
  1314. }
  1315. // invoke event
  1316. snprintf(npc_ev, ARRAYLENGTH(npc_ev), "%s::OnSellItem", nd->exname);
  1317. npc_event(sd, npc_ev, 0);
  1318. return 0;
  1319. }
  1320. /// Player item selling to npc shop.
  1321. ///
  1322. /// @param item_list 'n' pairs <index,amount>
  1323. /// @return result code for clif_parse_NpcSellListSend
  1324. int npc_selllist(struct map_session_data* sd, int n, unsigned short* item_list)
  1325. {
  1326. double z;
  1327. int i,skill;
  1328. struct npc_data *nd;
  1329. nullpo_retr(1, sd);
  1330. nullpo_retr(1, item_list);
  1331. if( ( nd = npc_checknear(sd, map_id2bl(sd->npc_shopid)) ) == NULL || nd->subtype != SHOP )
  1332. {
  1333. return 1;
  1334. }
  1335. z = 0;
  1336. // verify the sell list
  1337. for( i = 0; i < n; i++ )
  1338. {
  1339. int nameid, amount, idx, value;
  1340. idx = item_list[i*2]-2;
  1341. amount = item_list[i*2+1];
  1342. if( idx >= MAX_INVENTORY || idx < 0 || amount < 0 )
  1343. {
  1344. return 1;
  1345. }
  1346. nameid = sd->status.inventory[idx].nameid;
  1347. if( !nameid || !sd->inventory_data[idx] || sd->status.inventory[idx].amount < amount )
  1348. {
  1349. return 1;
  1350. }
  1351. if( nd->master_nd )
  1352. {// Script-controlled shops decide by themselves, what can be sold and at what price.
  1353. continue;
  1354. }
  1355. value = pc_modifysellvalue(sd, sd->inventory_data[idx]->value_sell);
  1356. z+= (double)value*amount;
  1357. }
  1358. if( nd->master_nd )
  1359. {// Script-controlled shops
  1360. return npc_selllist_sub(sd, n, item_list, nd->master_nd);
  1361. }
  1362. // delete items
  1363. for( i = 0; i < n; i++ )
  1364. {
  1365. int nameid, amount, idx;
  1366. idx = item_list[i*2]-2;
  1367. amount = item_list[i*2+1];
  1368. nameid = sd->status.inventory[idx].nameid;
  1369. if( sd->inventory_data[idx]->type == IT_PETEGG && sd->status.inventory[idx].card[0] == CARD0_PET )
  1370. {
  1371. if( search_petDB_index(sd->status.inventory[idx].nameid, PET_EGG) >= 0 )
  1372. {
  1373. intif_delete_petdata(MakeDWord(sd->status.inventory[idx].card[1], sd->status.inventory[idx].card[2]));
  1374. }
  1375. }
  1376. pc_delitem(sd, idx, amount, 0, 6, LOG_TYPE_NPC);
  1377. }
  1378. if( z > MAX_ZENY )
  1379. z = MAX_ZENY;
  1380. //Logs (S)hopping Zeny [Lupus]
  1381. log_zeny(sd, LOG_TYPE_NPC, sd, (int)z);
  1382. //Logs
  1383. pc_getzeny(sd, (int)z);
  1384. // custom merchant shop exp bonus
  1385. if( battle_config.shop_exp > 0 && z > 0 && ( skill = pc_checkskill(sd,MC_OVERCHARGE) ) > 0)
  1386. {
  1387. if( sd->status.skill[MC_OVERCHARGE].flag >= SKILL_FLAG_REPLACED_LV_0 )
  1388. skill = sd->status.skill[MC_OVERCHARGE].flag - SKILL_FLAG_REPLACED_LV_0;
  1389. if( skill > 0 )
  1390. {
  1391. z = z * (double)skill * (double)battle_config.shop_exp/10000.;
  1392. if( z < 1 )
  1393. z = 1;
  1394. pc_gainexp(sd, NULL, 0, (int)z, false);
  1395. }
  1396. }
  1397. return 0;
  1398. }
  1399. int npc_remove_map(struct npc_data* nd)
  1400. {
  1401. int m,i;
  1402. nullpo_retr(1, nd);
  1403. if(nd->bl.prev == NULL || nd->bl.m < 0)
  1404. return 1; //Not assigned to a map.
  1405. m = nd->bl.m;
  1406. clif_clearunit_area(&nd->bl,CLR_RESPAWN);
  1407. npc_unsetcells(nd);
  1408. map_delblock(&nd->bl);
  1409. //Remove npc from map[].npc list. [Skotlex]
  1410. ARR_FIND( 0, map[m].npc_num, i, map[m].npc[i] == nd );
  1411. if( i == map[m].npc_num ) return 2; //failed to find it?
  1412. map[m].npc_num--;
  1413. map[m].npc[i] = map[m].npc[map[m].npc_num];
  1414. map[m].npc[map[m].npc_num] = NULL;
  1415. return 0;
  1416. }
  1417. /**
  1418. * @see DBApply
  1419. */
  1420. static int npc_unload_ev(DBKey key, DBData *data, va_list ap)
  1421. {
  1422. struct event_data* ev = db_data2ptr(data);
  1423. char* npcname = va_arg(ap, char *);
  1424. if(strcmp(ev->nd->exname,npcname)==0){
  1425. db_remove(ev_db, key);
  1426. return 1;
  1427. }
  1428. return 0;
  1429. }
  1430. static int npc_unload_dup_sub(struct npc_data* nd, va_list args)
  1431. {
  1432. int src_id;
  1433. src_id = va_arg(args, int);
  1434. if (nd->src_id == src_id)
  1435. npc_unload(nd);
  1436. return 0;
  1437. }
  1438. //Removes all npcs that are duplicates of the passed one. [Skotlex]
  1439. void npc_unload_duplicates(struct npc_data* nd)
  1440. {
  1441. map_foreachnpc(npc_unload_dup_sub,nd->bl.id);
  1442. }
  1443. int npc_unload(struct npc_data* nd)
  1444. {
  1445. nullpo_ret(nd);
  1446. npc_remove_map(nd);
  1447. map_deliddb(&nd->bl);
  1448. strdb_remove(npcname_db, nd->exname);
  1449. if (nd->chat_id) // remove npc chatroom object and kick users
  1450. chat_deletenpcchat(nd);
  1451. #ifdef PCRE_SUPPORT
  1452. npc_chat_finalize(nd); // deallocate npc PCRE data structures
  1453. #endif
  1454. if( (nd->subtype == SHOP || nd->subtype == CASHSHOP) && nd->src_id == 0) //src check for duplicate shops [Orcao]
  1455. aFree(nd->u.shop.shop_item);
  1456. else
  1457. if( nd->subtype == SCRIPT )
  1458. {
  1459. struct s_mapiterator* iter;
  1460. struct block_list* bl;
  1461. ev_db->foreach(ev_db,npc_unload_ev,nd->exname); //Clean up all events related
  1462. iter = mapit_geteachpc();
  1463. for( bl = (struct block_list*)mapit_first(iter); mapit_exists(iter); bl = (struct block_list*)mapit_next(iter) )
  1464. {
  1465. struct map_session_data *sd = map_id2sd(bl->id);
  1466. if( sd && sd->npc_timer_id != INVALID_TIMER )
  1467. {
  1468. const struct TimerData *td = get_timer(sd->npc_timer_id);
  1469. if( td && td->id != nd->bl.id )
  1470. continue;
  1471. if( td && td->data )
  1472. ers_free(timer_event_ers, (void*)td->data);
  1473. delete_timer(sd->npc_timer_id, npc_timerevent);
  1474. sd->npc_timer_id = INVALID_TIMER;
  1475. }
  1476. }
  1477. mapit_free(iter);
  1478. if (nd->u.scr.timerid != INVALID_TIMER) {
  1479. const struct TimerData *td = NULL;
  1480. td = get_timer(nd->u.scr.timerid);
  1481. if (td && td->data)
  1482. ers_free(timer_event_ers, (void*)td->data);
  1483. delete_timer(nd->u.scr.timerid, npc_timerevent);
  1484. }
  1485. if (nd->u.scr.timer_event)
  1486. aFree(nd->u.scr.timer_event);
  1487. if (nd->src_id == 0) {
  1488. if(nd->u.scr.script) {
  1489. script_free_code(nd->u.scr.script);
  1490. nd->u.scr.script = NULL;
  1491. }
  1492. if (nd->u.scr.label_list) {
  1493. aFree(nd->u.scr.label_list);
  1494. nd->u.scr.label_list = NULL;
  1495. nd->u.scr.label_list_num = 0;
  1496. }
  1497. }
  1498. }
  1499. script_stop_sleeptimers(nd->bl.id);
  1500. aFree(nd);
  1501. return 0;
  1502. }
  1503. //
  1504. // NPC Source Files
  1505. //
  1506. /// Clears the npc source file list
  1507. static void npc_clearsrcfile(void)
  1508. {
  1509. struct npc_src_list* file = npc_src_files;
  1510. struct npc_src_list* file_tofree;
  1511. while( file != NULL )
  1512. {
  1513. file_tofree = file;
  1514. file = file->next;
  1515. aFree(file_tofree);
  1516. }
  1517. npc_src_files = NULL;
  1518. }
  1519. /// Adds a npc source file (or removes all)
  1520. void npc_addsrcfile(const char* name)
  1521. {
  1522. struct npc_src_list* file;
  1523. struct npc_src_list* file_prev = NULL;
  1524. if( strcmpi(name, "clear") == 0 )
  1525. {
  1526. npc_clearsrcfile();
  1527. return;
  1528. }
  1529. // prevent multiple insert of source files
  1530. file = npc_src_files;
  1531. while( file != NULL )
  1532. {
  1533. if( strcmp(name, file->name) == 0 )
  1534. return;// found the file, no need to insert it again
  1535. file_prev = file;
  1536. file = file->next;
  1537. }
  1538. file = (struct npc_src_list*)aMalloc(sizeof(struct npc_src_list) + strlen(name));
  1539. file->next = NULL;
  1540. strncpy(file->name, name, strlen(name) + 1);
  1541. if( file_prev == NULL )
  1542. npc_src_files = file;
  1543. else
  1544. file_prev->next = file;
  1545. }
  1546. /// Removes a npc source file (or all)
  1547. void npc_delsrcfile(const char* name)
  1548. {
  1549. struct npc_src_list* file = npc_src_files;
  1550. struct npc_src_list* file_prev = NULL;
  1551. if( strcmpi(name, "all") == 0 )
  1552. {
  1553. npc_clearsrcfile();
  1554. return;
  1555. }
  1556. while( file != NULL )
  1557. {
  1558. if( strcmp(file->name, name) == 0 )
  1559. {
  1560. if( npc_src_files == file )
  1561. npc_src_files = file->next;
  1562. else
  1563. file_prev->next = file->next;
  1564. aFree(file);
  1565. break;
  1566. }
  1567. file_prev = file;
  1568. file = file->next;
  1569. }
  1570. }
  1571. /// Parses and sets the name and exname of a npc.
  1572. /// Assumes that m, x and y are already set in nd.
  1573. static void npc_parsename(struct npc_data* nd, const char* name, const char* start, const char* buffer, const char* filepath)
  1574. {
  1575. const char* p;
  1576. struct npc_data* dnd;// duplicate npc
  1577. char newname[NAME_LENGTH];
  1578. // parse name
  1579. p = strstr(name,"::");
  1580. if( p )
  1581. {// <Display name>::<Unique name>
  1582. size_t len = p-name;
  1583. if( len > NAME_LENGTH )
  1584. {
  1585. 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), NAME_LENGTH);
  1586. safestrncpy(nd->name, name, sizeof(nd->name));
  1587. }
  1588. else
  1589. {
  1590. memcpy(nd->name, name, len);
  1591. memset(nd->name+len, 0, sizeof(nd->name)-len);
  1592. }
  1593. len = strlen(p+2);
  1594. if( len > NAME_LENGTH )
  1595. 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), NAME_LENGTH);
  1596. safestrncpy(nd->exname, p+2, sizeof(nd->exname));
  1597. }
  1598. else
  1599. {// <Display name>
  1600. size_t len = strlen(name);
  1601. if( len > NAME_LENGTH )
  1602. 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), NAME_LENGTH);
  1603. safestrncpy(nd->name, name, sizeof(nd->name));
  1604. safestrncpy(nd->exname, name, sizeof(nd->exname));
  1605. }
  1606. if( *nd->exname == '\0' || strstr(nd->exname,"::") != NULL )
  1607. {// invalid
  1608. snprintf(newname, ARRAYLENGTH(newname), "0_%d_%d_%d", nd->bl.m, nd->bl.x, nd->bl.y);
  1609. ShowWarning("npc_parsename: Invalid unique name in file '%s', line'%d'. Renaming '%s' to '%s'.\n", filepath, strline(buffer,start-buffer), nd->exname, newname);
  1610. safestrncpy(nd->exname, newname, sizeof(nd->exname));
  1611. }
  1612. if( (dnd=npc_name2id(nd->exname)) != NULL )
  1613. {// duplicate unique name, generate new one
  1614. char this_mapname[32];
  1615. char other_mapname[32];
  1616. int i = 0;
  1617. do
  1618. {
  1619. ++i;
  1620. snprintf(newname, ARRAYLENGTH(newname), "%d_%d_%d_%d", i, nd->bl.m, nd->bl.x, nd->bl.y);
  1621. }
  1622. while( npc_name2id(newname) != NULL );
  1623. strcpy(this_mapname, (nd->bl.m==-1?"(not on a map)":mapindex_id2name(map[nd->bl.m].index)));
  1624. strcpy(other_mapname, (dnd->bl.m==-1?"(not on a map)":mapindex_id2name(map[dnd->bl.m].index)));
  1625. ShowWarning("npc_parsename: Duplicate unique name in file '%s', line'%d'. Renaming '%s' to '%s'.\n", filepath, strline(buffer,start-buffer), nd->exname, newname);
  1626. 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);
  1627. ShowDebug("other npc:\n display name '%s'\n unique name '%s'\n map=%s, x=%d, y=%d\n", dnd->name, dnd->exname, other_mapname, dnd->bl.x, dnd->bl.y);
  1628. safestrncpy(nd->exname, newname, sizeof(nd->exname));
  1629. }
  1630. }
  1631. struct npc_data* npc_add_warp(short from_mapid, short from_x, short from_y, short xs, short ys, unsigned short to_mapindex, short to_x, short to_y)
  1632. {
  1633. int i;
  1634. struct npc_data *nd;
  1635. CREATE(nd, struct npc_data, 1);
  1636. nd->bl.id = npc_get_new_npc_id();
  1637. map_addnpc(from_mapid, nd);
  1638. nd->bl.prev = nd->bl.next = NULL;
  1639. nd->bl.m = from_mapid;
  1640. nd->bl.x = from_x;
  1641. nd->bl.y = from_y;
  1642. snprintf(nd->exname, ARRAYLENGTH(nd->exname), "warp_%d_%d_%d", from_mapid, from_x, from_y);
  1643. for( i = 0; npc_name2id(nd->exname) != NULL; ++i )
  1644. snprintf(nd->exname, ARRAYLENGTH(nd->exname), "warp%d_%d_%d_%d", i, from_mapid, from_x, from_y);
  1645. safestrncpy(nd->name, nd->exname, ARRAYLENGTH(nd->name));
  1646. if( battle_config.warp_point_debug )
  1647. nd->class_ = WARP_DEBUG_CLASS;
  1648. else
  1649. nd->class_ = WARP_CLASS;
  1650. nd->speed = 200;
  1651. nd->u.warp.mapindex = to_mapindex;
  1652. nd->u.warp.x = to_x;
  1653. nd->u.warp.y = to_y;
  1654. nd->u.warp.xs = xs;
  1655. nd->u.warp.ys = xs;
  1656. nd->bl.type = BL_NPC;
  1657. nd->subtype = WARP;
  1658. npc_setcells(nd);
  1659. map_addblock(&nd->bl);
  1660. status_set_viewdata(&nd->bl, nd->class_);
  1661. status_change_init(&nd->bl);
  1662. unit_dataset(&nd->bl);
  1663. if( map[nd->bl.m].users )
  1664. clif_spawn(&nd->bl);
  1665. strdb_put(npcname_db, nd->exname, nd);
  1666. return nd;
  1667. }
  1668. /// Parses a warp npc.
  1669. static const char* npc_parse_warp(char* w1, char* w2, char* w3, char* w4, const char* start, const char* buffer, const char* filepath)
  1670. {
  1671. int x, y, xs, ys, to_x, to_y, m;
  1672. unsigned short i;
  1673. char mapname[32], to_mapname[32];
  1674. struct npc_data *nd;
  1675. // w1=<from map name>,<fromX>,<fromY>,<facing>
  1676. // w4=<spanx>,<spany>,<to map name>,<toX>,<toY>
  1677. if( sscanf(w1, "%31[^,],%d,%d", mapname, &x, &y) != 3
  1678. || sscanf(w4, "%d,%d,%31[^,],%d,%d", &xs, &ys, to_mapname, &to_x, &to_y) != 5 )
  1679. {
  1680. 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);
  1681. return strchr(start,'\n');// skip and continue
  1682. }
  1683. m = map_mapname2mapid(mapname);
  1684. i = mapindex_name2id(to_mapname);
  1685. if( i == 0 )
  1686. {
  1687. 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);
  1688. return strchr(start,'\n');// skip and continue
  1689. }
  1690. CREATE(nd, struct npc_data, 1);
  1691. nd->bl.id = npc_get_new_npc_id();
  1692. map_addnpc(m, nd);
  1693. nd->bl.prev = nd->bl.next = NULL;
  1694. nd->bl.m = m;
  1695. nd->bl.x = x;
  1696. nd->bl.y = y;
  1697. npc_parsename(nd, w3, start, buffer, filepath);
  1698. if (!battle_config.warp_point_debug)
  1699. nd->class_ = WARP_CLASS;
  1700. else
  1701. nd->class_ = WARP_DEBUG_CLASS;
  1702. nd->speed = 200;
  1703. nd->u.warp.mapindex = i;
  1704. nd->u.warp.x = to_x;
  1705. nd->u.warp.y = to_y;
  1706. nd->u.warp.xs = xs;
  1707. nd->u.warp.ys = ys;
  1708. npc_warp++;
  1709. nd->bl.type = BL_NPC;
  1710. nd->subtype = WARP;
  1711. npc_setcells(nd);
  1712. map_addblock(&nd->bl);
  1713. status_set_viewdata(&nd->bl, nd->class_);
  1714. status_change_init(&nd->bl);
  1715. unit_dataset(&nd->bl);
  1716. if( map[nd->bl.m].users )
  1717. clif_spawn(&nd->bl);
  1718. strdb_put(npcname_db, nd->exname, nd);
  1719. return strchr(start,'\n');// continue
  1720. }
  1721. /// Parses a shop/cashshop npc.
  1722. static const char* npc_parse_shop(char* w1, char* w2, char* w3, char* w4, const char* start, const char* buffer, const char* filepath)
  1723. {
  1724. //TODO: could be rewritten to NOT need this temp array [ultramage]
  1725. #define MAX_SHOPITEM 100
  1726. struct npc_item_list items[MAX_SHOPITEM];
  1727. char *p;
  1728. int x, y, dir, m, i;
  1729. struct npc_data *nd;
  1730. enum npc_subtype type;
  1731. if( strcmp(w1,"-") == 0 )
  1732. {// 'floating' shop?
  1733. x = y = dir = 0;
  1734. m = -1;
  1735. }
  1736. else
  1737. {// w1=<map name>,<x>,<y>,<facing>
  1738. char mapname[32];
  1739. if( sscanf(w1, "%31[^,],%d,%d,%d", mapname, &x, &y, &dir) != 4
  1740. || strchr(w4, ',') == NULL )
  1741. {
  1742. 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);
  1743. return strchr(start,'\n');// skip and continue
  1744. }
  1745. m = map_mapname2mapid(mapname);
  1746. }
  1747. if( !strcasecmp(w2,"cashshop") )
  1748. type = CASHSHOP;
  1749. else
  1750. type = SHOP;
  1751. p = strchr(w4,',');
  1752. for( i = 0; i < ARRAYLENGTH(items) && p; ++i )
  1753. {
  1754. int nameid, value;
  1755. struct item_data* id;
  1756. if( sscanf(p, ",%d:%d", &nameid, &value) != 2 )
  1757. {
  1758. 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);
  1759. break;
  1760. }
  1761. if( (id = itemdb_exists(nameid)) == NULL )
  1762. {
  1763. ShowWarning("npc_parse_shop: Invalid sell item in file '%s', line '%d' (id '%d').\n", filepath, strline(buffer,start-buffer), nameid);
  1764. p = strchr(p+1,',');
  1765. continue;
  1766. }
  1767. if( value < 0 )
  1768. {
  1769. if( type == SHOP ) value = id->value_buy;
  1770. else value = 0; // Cashshop doesn't have a "buy price" in the item_db
  1771. }
  1772. if( type == SHOP && value*0.75 < id->value_sell*1.24 )
  1773. {// Exploit possible: you can buy and sell back with profit
  1774. ShowWarning("npc_parse_shop: Item %s [%d] discounted buying price (%d->%d) is less than overcharged selling price (%d->%d) at file '%s', line '%d'.\n",
  1775. id->name, nameid, value, (int)(value*0.75), id->value_sell, (int)(id->value_sell*1.24), filepath, strline(buffer,start-buffer));
  1776. }
  1777. //for logs filters, atcommands and iteminfo script command
  1778. if( id->maxchance == 0 )
  1779. id->maxchance = -1; // -1 would show that the item's sold in NPC Shop
  1780. items[i].nameid = nameid;
  1781. items[i].value = value;
  1782. p = strchr(p+1,',');
  1783. }
  1784. if( i == 0 )
  1785. {
  1786. ShowWarning("npc_parse_shop: Ignoring empty shop in file '%s', line '%d'.\n", filepath, strline(buffer,start-buffer));
  1787. return strchr(start,'\n');// continue
  1788. }
  1789. CREATE(nd, struct npc_data, 1);
  1790. CREATE(nd->u.shop.shop_item, struct npc_item_list, i);
  1791. memcpy(nd->u.shop.shop_item, items, sizeof(struct npc_item_list)*i);
  1792. nd->u.shop.count = i;
  1793. nd->bl.prev = nd->bl.next = NULL;
  1794. nd->bl.m = m;
  1795. nd->bl.x = x;
  1796. nd->bl.y = y;
  1797. nd->bl.id = npc_get_new_npc_id();
  1798. npc_parsename(nd, w3, start, buffer, filepath);
  1799. nd->class_ = m==-1?-1:atoi(w4);
  1800. nd->speed = 200;
  1801. ++npc_shop;
  1802. nd->bl.type = BL_NPC;
  1803. nd->subtype = type;
  1804. if( m >= 0 )
  1805. {// normal shop npc
  1806. map_addnpc(m,nd);
  1807. map_addblock(&nd->bl);
  1808. status_set_viewdata(&nd->bl, nd->class_);
  1809. status_change_init(&nd->bl);
  1810. unit_dataset(&nd->bl);
  1811. nd->ud.dir = dir;
  1812. if( map[nd->bl.m].users )
  1813. clif_spawn(&nd->bl);
  1814. } else
  1815. {// 'floating' shop?
  1816. map_addiddb(&nd->bl);
  1817. }
  1818. strdb_put(npcname_db, nd->exname, nd);
  1819. return strchr(start,'\n');// continue
  1820. }
  1821. /**
  1822. * NPCのラベルデータコンバート
  1823. * @see DBApply
  1824. */
  1825. int npc_convertlabel_db(DBKey key, DBData *data, va_list ap)
  1826. {
  1827. const char* lname = (const char*)key.str;
  1828. int lpos = db_data2i(data);
  1829. struct npc_label_list** label_list;
  1830. int* label_list_num;
  1831. const char* filepath;
  1832. struct npc_label_list* label;
  1833. const char *p;
  1834. int len;
  1835. nullpo_ret(label_list = va_arg(ap,struct npc_label_list**));
  1836. nullpo_ret(label_list_num = va_arg(ap,int*));
  1837. nullpo_ret(filepath = va_arg(ap,const char*));
  1838. // In case of labels not terminated with ':', for user defined function support
  1839. p = lname;
  1840. while( ISALNUM(*p) || *p == '_' )
  1841. ++p;
  1842. len = p-lname;
  1843. // here we check if the label fit into the buffer
  1844. if( len > 23 )
  1845. {
  1846. ShowError("npc_parse_script: label name longer than 23 chars! '%s'\n (%s)", lname, filepath);
  1847. return 0;
  1848. }
  1849. if( *label_list == NULL )
  1850. {
  1851. *label_list = (struct npc_label_list *) aCalloc (1, sizeof(struct npc_label_list));
  1852. *label_list_num = 0;
  1853. } else
  1854. *label_list = (struct npc_label_list *) aRealloc (*label_list, sizeof(struct npc_label_list)*(*label_list_num+1));
  1855. label = *label_list+*label_list_num;
  1856. safestrncpy(label->name, lname, sizeof(label->name));
  1857. label->pos = lpos;
  1858. ++(*label_list_num);
  1859. return 0;
  1860. }
  1861. // Skip the contents of a script.
  1862. static const char* npc_skip_script(const char* start, const char* buffer, const char* filepath)
  1863. {
  1864. const char* p;
  1865. int curly_count;
  1866. if( start == NULL )
  1867. return NULL;// nothing to skip
  1868. // initial bracket (assumes the previous part is ok)
  1869. p = strchr(start,'{');
  1870. if( p == NULL )
  1871. {
  1872. ShowError("npc_skip_script: Missing left curly in file '%s', line'%d'.", filepath, strline(buffer,start-buffer));
  1873. return NULL;// can't continue
  1874. }
  1875. // skip everything
  1876. for( curly_count = 1; curly_count > 0 ; )
  1877. {
  1878. p = skip_space(p+1) ;
  1879. if( *p == '}' )
  1880. {// right curly
  1881. --curly_count;
  1882. }
  1883. else if( *p == '{' )
  1884. {// left curly
  1885. ++curly_count;
  1886. }
  1887. else if( *p == '"' )
  1888. {// string
  1889. for( ++p; *p != '"' ; ++p )
  1890. {
  1891. if( *p == '\\' && (unsigned char)p[-1] <= 0x7e )
  1892. ++p;// escape sequence (not part of a multibyte character)
  1893. else if( *p == '\0' )
  1894. {
  1895. script_error(buffer, filepath, 0, "Unexpected end of string.", p);
  1896. return NULL;// can't continue
  1897. }
  1898. else if( *p == '\n' )
  1899. {
  1900. script_error(buffer, filepath, 0, "Unexpected newline at string.", p);
  1901. return NULL;// can't continue
  1902. }
  1903. }
  1904. }
  1905. else if( *p == '\0' )
  1906. {// end of buffer
  1907. ShowError("Missing %d right curlys at file '%s', line '%d'.\n", curly_count, filepath, strline(buffer,p-buffer));
  1908. return NULL;// can't continue
  1909. }
  1910. }
  1911. return p+1;// return after the last '}'
  1912. }
  1913. /// Parses a npc script.
  1914. ///
  1915. /// -%TAB%script%TAB%<NPC Name>%TAB%-1,{<code>}
  1916. /// <map name>,<x>,<y>,<facing>%TAB%script%TAB%<NPC Name>%TAB%<sprite id>,{<code>}
  1917. /// <map name>,<x>,<y>,<facing>%TAB%script%TAB%<NPC Name>%TAB%<sprite id>,<triggerX>,<triggerY>,{<code>}
  1918. static const char* npc_parse_script(char* w1, char* w2, char* w3, char* w4, const char* start, const char* buffer, const char* filepath)
  1919. {
  1920. int x, y, dir = 0, m, xs = 0, ys = 0, class_ = 0; // [Valaris] thanks to fov
  1921. char mapname[32];
  1922. struct script_code *script;
  1923. int i;
  1924. const char* end;
  1925. const char* script_start;
  1926. struct npc_label_list* label_list;
  1927. int label_list_num;
  1928. struct npc_data* nd;
  1929. if( strcmp(w1, "-") == 0 )
  1930. {// floating npc
  1931. x = 0;
  1932. y = 0;
  1933. m = -1;
  1934. }
  1935. else
  1936. {// npc in a map
  1937. if( sscanf(w1, "%31[^,],%d,%d,%d", mapname, &x, &y, &dir) != 4 )
  1938. {
  1939. 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);
  1940. return NULL;// unknown format, don't continue
  1941. }
  1942. m = map_mapname2mapid(mapname);
  1943. }
  1944. script_start = strstr(start,",{");
  1945. end = strchr(start,'\n');
  1946. if( strstr(w4,",{") == NULL || script_start == NULL || (end != NULL && script_start > end) )
  1947. {
  1948. 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);
  1949. return NULL;// can't continue
  1950. }
  1951. ++script_start;
  1952. end = npc_skip_script(script_start, buffer, filepath);
  1953. if( end == NULL )
  1954. return NULL;// (simple) parse error, don't continue
  1955. script = parse_script(script_start, filepath, strline(buffer,script_start-buffer), SCRIPT_USE_LABEL_DB);
  1956. label_list = NULL;
  1957. label_list_num = 0;
  1958. if( script )
  1959. {
  1960. DBMap* label_db = script_get_label_db();
  1961. label_db->foreach(label_db, npc_convertlabel_db, &label_list, &label_list_num, filepath);
  1962. db_clear(label_db); // not needed anymore, so clear the db
  1963. }
  1964. CREATE(nd, struct npc_data, 1);
  1965. if( sscanf(w4, "%d,%d,%d", &class_, &xs, &ys) == 3 )
  1966. {// OnTouch area defined
  1967. nd->u.scr.xs = xs;
  1968. nd->u.scr.ys = ys;
  1969. }
  1970. else
  1971. {// no OnTouch area
  1972. class_ = atoi(w4);
  1973. nd->u.scr.xs = -1;
  1974. nd->u.scr.ys = -1;
  1975. }
  1976. nd->bl.prev = nd->bl.next = NULL;
  1977. nd->bl.m = m;
  1978. nd->bl.x = x;
  1979. nd->bl.y = y;
  1980. npc_parsename(nd, w3, start, buffer, filepath);
  1981. nd->bl.id = npc_get_new_npc_id();
  1982. nd->class_ = class_;
  1983. nd->speed = 200;
  1984. nd->u.scr.script = script;
  1985. nd->u.scr.label_list = label_list;
  1986. nd->u.scr.label_list_num = label_list_num;
  1987. ++npc_script;
  1988. nd->bl.type = BL_NPC;
  1989. nd->subtype = SCRIPT;
  1990. if( m >= 0 )
  1991. {
  1992. map_addnpc(m, nd);
  1993. status_change_init(&nd->bl);
  1994. unit_dataset(&nd->bl);
  1995. nd->ud.dir = dir;
  1996. npc_setcells(nd);
  1997. map_addblock(&nd->bl);
  1998. if( class_ >= 0 )
  1999. {
  2000. status_set_viewdata(&nd->bl, nd->class_);
  2001. if( map[nd->bl.m].users )
  2002. clif_spawn(&nd->bl);
  2003. }
  2004. }
  2005. else
  2006. {
  2007. // we skip map_addnpc, but still add it to the list of ID's
  2008. map_addiddb(&nd->bl);
  2009. }
  2010. strdb_put(npcname_db, nd->exname, nd);
  2011. //-----------------------------------------
  2012. // Loop through labels to export them as necessary
  2013. for (i = 0; i < nd->u.scr.label_list_num; i++) {
  2014. if (npc_event_export(nd, i)) {
  2015. ShowWarning("npc_parse_script : duplicate event %s::%s (%s)\n",
  2016. nd->exname, nd->u.scr.label_list[i].name, filepath);
  2017. }
  2018. npc_timerevent_export(nd, i);
  2019. }
  2020. nd->u.scr.timerid = INVALID_TIMER;
  2021. return end;
  2022. }
  2023. /// Duplicate a warp, shop, cashshop or script. [Orcao]
  2024. /// warp: <map name>,<x>,<y>,<facing>%TAB%duplicate(<name of target>)%TAB%<NPC Name>%TAB%<spanx>,<spany>
  2025. /// shop/cashshop/npc: -%TAB%duplicate(<name of target>)%TAB%<NPC Name>%TAB%<sprite id>
  2026. /// shop/cashshop/npc: <map name>,<x>,<y>,<facing>%TAB%duplicate(<name of target>)%TAB%<NPC Name>%TAB%<sprite id>
  2027. /// npc: -%TAB%duplicate(<name of target>)%TAB%<NPC Name>%TAB%<sprite id>,<triggerX>,<triggerY>
  2028. /// npc: <map name>,<x>,<y>,<facing>%TAB%duplicate(<name of target>)%TAB%<NPC Name>%TAB%<sprite id>,<triggerX>,<triggerY>
  2029. const char* npc_parse_duplicate(char* w1, char* w2, char* w3, char* w4, const char* start, const char* buffer, const char* filepath)
  2030. {
  2031. int x, y, dir, m, xs = -1, ys = -1, class_ = 0;
  2032. char mapname[32];
  2033. char srcname[128];
  2034. int i;
  2035. const char* end;
  2036. size_t length;
  2037. int src_id;
  2038. int type;
  2039. struct npc_data* nd;
  2040. struct npc_data* dnd;
  2041. end = strchr(start,'\n');
  2042. length = strlen(w2);
  2043. // get the npc being duplicated
  2044. if( w2[length-1] != ')' || length <= 11 || length-11 >= sizeof(srcname) )
  2045. {// does not match 'duplicate(%127s)', name is empty or too long
  2046. ShowError("npc_parse_script: bad duplicate name in file '%s', line '%d' : %s\n", filepath, strline(buffer,start-buffer), w2);
  2047. return end;// next line, try to continue
  2048. }
  2049. safestrncpy(srcname, w2+10, length-10);
  2050. dnd = npc_name2id(srcname);
  2051. if( dnd == NULL) {
  2052. ShowError("npc_parse_script: original npc not found for duplicate in file '%s', line '%d' : %s\n", filepath, strline(buffer,start-buffer), srcname);
  2053. return end;// next line, try to continue
  2054. }
  2055. src_id = dnd->bl.id;
  2056. type = dnd->subtype;
  2057. // get placement
  2058. if( (type==SHOP || type==CASHSHOP || type==SCRIPT) && strcmp(w1, "-") == 0 )
  2059. {// floating shop/chashshop/script
  2060. x = y = dir = 0;
  2061. m = -1;
  2062. }
  2063. else
  2064. {
  2065. if( sscanf(w1, "%31[^,],%d,%d,%d", mapname, &x, &y, &dir) != 4 )// <map name>,<x>,<y>,<facing>
  2066. {
  2067. 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);
  2068. return end;// next line, try to continue
  2069. }
  2070. m = map_mapname2mapid(mapname);
  2071. }
  2072. if( type == WARP && sscanf(w4, "%d,%d", &xs, &ys) == 2 );// <spanx>,<spany>
  2073. else if( type == SCRIPT && sscanf(w4, "%d,%d,%d", &class_, &xs, &ys) == 3);// <sprite id>,<triggerX>,<triggerY>
  2074. else if( type != WARP ) class_ = atoi(w4);// <sprite id>
  2075. else
  2076. {
  2077. 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);
  2078. return end;// next line, try to continue
  2079. }
  2080. CREATE(nd, struct npc_data, 1);
  2081. nd->bl.prev = nd->bl.next = NULL;
  2082. nd->bl.m = m;
  2083. nd->bl.x = x;
  2084. nd->bl.y = y;
  2085. npc_parsename(nd, w3, start, buffer, filepath);
  2086. nd->bl.id = npc_get_new_npc_id();
  2087. nd->class_ = class_;
  2088. nd->speed = 200;
  2089. nd->src_id = src_id;
  2090. nd->bl.type = BL_NPC;
  2091. nd->subtype = (enum npc_subtype)type;
  2092. switch( type )
  2093. {
  2094. case SCRIPT:
  2095. ++npc_script;
  2096. nd->u.scr.xs = xs;
  2097. nd->u.scr.ys = ys;
  2098. nd->u.scr.script = dnd->u.scr.script;
  2099. nd->u.scr.label_list = dnd->u.scr.label_list;
  2100. nd->u.scr.label_list_num = dnd->u.scr.label_list_num;
  2101. break;
  2102. case SHOP:
  2103. case CASHSHOP:
  2104. ++npc_shop;
  2105. nd->u.shop.shop_item = dnd->u.shop.shop_item;
  2106. nd->u.shop.count = dnd->u.shop.count;
  2107. break;
  2108. case WARP:
  2109. ++npc_warp;
  2110. if( !battle_config.warp_point_debug )
  2111. nd->class_ = WARP_CLASS;
  2112. else
  2113. nd->class_ = WARP_DEBUG_CLASS;
  2114. nd->u.warp.xs = xs;
  2115. nd->u.warp.ys = ys;
  2116. nd->u.warp.mapindex = dnd->u.warp.mapindex;
  2117. nd->u.warp.x = dnd->u.warp.x;
  2118. nd->u.warp.y = dnd->u.warp.y;
  2119. break;
  2120. }
  2121. //Add the npc to its location
  2122. if( m >= 0 )
  2123. {
  2124. map_addnpc(m, nd);
  2125. status_change_init(&nd->bl);
  2126. unit_dataset(&nd->bl);
  2127. nd->ud.dir = dir;
  2128. npc_setcells(nd);
  2129. map_addblock(&nd->bl);
  2130. if( class_ >= 0 )
  2131. {
  2132. status_set_viewdata(&nd->bl, nd->class_);
  2133. if( map[nd->bl.m].users )
  2134. clif_spawn(&nd->bl);
  2135. }
  2136. }
  2137. else
  2138. {
  2139. // we skip map_addnpc, but still add it to the list of ID's
  2140. map_addiddb(&nd->bl);
  2141. }
  2142. strdb_put(npcname_db, nd->exname, nd);
  2143. if( type != SCRIPT )
  2144. return end;
  2145. //-----------------------------------------
  2146. // Loop through labels to export them as necessary
  2147. for (i = 0; i < nd->u.scr.label_list_num; i++) {
  2148. if (npc_event_export(nd, i)) {
  2149. ShowWarning("npc_parse_duplicate : duplicate event %s::%s (%s)\n",
  2150. nd->exname, nd->u.scr.label_list[i].name, filepath);
  2151. }
  2152. npc_timerevent_export(nd, i);
  2153. }
  2154. nd->u.scr.timerid = INVALID_TIMER;
  2155. return end;
  2156. }
  2157. int npc_duplicate4instance(struct npc_data *snd, int m)
  2158. {
  2159. char newname[NAME_LENGTH];
  2160. if( map[m].instance_id == 0 )
  2161. return 1;
  2162. snprintf(newname, ARRAYLENGTH(newname), "dup_%d_%d", map[m].instance_id, snd->bl.id);
  2163. if( npc_name2id(newname) != NULL )
  2164. { // Name already in use
  2165. ShowError("npc_duplicate4instance: the npcname (%s) is already in use while trying to duplicate npc %s in instance %d.\n", newname, snd->exname, map[m].instance_id);
  2166. return 1;
  2167. }
  2168. if( snd->subtype == WARP )
  2169. { // Adjust destination, if instanced
  2170. struct npc_data *wnd = NULL; // New NPC
  2171. int dm = map_mapindex2mapid(snd->u.warp.mapindex), im;
  2172. if( dm < 0 ) return 1;
  2173. im = instance_mapid2imapid(dm, map[m].instance_id);
  2174. if( im == -1 )
  2175. {
  2176. ShowError("npc_duplicate4instance: warp (%s) leading to instanced map (%s), but instance map is not attached to current instance.\n", map[dm].name, snd->exname);
  2177. return 1;
  2178. }
  2179. CREATE(wnd, struct npc_data, 1);
  2180. wnd->bl.id = npc_get_new_npc_id();
  2181. map_addnpc(m, wnd);
  2182. wnd->bl.prev = wnd->bl.next = NULL;
  2183. wnd->bl.m = m;
  2184. wnd->bl.x = snd->bl.x;
  2185. wnd->bl.y = snd->bl.y;
  2186. safestrncpy(wnd->name, "", ARRAYLENGTH(wnd->name));
  2187. safestrncpy(wnd->exname, newname, ARRAYLENGTH(wnd->exname));
  2188. wnd->class_ = WARP_CLASS;
  2189. wnd->speed = 200;
  2190. wnd->u.warp.mapindex = map_id2index(im);
  2191. wnd->u.warp.x = snd->u.warp.x;
  2192. wnd->u.warp.y = snd->u.warp.y;
  2193. wnd->u.warp.xs = snd->u.warp.xs;
  2194. wnd->u.warp.ys = snd->u.warp.ys;
  2195. wnd->bl.type = BL_NPC;
  2196. wnd->subtype = WARP;
  2197. npc_setcells(wnd);
  2198. map_addblock(&wnd->bl);
  2199. status_set_viewdata(&wnd->bl, wnd->class_);
  2200. status_change_init(&wnd->bl);
  2201. unit_dataset(&wnd->bl);
  2202. if( map[wnd->bl.m].users )
  2203. clif_spawn(&wnd->bl);
  2204. strdb_put(npcname_db, wnd->exname, wnd);
  2205. }
  2206. else
  2207. {
  2208. static char w1[50], w2[50], w3[50], w4[50];
  2209. const char* stat_buf = "- call from instancing subsystem -\n";
  2210. snprintf(w1, sizeof(w1), "%s,%d,%d,%d", map[m].name, snd->bl.x, snd->bl.y, snd->ud.dir);
  2211. snprintf(w2, sizeof(w2), "duplicate(%s)", snd->exname);
  2212. snprintf(w3, sizeof(w3), "%s::%s", snd->name, newname);
  2213. if( snd->u.scr.xs >= 0 && snd->u.scr.ys >= 0 )
  2214. snprintf(w4, sizeof(w4), "%d,%d,%d", snd->class_, snd->u.scr.xs, snd->u.scr.ys); // Touch Area
  2215. else
  2216. snprintf(w4, sizeof(w4), "%d", snd->class_);
  2217. npc_parse_duplicate(w1, w2, w3, w4, stat_buf, stat_buf, "INSTANCING");
  2218. }
  2219. return 0;
  2220. }
  2221. void npc_setcells(struct npc_data* nd)
  2222. {
  2223. int m = nd->bl.m, x = nd->bl.x, y = nd->bl.y, xs, ys;
  2224. int i,j;
  2225. switch(nd->subtype)
  2226. {
  2227. case WARP:
  2228. xs = nd->u.warp.xs;
  2229. ys = nd->u.warp.ys;
  2230. break;
  2231. case SCRIPT:
  2232. xs = nd->u.scr.xs;
  2233. ys = nd->u.scr.ys;
  2234. break;
  2235. default:
  2236. return; // Other types doesn't have touch area
  2237. }
  2238. if (m < 0 || xs < 0 || ys < 0)
  2239. return;
  2240. for (i = y-ys; i <= y+ys; i++) {
  2241. for (j = x-xs; j <= x+xs; j++) {
  2242. if (map_getcell(m, j, i, CELL_CHKNOPASS))
  2243. continue;
  2244. map_setcell(m, j, i, CELL_NPC, true);
  2245. }
  2246. }
  2247. }
  2248. int npc_unsetcells_sub(struct block_list* bl, va_list ap)
  2249. {
  2250. struct npc_data *nd = (struct npc_data*)bl;
  2251. int id = va_arg(ap,int);
  2252. if (nd->bl.id == id) return 0;
  2253. npc_setcells(nd);
  2254. return 1;
  2255. }
  2256. void npc_unsetcells(struct npc_data* nd)
  2257. {
  2258. int m = nd->bl.m, x = nd->bl.x, y = nd->bl.y, xs, ys;
  2259. int i,j, x0, x1, y0, y1;
  2260. if (nd->subtype == WARP) {
  2261. xs = nd->u.warp.xs;
  2262. ys = nd->u.warp.ys;
  2263. } else {
  2264. xs = nd->u.scr.xs;
  2265. ys = nd->u.scr.ys;
  2266. }
  2267. if (m < 0 || xs < 0 || ys < 0)
  2268. return;
  2269. //Locate max range on which we can locate npc cells
  2270. //FIXME: does this really do what it's supposed to do? [ultramage]
  2271. for(x0 = x-xs; x0 > 0 && map_getcell(m, x0, y, CELL_CHKNPC); x0--);
  2272. for(x1 = x+xs; x1 < map[m].xs-1 && map_getcell(m, x1, y, CELL_CHKNPC); x1++);
  2273. for(y0 = y-ys; y0 > 0 && map_getcell(m, x, y0, CELL_CHKNPC); y0--);
  2274. for(y1 = y+ys; y1 < map[m].ys-1 && map_getcell(m, x, y1, CELL_CHKNPC); y1++);
  2275. //Erase this npc's cells
  2276. for (i = y-ys; i <= y+ys; i++)
  2277. for (j = x-xs; j <= x+xs; j++)
  2278. map_setcell(m, j, i, CELL_NPC, false);
  2279. //Re-deploy NPC cells for other nearby npcs.
  2280. map_foreachinarea( npc_unsetcells_sub, m, x0, y0, x1, y1, BL_NPC, nd->bl.id );
  2281. }
  2282. void npc_movenpc(struct npc_data* nd, int x, int y)
  2283. {
  2284. const int m = nd->bl.m;
  2285. if (m < 0 || nd->bl.prev == NULL) return; //Not on a map.
  2286. x = cap_value(x, 0, map[m].xs-1);
  2287. y = cap_value(y, 0, map[m].ys-1);
  2288. map_foreachinrange(clif_outsight, &nd->bl, AREA_SIZE, BL_PC, &nd->bl);
  2289. map_moveblock(&nd->bl, x, y, gettick());
  2290. map_foreachinrange(clif_insight, &nd->bl, AREA_SIZE, BL_PC, &nd->bl);
  2291. }
  2292. /// Changes the display name of the npc.
  2293. ///
  2294. /// @param nd Target npc
  2295. /// @param newname New display name
  2296. void npc_setdisplayname(struct npc_data* nd, const char* newname)
  2297. {
  2298. nullpo_retv(nd);
  2299. safestrncpy(nd->name, newname, sizeof(nd->name));
  2300. if( map[nd->bl.m].users )
  2301. clif_charnameack(0, &nd->bl);
  2302. }
  2303. /// Changes the display class of the npc.
  2304. ///
  2305. /// @param nd Target npc
  2306. /// @param class_ New display class
  2307. void npc_setclass(struct npc_data* nd, short class_)
  2308. {
  2309. nullpo_retv(nd);
  2310. if( nd->class_ == class_ )
  2311. return;
  2312. if( map[nd->bl.m].users )
  2313. clif_clearunit_area(&nd->bl, CLR_OUTSIGHT);// fade out
  2314. nd->class_ = class_;
  2315. status_set_viewdata(&nd->bl, class_);
  2316. if( map[nd->bl.m].users )
  2317. clif_spawn(&nd->bl);// fade in
  2318. }
  2319. /// Parses a function.
  2320. /// function%TAB%script%TAB%<function name>%TAB%{<code>}
  2321. static const char* npc_parse_function(char* w1, char* w2, char* w3, char* w4, const char* start, const char* buffer, const char* filepath)
  2322. {
  2323. DBMap* func_db;
  2324. DBData old_data;
  2325. struct script_code *script;
  2326. const char* end;
  2327. const char* script_start;
  2328. script_start = strstr(start,"\t{");
  2329. end = strchr(start,'\n');
  2330. if( *w4 != '{' || script_start == NULL || (end != NULL && script_start > end) )
  2331. {
  2332. 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);
  2333. return NULL;// can't continue
  2334. }
  2335. ++script_start;
  2336. end = npc_skip_script(script_start,buffer,filepath);
  2337. if( end == NULL )
  2338. return NULL;// (simple) parse error, don't continue
  2339. script = parse_script(script_start, filepath, strline(buffer,start-buffer), SCRIPT_RETURN_EMPTY_SCRIPT);
  2340. if( script == NULL )// parse error, continue
  2341. return end;
  2342. func_db = script_get_userfunc_db();
  2343. if (func_db->put(func_db, db_str2key(w3), db_ptr2data(script), &old_data))
  2344. {
  2345. struct script_code *oldscript = db_data2ptr(&old_data);
  2346. ShowInfo("npc_parse_function: Overwriting user function [%s] (%s:%d)\n", w3, filepath, strline(buffer,start-buffer));
  2347. script_free_vars(&oldscript->script_vars);
  2348. aFree(oldscript->script_buf);
  2349. aFree(oldscript);
  2350. }
  2351. return end;
  2352. }
  2353. /*==========================================
  2354. * Parse Mob 1 - Parse mob list into each map
  2355. * Parse Mob 2 - Actually Spawns Mob
  2356. * [Wizputer]
  2357. *------------------------------------------*/
  2358. void npc_parse_mob2(struct spawn_data* mob)
  2359. {
  2360. int i;
  2361. for( i = mob->active; i < mob->num; ++i )
  2362. {
  2363. struct mob_data* md = mob_spawn_dataset(mob);
  2364. md->spawn = mob;
  2365. md->spawn->active++;
  2366. mob_spawn(md);
  2367. }
  2368. }
  2369. static const char* npc_parse_mob(char* w1, char* w2, char* w3, char* w4, const char* start, const char* buffer, const char* filepath)
  2370. {
  2371. int num, class_, m,x,y,xs,ys, i,j;
  2372. char mapname[32];
  2373. struct spawn_data mob, *data;
  2374. struct mob_db* db;
  2375. memset(&mob, 0, sizeof(struct spawn_data));
  2376. mob.state.boss = !strcmpi(w2,"boss_monster");
  2377. // w1=<map name>,<x>,<y>,<xs>,<ys>
  2378. // w4=<mob id>,<amount>,<delay1>,<delay2>,<event>
  2379. if( sscanf(w1, "%31[^,],%d,%d,%d,%d", mapname, &x, &y, &xs, &ys) < 3
  2380. || sscanf(w4, "%d,%d,%u,%u,%127[^\t\r\n]", &class_, &num, &mob.delay1, &mob.delay2, mob.eventname) < 2 )
  2381. {
  2382. 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);
  2383. return strchr(start,'\n');// skip and continue
  2384. }
  2385. if( mapindex_name2id(mapname) == 0 )
  2386. {
  2387. ShowError("npc_parse_mob: Unknown map '%s' in file '%s', line '%d'.\n", mapname, filepath, strline(buffer,start-buffer));
  2388. return strchr(start,'\n');// skip and continue
  2389. }
  2390. m = map_mapname2mapid(mapname);
  2391. if( m < 0 )//Not loaded on this map-server instance.
  2392. return strchr(start,'\n');// skip and continue
  2393. mob.m = (unsigned short)m;
  2394. if( x < 0 || x >= map[mob.m].xs || y < 0 || y >= map[mob.m].ys )
  2395. {
  2396. ShowError("npc_parse_mob: Spawn coordinates out of range: %s (%d,%d), map size is (%d,%d) - %s %s (file '%s', line '%d').\n", map[mob.m].name, x, y, (map[mob.m].xs-1), (map[mob.m].ys-1), w1, w3, filepath, strline(buffer,start-buffer));
  2397. return strchr(start,'\n');// skip and continue
  2398. }
  2399. // check monster ID if exists!
  2400. if( mobdb_checkid(class_) == 0 )
  2401. {
  2402. ShowError("npc_parse_mob: Unknown mob ID %d (file '%s', line '%d').\n", class_, filepath, strline(buffer,start-buffer));
  2403. return strchr(start,'\n');// skip and continue
  2404. }
  2405. if( num < 1 || num > 1000 )
  2406. {
  2407. 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));
  2408. return strchr(start,'\n');// skip and continue
  2409. }
  2410. mob.num = (unsigned short)num;
  2411. mob.active = 0;
  2412. mob.class_ = (short) class_;
  2413. mob.x = (unsigned short)x;
  2414. mob.y = (unsigned short)y;
  2415. mob.xs = (signed short)xs;
  2416. mob.ys = (signed short)ys;
  2417. if (mob.num > 1 && battle_config.mob_count_rate != 100) {
  2418. if ((mob.num = mob.num * battle_config.mob_count_rate / 100) < 1)
  2419. mob.num = 1;
  2420. }
  2421. if (battle_config.force_random_spawn || (mob.x == 0 && mob.y == 0))
  2422. { //Force a random spawn anywhere on the map.
  2423. mob.x = mob.y = 0;
  2424. mob.xs = mob.ys = -1;
  2425. }
  2426. if(mob.delay1>0xfffffff || mob.delay2>0xfffffff) {
  2427. ShowError("npc_parse_mob: Invalid spawn delays %u %u (file '%s', line '%d').\n", mob.delay1, mob.delay2, filepath, strline(buffer,start-buffer));
  2428. return strchr(start,'\n');// skip and continue
  2429. }
  2430. //Use db names instead of the spawn file ones.
  2431. if(battle_config.override_mob_names==1)
  2432. strcpy(mob.name,"--en--");
  2433. else if (battle_config.override_mob_names==2)
  2434. strcpy(mob.name,"--ja--");
  2435. else
  2436. safestrncpy(mob.name, w3, sizeof(mob.name));
  2437. //Verify dataset.
  2438. if( !mob_parse_dataset(&mob) )
  2439. {
  2440. ShowError("npc_parse_mob: Invalid dataset for monster ID %d (file '%s', line '%d').\n", class_, filepath, strline(buffer,start-buffer));
  2441. return strchr(start,'\n');// skip and continue
  2442. }
  2443. //Update mob spawn lookup database
  2444. db = mob_db(class_);
  2445. for( i = 0; i < ARRAYLENGTH(db->spawn); ++i )
  2446. {
  2447. if (map[mob.m].index == db->spawn[i].mapindex)
  2448. { //Update total
  2449. db->spawn[i].qty += mob.num;
  2450. //Re-sort list
  2451. for( j = i; j > 0 && db->spawn[j-1].qty < db->spawn[i].qty; --j );
  2452. if( j != i )
  2453. {
  2454. xs = db->spawn[i].mapindex;
  2455. ys = db->spawn[i].qty;
  2456. memmove(&db->spawn[j+1], &db->spawn[j], (i-j)*sizeof(db->spawn[0]));
  2457. db->spawn[j].mapindex = xs;
  2458. db->spawn[j].qty = ys;
  2459. }
  2460. break;
  2461. }
  2462. if (mob.num > db->spawn[i].qty)
  2463. { //Insert into list
  2464. memmove(&db->spawn[i+1], &db->spawn[i], sizeof(db->spawn) -(i+1)*sizeof(db->spawn[0]));
  2465. db->spawn[i].mapindex = map[mob.m].index;
  2466. db->spawn[i].qty = mob.num;
  2467. break;
  2468. }
  2469. }
  2470. //Now that all has been validated. We allocate the actual memory that the re-spawn data will use.
  2471. data = (struct spawn_data*)aMalloc(sizeof(struct spawn_data));
  2472. memcpy(data, &mob, sizeof(struct spawn_data));
  2473. // spawn / cache the new mobs
  2474. if( battle_config.dynamic_mobs && map_addmobtolist(data->m, data) >= 0 )
  2475. {
  2476. data->state.dynamic = true;
  2477. npc_cache_mob += data->num;
  2478. // check if target map has players
  2479. // (usually shouldn't occur when map server is just starting,
  2480. // but not the case when we do @reloadscript
  2481. if( map[data->m].users > 0 )
  2482. npc_parse_mob2(data);
  2483. }
  2484. else
  2485. {
  2486. data->state.dynamic = false;
  2487. npc_parse_mob2(data);
  2488. npc_delay_mob += data->num;
  2489. }
  2490. npc_mob++;
  2491. return strchr(start,'\n');// continue
  2492. }
  2493. /*==========================================
  2494. * マップフラグ行の解析
  2495. *------------------------------------------*/
  2496. static const char* npc_parse_mapflag(char* w1, char* w2, char* w3, char* w4, const char* start, const char* buffer, const char* filepath)
  2497. {
  2498. int m;
  2499. char mapname[32];
  2500. int state = 1;
  2501. // w1=<mapname>
  2502. if( sscanf(w1, "%31[^,]", mapname) != 1 )
  2503. {
  2504. 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);
  2505. return strchr(start,'\n');// skip and continue
  2506. }
  2507. m = map_mapname2mapid(mapname);
  2508. if( m < 0 )
  2509. {
  2510. ShowWarning("npc_parse_mapflag: Unknown map in file '%s', line '%d' : %s\n * w1=%s\n * w2=%s\n * w3=%s\n * w4=%s\n", mapname, filepath, strline(buffer,start-buffer), w1, w2, w3, w4);
  2511. return strchr(start,'\n');// skip and continue
  2512. }
  2513. if (w4 && !strcmpi(w4, "off"))
  2514. state = 0; //Disable mapflag rather than enable it. [Skotlex]
  2515. if (!strcmpi(w3, "nosave")) {
  2516. char savemap[32];
  2517. int savex, savey;
  2518. if (state == 0)
  2519. ; //Map flag disabled.
  2520. else if (!strcmpi(w4, "SavePoint")) {
  2521. map[m].save.map = 0;
  2522. map[m].save.x = -1;
  2523. map[m].save.y = -1;
  2524. } else if (sscanf(w4, "%31[^,],%d,%d", savemap, &savex, &savey) == 3) {
  2525. map[m].save.map = mapindex_name2id(savemap);
  2526. map[m].save.x = savex;
  2527. map[m].save.y = savey;
  2528. if (!map[m].save.map) {
  2529. 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);
  2530. map[m].save.x = -1;
  2531. map[m].save.y = -1;
  2532. }
  2533. }
  2534. map[m].flag.nosave = state;
  2535. }
  2536. else if (!strcmpi(w3,"autotrade"))
  2537. map[m].flag.autotrade=state;
  2538. else if (!strcmpi(w3,"allowks"))
  2539. map[m].flag.allowks=state; // [Kill Steal Protection]
  2540. else if (!strcmpi(w3,"town"))
  2541. map[m].flag.town=state;
  2542. else if (!strcmpi(w3,"nomemo"))
  2543. map[m].flag.nomemo=state;
  2544. else if (!strcmpi(w3,"noteleport"))
  2545. map[m].flag.noteleport=state;
  2546. else if (!strcmpi(w3,"nowarp"))
  2547. map[m].flag.nowarp=state;
  2548. else if (!strcmpi(w3,"nowarpto"))
  2549. map[m].flag.nowarpto=state;
  2550. else if (!strcmpi(w3,"noreturn"))
  2551. map[m].flag.noreturn=state;
  2552. else if (!strcmpi(w3,"monster_noteleport"))
  2553. map[m].flag.monster_noteleport=state;
  2554. else if (!strcmpi(w3,"nobranch"))
  2555. map[m].flag.nobranch=state;
  2556. else if (!strcmpi(w3,"nopenalty")) {
  2557. map[m].flag.noexppenalty=state;
  2558. map[m].flag.nozenypenalty=state;
  2559. }
  2560. else if (!strcmpi(w3,"pvp")) {
  2561. map[m].flag.pvp = state;
  2562. if( state && (map[m].flag.gvg || map[m].flag.gvg_dungeon || map[m].flag.gvg_castle) )
  2563. {
  2564. map[m].flag.gvg = 0;
  2565. map[m].flag.gvg_dungeon = 0;
  2566. map[m].flag.gvg_castle = 0;
  2567. ShowWarning("npc_parse_mapflag: You can't set PvP and GvG flags for the same map! Removing GvG flags from %s (file '%s', line '%d').\n", map[m].name, filepath, strline(buffer,start-buffer));
  2568. }
  2569. if( state && map[m].flag.battleground )
  2570. {
  2571. map[m].flag.battleground = 0;
  2572. ShowWarning("npc_parse_mapflag: You can't set GvG and BattleGround flags for the same map! Removing BattleGround flag from %s (file '%s', line '%d').\n", map[m].name, filepath, strline(buffer,start-buffer));
  2573. }
  2574. }
  2575. else if (!strcmpi(w3,"pvp_noparty"))
  2576. map[m].flag.pvp_noparty=state;
  2577. else if (!strcmpi(w3,"pvp_noguild"))
  2578. map[m].flag.pvp_noguild=state;
  2579. else if (!strcmpi(w3, "pvp_nightmaredrop")) {
  2580. char drop_arg1[16], drop_arg2[16];
  2581. int drop_id = 0, drop_type = 0, drop_per = 0;
  2582. if (sscanf(w4, "%[^,],%[^,],%d", drop_arg1, drop_arg2, &drop_per) == 3) {
  2583. int i;
  2584. if (!strcmpi(drop_arg1, "random"))
  2585. drop_id = -1;
  2586. else if (itemdb_exists((drop_id = atoi(drop_arg1))) == NULL)
  2587. drop_id = 0;
  2588. if (!strcmpi(drop_arg2, "inventory"))
  2589. drop_type = 1;
  2590. else if (!strcmpi(drop_arg2,"equip"))
  2591. drop_type = 2;
  2592. else if (!strcmpi(drop_arg2,"all"))
  2593. drop_type = 3;
  2594. if (drop_id != 0){
  2595. for (i = 0; i < MAX_DROP_PER_MAP; i++) {
  2596. if (map[m].drop_list[i].drop_id == 0){
  2597. map[m].drop_list[i].drop_id = drop_id;
  2598. map[m].drop_list[i].drop_type = drop_type;
  2599. map[m].drop_list[i].drop_per = drop_per;
  2600. break;
  2601. }
  2602. }
  2603. map[m].flag.pvp_nightmaredrop = 1;
  2604. }
  2605. } else if (!state) //Disable
  2606. map[m].flag.pvp_nightmaredrop = 0;
  2607. }
  2608. else if (!strcmpi(w3,"pvp_nocalcrank"))
  2609. map[m].flag.pvp_nocalcrank=state;
  2610. else if (!strcmpi(w3,"gvg")) {
  2611. map[m].flag.gvg = state;
  2612. if( state && map[m].flag.pvp )
  2613. {
  2614. map[m].flag.pvp = 0;
  2615. ShowWarning("npc_parse_mapflag: You can't set PvP and GvG flags for the same map! Removing PvP flag from %s (file '%s', line '%d').\n", map[m].name, filepath, strline(buffer,start-buffer));
  2616. }
  2617. if( state && map[m].flag.battleground )
  2618. {
  2619. map[m].flag.battleground = 0;
  2620. ShowWarning("npc_parse_mapflag: You can't set PvP and BattleGround flags for the same map! Removing BattleGround flag from %s (file '%s', line '%d').\n", map[m].name, filepath, strline(buffer,start-buffer));
  2621. }
  2622. }
  2623. else if (!strcmpi(w3,"gvg_noparty"))
  2624. map[m].flag.gvg_noparty=state;
  2625. else if (!strcmpi(w3,"gvg_dungeon")) {
  2626. map[m].flag.gvg_dungeon=state;
  2627. if (state) map[m].flag.pvp=0;
  2628. }
  2629. else if (!strcmpi(w3,"gvg_castle")) {
  2630. map[m].flag.gvg_castle=state;
  2631. if (state) map[m].flag.pvp=0;
  2632. }
  2633. else if (!strcmpi(w3,"battleground")) {
  2634. if( state )
  2635. {
  2636. if( sscanf(w4, "%d", &state) == 1 )
  2637. map[m].flag.battleground = state;
  2638. else
  2639. map[m].flag.battleground = 1; // Default value
  2640. }
  2641. else
  2642. map[m].flag.battleground = 0;
  2643. if( map[m].flag.battleground && map[m].flag.pvp )
  2644. {
  2645. map[m].flag.pvp = 0;
  2646. ShowWarning("npc_parse_mapflag: You can't set PvP and BattleGround flags for the same map! Removing PvP flag from %s (file '%s', line '%d').\n", map[m].name, filepath, strline(buffer,start-buffer));
  2647. }
  2648. if( map[m].flag.battleground && (map[m].flag.gvg || map[m].flag.gvg_dungeon || map[m].flag.gvg_castle) )
  2649. {
  2650. map[m].flag.gvg = 0;
  2651. map[m].flag.gvg_dungeon = 0;
  2652. map[m].flag.gvg_castle = 0;
  2653. ShowWarning("npc_parse_mapflag: You can't set GvG and BattleGround flags for the same map! Removing GvG flag from %s (file '%s', line '%d').\n", map[m].name, filepath, strline(buffer,start-buffer));
  2654. }
  2655. }
  2656. else if (!strcmpi(w3,"noexppenalty"))
  2657. map[m].flag.noexppenalty=state;
  2658. else if (!strcmpi(w3,"nozenypenalty"))
  2659. map[m].flag.nozenypenalty=state;
  2660. else if (!strcmpi(w3,"notrade"))
  2661. map[m].flag.notrade=state;
  2662. else if (!strcmpi(w3,"novending"))
  2663. map[m].flag.novending=state;
  2664. else if (!strcmpi(w3,"nodrop"))
  2665. map[m].flag.nodrop=state;
  2666. else if (!strcmpi(w3,"noskill"))
  2667. map[m].flag.noskill=state;
  2668. else if (!strcmpi(w3,"noicewall"))
  2669. map[m].flag.noicewall=state;
  2670. else if (!strcmpi(w3,"snow"))
  2671. map[m].flag.snow=state;
  2672. else if (!strcmpi(w3,"clouds"))
  2673. map[m].flag.clouds=state;
  2674. else if (!strcmpi(w3,"clouds2"))
  2675. map[m].flag.clouds2=state;
  2676. else if (!strcmpi(w3,"fog"))
  2677. map[m].flag.fog=state;
  2678. else if (!strcmpi(w3,"fireworks"))
  2679. map[m].flag.fireworks=state;
  2680. else if (!strcmpi(w3,"sakura"))
  2681. map[m].flag.sakura=state;
  2682. else if (!strcmpi(w3,"leaves"))
  2683. map[m].flag.leaves=state;
  2684. /**
  2685. * No longer available, keeping here just in case it's back someday. [Ind]
  2686. **/
  2687. //else if (!strcmpi(w3,"rain"))
  2688. // map[m].flag.rain=state;
  2689. else if (!strcmpi(w3,"nightenabled"))
  2690. map[m].flag.nightenabled=state;
  2691. else if (!strcmpi(w3,"nogo"))
  2692. map[m].flag.nogo=state;
  2693. else if (!strcmpi(w3,"noexp")) {
  2694. map[m].flag.nobaseexp=state;
  2695. map[m].flag.nojobexp=state;
  2696. }
  2697. else if (!strcmpi(w3,"nobaseexp"))
  2698. map[m].flag.nobaseexp=state;
  2699. else if (!strcmpi(w3,"nojobexp"))
  2700. map[m].flag.nojobexp=state;
  2701. else if (!strcmpi(w3,"noloot")) {
  2702. map[m].flag.nomobloot=state;
  2703. map[m].flag.nomvploot=state;
  2704. }
  2705. else if (!strcmpi(w3,"nomobloot"))
  2706. map[m].flag.nomobloot=state;
  2707. else if (!strcmpi(w3,"nomvploot"))
  2708. map[m].flag.nomvploot=state;
  2709. else if (!strcmpi(w3,"nocommand")) {
  2710. if (state) {
  2711. if (sscanf(w4, "%d", &state) == 1)
  2712. map[m].nocommand =state;
  2713. else //No level specified, block everyone.
  2714. map[m].nocommand =100;
  2715. } else
  2716. map[m].nocommand=0;
  2717. }
  2718. else if (!strcmpi(w3,"restricted")) {
  2719. if (state) {
  2720. map[m].flag.restricted=1;
  2721. sscanf(w4, "%d", &state);
  2722. map[m].zone |= 1<<(state+1);
  2723. } else {
  2724. map[m].flag.restricted=0;
  2725. map[m].zone = 0;
  2726. }
  2727. }
  2728. else if (!strcmpi(w3,"jexp")) {
  2729. map[m].jexp = (state) ? atoi(w4) : 100;
  2730. if( map[m].jexp < 0 ) map[m].jexp = 100;
  2731. map[m].flag.nojobexp = (map[m].jexp==0)?1:0;
  2732. }
  2733. else if (!strcmpi(w3,"bexp")) {
  2734. map[m].bexp = (state) ? atoi(w4) : 100;
  2735. if( map[m].bexp < 0 ) map[m].bexp = 100;
  2736. map[m].flag.nobaseexp = (map[m].bexp==0)?1:0;
  2737. }
  2738. else if (!strcmpi(w3,"loadevent"))
  2739. map[m].flag.loadevent=state;
  2740. else if (!strcmpi(w3,"nochat"))
  2741. map[m].flag.nochat=state;
  2742. else if (!strcmpi(w3,"partylock"))
  2743. map[m].flag.partylock=state;
  2744. else if (!strcmpi(w3,"guildlock"))
  2745. map[m].flag.guildlock=state;
  2746. else if (!strcmpi(w3,"reset"))
  2747. map[m].flag.reset=state;
  2748. else
  2749. ShowError("npc_parse_mapflag: unrecognized mapflag '%s' (file '%s', line '%d').\n", w3, filepath, strline(buffer,start-buffer));
  2750. return strchr(start,'\n');// continue
  2751. }
  2752. void npc_parsesrcfile(const char* filepath)
  2753. {
  2754. int m, lines = 0;
  2755. FILE* fp;
  2756. size_t len;
  2757. char* buffer;
  2758. const char* p;
  2759. // read whole file to buffer
  2760. fp = fopen(filepath, "rb");
  2761. if( fp == NULL )
  2762. {
  2763. ShowError("npc_parsesrcfile: File not found '%s'.\n", filepath);
  2764. return;
  2765. }
  2766. fseek(fp, 0, SEEK_END);
  2767. len = ftell(fp);
  2768. buffer = (char*)aMalloc(len+1);
  2769. fseek(fp, 0, SEEK_SET);
  2770. len = fread(buffer, sizeof(char), len, fp);
  2771. buffer[len] = '\0';
  2772. if( ferror(fp) )
  2773. {
  2774. ShowError("npc_parsesrcfile: Failed to read file '%s' - %s\n", filepath, strerror(errno));
  2775. aFree(buffer);
  2776. fclose(fp);
  2777. return;
  2778. }
  2779. fclose(fp);
  2780. // parse buffer
  2781. for( p = skip_space(buffer); p && *p ; p = skip_space(p) )
  2782. {
  2783. int pos[9];
  2784. char w1[2048], w2[2048], w3[2048], w4[2048];
  2785. int i, count;
  2786. lines++;
  2787. // w1<TAB>w2<TAB>w3<TAB>w4
  2788. count = sv_parse(p, len+buffer-p, 0, '\t', pos, ARRAYLENGTH(pos), (e_svopt)(SV_TERMINATE_LF|SV_TERMINATE_CRLF));
  2789. if( count < 0 )
  2790. {
  2791. ShowError("npc_parsesrcfile: Parse error in file '%s', line '%d'. Stopping...\n", filepath, strline(buffer,p-buffer));
  2792. break;
  2793. }
  2794. // fill w1
  2795. if( pos[3]-pos[2] > ARRAYLENGTH(w1)-1 )
  2796. ShowWarning("npc_parsesrcfile: w1 truncated, too much data (%d) in file '%s', line '%d'.\n", pos[3]-pos[2], filepath, strline(buffer,p-buffer));
  2797. i = min(pos[3]-pos[2], ARRAYLENGTH(w1)-1);
  2798. memcpy(w1, p+pos[2], i*sizeof(char));
  2799. w1[i] = '\0';
  2800. // fill w2
  2801. if( pos[5]-pos[4] > ARRAYLENGTH(w2)-1 )
  2802. ShowWarning("npc_parsesrcfile: w2 truncated, too much data (%d) in file '%s', line '%d'.\n", pos[5]-pos[4], filepath, strline(buffer,p-buffer));
  2803. i = min(pos[5]-pos[4], ARRAYLENGTH(w2)-1);
  2804. memcpy(w2, p+pos[4], i*sizeof(char));
  2805. w2[i] = '\0';
  2806. // fill w3
  2807. if( pos[7]-pos[6] > ARRAYLENGTH(w3)-1 )
  2808. ShowWarning("npc_parsesrcfile: w3 truncated, too much data (%d) in file '%s', line '%d'.\n", pos[7]-pos[6], filepath, strline(buffer,p-buffer));
  2809. i = min(pos[7]-pos[6], ARRAYLENGTH(w3)-1);
  2810. memcpy(w3, p+pos[6], i*sizeof(char));
  2811. w3[i] = '\0';
  2812. // fill w4 (to end of line)
  2813. if( pos[1]-pos[8] > ARRAYLENGTH(w4)-1 )
  2814. ShowWarning("npc_parsesrcfile: w4 truncated, too much data (%d) in file '%s', line '%d'.\n", pos[1]-pos[8], filepath, strline(buffer,p-buffer));
  2815. if( pos[8] != -1 )
  2816. {
  2817. i = min(pos[1]-pos[8], ARRAYLENGTH(w4)-1);
  2818. memcpy(w4, p+pos[8], i*sizeof(char));
  2819. w4[i] = '\0';
  2820. }
  2821. else
  2822. w4[0] = '\0';
  2823. if( count < 3 )
  2824. {// Unknown syntax
  2825. 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);
  2826. break;
  2827. }
  2828. if( strcmp(w1,"-") !=0 && strcasecmp(w1,"function") != 0 )
  2829. {// w1 = <map name>,<x>,<y>,<facing>
  2830. char mapname[2048];
  2831. sscanf(w1,"%[^,]",mapname);
  2832. if( !mapindex_name2id(mapname) )
  2833. {// Incorrect map, we must skip the script info...
  2834. ShowError("npc_parsesrcfile: Unknown map '%s' in file '%s', line '%d'. Skipping line...\n", mapname, filepath, strline(buffer,p-buffer));
  2835. if( strcasecmp(w2,"script") == 0 && count > 3 )
  2836. {
  2837. if((p = npc_skip_script(p,buffer,filepath)) == NULL)
  2838. {
  2839. break;
  2840. }
  2841. }
  2842. p = strchr(p,'\n');// next line
  2843. continue;
  2844. }
  2845. m = map_mapname2mapid(mapname);
  2846. if( m < 0 )
  2847. {// "mapname" is not assigned to this server, we must skip the script info...
  2848. if( strcasecmp(w2,"script") == 0 && count > 3 )
  2849. {
  2850. if((p = npc_skip_script(p,buffer,filepath)) == NULL)
  2851. {
  2852. break;
  2853. }
  2854. }
  2855. p = strchr(p,'\n');// next line
  2856. continue;
  2857. }
  2858. }
  2859. if( strcasecmp(w2,"warp") == 0 && count > 3 )
  2860. {
  2861. p = npc_parse_warp(w1,w2,w3,w4, p, buffer, filepath);
  2862. }
  2863. else if( (!strcasecmp(w2,"shop") || !strcasecmp(w2,"cashshop")) && count > 3 )
  2864. {
  2865. p = npc_parse_shop(w1,w2,w3,w4, p, buffer, filepath);
  2866. }
  2867. else if( strcasecmp(w2,"script") == 0 && count > 3 )
  2868. {
  2869. if( strcasecmp(w1,"function") == 0 )
  2870. p = npc_parse_function(w1, w2, w3, w4, p, buffer, filepath);
  2871. else
  2872. p = npc_parse_script(w1,w2,w3,w4, p, buffer, filepath);
  2873. }
  2874. else if( (i=0, sscanf(w2,"duplicate%n",&i), (i > 0 && w2[i] == '(')) && count > 3 )
  2875. {
  2876. p = npc_parse_duplicate(w1,w2,w3,w4, p, buffer, filepath);
  2877. }
  2878. else if( (strcmpi(w2,"monster") == 0 || strcmpi(w2,"boss_monster") == 0) && count > 3 )
  2879. {
  2880. p = npc_parse_mob(w1, w2, w3, w4, p, buffer, filepath);
  2881. }
  2882. else if( strcmpi(w2,"mapflag") == 0 && count >= 3 )
  2883. {
  2884. p = npc_parse_mapflag(w1, w2, trim(w3), trim(w4), p, buffer, filepath);
  2885. }
  2886. else
  2887. {
  2888. 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);
  2889. p = strchr(p,'\n');// skip and continue
  2890. }
  2891. }
  2892. aFree(buffer);
  2893. return;
  2894. }
  2895. int npc_script_event(struct map_session_data* sd, enum npce_event type)
  2896. {
  2897. int i;
  2898. if (type == NPCE_MAX)
  2899. return 0;
  2900. if (!sd) {
  2901. ShowError("npc_script_event: NULL sd. Event Type %d\n", type);
  2902. return 0;
  2903. }
  2904. for (i = 0; i<script_event[type].event_count; i++)
  2905. npc_event_sub(sd,script_event[type].event[i],script_event[type].event_name[i]);
  2906. return i;
  2907. }
  2908. void npc_read_event_script(void)
  2909. {
  2910. int i;
  2911. struct {
  2912. char *name;
  2913. const char *event_name;
  2914. } config[] = {
  2915. {"Login Event",script_config.login_event_name},
  2916. {"Logout Event",script_config.logout_event_name},
  2917. {"Load Map Event",script_config.loadmap_event_name},
  2918. {"Base LV Up Event",script_config.baselvup_event_name},
  2919. {"Job LV Up Event",script_config.joblvup_event_name},
  2920. {"Die Event",script_config.die_event_name},
  2921. {"Kill PC Event",script_config.kill_pc_event_name},
  2922. {"Kill NPC Event",script_config.kill_mob_event_name},
  2923. };
  2924. for (i = 0; i < NPCE_MAX; i++)
  2925. {
  2926. DBIterator* iter;
  2927. DBKey key;
  2928. DBData *data;
  2929. char name[64]="::";
  2930. strncpy(name+2,config[i].event_name,62);
  2931. script_event[i].event_count = 0;
  2932. iter = db_iterator(ev_db);
  2933. for( data = iter->first(iter,&key); iter->exists(iter); data = iter->next(iter,&key) )
  2934. {
  2935. const char* p = key.str;
  2936. struct event_data* ed = db_data2ptr(data);
  2937. unsigned char count = script_event[i].event_count;
  2938. if( count >= ARRAYLENGTH(script_event[i].event) )
  2939. {
  2940. ShowWarning("npc_read_event_script: too many occurences of event '%s'!\n", config[i].event_name);
  2941. break;
  2942. }
  2943. if( (p=strchr(p,':')) && p && strcmpi(name,p)==0 )
  2944. {
  2945. script_event[i].event[count] = ed;
  2946. script_event[i].event_name[count] = key.str;
  2947. script_event[i].event_count++;
  2948. }
  2949. }
  2950. dbi_destroy(iter);
  2951. }
  2952. if (battle_config.etc_log) {
  2953. //Print summary.
  2954. for (i = 0; i < NPCE_MAX; i++)
  2955. ShowInfo("%s: %d '%s' events.\n", config[i].name, script_event[i].event_count, config[i].event_name);
  2956. }
  2957. }
  2958. int npc_reload(void)
  2959. {
  2960. struct npc_src_list *nsl;
  2961. int m, i;
  2962. int npc_new_min = npc_id;
  2963. struct s_mapiterator* iter;
  2964. struct block_list* bl;
  2965. //Remove all npcs/mobs. [Skotlex]
  2966. iter = mapit_geteachiddb();
  2967. for( bl = (struct block_list*)mapit_first(iter); mapit_exists(iter); bl = (struct block_list*)mapit_next(iter) )
  2968. {
  2969. switch(bl->type) {
  2970. case BL_NPC:
  2971. if( bl->id != fake_nd->bl.id )// don't remove fake_nd
  2972. npc_unload((struct npc_data *)bl);
  2973. break;
  2974. case BL_MOB:
  2975. unit_free(bl,CLR_OUTSIGHT);
  2976. break;
  2977. }
  2978. }
  2979. mapit_free(iter);
  2980. if(battle_config.dynamic_mobs)
  2981. {// dynamic check by [random]
  2982. for (m = 0; m < map_num; m++) {
  2983. for (i = 0; i < MAX_MOB_LIST_PER_MAP; i++) {
  2984. if (map[m].moblist[i] != NULL) {
  2985. aFree(map[m].moblist[i]);
  2986. map[m].moblist[i] = NULL;
  2987. }
  2988. if( map[m].mob_delete_timer != INVALID_TIMER )
  2989. { // Mobs were removed anyway,so delete the timer [Inkfish]
  2990. delete_timer(map[m].mob_delete_timer, map_removemobs_timer);
  2991. map[m].mob_delete_timer = INVALID_TIMER;
  2992. }
  2993. }
  2994. }
  2995. if (map[m].npc_num > 0)
  2996. ShowWarning("npc_reload: %d npcs weren't removed at map %s!\n", map[m].npc_num, map[m].name);
  2997. }
  2998. // clear mob spawn lookup index
  2999. mob_clear_spawninfo();
  3000. // clear npc-related data structures
  3001. ev_db->clear(ev_db,NULL);
  3002. npcname_db->clear(npcname_db,NULL);
  3003. npc_warp = npc_shop = npc_script = 0;
  3004. npc_mob = npc_cache_mob = npc_delay_mob = 0;
  3005. // reset mapflags
  3006. map_flags_init();
  3007. //TODO: the following code is copy-pasted from do_init_npc(); clean it up
  3008. // Reloading npcs now
  3009. for (nsl = npc_src_files; nsl; nsl = nsl->next)
  3010. {
  3011. ShowStatus("Loading NPC file: %s"CL_CLL"\r", nsl->name);
  3012. npc_parsesrcfile(nsl->name);
  3013. }
  3014. ShowInfo ("Done loading '"CL_WHITE"%d"CL_RESET"' NPCs:"CL_CLL"\n"
  3015. "\t-'"CL_WHITE"%d"CL_RESET"' Warps\n"
  3016. "\t-'"CL_WHITE"%d"CL_RESET"' Shops\n"
  3017. "\t-'"CL_WHITE"%d"CL_RESET"' Scripts\n"
  3018. "\t-'"CL_WHITE"%d"CL_RESET"' Spawn sets\n"
  3019. "\t-'"CL_WHITE"%d"CL_RESET"' Mobs Cached\n"
  3020. "\t-'"CL_WHITE"%d"CL_RESET"' Mobs Not Cached\n",
  3021. npc_id - npc_new_min, npc_warp, npc_shop, npc_script, npc_mob, npc_cache_mob, npc_delay_mob);
  3022. for( i = 0; i < ARRAYLENGTH(instance); ++i )
  3023. instance_init(instance[i].instance_id);
  3024. //Re-read the NPC Script Events cache.
  3025. npc_read_event_script();
  3026. //Execute the OnInit event for freshly loaded npcs. [Skotlex]
  3027. ShowStatus("Event '"CL_WHITE"OnInit"CL_RESET"' executed with '"CL_WHITE"%d"CL_RESET"' NPCs.\n",npc_event_doall("OnInit"));
  3028. // Execute rest of the startup events if connected to char-server. [Lance]
  3029. if(!CheckForCharServer()){
  3030. ShowStatus("Event '"CL_WHITE"OnInterIfInit"CL_RESET"' executed with '"CL_WHITE"%d"CL_RESET"' NPCs.\n", npc_event_doall("OnInterIfInit"));
  3031. ShowStatus("Event '"CL_WHITE"OnInterIfInitOnce"CL_RESET"' executed with '"CL_WHITE"%d"CL_RESET"' NPCs.\n", npc_event_doall("OnInterIfInitOnce"));
  3032. }
  3033. return 0;
  3034. }
  3035. /*==========================================
  3036. * 終了
  3037. *------------------------------------------*/
  3038. int do_final_npc(void)
  3039. {
  3040. int i;
  3041. struct block_list *bl;
  3042. for (i = START_NPC_NUM; i < npc_id; i++){
  3043. if ((bl = map_id2bl(i))){
  3044. if (bl->type == BL_NPC)
  3045. npc_unload((struct npc_data *)bl);
  3046. else if (bl->type&(BL_MOB|BL_PET|BL_HOM|BL_MER))
  3047. unit_free(bl, CLR_OUTSIGHT);
  3048. }
  3049. }
  3050. ev_db->destroy(ev_db, NULL);
  3051. //There is no free function for npcname_db because at this point there shouldn't be any npcs left!
  3052. //So if there is anything remaining, let the memory manager catch it and report it.
  3053. npcname_db->destroy(npcname_db, NULL);
  3054. ers_destroy(timer_event_ers);
  3055. npc_clearsrcfile();
  3056. return 0;
  3057. }
  3058. static void npc_debug_warps_sub(struct npc_data* nd)
  3059. {
  3060. int m;
  3061. if (nd->bl.type != BL_NPC || nd->subtype != WARP || nd->bl.m < 0)
  3062. return;
  3063. m = map_mapindex2mapid(nd->u.warp.mapindex);
  3064. if (m < 0) return; //Warps to another map, nothing to do about it.
  3065. if (nd->u.warp.x == 0 && nd->u.warp.y == 0) return; // random warp
  3066. if (map_getcell(m, nd->u.warp.x, nd->u.warp.y, CELL_CHKNPC)) {
  3067. ShowWarning("Warp %s at %s(%d,%d) warps directly on top of an area npc at %s(%d,%d)\n",
  3068. nd->name,
  3069. map[nd->bl.m].name, nd->bl.x, nd->bl.y,
  3070. map[m].name, nd->u.warp.x, nd->u.warp.y
  3071. );
  3072. }
  3073. if (map_getcell(m, nd->u.warp.x, nd->u.warp.y, CELL_CHKNOPASS)) {
  3074. ShowWarning("Warp %s at %s(%d,%d) warps to a non-walkable tile at %s(%d,%d)\n",
  3075. nd->name,
  3076. map[nd->bl.m].name, nd->bl.x, nd->bl.y,
  3077. map[m].name, nd->u.warp.x, nd->u.warp.y
  3078. );
  3079. }
  3080. }
  3081. static void npc_debug_warps(void)
  3082. {
  3083. int m, i;
  3084. for (m = 0; m < map_num; m++)
  3085. for (i = 0; i < map[m].npc_num; i++)
  3086. npc_debug_warps_sub(map[m].npc[i]);
  3087. }
  3088. /*==========================================
  3089. * npc initialization
  3090. *------------------------------------------*/
  3091. int do_init_npc(void)
  3092. {
  3093. struct npc_src_list *file;
  3094. int i;
  3095. //Stock view data for normal npcs.
  3096. memset(&npc_viewdb, 0, sizeof(npc_viewdb));
  3097. npc_viewdb[0].class_ = INVISIBLE_CLASS; //Invisible class is stored here.
  3098. for( i = 1; i < MAX_NPC_CLASS; i++ )
  3099. npc_viewdb[i].class_ = i;
  3100. ev_db = strdb_alloc((DBOptions)(DB_OPT_DUP_KEY|DB_OPT_RELEASE_DATA),2*NAME_LENGTH+2+1);
  3101. npcname_db = strdb_alloc(DB_OPT_BASE,NAME_LENGTH);
  3102. timer_event_ers = ers_new(sizeof(struct timer_event_data));
  3103. // process all npc files
  3104. ShowStatus("Loading NPCs...\r");
  3105. for( file = npc_src_files; file != NULL; file = file->next )
  3106. {
  3107. ShowStatus("Loading NPC file: %s"CL_CLL"\r", file->name);
  3108. npc_parsesrcfile(file->name);
  3109. }
  3110. ShowInfo ("Done loading '"CL_WHITE"%d"CL_RESET"' NPCs:"CL_CLL"\n"
  3111. "\t-'"CL_WHITE"%d"CL_RESET"' Warps\n"
  3112. "\t-'"CL_WHITE"%d"CL_RESET"' Shops\n"
  3113. "\t-'"CL_WHITE"%d"CL_RESET"' Scripts\n"
  3114. "\t-'"CL_WHITE"%d"CL_RESET"' Spawn sets\n"
  3115. "\t-'"CL_WHITE"%d"CL_RESET"' Mobs Cached\n"
  3116. "\t-'"CL_WHITE"%d"CL_RESET"' Mobs Not Cached\n",
  3117. npc_id - START_NPC_NUM, npc_warp, npc_shop, npc_script, npc_mob, npc_cache_mob, npc_delay_mob);
  3118. // set up the events cache
  3119. memset(script_event, 0, sizeof(script_event));
  3120. npc_read_event_script();
  3121. //Debug function to locate all endless loop warps.
  3122. if (battle_config.warp_point_debug)
  3123. npc_debug_warps();
  3124. add_timer_func_list(npc_event_do_clock,"npc_event_do_clock");
  3125. add_timer_func_list(npc_timerevent,"npc_timerevent");
  3126. // Init dummy NPC
  3127. fake_nd = (struct npc_data *)aCalloc(1,sizeof(struct npc_data));
  3128. fake_nd->bl.m = -1;
  3129. fake_nd->bl.id = npc_get_new_npc_id();
  3130. fake_nd->class_ = -1;
  3131. fake_nd->speed = 200;
  3132. strcpy(fake_nd->name,"FAKE_NPC");
  3133. memcpy(fake_nd->exname, fake_nd->name, 9);
  3134. npc_script++;
  3135. fake_nd->bl.type = BL_NPC;
  3136. fake_nd->subtype = SCRIPT;
  3137. strdb_put(npcname_db, fake_nd->exname, fake_nd);
  3138. fake_nd->u.scr.timerid = INVALID_TIMER;
  3139. map_addiddb(&fake_nd->bl);
  3140. // End of initialization
  3141. return 0;
  3142. }