root/src/map/npc.c @ 6

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