npc.c 86 KB

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