root/src/map/mob.c @ 1

Revision 1, 135.1 kB (checked in by jinshiro, 17 years ago)
RevLine 
[1]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/db.h"
7#include "../common/nullpo.h"
8#include "../common/malloc.h"
9#include "../common/showmsg.h"
10#include "../common/ers.h"
11#include "../common/strlib.h"
12#include "../common/utils.h"
13#include "../common/socket.h"
14
15#include "map.h"
16#include "path.h"
17#include "clif.h"
18#include "intif.h"
19#include "pc.h"
20#include "pet.h"
21#include "status.h"
22#include "mob.h"
23#include "mercenary.h"  //[orn]
24#include "guild.h"
25#include "itemdb.h"
26#include "skill.h"
27#include "battle.h"
28#include "party.h"
29#include "npc.h"
30#include "log.h"
31#include "script.h"
32#include "atcommand.h"
33#include "date.h"
34#include "irc.h"
35
36#include <stdio.h>
37#include <stdlib.h>
38#include <stdarg.h>
39#include <string.h>
40#include <math.h>
41
42#define ACTIVE_AI_RANGE 2       //Distance added on top of 'AREA_SIZE' at which mobs enter active AI mode.
43
44#define IDLE_SKILL_INTERVAL 10  //Active idle skills should be triggered every 1 second (1000/MIN_MOBTHINKTIME)
45
46#define MOB_LAZYSKILLPERC 0     // Probability for mobs far from players from doing their IDLE skill. (rate of 1000 minute)
47// Move probability for mobs away from players (rate of 1000 minute)
48// in Aegis, this is 100% for mobs that have been activated by players and none otherwise.
49#define MOB_LAZYMOVEPERC(md) (md->state.spotted?1000:0)
50#define MOB_LAZYWARPPERC 20     // Warp probability in the negligent mode MOB (rate of 1000 minute)
51
52#define MAX_MINCHASE 30 //Max minimum chase value to use for mobs.
53#define RUDE_ATTACKED_COUNT 2   //After how many rude-attacks should the skill be used?
54//Used to determine default enemy type of mobs (for use in eachinrange calls)
55#define DEFAULT_ENEMY_TYPE(md) (md->special_state.ai?BL_CHAR:BL_PC|BL_HOM)
56
57//Dynamic mob database, allows saving of memory when there's big gaps in the mob_db [Skotlex]
58struct mob_db *mob_db_data[MAX_MOB_DB+1];
59struct mob_db *mob_dummy = NULL;        //Dummy mob to be returned when a non-existant one is requested.
60
61struct mob_db *mob_db(int index) { if (index < 0 || index > MAX_MOB_DB || mob_db_data[index] == NULL) return mob_dummy; return mob_db_data[index]; }
62
63static struct eri *item_drop_ers; //For loot drops delay structures.
64static struct eri *item_drop_list_ers;
65
66static struct {
67        int qty;
68        int class_[350];
69} summon[MAX_RANDOMMONSTER];
70
71static DBMap* barricade_db;
72
73#define CLASSCHANGE_BOSS_NUM 21
74
75/*==========================================
76 * Local prototype declaration   (only required thing)
77 *------------------------------------------*/
78static int mob_makedummymobdb(int);
79static int mob_spawn_guardian_sub(int tid, unsigned int tick, int id, intptr data);
80int mobskill_use(struct mob_data *md,unsigned int tick,int event);
81int mob_skillid2skillidx(int class_,int skillid);
82
83/*==========================================
84 * Mob is searched with a name.
85 *------------------------------------------*/
86int mobdb_searchname(const char *str)
87{
88        int i;
89        struct mob_db* mob;
90        for(i=0;i<=MAX_MOB_DB;i++){
91                mob = mob_db(i);
92                if(mob == mob_dummy) //Skip dummy mobs.
93                        continue;
94                if(strcmpi(mob->name,str)==0 || strcmpi(mob->jname,str)==0 || strcmpi(mob->sprite,str)==0)
95                        return i;
96        }
97
98        return 0;
99}
100static int mobdb_searchname_array_sub(struct mob_db* mob, const char *str)
101{
102        if (mob == mob_dummy)
103                return 1; //Invalid mob.
104        if(!mob->base_exp && !mob->job_exp)
105                return 1; //Discount slave-mobs (no exp) as requested by Playtester. [Skotlex]
106        if(stristr(mob->jname,str))
107                return 0;
108        if(stristr(mob->name,str))
109                return 0;
110        return strcmpi(mob->jname,str);
111}
112
113/*==========================================
114 * Founds up to N matches. Returns number of matches [Skotlex]
115 *------------------------------------------*/
116int mobdb_searchname_array(struct mob_db** data, int size, const char *str)
117{
118        int count = 0, i;
119        struct mob_db* mob;
120        for(i=0;i<=MAX_MOB_DB;i++){
121                mob = mob_db(i);
122                if (mob == mob_dummy)
123                        continue;
124                if (!mobdb_searchname_array_sub(mob, str)) {
125                        if (count < size)
126                                data[count] = mob;
127                        count++;       
128                }
129        }
130        return count;
131}
132
133/*==========================================
134 * Id Mob is checked.
135 *------------------------------------------*/
136int mobdb_checkid(const int id)
137{
138        if (mob_db(id) == mob_dummy)
139                return 0;
140        if (mob_is_clone(id)) //checkid is used mostly for random ID based code, therefore clone mobs are out of the question.
141                return 0;
142        return id;
143}
144
145/*==========================================
146 * Returns the view data associated to this mob class.
147 *------------------------------------------*/
148struct view_data * mob_get_viewdata(int class_) 
149{
150        if (mob_db(class_) == mob_dummy)
151                return 0;
152        return &mob_db(class_)->vd;
153}
154/*==========================================
155 * Cleans up mob-spawn data to make it "valid"
156 *------------------------------------------*/
157int mob_parse_dataset(struct spawn_data *data)
158{
159        int i;
160        //FIXME: This implementation is not stable, npc scripts will stop working once MAX_MOB_DB changes value! [Skotlex]
161        if(data->class_ > 2*MAX_MOB_DB){ // large/tiny mobs [Valaris]
162                data->state.size=2;
163                data->class_ -= 2*MAX_MOB_DB;
164        } else if (data->class_ > MAX_MOB_DB) {
165                data->state.size=1;
166                data->class_ -= MAX_MOB_DB;
167        }
168       
169        if ((!mobdb_checkid(data->class_) && !mob_is_clone(data->class_)) || !data->num)
170                return 0;
171
172        //better safe than sorry, current md->npc_event has a size of 50
173        if ((i=strlen(data->eventname)) >= 50)
174                return 0;
175
176        if (data->eventname[0])
177        {
178                if(i <= 2)
179                {       //Portable monster big/small implementation. [Skotlex]
180                        i = atoi(data->eventname);
181                        if (i) {
182                                if (i&2)
183                                        data->state.size=1;
184                                else if (i&4)
185                                        data->state.size=2;
186                                if (i&8)
187                                        data->state.ai=1;
188                                data->eventname[0] = '\0'; //Clear event as it is not used.
189                        }
190                } else {
191                        if (data->eventname[i-1] == '"')
192                                data->eventname[i-1] = '\0'; //Remove trailing quote.
193                        if (data->eventname[0] == '"') //Strip leading quotes
194                                memmove(data->eventname, data->eventname+1, i-1);
195                }
196        }
197        if (!data->level)
198                data->level = mob_db(data->class_)->lv;
199
200        if(strcmp(data->name,"--en--")==0)
201                strncpy(data->name,mob_db(data->class_)->name,NAME_LENGTH-1);
202        else if(strcmp(data->name,"--ja--")==0)
203                strncpy(data->name,mob_db(data->class_)->jname,NAME_LENGTH-1);
204
205        return 1;
206}
207/*==========================================
208 * Generates the basic mob data using the spawn_data provided.
209 *------------------------------------------*/
210struct mob_data* mob_spawn_dataset(struct spawn_data *data)
211{
212        struct mob_data *md = (struct mob_data*)aCalloc(1, sizeof(struct mob_data));
213        md->bl.id= npc_get_new_npc_id();
214        md->bl.type = BL_MOB;
215        md->bl.m = data->m;
216        md->bl.x = data->x;
217        md->bl.y = data->y;
218        md->class_ = data->class_;
219        md->db = mob_db(md->class_);
220        memcpy(md->name, data->name, NAME_LENGTH);
221        if (data->state.ai)
222                md->special_state.ai = data->state.ai;
223        if (data->state.size)
224                md->special_state.size = data->state.size;
225        if (data->eventname[0] && strlen(data->eventname) >= 4)
226                memcpy(md->npc_event, data->eventname, 50);
227        md->level = data->level;
228
229        if(md->db->status.mode&MD_LOOTER)
230                md->lootitem = (struct item *)aCalloc(LOOTITEM_SIZE,sizeof(struct item));
231        md->deletetimer = -1;
232        md->skillidx = -1;
233        status_set_viewdata(&md->bl, md->class_);
234        status_change_init(&md->bl);
235        unit_dataset(&md->bl);
236       
237        map_addiddb(&md->bl);
238        return md;
239}
240
241/*==========================================
242 * Fetches a random mob_id [Skotlex]
243 * type: Where to fetch from:
244 * 0: dead branch list
245 * 1: poring list
246 * 2: bloody branch list
247 * flag:
248 * &1: Apply the summon success chance found in the list (otherwise get any monster from the db)
249 * &2: Apply a monster check level.
250 * &4: Selected monster should not be a boss type
251 * &8: Selected monster must have normal spawn.
252 * lv: Mob level to check against
253 *------------------------------------------*/
254int mob_get_random_id(int type, int flag, int lv)
255{
256        struct mob_db *mob;
257        int i=0, class_;
258        if(type < 0 || type >= MAX_RANDOMMONSTER) {
259                ShowError("mob_get_random_id: Invalid type (%d) of random monster.\n", type);
260                return 0;
261        }
262        do {
263                if (type)
264                        class_ = summon[type].class_[rand()%summon[type].qty];
265                else //Dead branch
266                        class_ = rand() % MAX_MOB_DB;
267                mob = mob_db(class_);
268        } while ((mob == mob_dummy ||
269                mob_is_clone(class_) ||
270                (flag&1 && mob->summonper[type] <= rand() % 1000000) ||
271                (flag&2 && lv < mob->lv) ||
272                (flag&4 && mob->status.mode&MD_BOSS) ||
273                (flag&8 && mob->spawn[0].qty < 1)
274        ) && (i++) < MAX_MOB_DB);
275
276        if(i >= MAX_MOB_DB)
277                class_ = mob_db_data[0]->summonper[type];
278        return class_;
279}
280
281/*==========================================
282 * Kill Steal Protection [Zephyrus]
283 *------------------------------------------*/
284bool mob_ksprotected (struct block_list *src, struct block_list *target)
285{
286        struct block_list *s_bl, *t_bl;
287        struct map_session_data
288                *sd,    // Source
289                *pl_sd, // Owner
290                *t_sd;  // Mob Target
291        struct status_change_entry *sce;
292        struct mob_data *md;
293        unsigned int tick = gettick();
294        char output[128];
295
296        if( !battle_config.ksprotection )
297                return false; // KS Protection Disabled
298
299        if( !(md = BL_CAST(BL_MOB,target)) )
300                return false; // Tarjet is not MOB
301
302        if( (s_bl = battle_get_master(src)) == NULL )
303                s_bl = src;
304
305        if( !(sd = BL_CAST(BL_PC,s_bl)) )
306                return false; // Master is not PC
307
308        t_bl = map_id2bl(md->target_id);
309        if( !t_bl || (s_bl = battle_get_master(t_bl)) == NULL )
310                s_bl = t_bl;
311
312        t_sd = BL_CAST(BL_PC,s_bl);
313
314        do {
315                if( map[md->bl.m].flag.allowks || map_flag_ks(md->bl.m) )
316                        return false; // Ignores GVG, PVP and AllowKS map flags
317
318                if( md->db->mexp || md->master_id )
319                        return false; // MVP, Slaves mobs ignores KS
320
321                if( (sce = md->sc.data[SC_KSPROTECTED]) == NULL )
322                        break; // No KS Protected
323
324                if( sd->bl.id == sce->val1 || // Same Owner
325                        (sce->val2 == 2 && sd->status.party_id && sd->status.party_id == sce->val3) || // Party KS allowed
326                        (sce->val2 == 3 && sd->status.guild_id && sd->status.guild_id == sce->val4) ) // Guild KS allowed
327                        break;
328
329                if( t_sd && (
330                        (sce->val2 == 1 && sce->val1 != t_sd->bl.id) ||
331                        (sce->val2 == 2 && sce->val3 && sce->val3 != t_sd->status.party_id) ||
332                        (sce->val2 == 3 && sce->val4 && sce->val4 != t_sd->status.guild_id)) )
333                        break;
334
335                if( (pl_sd = map_id2sd(sce->val1)) == NULL || pl_sd->bl.m != md->bl.m )
336                        break;
337
338                if( !pl_sd->state.noks )
339                        return false; // No KS Protected, but normal players should be protected too
340
341                // Message to KS
342                if( DIFF_TICK(sd->ks_floodprotect_tick, tick) <= 0 )
343                {
344                        sprintf(output, "[KS Warning!! - Owner : %s]", pl_sd->status.name);
345                        clif_disp_onlyself(sd, output, strlen(output));
346
347                        sd->ks_floodprotect_tick = tick + 2000;
348                }
349
350                // Message to Owner
351                if( DIFF_TICK(pl_sd->ks_floodprotect_tick, tick) <= 0 )
352                {
353                        sprintf(output, "[Warning!! - %s is KS you]", sd->status.name);
354                        clif_disp_onlyself(pl_sd, output, strlen(output));
355
356                        pl_sd->ks_floodprotect_tick = tick + 2000;
357                }
358
359                return true;
360        } while(0);
361
362        status_change_start(target, SC_KSPROTECTED, 10000, sd->bl.id, sd->state.noks, sd->status.party_id, sd->status.guild_id, battle_config.ksprotection, 0);
363
364        return false;
365}
366
367struct mob_data *mob_once_spawn_sub(struct block_list *bl, int m, short x, short y, const char *mobname, int class_, const char *event)
368{
369        struct spawn_data data;
370       
371        memset(&data, 0, sizeof(struct spawn_data));
372        data.m = m;
373        data.num = 1;
374        data.class_ = class_;
375        if (mobname)
376                safestrncpy(data.name, mobname, sizeof(data.name));
377        else
378        if(battle_config.override_mob_names==1)
379                strcpy(data.name,"--en--");
380        else
381                strcpy(data.name,"--ja--");
382
383        if (event)
384                safestrncpy(data.eventname, event, sizeof(data.eventname));
385       
386        // Locate spot next to player.
387        if (bl && (x < 0 || y < 0))
388                map_search_freecell(bl, m, &x, &y, 1, 1, 0);
389
390        // if none found, pick random position on map
391        if (x <= 0 || y <= 0 || map_getcell(m,x,y,CELL_CHKNOREACH))
392                map_search_freecell(NULL, m, &x, &y, -1, -1, 1);
393       
394        data.x = x;
395        data.y = y;
396
397        if (!mob_parse_dataset(&data))
398                return NULL;
399
400        return mob_spawn_dataset(&data);
401}
402
403/*==========================================
404 * Spawn a single mob on the specified coordinates.
405 *------------------------------------------*/
406int mob_once_spawn(struct map_session_data* sd, int m, short x, short y, const char* mobname, int class_, int amount, const char* event)
407{
408        struct mob_data* md = NULL;
409        int count, lv;
410       
411        if (m < 0 || amount <= 0)
412                return 0; // invalid input
413
414        if(sd)
415                lv = sd->status.base_level;
416        else
417                lv = 255;
418
419        for (count = 0; count < amount; count++)
420        {
421                int c = ( class_ >= 0 ) ? class_ : mob_get_random_id(-class_-1, battle_config.random_monster_checklv?3:1, lv);
422                md = mob_once_spawn_sub(sd?&sd->bl:NULL, m, x, y, mobname, c, event);
423
424                if (!md) continue;
425
426                if(class_ == MOBID_EMPERIUM) {
427                        struct guild_castle* gc = guild_mapindex2gc(map[m].index);
428                        struct guild* g = gc?guild_search(gc->guild_id):NULL;
429                        if(gc) {
430                                md->guardian_data = (struct guardian_data*)aCalloc(1, sizeof(struct guardian_data));
431                                md->guardian_data->castle = gc;
432                                md->guardian_data->number = MAX_GUARDIANS;
433                                md->guardian_data->guild_id = gc->guild_id;
434                                if (g)
435                                {
436                                        md->guardian_data->emblem_id = g->emblem_id;
437                                        memcpy(md->guardian_data->guild_name, g->name, NAME_LENGTH);
438                                }
439                                else if (gc->guild_id) //Guild not yet available, retry in 5.
440                                        add_timer(gettick()+5000,mob_spawn_guardian_sub,md->bl.id,md->guardian_data->guild_id);
441                        }
442                }       // end addition [Valaris]
443
444                mob_spawn(md);
445
446                if (class_ < 0 && battle_config.dead_branch_active)
447                        //Behold Aegis's masterful decisions yet again...
448                        //"I understand the "Aggressive" part, but the "Can Move" and "Can Attack" is just stupid" - Poki#3
449                        sc_start4(&md->bl, SC_MODECHANGE, 100, 1, 0, MD_AGGRESSIVE|MD_CANATTACK|MD_CANMOVE, 0, 60000);
450        }
451
452        return (md)?md->bl.id : 0; // id of last spawned mob
453}
454
455/*==========================================
456 * Spawn mobs in the specified area.
457 *------------------------------------------*/
458int mob_once_spawn_area(struct map_session_data* sd,int m,int x0,int y0,int x1,int y1,const char* mobname,int class_,int amount,const char* event)
459{
460        int i,max,id=0;
461        int lx=-1,ly=-1;
462
463        if (m < 0 || amount <= 0)
464                return 0; // invalid input
465
466        // normalize x/y coordinates
467        if( x0 > x1 ) swap(x0,x1);
468        if( y0 > y1 ) swap(y0,y1);
469
470        // choose a suitable max. number of attempts
471        max = (y1-y0+1)*(x1-x0+1)*3;
472        if( max > 1000 )
473                max = 1000;
474
475        // spawn mobs, one by one
476        for( i = 0; i < amount; i++)
477        {
478                int x,y;
479                int j = 0;
480
481                // find a suitable map cell
482                do {
483                        x = rand()%(x1-x0+1)+x0;
484                        y = rand()%(y1-y0+1)+y0;
485                        j++;
486                } while( map_getcell(m,x,y,CELL_CHKNOPASS) && j < max );
487
488                if( j == max )
489                {// attempt to find an available cell failed
490                        if( lx == -1 && ly == -1 )
491                                return 0; // total failure
492                       
493                        // fallback to last good x/y pair
494                        x = lx;
495                        y = ly;
496                }
497
498                // record last successful coordinates
499                lx = x;
500                ly = y;
501
502                id = mob_once_spawn(sd,m,x,y,mobname,class_,1,event);
503        }
504
505        return id; // id of last spawned mob
506}
507/*==========================================
508 * Barricades [Zephyrus]
509 *------------------------------------------*/
510void mob_barricade_nextxy(short x, short y, short dir, int pos, short *x1, short *y1)
511{ // Calculates Next X-Y Position
512        if( dir == 0 || dir == 4 )
513                *x1 = x; // Keep X
514        else if( dir > 0 && dir < 4 )
515                *x1 = x - pos; // Going left
516        else
517                *x1 = x + pos; // Going right
518
519        if( dir == 2 || dir == 6 )
520                *y1 = y;
521        else if( dir > 2 && dir < 6 )
522                *y1 = y - pos;
523        else
524                *y1 = y + pos;
525}
526
527short mob_barricade_build(short m, short x, short y, const char* mobname, short count, short dir, bool killable, bool walkable, bool shootable, bool odd, const char* event)
528{
529        int i, j;
530        short x1, y1;
531        struct mob_data *md;
532        struct barricade_data *barricade;
533
534        if( count <= 0 ) return 1;
535        if( !event ) return 2;
536        if( (barricade = (struct barricade_data *)strdb_get(barricade_db,event)) != NULL ) return 3; // Already a barricade with event name
537        if( map_getcell(m, x, y, CELL_CHKNOREACH) ) return 4; // Starting cell problem
538
539        CREATE(barricade, struct barricade_data, 1);
540
541        barricade->dir = dir;
542        barricade->x = x;
543        barricade->y = y;
544        barricade->m = m;
545        safestrncpy(barricade->npc_event, event, sizeof(barricade->npc_event));
546        barricade->amount = 0;
547        barricade->killable = killable;
548        barricade->shootable = shootable;
549        barricade->walkable = walkable;
550       
551        for( i = 0; i < count; i++ )
552        {
553                mob_barricade_nextxy(x, y, dir, i, &x1, &y1);
554
555                if( map_getcell(m, x1, y1, CELL_CHKNOREACH) ) break; // Collision
556
557                if( (odd && i % 2 != 0) || (!odd && i % 2 == 0) )
558                {
559                        barricade->amount++;
560
561                        if( map[m].flag.gvg_castle )
562                                j = mob_spawn_guardian(map[m].name, x1, y1, mobname, 1905, "", 0, false);
563                        else
564                                j = mob_once_spawn(NULL, m, x1, y1, mobname, 1905, 1, "");
565
566                        if( (md = (struct mob_data *)map_id2bl(j)) != NULL )
567                                md->barricade = barricade;
568                }
569
570                if( !barricade->walkable ) map_setcell(m, x1, y1, CELL_WALKABLE, false);
571                map_setcell(m, x1, y1, CELL_SHOOTABLE, barricade->shootable);
572
573                clif_changemapcell(0, m, x1, y1, map_getcell(barricade->m, x1, y1, CELL_GETTYPE), ALL_SAMEMAP);
574        }
575
576        barricade->count = i;
577
578        strdb_put(barricade_db, barricade->npc_event, barricade);
579        map[m].barricade_num++;
580
581        return 0;
582}
583
584void mob_barricade_get(struct map_session_data *sd)
585{ // Update Barricade cell in client - Required only on changemap
586        struct barricade_data *barricade;
587        DBIterator* iter;
588        DBKey key;
589        short x1, y1;
590        int i;
591
592        if( map[sd->bl.m].barricade_num <= 0 )
593                return;
594
595        iter = barricade_db->iterator(barricade_db);
596        for( barricade = (struct barricade_data *)iter->first(iter,&key); iter->exists(iter); barricade = (struct barricade_data *)iter->next(iter,&key) )
597        {
598                if( sd->bl.m != barricade->m )
599                        continue;
600
601                for( i = 0; i < barricade->count; i++ )
602                {
603                        mob_barricade_nextxy(barricade->x, barricade->y, barricade->dir, i, &x1, &y1);
604                        clif_changemapcell(sd->fd, barricade->m, x1, y1, map_getcell(barricade->m, x1, y1, CELL_GETTYPE), SELF);
605                }
606        }
607        iter->destroy(iter);
608}
609
610static void mob_barricade_break(struct barricade_data *barricade, struct block_list *src)
611{
612        int i;
613        struct map_session_data *sd = NULL;
614        short x1, y1;
615       
616        if( barricade == NULL )
617                return;
618
619        if( --barricade->amount > 0 )
620                return; // There are still barricades
621
622        for( i = 0; i < barricade->count; i++ )
623        {
624                mob_barricade_nextxy(barricade->x, barricade->y, barricade->dir, i, &x1, &y1);
625
626                if( !barricade->walkable ) map_setcell(barricade->m, x1, y1, CELL_WALKABLE, true);
627                map_setcell(barricade->m, x1, y1, CELL_SHOOTABLE, !barricade->shootable);
628                clif_changemapcell(0, barricade->m, x1, y1, map_getcell(barricade->m, x1, y1, CELL_GETTYPE), ALL_SAMEMAP);
629        }
630
631        if( src )
632                switch( src->type )
633                {
634                case BL_PC:
635                        sd = BL_CAST(BL_PC,src);
636                        break;
637                case BL_PET:
638                        sd = ((TBL_PET*)src)->msd;
639                        break;
640                case BL_HOM:
641                        sd = ((TBL_HOM*)src)->master;
642                        break;
643                }
644
645        if( sd ) npc_event(sd, barricade->npc_event, 0);
646
647        map[barricade->m].barricade_num--;
648        strdb_remove(barricade_db, barricade->npc_event);
649}
650
651static int mob_barricade_destroy_sub(struct block_list *bl, va_list ap)
652{
653        TBL_MOB* md = (TBL_MOB*)bl;
654        char *event = va_arg(ap,char *);
655
656        if( md->barricade == NULL )
657                return 0;
658
659        if( strcmp(event, md->barricade->npc_event) == 0 )
660                status_kill(bl);
661
662        return 0;
663}
664
665void mob_barricade_destroy(short m, const char *event)
666{
667        if( !event )
668                return;
669
670        map_foreachinmap(mob_barricade_destroy_sub, m, BL_MOB, event, 0);
671}
672
673void mod_barricade_clearall(void)
674{
675        struct barricade_data *barricade;
676        DBIterator* iter;
677        DBKey key;
678        short x1, y1;
679        int i;
680
681        iter = barricade_db->iterator(barricade_db);
682        for( barricade = (struct barricade_data *)iter->first(iter,&key); iter->exists(iter); barricade = (struct barricade_data *)iter->next(iter,&key) )
683        {
684                for( i = 0; i < barricade->count; i++ )
685                {
686                        mob_barricade_nextxy(barricade->x, barricade->y, barricade->dir, i, &x1, &y1);
687
688                        if( !barricade->walkable ) map_setcell(barricade->m, x1, y1, CELL_WALKABLE, true);
689                        map_setcell(barricade->m, x1, y1, CELL_SHOOTABLE, !barricade->shootable);
690                        clif_changemapcell(0, barricade->m, x1, y1, map_getcell(barricade->m, x1, y1, CELL_GETTYPE), ALL_SAMEMAP);
691                }
692        }
693        iter->destroy(iter);
694
695        barricade_db->clear(barricade_db, NULL);
696}
697
698/*==========================================
699 * Set a Guardian's guild data [Skotlex]
700 *------------------------------------------*/
701static int mob_spawn_guardian_sub(int tid, unsigned int tick, int id, intptr data)
702{       //Needed because the guild_data may not be available at guardian spawn time.
703        struct block_list* bl = map_id2bl(id);
704        struct mob_data* md; 
705        struct guild* g;
706        int guardup_lv;
707
708        if (bl == NULL) //It is possible mob was already removed from map when the castle has no owner. [Skotlex]
709                return 0;
710       
711        if (bl->type != BL_MOB)
712        {
713                ShowError("mob_spawn_guardian_sub: Block error!\n");
714                return 0;
715        }
716       
717        md = (struct mob_data*)bl;
718        nullpo_retr(0, md->guardian_data);
719        g = guild_search((int)data);
720
721        if (g == NULL)
722        {       //Liberate castle, if the guild is not found this is an error! [Skotlex]
723                ShowError("mob_spawn_guardian_sub: Couldn't load guild %d!\n", (int)data);
724                if (md->class_ == MOBID_EMPERIUM)
725                {       //Not sure this is the best way, but otherwise we'd be invoking this for ALL guardians spawned later on.
726                        md->guardian_data->guild_id = 0;
727                        if (md->guardian_data->castle->guild_id) //Free castle up.
728                        {
729                                ShowNotice("Clearing ownership of castle %d (%s)\n", md->guardian_data->castle->castle_id, md->guardian_data->castle->castle_name);
730                                guild_castledatasave(md->guardian_data->castle->castle_id, 1, 0);
731                        }
732                } else {
733                        if( md->guardian_data->number >= 0 && md->guardian_data->number < MAX_GUARDIANS && md->guardian_data->castle->guardian[md->guardian_data->number].visible )
734                        {       //Safe removal of guardian.
735                                md->guardian_data->castle->guardian[md->guardian_data->number].visible = 0;
736                                guild_castledatasave(md->guardian_data->castle->castle_id, 10+md->guardian_data->number,0);
737                        }
738                        unit_free(&md->bl,0); //Remove guardian.
739                }
740                return 0;
741        }
742        guardup_lv = guild_checkskill(g,GD_GUARDUP);
743        md->guardian_data->emblem_id = g->emblem_id;
744        memcpy(md->guardian_data->guild_name, g->name, NAME_LENGTH);
745        md->guardian_data->guardup_lv = guardup_lv;
746        if( guardup_lv )
747                status_calc_mob(md, 0); //Give bonuses.
748        return 0;
749}
750
751/*==========================================
752 * Summoning Guardians [Valaris]
753 *------------------------------------------*/
754int mob_spawn_guardian(const char* mapname, short x, short y, const char* mobname, int class_, const char* event, int guardian, bool has_index)
755{
756        struct mob_data *md=NULL;
757        struct spawn_data data;
758        struct guild *g=NULL;
759        struct guild_castle *gc;
760        int m;
761        memset(&data, 0, sizeof(struct spawn_data));
762        data.num = 1;
763
764        m=map_mapname2mapid(mapname);
765
766        if(m<0)
767        {
768                ShowWarning("mob_spawn_guardian: Map [%s] not found.\n", mapname);
769                return 0;
770        }
771        data.m = m;
772        data.num = 1;
773        if(class_<=0) {
774                class_ = mob_get_random_id(-class_-1, 1, 99);
775                if (!class_) return 0;
776        }
777
778        data.class_ = class_;
779
780        if( !has_index )
781        {
782                guardian = -1;
783        }
784        else if( guardian < 0 || guardian >= MAX_GUARDIANS )
785        {
786                ShowError("mob_spawn_guardian: Invalid guardian index %d for guardian %d (castle map %s)\n", guardian, class_, map[m].name);
787                return 0;
788        }
789       
790        if((x<=0 || y<=0) && !map_search_freecell(NULL, m, &x, &y, -1,-1, 0))
791        {
792                ShowWarning("mob_spawn_guardian: Couldn't locate a spawn cell for guardian class %d (index %d) at castle map %s\n",class_, guardian, map[m].name);
793                return 0;
794        }
795        data.x = x;
796        data.y = y;
797        safestrncpy(data.name, mobname, sizeof(data.name));
798        safestrncpy(data.eventname, event, sizeof(data.eventname));
799        if (!mob_parse_dataset(&data))
800                return 0;
801       
802        gc=guild_mapname2gc(map[m].name);
803        if (gc == NULL)
804        {
805                ShowError("mob_spawn_guardian: No castle set at map %s\n", map[m].name);
806                return 0;
807        }
808        if (!gc->guild_id)
809                ShowWarning("mob_spawn_guardian: Spawning guardian %d on a castle with no guild (castle map %s)\n", class_, map[m].name);
810        else
811                g = guild_search(gc->guild_id);
812
813        if( has_index && gc->guardian[guardian].id )
814        {       //Check if guardian already exists, refuse to spawn if so.
815                struct mob_data *md2 = (TBL_MOB*)map_id2bl(gc->guardian[guardian].id);
816                if (md2 && md2->bl.type == BL_MOB &&
817                        md2->guardian_data && md2->guardian_data->number == guardian)
818                {
819                        ShowError("mob_spawn_guardian: Attempted to spawn guardian in position %d which already has a guardian (castle map %s)\n", guardian, map[m].name);
820                        return 0;
821                }
822        }
823
824        md = mob_spawn_dataset(&data);
825        md->guardian_data = (struct guardian_data*)aCalloc(1, sizeof(struct guardian_data));
826        md->guardian_data->number = guardian;
827        md->guardian_data->guild_id = gc->guild_id;
828        md->guardian_data->castle = gc;
829        if( has_index )
830        {// permanent guardian
831                gc->guardian[guardian].id = md->bl.id;
832        }
833        else
834        {// temporary guardian
835                int i;
836                ARR_FIND(0, gc->temp_guardians_max, i, gc->temp_guardians[i] == 0);
837                if( i == gc->temp_guardians_max )
838                {
839                        ++(gc->temp_guardians_max);
840                        RECREATE(gc->temp_guardians, int, gc->temp_guardians_max);
841                }
842                gc->temp_guardians[i] = md->bl.id;
843        }
844        if (g)
845        {
846                md->guardian_data->emblem_id = g->emblem_id;
847                memcpy (md->guardian_data->guild_name, g->name, NAME_LENGTH);
848                md->guardian_data->guardup_lv = guild_checkskill(g,GD_GUARDUP);
849        } else if (md->guardian_data->guild_id)
850                add_timer(gettick()+5000,mob_spawn_guardian_sub,md->bl.id,md->guardian_data->guild_id);
851        mob_spawn(md);
852
853        return md->bl.id;
854}
855
856/*==========================================
857 * Reachability to a Specification ID existence place
858 * state indicates type of 'seek' mob should do:
859 * - MSS_LOOT: Looking for item, path must be easy.
860 * - MSS_RUSH: Chasing attacking player, path is complex
861 * - MSS_FOLLOW: Initiative/support seek, path is complex
862 *------------------------------------------*/
863int mob_can_reach(struct mob_data *md,struct block_list *bl,int range, int state)
864{
865        int easy = 0;
866
867        nullpo_retr(0, md);
868        nullpo_retr(0, bl);
869        switch (state) {
870                case MSS_RUSH:
871                case MSS_FOLLOW:
872                        easy = 0; //(battle_config.mob_ai&0x1?0:1);
873                        break;
874                case MSS_LOOT:
875                default:
876                        easy = 1;
877                        break;
878        }
879        return unit_can_reach_bl(&md->bl, bl, range, easy, NULL, NULL);
880}
881
882/*==========================================
883 * Links nearby mobs (supportive mobs)
884 *------------------------------------------*/
885int mob_linksearch(struct block_list *bl,va_list ap)
886{
887        struct mob_data *md;
888        int class_;
889        struct block_list *target;
890        unsigned int tick;
891       
892        nullpo_retr(0, bl);
893        nullpo_retr(0, ap);
894        md=(struct mob_data *)bl;
895        class_ = va_arg(ap, int);
896        target = va_arg(ap, struct block_list *);
897        tick=va_arg(ap, unsigned int);
898
899        if (md->class_ == class_ && DIFF_TICK(md->last_linktime, tick) < MIN_MOBLINKTIME
900                && !md->target_id)
901        {
902                md->last_linktime = tick;
903                if( mob_can_reach(md,target,md->db->range2, MSS_FOLLOW) ){      // Reachability judging
904                        md->target_id = target->id;
905                        md->min_chase=md->db->range3;
906                        return 1;
907                }
908        }
909
910        return 0;
911}
912
913/*==========================================
914 * mob spawn with delay (timer function)
915 *------------------------------------------*/
916static int mob_delayspawn(int tid, unsigned int tick, int id, intptr data)
917{
918        struct block_list *bl = map_id2bl(id);
919        if (bl && bl->type == BL_MOB && bl->prev == NULL)
920                mob_spawn((TBL_MOB*)bl);
921        return 0;
922}
923
924/*==========================================
925 * spawn timing calculation
926 *------------------------------------------*/
927int mob_setdelayspawn(struct mob_data *md)
928{
929        unsigned int spawntime;
930
931        if (!md->spawn) //Doesn't has respawn data!
932                return unit_free(&md->bl,1);
933
934        spawntime = md->spawn->delay1; //Base respawn time
935        if (md->spawn->delay2) //random variance
936                spawntime+= rand()%md->spawn->delay2;
937
938        if (spawntime < 5000) //Min respawn time (is it needed?)
939                spawntime = 5000;
940
941        add_timer(gettick()+spawntime, mob_delayspawn, md->bl.id, 0);
942        return 0;
943}
944
945static int mob_count_sub(struct block_list *bl,va_list ap)
946{
947        return 1;
948}
949
950/*==========================================
951 * Mob spawning. Initialization is also variously here.
952 *------------------------------------------*/
953int mob_spawn (struct mob_data *md)
954{
955        int i=0;
956        unsigned int c =0, tick = gettick();
957
958        md->last_thinktime = tick;
959        if (md->bl.prev != NULL)
960                unit_remove_map(&md->bl,2);
961        else
962        if (md->spawn && md->class_ != md->spawn->class_)
963        {
964                md->class_ = md->spawn->class_;
965                status_set_viewdata(&md->bl, md->class_);
966                md->db = mob_db(md->class_);
967                memcpy(md->name,md->spawn->name,NAME_LENGTH);
968        }
969
970        if (md->spawn) { //Respawn data
971                md->bl.m = md->spawn->m;
972                md->bl.x = md->spawn->x;
973                md->bl.y = md->spawn->y;
974
975                if ((md->bl.x == 0 && md->bl.y == 0) || md->spawn->xs || md->spawn->ys)
976                {       //Monster can be spawned on an area.
977                        if (!map_search_freecell(&md->bl, -1,
978                                &md->bl.x, &md->bl.y, md->spawn->xs, md->spawn->ys,
979                                battle_config.no_spawn_on_player?4:0)) {
980                                // retry again later
981                                add_timer(tick+5000,mob_delayspawn,md->bl.id,0);
982                                return 1;
983                        }
984                } else if (battle_config.no_spawn_on_player>99 &&
985                        map_foreachinrange(mob_count_sub, &md->bl, AREA_SIZE, BL_PC))
986                {       //retry again later (players on sight)
987                        add_timer(tick+5000,mob_delayspawn,md->bl.id,0);
988                        return 1;
989                }
990        }
991
992        memset(&md->state, 0, sizeof(md->state));
993        status_calc_mob(md, 1);
994        md->attacked_id = 0;
995        md->target_id = 0;
996        md->move_fail_count = 0;
997
998//      md->master_id = 0;
999        md->master_dist = 0;
1000
1001        md->state.aggressive = md->status.mode&MD_ANGRY?1:0;
1002        md->state.skillstate = MSS_IDLE;
1003        md->next_walktime = tick+rand()%5000+1000;
1004        md->last_linktime = tick;
1005        md->last_pcneartime = 0;
1006
1007        for (i = 0, c = tick-1000*3600*10; i < MAX_MOBSKILL; i++)
1008                md->skilldelay[i] = c;
1009
1010        memset(md->dmglog, 0, sizeof(md->dmglog));
1011        md->tdmg = 0;
1012        if (md->lootitem)
1013                memset(md->lootitem, 0, sizeof(md->lootitem));
1014        md->lootitem_count = 0;
1015
1016        if(md->db->option)
1017                // Added for carts, falcons and pecos for cloned monsters. [Valaris]
1018                md->sc.option = md->db->option;
1019
1020        map_addblock(&md->bl);
1021        clif_spawn(&md->bl);
1022        skill_unit_move(&md->bl,tick,1);
1023        mobskill_use(md, tick, MSC_SPAWN);
1024        return 0;
1025}
1026
1027/*==========================================
1028 * Determines if the mob can change target. [Skotlex]
1029 *------------------------------------------*/
1030static int mob_can_changetarget(struct mob_data* md, struct block_list* target, int mode)
1031{
1032        // if the monster was provoked ignore the above rule [celest]
1033        if(md->state.provoke_flag)
1034        {       
1035                if (md->state.provoke_flag == target->id)
1036                        return 1;
1037                else if (!(battle_config.mob_ai&0x4))
1038                        return 0;
1039        }
1040       
1041        switch (md->state.skillstate) {
1042                case MSS_BERSERK:
1043                        if (!(mode&MD_CHANGETARGET_MELEE))
1044                                return 0;
1045                        return (battle_config.mob_ai&0x4 || check_distance_bl(&md->bl, target, 3));
1046                case MSS_RUSH:
1047                        return (mode&MD_CHANGETARGET_CHASE);
1048                case MSS_FOLLOW:
1049                case MSS_ANGRY:
1050                case MSS_IDLE:
1051                case MSS_WALK:
1052                case MSS_LOOT:
1053                        return 1;
1054                default:
1055                        return 0;
1056        }
1057}
1058
1059/*==========================================
1060 * Determination for an attack of a monster
1061 *------------------------------------------*/
1062int mob_target(struct mob_data *md,struct block_list *bl,int dist)
1063{
1064        nullpo_retr(0, md);
1065        nullpo_retr(0, bl);
1066
1067        // Nothing will be carried out if there is no mind of changing TAGE by TAGE ending.
1068        if(md->target_id && !mob_can_changetarget(md, bl, status_get_mode(&md->bl)))
1069                return 0;
1070
1071        if(!status_check_skilluse(&md->bl, bl, 0, 0))
1072                return 0;
1073
1074        md->target_id = bl->id; // Since there was no disturbance, it locks on to target.
1075        if (md->state.provoke_flag && bl->id != md->state.provoke_flag)
1076                md->state.provoke_flag = 0;
1077        md->min_chase=dist+md->db->range3;
1078        if(md->min_chase>MAX_MINCHASE)
1079                md->min_chase=MAX_MINCHASE;
1080        return 0;
1081}
1082
1083/*==========================================
1084 * The ?? routine of an active monster
1085 *------------------------------------------*/
1086static int mob_ai_sub_hard_activesearch(struct block_list *bl,va_list ap)
1087{
1088        struct mob_data *md;
1089        struct block_list **target;
1090        int dist;
1091
1092        nullpo_retr(0, bl);
1093        nullpo_retr(0, ap);
1094        md=va_arg(ap,struct mob_data *);
1095        target= va_arg(ap,struct block_list**);
1096
1097        //If can't seek yet, not an enemy, or you can't attack it, skip.
1098        if ((*target) == bl || !status_check_skilluse(&md->bl, bl, 0, 0))
1099                return 0;
1100
1101        if(battle_check_target(&md->bl,bl,BCT_ENEMY)<=0)
1102                return 0;
1103
1104        if(md->nd && mob_script_callback(md, bl, CALLBACK_DETECT))
1105                return 1; // We have script handling the work.
1106
1107        switch (bl->type)
1108        {
1109        case BL_PC:
1110                if (((TBL_PC*)bl)->state.gangsterparadise &&
1111                        !(status_get_mode(&md->bl)&MD_BOSS))
1112                        return 0; //Gangster paradise protection.
1113        default:
1114                if (battle_config.hom_setting&0x4 &&
1115                        (*target) && (*target)->type == BL_HOM && bl->type != BL_HOM)
1116                        return 0; //For some reason Homun targets are never overriden.
1117
1118                dist = distance_bl(&md->bl, bl);
1119                if(
1120                        ((*target) == NULL || !check_distance_bl(&md->bl, *target, dist)) &&
1121                        battle_check_range(&md->bl,bl,md->db->range2)
1122                ) { //Pick closest target?
1123                        (*target) = bl;
1124                        md->target_id=bl->id;
1125                        md->min_chase= dist + md->db->range3;
1126                        if(md->min_chase>MAX_MINCHASE)
1127                                md->min_chase=MAX_MINCHASE;
1128                        return 1;
1129                }
1130                break;
1131        }
1132        return 0;
1133}
1134
1135/*==========================================
1136 * chase target-change routine.
1137 *------------------------------------------*/
1138static int mob_ai_sub_hard_changechase(struct block_list *bl,va_list ap)
1139{
1140        struct mob_data *md;
1141        struct block_list **target;
1142
1143        nullpo_retr(0, bl);
1144        nullpo_retr(0, ap);
1145        md=va_arg(ap,struct mob_data *);
1146        target= va_arg(ap,struct block_list**);
1147
1148        //If can't seek yet, not an enemy, or you can't attack it, skip.
1149        if ((*target) == bl ||
1150                battle_check_target(&md->bl,bl,BCT_ENEMY)<=0 ||
1151                !status_check_skilluse(&md->bl, bl, 0, 0))
1152                return 0;
1153
1154        if(battle_check_range (&md->bl, bl, md->status.rhw.range))
1155        {
1156                (*target) = bl;
1157                md->target_id=bl->id;
1158                md->min_chase= md->db->range3;
1159        }
1160        return 1;
1161}
1162
1163
1164/*==========================================
1165 * loot monster item search
1166 *------------------------------------------*/
1167static int mob_ai_sub_hard_lootsearch(struct block_list *bl,va_list ap)
1168{
1169        struct mob_data* md;
1170        struct block_list **target;
1171        int dist;
1172
1173        md=va_arg(ap,struct mob_data *);
1174        target= va_arg(ap,struct block_list**);
1175
1176        dist=distance_bl(&md->bl, bl);
1177        if(mob_can_reach(md,bl,dist+1, MSS_LOOT) && 
1178                ((*target) == NULL || !check_distance_bl(&md->bl, *target, dist)) //New target closer than previous one.
1179        ) {
1180                (*target) = bl;
1181                md->target_id=bl->id;
1182                md->min_chase=md->db->range3;
1183        }
1184        return 0;
1185}
1186
1187static int mob_warpchase_sub(struct block_list *bl,va_list ap)
1188{
1189        struct mob_data* md;
1190        struct block_list *target;
1191        struct npc_data **target_nd;
1192        struct npc_data *nd;
1193        int *min_distance;
1194        int cur_distance;
1195
1196        md=va_arg(ap,struct mob_data *);
1197        target= va_arg(ap, struct block_list*);
1198        target_nd= va_arg(ap, struct npc_data**);
1199        min_distance= va_arg(ap, int*);
1200
1201        nd = (TBL_NPC*) bl;
1202
1203        if(nd->subtype != WARP)
1204                return 0; //Not a warp
1205
1206        if(nd->u.warp.mapindex != map[target->m].index)
1207                return 0; //Does not lead to the same map.
1208
1209        cur_distance = distance_blxy(target, nd->u.warp.x, nd->u.warp.y);
1210        if (cur_distance < *min_distance)
1211        {       //Pick warp that leads closest to target.
1212                *target_nd = nd;
1213                *min_distance = cur_distance;
1214                return 1;
1215        }       
1216        return 0;
1217}
1218/*==========================================
1219 * Processing of slave monsters
1220 *------------------------------------------*/
1221static int mob_ai_sub_hard_slavemob(struct mob_data *md,unsigned int tick)
1222{
1223        struct block_list *bl;
1224        int old_dist;
1225
1226        bl=map_id2bl(md->master_id);
1227
1228        if (!bl || status_isdead(bl)) {
1229                status_kill(&md->bl);
1230                return 1;
1231        }
1232        if (bl->prev == NULL)
1233                return 0; //Master not on a map? Could be warping, do not process.
1234
1235        if(status_get_mode(&md->bl)&MD_CANMOVE)
1236        {       //If the mob can move, follow around. [Check by Skotlex]
1237               
1238                // Distance with between slave and master is measured.
1239                old_dist=md->master_dist;
1240                md->master_dist=distance_bl(&md->bl, bl);
1241
1242                // Since the master was in near immediately before, teleport is carried out and it pursues.
1243                if(bl->m != md->bl.m || 
1244                        (old_dist<10 && md->master_dist>18) ||
1245                        md->master_dist > MAX_MINCHASE
1246                ){
1247                        md->master_dist = 0;
1248                        unit_warp(&md->bl,bl->m,bl->x,bl->y,3);
1249                        return 1;
1250                }
1251
1252                if(md->target_id) //Slave is busy with a target.
1253                        return 0;
1254
1255                // Approach master if within view range, chase back to Master's area also if standing on top of the master.
1256                if((md->master_dist>MOB_SLAVEDISTANCE || md->master_dist == 0) &&
1257                        unit_can_move(&md->bl))
1258                {
1259                        short x = bl->x, y = bl->y;
1260                        mob_stop_attack(md);
1261                        if(map_search_freecell(&md->bl, bl->m, &x, &y, MOB_SLAVEDISTANCE, MOB_SLAVEDISTANCE, 1)
1262                                && unit_walktoxy(&md->bl, x, y, 0))
1263                                return 1;
1264                }       
1265        } else if (bl->m != md->bl.m && map_flag_gvg(md->bl.m)) {
1266                //Delete the summoned mob if it's in a gvg ground and the master is elsewhere. [Skotlex]
1267                status_kill(&md->bl);
1268                return 1;
1269        }
1270       
1271        //Avoid attempting to lock the master's target too often to avoid unnecessary overload. [Skotlex]
1272        if (DIFF_TICK(md->last_linktime, tick) < MIN_MOBLINKTIME && !md->target_id)
1273        {
1274                struct unit_data *ud = unit_bl2ud(bl);
1275                md->last_linktime = tick;
1276               
1277                if (ud) {
1278                        struct block_list *tbl=NULL;
1279                        if (ud->target && ud->state.attack_continue)
1280                                tbl=map_id2bl(ud->target);
1281                        else if (ud->skilltarget) {
1282                                tbl = map_id2bl(ud->skilltarget);
1283                                //Required check as skilltarget is not always an enemy. [Skotlex]
1284                                if (tbl && battle_check_target(&md->bl, tbl, BCT_ENEMY) <= 0)
1285                                        tbl = NULL;
1286                        }
1287                        if (tbl && status_check_skilluse(&md->bl, tbl, 0, 0)) {
1288                                if(md->nd)
1289                                        mob_script_callback(md, bl, CALLBACK_ASSIST);
1290                                md->target_id=tbl->id;
1291                                md->min_chase=md->db->range3+distance_bl(&md->bl, tbl);
1292                                if(md->min_chase>MAX_MINCHASE)
1293                                        md->min_chase=MAX_MINCHASE;
1294                                return 1;
1295                        }
1296                }
1297        }
1298        return 0;
1299}
1300
1301/*==========================================
1302 * A lock of target is stopped and mob moves to a standby state.
1303 * This also triggers idle skill/movement since the AI can get stuck
1304 * when trying to pick new targets when the current chosen target is
1305 * unreachable.
1306 *------------------------------------------*/
1307int mob_unlocktarget(struct mob_data *md, unsigned int tick)
1308{
1309        nullpo_retr(0, md);
1310
1311        if(md->nd)
1312                mob_script_callback(md, map_id2bl(md->target_id), CALLBACK_UNLOCK);
1313
1314        switch (md->state.skillstate) {
1315        case MSS_WALK:
1316                if (md->ud.walktimer != -1)
1317                        break;
1318                //Because it is not unset when the mob finishes walking.
1319                md->state.skillstate = MSS_IDLE;
1320        case MSS_IDLE:
1321                // Idle skill.
1322                if ((md->target_id || !(++md->ud.walk_count%IDLE_SKILL_INTERVAL)) &&
1323                        mobskill_use(md, tick, -1))
1324                        break;
1325                //Random walk.
1326                if (!md->master_id &&
1327                        DIFF_TICK(md->next_walktime, tick) <= 0 &&
1328                        !mob_randomwalk(md,tick))
1329                        //Delay next random walk when this one failed.
1330                        md->next_walktime=tick+rand()%3000;
1331                break;
1332        default:
1333                mob_stop_attack(md);
1334                if (battle_config.mob_ai&0x8)
1335                        mob_stop_walking(md,1); //Immediately stop chasing.
1336                md->state.skillstate = MSS_IDLE;
1337                md->next_walktime=tick+rand()%3000+3000;
1338                break;
1339        }
1340        if (md->target_id) {
1341                md->target_id=0;
1342                md->ud.target = 0;
1343        }
1344        return 0;
1345}
1346/*==========================================
1347 * Random walk
1348 *------------------------------------------*/
1349int mob_randomwalk(struct mob_data *md,unsigned int tick)
1350{
1351        const int retrycount=20;
1352        int i,x,y,c,d;
1353        int speed;
1354
1355        nullpo_retr(0, md);
1356
1357        if(DIFF_TICK(md->next_walktime,tick)>0 ||
1358           md->state.no_random_walk ||
1359           !unit_can_move(&md->bl) ||
1360           !(status_get_mode(&md->bl)&MD_CANMOVE))
1361                return 0;
1362       
1363        d =12-md->move_fail_count;
1364        if(d<5) d=5;
1365        for(i=0;i<retrycount;i++){      // Search of a movable place
1366                int r=rand();
1367                x=r%(d*2+1)-d;
1368                y=r/(d*2+1)%(d*2+1)-d;
1369                x+=md->bl.x;
1370                y+=md->bl.y;
1371
1372                if((map_getcell(md->bl.m,x,y,CELL_CHKPASS)) && unit_walktoxy(&md->bl,x,y,1)){
1373                        break;
1374                }
1375        }
1376        if(i==retrycount){
1377                md->move_fail_count++;
1378                if(md->move_fail_count>1000){
1379                        ShowWarning("MOB can't move. random spawn %d, class = %d, at %s (%d,%d)\n",md->bl.id,md->class_,map[md->bl.m].name, md->bl.x, md->bl.y);
1380                        md->move_fail_count=0;
1381                        mob_spawn(md);
1382                }
1383                return 0;
1384        }
1385        speed=status_get_speed(&md->bl);
1386        for(i=c=0;i<md->ud.walkpath.path_len;i++){      // The next walk start time is calculated.
1387                if(md->ud.walkpath.path[i]&1)
1388                        c+=speed*14/10;
1389                else
1390                        c+=speed;
1391        }
1392        md->state.skillstate=MSS_WALK;
1393        md->move_fail_count=0;
1394        md->next_walktime = tick+rand()%3000+3000+c;
1395        return 1;
1396}
1397
1398int mob_warpchase(struct mob_data *md, struct block_list *target)
1399{
1400        struct npc_data *warp = NULL;
1401        int distance = AREA_SIZE;
1402        if (!(target && battle_config.mob_ai&0x40 && battle_config.mob_warp&1))
1403                return 0; //Can't warp chase.
1404
1405        if (target->m == md->bl.m && check_distance_bl(&md->bl, target, AREA_SIZE))
1406                return 0; //No need to do a warp chase.
1407
1408        if (md->ud.walktimer != -1 &&
1409                map_getcell(md->bl.m,md->ud.to_x,md->ud.to_y,CELL_CHKNPC))
1410                return 1; //Already walking to a warp.
1411
1412        //Search for warps within mob's viewing range.
1413        map_foreachinrange (mob_warpchase_sub, &md->bl,
1414                md->db->range2, BL_NPC, md, target, &warp, &distance);
1415
1416        if (warp && unit_walktobl(&md->bl, &warp->bl, 0, 1))
1417                return 1;
1418        return 0;
1419}
1420
1421/*==========================================
1422 * AI of MOB whose is near a Player
1423 *------------------------------------------*/
1424static bool mob_ai_sub_hard(struct mob_data *md, unsigned int tick)
1425{
1426        struct block_list *tbl = NULL, *abl = NULL;
1427        int dist;
1428        int mode;
1429        int search_size;
1430        int view_range, can_move;
1431
1432        if(md->bl.prev == NULL || md->status.hp <= 0)
1433                return false;
1434               
1435        if (DIFF_TICK(tick, md->last_thinktime) < MIN_MOBTHINKTIME)
1436                return false;
1437
1438        md->last_thinktime = tick;
1439
1440        if (md->ud.skilltimer != -1)
1441                return false;
1442
1443        if(md->ud.walktimer != -1 && md->ud.walkpath.path_pos <= 3)
1444                return false;
1445
1446        // Abnormalities
1447        if((md->sc.opt1 > 0 && md->sc.opt1 != OPT1_STONEWAIT) || md->sc.data[SC_BLADESTOP])
1448        {       //Should reset targets.
1449                md->target_id = md->attacked_id = 0;
1450                return false;
1451        }
1452
1453        if (md->sc.count && md->sc.data[SC_BLIND])
1454                view_range = 3;
1455        else
1456                view_range = md->db->range2;
1457        mode = status_get_mode(&md->bl);
1458
1459        can_move = (mode&MD_CANMOVE)&&unit_can_move(&md->bl);
1460
1461        if (md->target_id)
1462        {       //Check validity of current target. [Skotlex]
1463                tbl = map_id2bl(md->target_id);
1464                if (!tbl || tbl->m != md->bl.m ||
1465                        (md->ud.attacktimer == -1 && !status_check_skilluse(&md->bl, tbl, 0, 0)) ||
1466                        (md->ud.walktimer != -1 && !(battle_config.mob_ai&0x1) && !check_distance_bl(&md->bl, tbl, md->min_chase)) ||
1467                        (
1468                                tbl->type == BL_PC &&
1469                                ((((TBL_PC*)tbl)->state.gangsterparadise && !(mode&MD_BOSS)) ||
1470                                ((TBL_PC*)tbl)->invincible_timer != INVALID_TIMER)
1471                )) {    //Unlock current target.
1472                        if (mob_warpchase(md, tbl))
1473                                return true; //Chasing this target.
1474                        mob_unlocktarget(md, tick-(battle_config.mob_ai&0x8?3000:0)); //Imediately do random walk.
1475                        tbl = NULL;
1476                }
1477        }
1478                       
1479        // Check for target change.
1480        if (md->attacked_id && mode&MD_CANATTACK)
1481        {
1482                if (md->attacked_id == md->target_id)
1483                {       //Rude attacked check.
1484                        if (!battle_check_range(&md->bl, tbl, md->status.rhw.range) &&
1485                                (       //Can't attack back and can't reach back.
1486                                        (!can_move && DIFF_TICK(tick, md->ud.canmove_tick) > 0 &&
1487                                                (battle_config.mob_ai&0x2 || md->sc.data[SC_SPIDERWEB])) ||
1488                                        (!mob_can_reach(md, tbl, md->min_chase, MSS_RUSH))
1489                                ) &&
1490                                md->state.attacked_count++ >= RUDE_ATTACKED_COUNT &&
1491                                !mobskill_use(md, tick, MSC_RUDEATTACKED) && //If can't rude Attack
1492                                can_move && unit_escape(&md->bl, tbl, rand()%10 +1)) //Attempt escape
1493                        {       //Escaped
1494                                md->attacked_id = 0;
1495                                return true;
1496                        }
1497                } else
1498                if ((abl= map_id2bl(md->attacked_id)) && (!tbl || mob_can_changetarget(md, abl, mode))) {
1499                        if (md->bl.m != abl->m || abl->prev == NULL ||
1500                                (dist = distance_bl(&md->bl, abl)) >= MAX_MINCHASE ||
1501                                battle_check_target(&md->bl, abl, BCT_ENEMY) <= 0 ||
1502                                (battle_config.mob_ai&0x2 && !status_check_skilluse(&md->bl, abl, 0, 0)) || //Retaliate check
1503                                (!battle_check_range(&md->bl, abl, md->status.rhw.range) &&
1504                                        ( //Reach check
1505                                        (!can_move && DIFF_TICK(tick, md->ud.canmove_tick) > 0 &&
1506                                                        (battle_config.mob_ai&0x2 || md->sc.data[SC_SPIDERWEB])) ||
1507                                                !mob_can_reach(md, abl, dist+md->db->range3, MSS_RUSH)
1508                                        )
1509                                )
1510                        )       {       //Rude attacked
1511                                if (md->state.attacked_count++ >= RUDE_ATTACKED_COUNT &&
1512                                        !mobskill_use(md, tick, MSC_RUDEATTACKED) && can_move &&
1513                                        !tbl && unit_escape(&md->bl, abl, rand()%10 +1))
1514                                {       //Escaped.
1515                                        //TODO: Maybe it shouldn't attempt to run if it has another, valid target?
1516                                        md->attacked_id = 0;
1517                                        return true;
1518                                }
1519                        } else if (!(battle_config.mob_ai&0x2) && !status_check_skilluse(&md->bl, abl, 0, 0)) {
1520                                //Can't attack back, but didn't invoke a rude attacked skill...
1521                        } else { //Attackable
1522                                if (!tbl || dist < md->status.rhw.range || !check_distance_bl(&md->bl, tbl, dist)
1523                                        || battle_gettarget(tbl) != md->bl.id)
1524                                {       //Change if the new target is closer than the actual one
1525                                        //or if the previous target is not attacking the mob. [Skotlex]
1526                                        md->target_id = md->attacked_id; // set target
1527                                        if (md->state.attacked_count)
1528                                          md->state.attacked_count--; //Should we reset rude attack count?
1529                                        md->min_chase = dist+md->db->range3;
1530                                        if(md->min_chase>MAX_MINCHASE)
1531                                                md->min_chase=MAX_MINCHASE;
1532                                        tbl = abl; //Set the new target
1533                                }
1534                        }
1535                }
1536                //Clear it since it's been checked for already.
1537                md->attacked_id = 0;
1538        }
1539       
1540        // Processing of slave monster
1541        if (md->master_id > 0 && mob_ai_sub_hard_slavemob(md, tick))
1542                return true;
1543
1544        // Scan area for targets
1545        if (!tbl && mode&MD_LOOTER && md->lootitem && DIFF_TICK(tick, md->ud.canact_tick) > 0 &&
1546                (md->lootitem_count < LOOTITEM_SIZE || battle_config.monster_loot_type != 1))
1547        {       // Scan area for items to loot, avoid trying to loot of the mob is full and can't consume the items.
1548                map_foreachinrange (mob_ai_sub_hard_lootsearch, &md->bl,
1549                        view_range, BL_ITEM, md, &tbl);
1550        }
1551
1552        if ((!tbl && mode&MD_AGGRESSIVE) || md->state.skillstate == MSS_FOLLOW)
1553        {
1554                map_foreachinrange (mob_ai_sub_hard_activesearch, &md->bl,
1555                        view_range, DEFAULT_ENEMY_TYPE(md), md, &tbl);
1556        } else
1557        if (mode&MD_CHANGECHASE && (md->state.skillstate == MSS_RUSH || md->state.skillstate == MSS_FOLLOW))
1558        {
1559                search_size = view_range<md->status.rhw.range ? view_range:md->status.rhw.range;
1560                map_foreachinrange (mob_ai_sub_hard_changechase, &md->bl,
1561                                search_size, DEFAULT_ENEMY_TYPE(md), md, &tbl);
1562        }
1563
1564        if (!tbl) { //No targets available.
1565                if (mode&MD_ANGRY && !md->state.aggressive)
1566                        md->state.aggressive = 1; //Restore angry state when no targets are available.
1567                //This handles triggering idle walk/skill.
1568                mob_unlocktarget(md, tick);
1569                return true;
1570        }
1571       
1572        //Target exists, attack or loot as applicable.
1573        if (tbl->type == BL_ITEM)
1574        {       //Loot time.
1575                struct flooritem_data *fitem;
1576                if (md->ud.target == tbl->id && md->ud.walktimer != -1)
1577                        return true; //Already locked.
1578                if (md->lootitem == NULL)
1579                {       //Can't loot...
1580                        mob_unlocktarget (md, tick);
1581                        return true;
1582                }
1583                if (!check_distance_bl(&md->bl, tbl, 1))
1584                {       //Still not within loot range.
1585                        if (!(mode&MD_CANMOVE))
1586                        {       //A looter that can't move? Real smart.
1587                                mob_unlocktarget(md,tick);
1588                                return true;
1589                        }
1590                        if (!can_move) //Stuck. Wait before walking.
1591                                return true;
1592                        md->state.skillstate = MSS_LOOT;
1593                        if (!unit_walktobl(&md->bl, tbl, 0, 1))
1594                                mob_unlocktarget(md, tick); //Can't loot...
1595                        return true;
1596                }
1597                //Within looting range.
1598                if (md->ud.attacktimer != -1)
1599                        return true; //Busy attacking?
1600
1601                fitem = (struct flooritem_data *)tbl;
1602                if(log_config.enable_logs&0x10) //Logs items, taken by (L)ooter Mobs [Lupus]
1603                        log_pick_mob(md, "L", fitem->item_data.nameid, fitem->item_data.amount, &fitem->item_data);
1604
1605                if (md->lootitem_count < LOOTITEM_SIZE) {
1606                        memcpy (&md->lootitem[md->lootitem_count++], &fitem->item_data, sizeof(md->lootitem[0]));
1607                } else {        //Destroy first looted item...
1608                        if (md->lootitem[0].card[0] == CARD0_PET)
1609                                intif_delete_petdata( MakeDWord(md->lootitem[0].card[1],md->lootitem[0].card[2]) );
1610                        memmove(&md->lootitem[0], &md->lootitem[1], (LOOTITEM_SIZE-1)*sizeof(md->lootitem[0]));
1611                        memcpy (&md->lootitem[LOOTITEM_SIZE-1], &fitem->item_data, sizeof(md->lootitem[0]));
1612                }
1613                if (pcdb_checkid(md->vd->class_))
1614                {       //Give them walk act/delay to properly mimic players. [Skotlex]
1615                        clif_takeitem(&md->bl,tbl);
1616                        md->ud.canact_tick = tick + md->status.amotion;
1617                        unit_set_walkdelay(&md->bl, tick, md->status.amotion, 1);
1618                }
1619                //Clear item.
1620                map_clearflooritem (tbl->id);
1621                mob_unlocktarget (md,tick);
1622                return true;
1623        }
1624        //Attempt to attack.
1625        //At this point we know the target is attackable, we just gotta check if the range matches.
1626        if (md->ud.target == tbl->id && md->ud.attacktimer != -1) //Already locked.
1627                return true;
1628       
1629        if (battle_check_range (&md->bl, tbl, md->status.rhw.range))
1630        {       //Target within range, engage
1631                unit_attack(&md->bl,tbl->id,1);
1632                return true;
1633        }
1634
1635        //Out of range...
1636        if (!(mode&MD_CANMOVE))
1637        {       //Can't chase. Attempt an idle skill before unlocking.
1638                md->state.skillstate = MSS_IDLE;
1639                if (!mobskill_use(md, tick, -1))
1640                        mob_unlocktarget(md,tick);
1641                return true;
1642        }
1643
1644        if (!can_move)
1645        {       //Stuck. Attempt an idle skill
1646                md->state.skillstate = MSS_IDLE;
1647                if (!(++md->ud.walk_count%IDLE_SKILL_INTERVAL))
1648                        mobskill_use(md, tick, -1);
1649                return true;
1650        }
1651
1652        if (md->ud.walktimer != -1 && md->ud.target == tbl->id &&
1653                (
1654                        !(battle_config.mob_ai&0x1) ||
1655                        check_distance_blxy(tbl, md->ud.to_x, md->ud.to_y, md->status.rhw.range)
1656        )) //Current target tile is still within attack range.
1657                return true;
1658
1659        //Follow up if possible.
1660        if(!mob_can_reach(md, tbl, md->min_chase, MSS_RUSH) ||
1661                !unit_walktobl(&md->bl, tbl, md->status.rhw.range, 2))
1662                mob_unlocktarget(md,tick);
1663
1664        return true;
1665}
1666
1667static int mob_ai_sub_hard_timer(struct block_list *bl,va_list ap)
1668{
1669        struct mob_data *md = (struct mob_data*)bl;
1670        unsigned int tick = va_arg(ap, unsigned int);
1671        if (mob_ai_sub_hard(md, tick)) 
1672        {       //Hard AI triggered.
1673                if(!md->state.spotted)
1674                        md->state.spotted = 1;
1675                md->last_pcneartime = tick;
1676        }
1677        return 0;
1678}
1679
1680/*==========================================
1681 * Serious processing for mob in PC field of view (foreachclient)
1682 *------------------------------------------*/
1683static int mob_ai_sub_foreachclient(struct map_session_data *sd,va_list ap)
1684{
1685        unsigned int tick;
1686        tick=va_arg(ap,unsigned int);
1687        map_foreachinrange(mob_ai_sub_hard_timer,&sd->bl, AREA_SIZE+ACTIVE_AI_RANGE, BL_MOB,tick);
1688
1689        return 0;
1690}
1691
1692/*==========================================
1693 * Negligent mode MOB AI (PC is not in near)
1694 *------------------------------------------*/
1695static int mob_ai_sub_lazy(struct mob_data *md, va_list args)
1696{
1697        unsigned int tick;
1698        int mode;
1699
1700        nullpo_retr(0, md);
1701
1702        if(md->bl.prev == NULL)
1703                return 0;
1704
1705        tick = va_arg(args,unsigned int);
1706
1707        if (md->nd || (battle_config.mob_ai&0x20 && map[md->bl.m].users>0))
1708                return (int)mob_ai_sub_hard(md, tick);
1709
1710        if (md->bl.prev==NULL || md->status.hp == 0)
1711                return 1;
1712
1713        if(battle_config.mob_active_time &&
1714                md->last_pcneartime &&
1715                !(md->status.mode&MD_BOSS) &&
1716                DIFF_TICK(tick,md->last_thinktime) > MIN_MOBTHINKTIME)
1717        {
1718                if (DIFF_TICK(tick,md->last_pcneartime) < battle_config.mob_active_time)
1719                        return (int)mob_ai_sub_hard(md, tick);
1720                md->last_pcneartime = 0;
1721        }
1722
1723        if(battle_config.boss_active_time &&
1724                md->last_pcneartime &&
1725                (md->status.mode&MD_BOSS) &&
1726                DIFF_TICK(tick,md->last_thinktime) > MIN_MOBTHINKTIME)
1727        {
1728                if (DIFF_TICK(tick,md->last_pcneartime) < battle_config.boss_active_time)
1729                        return (int)mob_ai_sub_hard(md, tick);
1730                md->last_pcneartime = 0;
1731        }
1732
1733        if(DIFF_TICK(tick,md->last_thinktime)< 10*MIN_MOBTHINKTIME)
1734                return 0;
1735
1736        md->last_thinktime=tick;
1737
1738        if (md->master_id) {
1739                mob_ai_sub_hard_slavemob (md,tick);
1740                return 0;
1741        }
1742
1743        mode = status_get_mode(&md->bl);
1744        if(DIFF_TICK(md->next_walktime,tick)<0 &&
1745                (mode&MD_CANMOVE) && unit_can_move(&md->bl) ){
1746
1747                if( map[md->bl.m].users>0 ){
1748                        // Since PC is in the same map, somewhat better negligent processing is carried out.
1749
1750                        // It sometimes moves.
1751                        if(rand()%1000<MOB_LAZYMOVEPERC(md))
1752                                mob_randomwalk(md,tick);
1753                        else if(rand()%1000<MOB_LAZYSKILLPERC) //Chance to do a mob's idle skill.
1754                                mobskill_use(md, tick, -1);
1755                        // MOB which is not not the summons MOB but BOSS, either sometimes reboils.
1756                        // People don't want this, it seems custom, noone can prove it....
1757//                      else if( rand()%1000<MOB_LAZYWARPPERC
1758//                              && (md->spawn && !md->spawn->x && !md->spawn->y)
1759//                              && !md->target_id && !(mode&MD_BOSS))
1760//                              unit_warp(&md->bl,-1,-1,-1,0);
1761                }else{
1762                        // Since PC is not even in the same map, suitable processing is carried out even if it takes.
1763
1764                        // MOB which is not BOSS which is not Summons MOB, either -- a case -- sometimes -- leaping
1765                        if( rand()%1000<MOB_LAZYWARPPERC
1766                                && (md->spawn && !md->spawn->x && !md->spawn->y)
1767                                && !(mode&MD_BOSS))
1768                                unit_warp(&md->bl,-1,-1,-1,0);
1769                }
1770
1771                md->next_walktime = tick+rand()%10000+5000;
1772        }
1773        return 0;
1774}
1775
1776/*==========================================
1777 * Negligent processing for mob outside PC field of view   (interval timer function)
1778 *------------------------------------------*/
1779static int mob_ai_lazy(int tid, unsigned int tick, int id, intptr data)
1780{
1781        map_foreachmob(mob_ai_sub_lazy,tick);
1782        return 0;
1783}
1784
1785/*==========================================
1786 * Serious processing for mob in PC field of view   (interval timer function)
1787 *------------------------------------------*/
1788static int mob_ai_hard(int tid, unsigned int tick, int id, intptr data)
1789{
1790
1791        if (battle_config.mob_ai&0x20)
1792                map_foreachmob(mob_ai_sub_lazy,tick);
1793        else
1794                map_foreachpc(mob_ai_sub_foreachclient,tick);
1795
1796        return 0;
1797}
1798
1799/*==========================================
1800 * Initializes the delay drop structure for mob-dropped items.
1801 *------------------------------------------*/
1802static struct item_drop* mob_setdropitem(int nameid, int qty)
1803{
1804        struct item_drop *drop = ers_alloc(item_drop_ers, struct item_drop);
1805        memset(&drop->item_data, 0, sizeof(struct item));
1806        drop->item_data.nameid = nameid;
1807        drop->item_data.amount = qty;
1808        drop->item_data.identify = itemdb_isidentified(nameid);
1809        drop->next = NULL;
1810        return drop;
1811};
1812
1813/*==========================================
1814 * Initializes the delay drop structure for mob-looted items.
1815 *------------------------------------------*/
1816static struct item_drop* mob_setlootitem(struct item* item)
1817{
1818        struct item_drop *drop = ers_alloc(item_drop_ers, struct item_drop);
1819        memcpy(&drop->item_data, item, sizeof(struct item));
1820        drop->next = NULL;
1821        return drop;
1822};
1823
1824/*==========================================
1825 * item drop with delay (timer function)
1826 *------------------------------------------*/
1827static int mob_delay_item_drop(int tid, unsigned int tick, int id, intptr data)
1828{
1829        struct item_drop_list *list;
1830        struct item_drop *ditem, *ditem_prev;
1831        list=(struct item_drop_list *)id;
1832        ditem = list->item;
1833        while (ditem) {
1834                map_addflooritem(&ditem->item_data,ditem->item_data.amount,
1835                        list->m,list->x,list->y,
1836                        list->first_charid,list->second_charid,list->third_charid,0);
1837                ditem_prev = ditem;
1838                ditem = ditem->next;
1839                ers_free(item_drop_ers, ditem_prev);
1840        }
1841        ers_free(item_drop_list_ers, list);
1842        return 0;
1843}
1844
1845/*==========================================
1846 * Sets the item_drop into the item_drop_list.
1847 * Also performs logging and autoloot if enabled.
1848 * rate is the drop-rate of the item, required for autoloot.
1849 * flag : Killed only by homunculus?
1850 *------------------------------------------*/
1851static void mob_item_drop(struct mob_data *md, struct item_drop_list *dlist, struct item_drop *ditem, int loot, int drop_rate, unsigned short flag)
1852{
1853        TBL_PC* sd;
1854
1855        if(log_config.enable_logs&0x10)
1856        {       //Logs items, dropped by mobs [Lupus]
1857                if (loot)
1858                        log_pick_mob(md, "L", ditem->item_data.nameid, -ditem->item_data.amount, &ditem->item_data);
1859                else
1860                        log_pick_mob(md, "M", ditem->item_data.nameid, -ditem->item_data.amount, NULL);
1861        }
1862
1863        sd = map_charid2sd(dlist->first_charid);
1864        if( sd == NULL ) sd = map_charid2sd(dlist->second_charid);
1865        if( sd == NULL ) sd = map_charid2sd(dlist->third_charid);
1866
1867        if( sd
1868                && (drop_rate <= sd->state.autoloot || ditem->item_data.nameid == sd->state.autolootid)
1869                && (battle_config.idle_no_autoloot == 0 || DIFF_TICK(last_tick, sd->idletime) < battle_config.idle_no_autoloot)
1870                && (battle_config.homunculus_autoloot?1:!flag)
1871#ifdef AUTOLOOT_DISTANCE
1872                && check_distance_blxy(&sd->bl, dlist->x, dlist->y, AUTOLOOT_DISTANCE)
1873#endif
1874        ) {     //Autoloot.
1875                if (party_share_loot(party_search(sd->status.party_id),
1876                        sd, &ditem->item_data, sd->status.char_id) == 0
1877                ) {
1878                        ers_free(item_drop_ers, ditem);
1879                        return;
1880                }
1881        }
1882        ditem->next = dlist->item;
1883        dlist->item = ditem;
1884}
1885
1886int mob_timer_delete(int tid, unsigned int tick, int id, intptr data)
1887{
1888        struct block_list *bl=map_id2bl(id);
1889        nullpo_retr(0, bl);
1890        if (bl->type != BL_MOB)
1891                return 0; //??
1892//for Alchemist CANNIBALIZE [Lupus]
1893        ((TBL_MOB*)bl)->deletetimer = -1;
1894        unit_free(bl,3);
1895        return 0;
1896}
1897
1898int mob_convertslave_sub(struct block_list *bl,va_list ap)
1899{
1900        struct mob_data *md, *md2 = NULL;
1901
1902        nullpo_retr(0, bl);
1903        nullpo_retr(0, ap);
1904        nullpo_retr(0, md = (struct mob_data *)bl);
1905
1906        md2=va_arg(ap,TBL_MOB *);
1907
1908        if(md->master_id > 0 && md->master_id == md2->bl.id){
1909                md->state.killer = md2->state.killer;
1910                md->special_state.ai = md2->special_state.ai;
1911                md->nd = md2->nd;
1912                md->callback_flag = md2->callback_flag;
1913        }
1914
1915        return 0;
1916}
1917
1918int mob_convertslave(struct mob_data *md)
1919{
1920        nullpo_retr(0, md);
1921
1922        map_foreachinmap(mob_convertslave_sub, md->bl.m, BL_MOB, md);
1923        return 0;
1924}
1925
1926/*==========================================
1927 *
1928 *------------------------------------------*/
1929int mob_deleteslave_sub(struct block_list *bl,va_list ap)
1930{
1931        struct mob_data *md;
1932        int id;
1933
1934        nullpo_retr(0, bl);
1935        nullpo_retr(0, ap);
1936        nullpo_retr(0, md = (struct mob_data *)bl);
1937
1938        id=va_arg(ap,int);
1939        if(md->master_id > 0 && md->master_id == id )
1940                status_kill(bl);
1941        return 0;
1942}
1943
1944/*==========================================
1945 *
1946 *------------------------------------------*/
1947int mob_deleteslave(struct mob_data *md)
1948{
1949        nullpo_retr(0, md);
1950
1951        map_foreachinmap(mob_deleteslave_sub, md->bl.m, BL_MOB,md->bl.id);
1952        return 0;
1953}
1954// Mob respawning through KAIZEL or NPC_REBIRTH [Skotlex]
1955int mob_respawn(int tid, unsigned int tick, int id, intptr data)
1956{
1957        struct block_list *bl = map_id2bl(id);
1958
1959        if(!bl) return 0;
1960        status_revive(bl, (uint8)data, 0);
1961        return 1;
1962}
1963
1964void mob_log_damage(struct mob_data *md, struct block_list *src, int damage)
1965{
1966        int char_id = 0, flag = 0;
1967        if(damage < 0) return; //Do nothing for absorbed damage.
1968
1969        if(!damage && !(src->type&DEFAULT_ENEMY_TYPE(md)))
1970                return; //Do not log non-damaging effects from non-enemies.
1971
1972        switch (src->type) {
1973        case BL_PC:
1974        {
1975                struct map_session_data *sd = (TBL_PC*)src;
1976                char_id = sd->status.char_id;
1977                if (damage)
1978                        md->attacked_id = src->id;
1979                break;
1980        }
1981        case BL_HOM:    //[orn]
1982        {
1983                struct homun_data *hd = (TBL_HOM*)src;
1984                flag = 1;
1985                if (hd->master)
1986                        char_id = hd->master->status.char_id;
1987                if (damage)
1988                        md->attacked_id = src->id;
1989                break;
1990        }
1991        case BL_PET:
1992        {
1993                struct pet_data *pd = (TBL_PET*)src;
1994                if (battle_config.pet_attack_exp_to_master && pd->msd) {
1995                        char_id = pd->msd->status.char_id;
1996                        damage=(damage*battle_config.pet_attack_exp_rate)/100; //Modify logged damage accordingly.
1997                }
1998                //Let mobs retaliate against the pet's master [Skotlex]
1999                if(pd->msd && damage)
2000                        md->attacked_id = pd->msd->bl.id;
2001                break;
2002        }
2003        case BL_MOB:
2004        {
2005                struct mob_data* md2 = (TBL_MOB*)src;
2006                if(md2->special_state.ai && md2->master_id) {
2007                        struct map_session_data* msd = map_id2sd(md2->master_id);
2008                        if (msd) char_id = msd->status.char_id;
2009                }
2010                if (!damage)
2011                        break;
2012                //Let players decide whether to retaliate versus the master or the mob. [Skotlex]
2013                if (md2->master_id && battle_config.retaliate_to_master)
2014                        md->attacked_id = md2->master_id;
2015                else
2016                        md->attacked_id = src->id;
2017                break;
2018        }
2019        default: //For all unhandled types.
2020                md->attacked_id = src->id;
2021        }
2022        //Log damage...
2023        if(char_id) {
2024                int i,minpos;
2025                unsigned int mindmg;
2026                for(i=0,minpos=DAMAGELOG_SIZE-1,mindmg=UINT_MAX;i<DAMAGELOG_SIZE;i++){
2027                        if(md->dmglog[i].id==char_id &&
2028                                md->dmglog[i].flag==flag)
2029                                break;
2030                        if(md->dmglog[i].id==0) {       //Store data in first empty slot.
2031                                md->dmglog[i].id  = char_id;
2032                                md->dmglog[i].flag= flag;
2033                                break;
2034                        }
2035                        if(md->dmglog[i].dmg<mindmg && i)
2036                        {       //Never overwrite first hit slot (he gets double exp bonus)
2037                                minpos=i;
2038                                mindmg=md->dmglog[i].dmg;
2039                        }
2040                }
2041                if(i<DAMAGELOG_SIZE)
2042                        md->dmglog[i].dmg+=damage;
2043                else {
2044                        md->dmglog[minpos].id  = char_id;
2045                        md->dmglog[minpos].flag= flag;
2046                        md->dmglog[minpos].dmg = damage;
2047                }
2048        }
2049        return;
2050}
2051//Call when a mob has received damage.
2052void mob_damage(struct mob_data *md, struct block_list *src, int damage)
2053{
2054        if (damage > 0)
2055        {       //Store total damage...
2056                if (UINT_MAX - (unsigned int)damage > md->tdmg)
2057                        md->tdmg+=damage;
2058                else if (md->tdmg == UINT_MAX)
2059                        damage = 0; //Stop recording damage once the cap has been reached.
2060                else { //Cap damage log...
2061                        damage = (int)(UINT_MAX - md->tdmg);
2062                        md->tdmg = UINT_MAX;
2063                }
2064                if (md->state.aggressive)
2065                {       //No longer aggressive, change to retaliate AI.
2066                        md->state.aggressive = 0;
2067                        if(md->state.skillstate== MSS_ANGRY)
2068                                md->state.skillstate = MSS_BERSERK;
2069                        if(md->state.skillstate== MSS_FOLLOW)
2070                                md->state.skillstate = MSS_RUSH;
2071                }
2072                //Log damage
2073                if (src) mob_log_damage(md, src, damage);
2074        }
2075
2076        if (battle_config.show_mob_info&3)
2077                clif_charnameack (0, &md->bl);
2078       
2079        if (!src)
2080                return;
2081       
2082        if(md->nd)
2083                mob_script_callback(md, src, CALLBACK_ATTACK);
2084       
2085        if(md->special_state.ai==2/* && md->master_id == src->id*/)
2086        {       //LOne WOlf explained that ANYONE can trigger the marine countdown skill. [Skotlex]
2087                md->state.alchemist = 1;
2088                mobskill_use(md, gettick(), MSC_ALCHEMIST);
2089        }
2090}
2091
2092/*==========================================
2093 * Signals death of mob.
2094 * type&1 -> no drops, type&2 -> no exp
2095 *------------------------------------------*/
2096int mob_dead(struct mob_data *md, struct block_list *src, int type)
2097{
2098        struct status_data *status;
2099        struct map_session_data *sd = NULL, *tmpsd[DAMAGELOG_SIZE];
2100        struct map_session_data *mvp_sd = NULL, *second_sd = NULL, *third_sd = NULL;
2101       
2102        struct {
2103                struct party_data *p;
2104                int id,zeny;
2105                unsigned int base_exp,job_exp;
2106        } pt[DAMAGELOG_SIZE];
2107        int i,temp,count,pnum=0,m=md->bl.m;
2108        unsigned int mvp_damage, tick = gettick();
2109        unsigned short flaghom = 1; // [Zephyrus] Does the mob only received damage from homunculus?
2110
2111        if(src && src->type == BL_PC) {
2112                sd = (struct map_session_data *)src;
2113                mvp_sd = sd;
2114        }
2115
2116        status = &md->status;
2117               
2118        if( md->guardian_data && md->guardian_data->number >= 0 && md->guardian_data->number < MAX_GUARDIANS )
2119                guild_castledatasave(md->guardian_data->castle->castle_id, 10+md->guardian_data->number,0);
2120
2121        md->state.skillstate = MSS_DEAD;       
2122        mobskill_use(md,tick,-1);       //On Dead skill.
2123
2124        map_freeblock_lock();
2125
2126        memset(pt,0,sizeof(pt));
2127
2128        if(src && src->type == BL_MOB)
2129                mob_unlocktarget((struct mob_data *)src,tick);
2130
2131        if(sd) {
2132                int sp = 0, hp = 0;
2133                sp += sd->sp_gain_value;
2134                sp += sd->sp_gain_race[status->race];
2135                sp += sd->sp_gain_race[status->mode&MD_BOSS?RC_BOSS:RC_NONBOSS];
2136                hp += sd->hp_gain_value;
2137                if (hp||sp)
2138                        status_heal(src, hp, sp, battle_config.show_hp_sp_gain?2:0);
2139                if (sd->mission_mobid == md->class_) { //TK_MISSION [Skotlex]
2140                        if (++sd->mission_count >= 100 && (temp = mob_get_random_id(0, 0xE, sd->status.base_level)))
2141                        {
2142                                pc_addfame(sd, 1);
2143                                sd->mission_mobid = temp;
2144                                pc_setglobalreg(sd,"TK_MISSION_ID", temp);
2145                                sd->mission_count = 0;
2146                                clif_mission_info(sd, temp, 0);
2147                        }
2148                        pc_setglobalreg(sd,"TK_MISSION_COUNT", sd->mission_count);
2149                }
2150        }
2151
2152        // filter out entries not eligible for exp distribution
2153        memset(tmpsd,0,sizeof(tmpsd));
2154        for(i = 0, count = 0, mvp_damage = 0; i < DAMAGELOG_SIZE && md->dmglog[i].id; i++)
2155        {
2156                struct map_session_data* tsd = map_charid2sd(md->dmglog[i].id);
2157
2158                if(tsd == NULL)
2159                        continue; // skip empty entries
2160                if(tsd->bl.m != m)
2161                        continue; // skip players not on this map
2162                count++; //Only logged into same map chars are counted for the total.
2163                if (pc_isdead(tsd))
2164                        continue; // skip dead players
2165                if(md->dmglog[i].flag && !merc_is_hom_active(tsd->hd))
2166                        continue; // skip homunc's share if inactive
2167
2168                if(md->dmglog[i].dmg > mvp_damage)
2169                {
2170                        third_sd = second_sd;
2171                        second_sd = mvp_sd;
2172                        mvp_sd = tsd;
2173                        mvp_damage = md->dmglog[i].dmg;
2174                }
2175
2176                tmpsd[i] = tsd; // record as valid damage-log entry
2177
2178                if(!md->dmglog[i].flag && flaghom)
2179                        flaghom = 0; // Damage received from other Types != Homunculus
2180        }
2181
2182        if(!battle_config.exp_calc_type && count > 1)
2183        {       //Apply first-attacker 200% exp share bonus
2184                //TODO: Determine if this should go before calculating the MVP player instead of after.
2185                if (UINT_MAX - md->dmglog[0].dmg > md->tdmg) {
2186                        md->tdmg += md->dmglog[0].dmg;
2187                        md->dmglog[0].dmg<<=1;
2188                } else {
2189                        md->dmglog[0].dmg+= UINT_MAX - md->tdmg;
2190                        md->tdmg = UINT_MAX;
2191                }
2192        }
2193
2194        if(!(type&2) && //No exp
2195                (!map[m].flag.pvp || battle_config.pvp_exp) && //Pvp no exp rule [MouseJstr]
2196                (!md->master_id || !md->special_state.ai) && //Only player-summoned mobs do not give exp. [Skotlex]
2197                (!map[m].flag.nobaseexp || !map[m].flag.nojobexp) //Gives Exp
2198        ) { //Experience calculation.
2199                int bonus = 100; //Bonus on top of your share (common to all attackers).
2200                if (md->sc.data[SC_RICHMANKIM])
2201                        bonus += md->sc.data[SC_RICHMANKIM]->val2;
2202                if(sd) {
2203                        temp = status_get_class(&md->bl);
2204                        if(sd->sc.data[SC_MIRACLE]) i = 2; //All mobs are Star Targets
2205                        else
2206                        ARR_FIND(0, 3, i, temp == sd->hate_mob[i] &&
2207                                (battle_config.allow_skill_without_day || sg_info[i].day_func()));
2208                        if(i<3 && (temp=pc_checkskill(sd,sg_info[i].bless_id)))
2209                                bonus += (i==2?20:10)*temp;
2210                }
2211                if(battle_config.mobs_level_up && md->level > md->db->lv) // [Valaris]
2212                        bonus += (md->level-md->db->lv)*battle_config.mobs_level_up_exp_rate;
2213
2214        for(i = 0; i < DAMAGELOG_SIZE && md->dmglog[i].id; i++)
2215        {
2216                int flag=1,zeny=0;
2217                unsigned int base_exp, job_exp;
2218                double per; //Your share of the mob's exp
2219
2220                if (!tmpsd[i]) continue;
2221
2222                if (!battle_config.exp_calc_type && md->tdmg)
2223                        //jAthena's exp formula based on total damage.
2224                        per = (double)md->dmglog[i].dmg/(double)md->tdmg;
2225                else {
2226                        //eAthena's exp formula based on max hp.
2227                        per = (double)md->dmglog[i].dmg/(double)status->max_hp;
2228                        if (per > 2) per = 2; // prevents unlimited exp gain
2229                }
2230       
2231                if (count>1 && battle_config.exp_bonus_attacker) {
2232                        //Exp bonus per additional attacker.
2233                        if (count > battle_config.exp_bonus_max_attacker)
2234                                count = battle_config.exp_bonus_max_attacker;
2235                        per += per*((count-1)*battle_config.exp_bonus_attacker)/100.;
2236                }
2237
2238                // change experience for different sized monsters [Valaris]
2239                if(md->special_state.size==1)
2240                        per /=2.;
2241                else if(md->special_state.size==2)
2242                        per *=2.;
2243               
2244       
2245                if(battle_config.zeny_from_mobs && md->level) {
2246                         // zeny calculation moblv + random moblv [Valaris]
2247                        zeny=(int) ((md->level+rand()%md->level)*per*bonus/100.);
2248                        if(md->db->mexp > 0)
2249                                zeny*=rand()%250;
2250                }
2251
2252                if (map[m].flag.nobaseexp || !md->db->base_exp)
2253                        base_exp = 0; 
2254                else
2255                        base_exp = (unsigned int)cap_value(md->db->base_exp * per * bonus/100. * map[m].bexp/100., 1, UINT_MAX);
2256               
2257                if (map[m].flag.nojobexp || !md->db->job_exp || md->dmglog[i].flag) //Homun earned job-exp is always lost.
2258                        job_exp = 0; 
2259                else
2260                        job_exp = (unsigned int)cap_value(md->db->job_exp * per * bonus/100. * map[m].jexp/100., 1, UINT_MAX);
2261               
2262                if((temp = tmpsd[i]->status.party_id )>0 && !md->dmglog[i].flag) //Homun-done damage (flag 1) is not given to party
2263                {
2264                        int j;
2265                        for(j=0;j<pnum && pt[j].id!=temp;j++); //Locate party.
2266
2267                        if(j==pnum){ //Possibly add party.
2268                                pt[pnum].p = party_search(temp);
2269                                if(pt[pnum].p && pt[pnum].p->party.exp)
2270                                {
2271                                        pt[pnum].id=temp;
2272                                        pt[pnum].base_exp=base_exp;
2273                                        pt[pnum].job_exp=job_exp;
2274                                        pt[pnum].zeny=zeny; // zeny share [Valaris]
2275                                        pnum++;
2276                                        flag=0;
2277                                }
2278                        }else{  //Add to total
2279                                if (pt[j].base_exp > UINT_MAX - base_exp)
2280                                        pt[j].base_exp=UINT_MAX;
2281                                else
2282                                        pt[j].base_exp+=base_exp;
2283                               
2284                                if (pt[j].job_exp > UINT_MAX - job_exp)
2285                                        pt[j].job_exp=UINT_MAX;
2286                                else
2287                                        pt[j].job_exp+=job_exp;
2288                               
2289                                pt[j].zeny+=zeny;  // zeny share [Valaris]
2290                                flag=0;
2291                        }
2292                }
2293                if(flag) {
2294                        if(base_exp && md->dmglog[i].flag) //tmpsd[i] is null if it has no homunc.
2295                                merc_hom_gainexp(tmpsd[i]->hd, base_exp);
2296                        if(base_exp || job_exp)
2297                                pc_gainexp(tmpsd[i], &md->bl, base_exp, job_exp);
2298                        if(zeny) // zeny from mobs [Valaris]
2299                                pc_getzeny(tmpsd[i], zeny);
2300                }
2301        }
2302       
2303        for(i=0;i<pnum;i++) //Party share.
2304                party_exp_share(pt[i].p, &md->bl, pt[i].base_exp,pt[i].job_exp,pt[i].zeny);
2305
2306        } //End EXP giving.
2307       
2308        if (!(type&1) &&
2309                !map[m].flag.nomobloot &&
2310                (
2311                        !md->special_state.ai || //Non special mob
2312                        battle_config.alchemist_summon_reward == 2 || //All summoned give drops
2313                        (md->special_state.ai==2 && battle_config.alchemist_summon_reward == 1) //Marine Sphere Drops items.
2314                )
2315        ) {     //item drop
2316                struct item_drop_list *dlist = ers_alloc(item_drop_list_ers, struct item_drop_list);
2317                struct item_drop *ditem;
2318                int drop_rate;
2319                dlist->m = md->bl.m;
2320                dlist->x = md->bl.x;
2321                dlist->y = md->bl.y;
2322                dlist->first_charid = (mvp_sd ? mvp_sd->status.char_id : 0);
2323                dlist->second_charid = (second_sd ? second_sd->status.char_id : 0);
2324                dlist->third_charid = (third_sd ? third_sd->status.char_id : 0);
2325                dlist->item = NULL;
2326
2327                for (i = 0; i < MAX_MOB_DROP; i++)
2328                {
2329                        if (md->db->dropitem[i].nameid <= 0)
2330                                continue;
2331                        if (!itemdb_exists(md->db->dropitem[i].nameid))
2332                                continue;
2333                        drop_rate = md->db->dropitem[i].p;
2334                        if (drop_rate <= 0) {
2335                                if (battle_config.drop_rate0item)
2336                                        continue;
2337                                drop_rate = 1;
2338                        }
2339
2340                        // change drops depending on monsters size [Valaris]
2341                        if(md->special_state.size==1 && drop_rate >= 2)
2342                                drop_rate/=2;
2343                        else if(md->special_state.size==2)
2344                                drop_rate*=2;
2345                        if (src) {
2346                                //Drops affected by luk as a fixed increase [Valaris]
2347                                if (battle_config.drops_by_luk)
2348                                        drop_rate += status_get_luk(src)*battle_config.drops_by_luk/100;
2349                                //Drops affected by luk as a % increase [Skotlex]
2350                                if (battle_config.drops_by_luk2)
2351                                        drop_rate += (int)(0.5+drop_rate*status_get_luk(src)*battle_config.drops_by_luk2/10000.);
2352                        }
2353                        if (sd && battle_config.pk_mode &&
2354                                (int)(md->level - sd->status.base_level) >= 20)
2355                                drop_rate = (int)(drop_rate*1.25); // pk_mode increase drops if 20 level difference [Valaris]
2356
2357                        // attempt to drop the item
2358                        if (rand() % 10000 >= drop_rate)
2359                        {       // Double try by Bubble Gum
2360                                if (!(sd && sd->sc.data[SC_ITEMBOOST] && rand() % 10000 < drop_rate))
2361                                        continue;
2362                        }
2363
2364                        ditem = mob_setdropitem(md->db->dropitem[i].nameid, 1);
2365
2366                        //A Rare Drop Global Announce by Lupus
2367                        if(drop_rate<=battle_config.rare_drop_announce) {
2368                                struct item_data *i_data;
2369                                char message[128];
2370                                i_data = itemdb_search(ditem->item_data.nameid);
2371                                sprintf (message, msg_txt(541), (mvp_sd?mvp_sd->status.name:"???"), md->name, i_data->jname, (float)drop_rate/100);
2372                                //MSG: "'%s' won %s's %s (chance: %0.02f%%)"
2373                                intif_GMmessage(message,strlen(message)+1,0);
2374                        }
2375                        // Announce first, or else ditem will be freed. [Lance]
2376                        // By popular demand, use base drop rate for autoloot code. [Skotlex]
2377                        mob_item_drop(md, dlist, ditem, 0, md->db->dropitem[i].p, flaghom);
2378                }
2379
2380                // Ore Discovery [Celest]
2381                if (sd == mvp_sd && pc_checkskill(sd,BS_FINDINGORE)>0 && battle_config.finding_ore_rate/10 >= rand()%10000) {
2382                        ditem = mob_setdropitem(itemdb_searchrandomid(IG_FINDINGORE), 1);
2383                        mob_item_drop(md, dlist, ditem, 0, battle_config.finding_ore_rate/10, 0);
2384                }
2385
2386                if(sd) {
2387                        // process script-granted extra drop bonuses
2388                        int itemid = 0;
2389                        for (i = 0; i < ARRAYLENGTH(sd->add_drop) && (sd->add_drop[i].id || sd->add_drop[i].group); i++)
2390                        {
2391                                if (sd->add_drop[i].race & (1<<status->race) ||
2392                                        sd->add_drop[i].race & 1<<(status->mode&MD_BOSS?RC_BOSS:RC_NONBOSS))
2393                                {
2394                                        //check if the bonus item drop rate should be multiplied with mob level/10 [Lupus]
2395                                        if(sd->add_drop[i].rate < 0) {
2396                                                //it's negative, then it should be multiplied. e.g. for Mimic,Myst Case Cards, etc
2397                                                // rate = base_rate * (mob_level/10) + 1
2398                                                drop_rate = -sd->add_drop[i].rate*(md->level/10)+1;
2399                                                drop_rate = cap_value(drop_rate, battle_config.item_drop_adddrop_min, battle_config.item_drop_adddrop_max);
2400                                                if (drop_rate > 10000) drop_rate = 10000;
2401                                        }
2402                                        else
2403                                                //it's positive, then it goes as it is
2404                                                drop_rate = sd->add_drop[i].rate;
2405                                       
2406                                        if (rand()%10000 >= drop_rate)
2407                                                continue;
2408                                        itemid = (sd->add_drop[i].id > 0) ? sd->add_drop[i].id : itemdb_searchrandomid(sd->add_drop[i].group);
2409                                        mob_item_drop(md, dlist, mob_setdropitem(itemid,1), 0, drop_rate, 0);
2410                                }
2411                        }
2412                       
2413                        // process script-granted zeny bonus (get_zeny_num) [Skotlex]
2414                        if(sd->get_zeny_num && rand()%100 < sd->get_zeny_rate)
2415                        {
2416                                i = sd->get_zeny_num > 0?sd->get_zeny_num:-md->level*sd->get_zeny_num;
2417                                if (!i) i = 1;
2418                                pc_getzeny(sd, 1+rand()%i);
2419                        }
2420                }
2421               
2422                // process items looted by the mob
2423                if(md->lootitem) {
2424                        for(i = 0; i < md->lootitem_count; i++)
2425                                mob_item_drop(md, dlist, mob_setlootitem(&md->lootitem[i]), 1, 10000, 0);
2426                }
2427                if (dlist->item) //There are drop items.
2428                        add_timer(tick + (!battle_config.delay_battle_damage?500:0), mob_delay_item_drop, (int)dlist, 0);
2429                else //No drops
2430                        ers_free(item_drop_list_ers, dlist);
2431        } else if (md->lootitem && md->lootitem_count) {        //Loot MUST drop!
2432                struct item_drop_list *dlist = ers_alloc(item_drop_list_ers, struct item_drop_list);
2433                dlist->m = md->bl.m;
2434                dlist->x = md->bl.x;
2435                dlist->y = md->bl.y;
2436                dlist->first_charid = (mvp_sd ? mvp_sd->status.char_id : 0);
2437                dlist->second_charid = (second_sd ? second_sd->status.char_id : 0);
2438                dlist->third_charid = (third_sd ? third_sd->status.char_id : 0);
2439                dlist->item = NULL;
2440                for(i = 0; i < md->lootitem_count; i++)
2441                        mob_item_drop(md, dlist, mob_setlootitem(&md->lootitem[i]), 1, 10000, 0);
2442                add_timer(tick + (!battle_config.delay_battle_damage?500:0), mob_delay_item_drop, (int)dlist, 0);
2443        }
2444
2445        if(mvp_sd && md->db->mexp > 0 && !md->special_state.ai)
2446        {
2447                int log_mvp[2] = {0};
2448                int j;
2449                unsigned int mexp;
2450                struct item item;
2451                double exp;
2452               
2453                //mapflag: noexp check [Lorky]
2454                if (map[m].flag.nobaseexp || type&2)
2455                        exp =1; 
2456                else {
2457                        exp = md->db->mexp;
2458                        if (count > 1)
2459                                exp += exp*(battle_config.exp_bonus_attacker*(count-1))/100.; //[Gengar]
2460                }
2461               
2462                mexp = (unsigned int)cap_value(exp, 1, UINT_MAX);
2463
2464                if(use_irc && irc_announce_mvp_flag)
2465                        irc_announce_mvp(mvp_sd,md);
2466
2467                clif_mvp_effect(mvp_sd);
2468                clif_mvp_exp(mvp_sd,mexp);
2469                pc_gainexp(mvp_sd, &md->bl, mexp,0);
2470                log_mvp[1] = mexp;
2471                if(map[m].flag.nomvploot || type&1)
2472                        ; //No drops.
2473                else
2474                for(j=0;j<3;j++)
2475                {
2476                        i = rand() % 3;
2477                       
2478                        if(md->db->mvpitem[i].nameid <= 0)
2479                                continue;
2480                        if(!itemdb_exists(md->db->mvpitem[i].nameid))
2481                                continue;
2482                       
2483                        temp = md->db->mvpitem[i].p;
2484                        if(temp <= 0 && !battle_config.drop_rate0item)
2485                                temp = 1;
2486                        if(temp <= rand()%10000+1) //if ==0, then it doesn't drop
2487                                continue;
2488
2489                        memset(&item,0,sizeof(item));
2490                        item.nameid=md->db->mvpitem[i].nameid;
2491                        item.identify= itemdb_isidentified(item.nameid);
2492                        clif_mvp_item(mvp_sd,item.nameid);
2493                        log_mvp[0] = item.nameid;
2494                       
2495                        //A Rare MVP Drop Global Announce by Lupus
2496                        if(temp<=battle_config.rare_drop_announce) {
2497                                struct item_data *i_data;
2498                                char message[128];
2499                                i_data = itemdb_exists(item.nameid);
2500                                sprintf (message, msg_txt(541), mvp_sd->status.name, md->name, i_data->jname, temp/100.);
2501                                //MSG: "'%s' won %s's %s (chance: %0.02f%%)"
2502                                intif_GMmessage(message,strlen(message)+1,0);
2503                        }
2504
2505                        if((temp = pc_additem(mvp_sd,&item,1)) != 0) {
2506                                clif_additem(mvp_sd,0,0,temp);
2507                                map_addflooritem(&item,1,mvp_sd->bl.m,mvp_sd->bl.x,mvp_sd->bl.y,mvp_sd->status.char_id,(second_sd?second_sd->status.char_id:0),(third_sd?third_sd->status.char_id:0),1);
2508                        }
2509                       
2510                        if(log_config.enable_logs&0x200)        {//Logs items, MVP prizes [Lupus]
2511                                log_pick_mob(md, "M", item.nameid, -1, NULL);
2512                                if (!temp)
2513                                        log_pick_pc(mvp_sd, "P", item.nameid, 1, NULL);
2514                        }
2515                        break;
2516                }
2517
2518                if(log_config.mvpdrop > 0)
2519                        log_mvpdrop(mvp_sd, md->class_, log_mvp);
2520        }
2521
2522        if (type&2 && !sd && md->class_ == MOBID_EMPERIUM)
2523                //Emperium destroyed by script. Discard mvp character. [Skotlex]
2524                mvp_sd = NULL;
2525
2526        if(src && src->type == BL_MOB){
2527                struct mob_data *smd = (struct mob_data *)src;
2528                if(smd->nd)
2529                        mob_script_callback(smd, &md->bl, CALLBACK_KILL);
2530        }
2531
2532        if(md->nd)
2533                mob_script_callback(md, src, CALLBACK_DEAD);
2534        else
2535        if(md->npc_event[0] && !md->npc_killmonster)
2536        {
2537                md->status.hp = 0; //So that npc_event invoked functions KNOW that I am dead.
2538                if(src) 
2539                switch (src->type) {
2540                case BL_PET:
2541                        sd = ((TBL_PET*)src)->msd;
2542                        break;
2543                case BL_HOM:
2544                        sd = ((TBL_HOM*)src)->master;
2545                        break;
2546                }
2547                if(sd && battle_config.mob_npc_event_type) {
2548                        pc_setglobalreg(sd,"killerrid",sd->bl.id);
2549                        npc_event(sd,md->npc_event,0);
2550                } else if(mvp_sd) {
2551                        pc_setglobalreg(mvp_sd,"killerrid",sd?sd->bl.id:0);
2552                        npc_event(mvp_sd,md->npc_event,0);
2553                }
2554                else
2555                        npc_event_do(md->npc_event);
2556                       
2557                md->status.hp = 1;
2558        } else if (mvp_sd) {    //lordalfa
2559                pc_setglobalreg(mvp_sd,"killedrid",md->class_);
2560                npc_script_event(mvp_sd, NPCE_KILLNPC); // PCKillNPC [Lance]
2561        }
2562
2563        if( md->barricade != NULL )
2564                mob_barricade_break(md->barricade, src);
2565
2566        if(md->deletetimer!=-1) {
2567                delete_timer(md->deletetimer,mob_timer_delete);
2568                md->deletetimer=-1;
2569        }
2570
2571        mob_deleteslave(md);
2572       
2573        map_freeblock_unlock();
2574
2575        if(pcdb_checkid(md->vd->class_))
2576        {       //Player mobs are not removed automatically by the client.
2577                if(md->nd){
2578                        md->vd->dead_sit = 1;
2579                        return 1; // Let the dead body stay there.. we have something to do with it :D
2580                } else
2581                        clif_clearunit_delayed(&md->bl, tick+3000);
2582        }
2583
2584        if(!md->spawn) //Tell status_damage to remove it from memory.
2585                return 5; // Note: Actually, it's 4. Oh well...
2586       
2587        mob_setdelayspawn(md); //Set respawning.
2588        return 3; //Remove from map.
2589}
2590
2591void mob_revive(struct mob_data *md, unsigned int hp)
2592{
2593        unsigned int tick = gettick();
2594        md->state.skillstate = MSS_IDLE;
2595        md->last_thinktime = tick;
2596        md->next_walktime = tick+rand()%50+5000;
2597        md->last_linktime = tick;
2598        md->last_pcneartime = 0;
2599        if (!md->bl.prev)
2600                map_addblock(&md->bl);
2601        if(pcdb_checkid(md->vd->class_) && md->nd)
2602                md->vd->dead_sit = 0;
2603        else
2604                clif_spawn(&md->bl);
2605        skill_unit_move(&md->bl,tick,1);
2606        mobskill_use(md, tick, MSC_SPAWN);
2607        if (battle_config.show_mob_info&3)
2608                clif_charnameack (0, &md->bl);
2609}
2610
2611int mob_guardian_guildchange(struct block_list *bl,va_list ap)
2612{
2613        struct mob_data *md;
2614        struct guild* g;
2615
2616        nullpo_retr(0, bl);
2617        nullpo_retr(0, md = (struct mob_data *)bl);
2618
2619        if (!md->guardian_data)
2620                return 0;
2621
2622        if (md->guardian_data->castle->guild_id == 0)
2623        {       //Castle with no owner? Delete the guardians.
2624                if (md->class_ == MOBID_EMPERIUM)
2625                {       //But don't delete the emperium, just clear it's guild-data
2626                        md->guardian_data->guild_id = 0;
2627                        md->guardian_data->emblem_id = 0;
2628                        md->guardian_data->guild_name[0] = '\0';
2629                } else {
2630                        if( md->guardian_data->number >= 0 && md->guardian_data->number < MAX_GUARDIANS && md->guardian_data->castle->guardian[md->guardian_data->number].visible )
2631                        {       //Safe removal of guardian.
2632                                md->guardian_data->castle->guardian[md->guardian_data->number].visible = 0;
2633                                guild_castledatasave(md->guardian_data->castle->castle_id, 10+md->guardian_data->number,0);
2634                        }
2635                        unit_free(&md->bl,0); //Remove guardian.
2636                }
2637                return 0;
2638        }
2639       
2640        g = guild_search(md->guardian_data->castle->guild_id);
2641        if (g == NULL)
2642        {       //Properly remove guardian info from Castle data.
2643                ShowError("mob_guardian_guildchange: New Guild (id %d) does not exists!\n", md->guardian_data->guild_id);
2644                if( md->guardian_data->number >= 0 && md->guardian_data->number < MAX_GUARDIANS )
2645                {
2646                        md->guardian_data->castle->guardian[md->guardian_data->number].visible = 0;
2647                        guild_castledatasave(md->guardian_data->castle->castle_id, 10+md->guardian_data->number,0);
2648                }
2649                unit_free(&md->bl,0);
2650                return 0;
2651        }
2652
2653        md->guardian_data->guild_id = g->guild_id;
2654        md->guardian_data->emblem_id = g->emblem_id;
2655        md->guardian_data->guardup_lv = guild_checkskill(g,GD_GUARDUP);
2656        memcpy(md->guardian_data->guild_name, g->name, NAME_LENGTH);
2657
2658        return 1;       
2659}
2660       
2661/*==========================================
2662 * Pick a random class for the mob
2663 *------------------------------------------*/
2664int mob_random_class (int *value, size_t count)
2665{
2666        nullpo_retr(0, value);
2667
2668        // no count specified, look into the array manually, but take only max 5 elements
2669        if (count < 1) {
2670                count = 0;
2671                while(count < 5 && mobdb_checkid(value[count])) count++;
2672                if(count < 1)   // nothing found
2673                        return 0;
2674        } else {
2675                // check if at least the first value is valid
2676                if(mobdb_checkid(value[0]) == 0)
2677                        return 0;
2678        }
2679        //Pick a random value, hoping it exists. [Skotlex]
2680        return mobdb_checkid(value[rand()%count]);
2681}
2682
2683/*==========================================
2684 * Change mob base class
2685 *------------------------------------------*/
2686int mob_class_change (struct mob_data *md, int class_)
2687{
2688        unsigned int tick = gettick();
2689        int i, c, hp_rate;
2690
2691        nullpo_retr(0, md);
2692
2693        if (md->bl.prev == NULL)
2694                return 0;
2695
2696        //Disable class changing for some targets...
2697        if (md->guardian_data)
2698                return 0; //Guardians/Emperium
2699
2700        if (md->class_ >= 1324 && md->class_ <= 1363)
2701                return 0; //Treasure Boxes
2702
2703        if (md->special_state.ai > 1)
2704                return 0; //Marine Spheres and Floras.
2705
2706        if (mob_is_clone(md->class_))
2707                return 0; //Clones
2708
2709        if (md->class_ == class_)
2710                return 0; //Nothing to change.
2711
2712        hp_rate = get_percentage(md->status.hp, md->status.max_hp);
2713        md->class_ = class_;
2714        md->db = mob_db(class_);
2715        if (battle_config.override_mob_names==1)
2716                memcpy(md->name,md->db->name,NAME_LENGTH);
2717        else
2718                memcpy(md->name,md->db->jname,NAME_LENGTH);
2719
2720        mob_stop_attack(md);
2721        mob_stop_walking(md, 0);
2722        unit_skillcastcancel(&md->bl, 0);
2723        status_set_viewdata(&md->bl, class_);
2724        clif_mob_class_change(md,class_);
2725        status_calc_mob(md, 3);
2726        md->ud.state.speed_changed = 1; //Speed change update.
2727
2728        if (battle_config.monster_class_change_recover) {
2729                memset(md->dmglog, 0, sizeof(md->dmglog));
2730                md->tdmg = 0;
2731        } else {
2732                md->status.hp = md->status.max_hp*hp_rate/100;
2733                if(md->status.hp < 1) md->status.hp = 1;
2734        }
2735
2736        for(i=0,c=tick-1000*3600*10;i<MAX_MOBSKILL;i++)
2737                md->skilldelay[i] = c;
2738
2739        if(md->lootitem == NULL && md->db->status.mode&MD_LOOTER)
2740                md->lootitem=(struct item *)aCalloc(LOOTITEM_SIZE,sizeof(struct item));
2741
2742        //Targets should be cleared no morph
2743        md->target_id = md->attacked_id = 0;
2744
2745        //Need to update name display.
2746        clif_charnameack(0, &md->bl);
2747
2748        return 0;
2749}
2750
2751/*==========================================
2752 * mob‰ñ•œ
2753 *------------------------------------------*/
2754void mob_heal(struct mob_data *md,unsigned int heal)
2755{
2756        if (battle_config.show_mob_info&3)
2757                clif_charnameack (0, &md->bl);
2758}
2759
2760/*==========================================
2761 * Added by RoVeRT
2762 *------------------------------------------*/
2763int mob_warpslave_sub(struct block_list *bl,va_list ap)
2764{
2765        struct mob_data *md=(struct mob_data *)bl;
2766        struct block_list *master;
2767        short x,y,range=0;
2768        master = va_arg(ap, struct block_list*);
2769        range = va_arg(ap, int);
2770       
2771        if(md->master_id!=master->id)
2772                return 0;
2773
2774        map_search_freecell(master, 0, &x, &y, range, range, 0);
2775        unit_warp(&md->bl, master->m, x, y,2);
2776        return 1;
2777}
2778
2779/*==========================================
2780 * Added by RoVeRT
2781 * Warps slaves. Range is the area around the master that they can
2782 * appear in randomly.
2783 *------------------------------------------*/
2784int mob_warpslave(struct block_list *bl, int range)
2785{
2786        if (range < 1)
2787                range = 1; //Min range needed to avoid crashes and stuff. [Skotlex]
2788       
2789        return map_foreachinmap(mob_warpslave_sub, bl->m, BL_MOB, bl, range);
2790}
2791
2792/*==========================================
2793 * ‰æ–Ê“à‚ÌŽæ‚芪‚«‚̐”ŒvŽZ—p(foreachinarea)
2794 *------------------------------------------*/
2795int mob_countslave_sub(struct block_list *bl,va_list ap)
2796{
2797        int id;
2798        struct mob_data *md;
2799        id=va_arg(ap,int);
2800       
2801        md = (struct mob_data *)bl;
2802        if( md->master_id==id )
2803                return 1;
2804        return 0;
2805}
2806
2807/*==========================================
2808 * ‰æ–Ê“à‚ÌŽæ‚芪‚«‚̐”ŒvŽZ
2809 *------------------------------------------*/
2810int mob_countslave(struct block_list *bl)
2811{
2812        return map_foreachinmap(mob_countslave_sub, bl->m, BL_MOB,bl->id);
2813}
2814
2815/*==========================================
2816 * Summons amount slaves contained in the value[5] array using round-robin. [adapted by Skotlex]
2817 *------------------------------------------*/
2818int mob_summonslave(struct mob_data *md2,int *value,int amount,int skill_id)
2819{
2820        struct mob_data *md;
2821        struct spawn_data data;
2822        int count = 0,k=0,hp_rate=0;
2823
2824        nullpo_retr(0, md2);
2825        nullpo_retr(0, value);
2826
2827        memset(&data, 0, sizeof(struct spawn_data));
2828        data.m = md2->bl.m;
2829        data.x = md2->bl.x;
2830        data.y = md2->bl.y;
2831        data.num = 1;
2832        data.state.size = md2->special_state.size;
2833        data.state.ai = md2->special_state.ai;
2834
2835        if(mobdb_checkid(value[0]) == 0)
2836                return 0;
2837
2838        while(count < 5 && mobdb_checkid(value[count])) count++;
2839        if(count < 1) return 0;
2840        if (amount > 0 && amount < count) { //Do not start on 0, pick some random sub subset [Skotlex]
2841                k = rand()%count;
2842                amount+=k; //Increase final value by same amount to preserve total number to summon.
2843        }
2844       
2845        if (!battle_config.monster_class_change_recover &&
2846                (skill_id == NPC_TRANSFORMATION || skill_id == NPC_METAMORPHOSIS))
2847                hp_rate = get_percentage(md2->status.hp, md2->status.max_hp);
2848
2849        for(;k<amount;k++) {
2850                short x,y;
2851                data.class_ = value[k%count]; //Summon slaves in round-robin fashion. [Skotlex]
2852                if (mobdb_checkid(data.class_) == 0)
2853                        continue;
2854
2855                if (map_search_freecell(&md2->bl, 0, &x, &y, MOB_SLAVEDISTANCE, MOB_SLAVEDISTANCE, 0)) {
2856                        data.x = x;
2857                        data.y = y;
2858                } else {
2859                        data.x = md2->bl.x;
2860                        data.y = md2->bl.y;
2861                }
2862
2863                //These two need to be loaded from the db for each slave.
2864                if(battle_config.override_mob_names==1)
2865                        strcpy(data.name,"--en--");
2866                else
2867                        strcpy(data.name,"--ja--");
2868
2869                data.level = 0;
2870                if (!mob_parse_dataset(&data))
2871                        continue;
2872               
2873                md= mob_spawn_dataset(&data);
2874                if(skill_id == NPC_SUMMONSLAVE){
2875                        md->master_id=md2->bl.id;
2876                        md->state.killer = md2->state.killer;
2877                        md->special_state.ai = md2->special_state.ai;
2878                        md->nd = md2->nd;
2879                        md->callback_flag = md2->callback_flag;
2880                }
2881                mob_spawn(md);
2882               
2883                if (hp_rate) //Scale HP
2884                        md->status.hp = md->status.max_hp*hp_rate/100;
2885
2886                //Inherit the aggressive mode of the master.
2887                if (battle_config.slaves_inherit_mode && md->master_id)
2888                {
2889                        switch (battle_config.slaves_inherit_mode) {
2890                        case 1: //Always aggressive
2891                                if (!(md->status.mode&MD_AGGRESSIVE))
2892                                        sc_start4(&md->bl, SC_MODECHANGE, 100,1,0, MD_AGGRESSIVE, 0, 0);
2893                                break;
2894                        case 2: //Always passive
2895                                if (md->status.mode&MD_AGGRESSIVE)
2896                                        sc_start4(&md->bl, SC_MODECHANGE, 100,1,0, 0, MD_AGGRESSIVE, 0);
2897                                break;
2898                        default: //Copy master.
2899                                if (md2->status.mode&MD_AGGRESSIVE)
2900                                        sc_start4(&md->bl, SC_MODECHANGE, 100,1,0, MD_AGGRESSIVE, 0, 0);
2901                                else
2902                                        sc_start4(&md->bl, SC_MODECHANGE, 100,1,0, 0, MD_AGGRESSIVE, 0);
2903                                break;
2904                        }
2905                }
2906
2907                clif_skill_nodamage(&md->bl,&md->bl,skill_id,amount,1);
2908        }
2909
2910        return 0;
2911}
2912
2913/*==========================================
2914 *MOBskill‚©‚çŠY“–skillid‚Ìskillidx‚ð•Ô‚·
2915 *------------------------------------------*/
2916int mob_skillid2skillidx(int class_,int skillid)
2917{
2918        int i, max = mob_db(class_)->maxskill;
2919        struct mob_skill *ms=mob_db(class_)->skill;
2920
2921        if(ms==NULL)
2922                return -1;
2923
2924        ARR_FIND( 0, max, i, ms[i].skill_id == skillid );
2925        return ( i < max ) ? i : -1;
2926}
2927
2928/*==========================================
2929 * Friendly Mob whose HP is decreasing by a nearby MOB is looked for.
2930 *------------------------------------------*/
2931int mob_getfriendhprate_sub(struct block_list *bl,va_list ap)
2932{
2933        int min_rate, max_rate,rate;
2934        struct block_list **fr;
2935        struct mob_data *md;
2936
2937        md = va_arg(ap,struct mob_data *);
2938        min_rate=va_arg(ap,int);
2939        max_rate=va_arg(ap,int);
2940        fr=va_arg(ap,struct block_list **);
2941
2942        if( md->bl.id == bl->id && !(battle_config.mob_ai&0x10))
2943                return 0;
2944
2945        if ((*fr) != NULL) //A friend was already found.
2946                return 0;
2947       
2948        if (battle_check_target(&md->bl,bl,BCT_ENEMY)>0)
2949                return 0;
2950       
2951        rate = get_percentage(status_get_hp(bl), status_get_max_hp(bl));
2952       
2953        if (rate >= min_rate && rate <= max_rate)
2954                (*fr) = bl;
2955        return 1;
2956}
2957static struct block_list *mob_getfriendhprate(struct mob_data *md,int min_rate,int max_rate)
2958{
2959        struct block_list *fr=NULL;
2960        int type = BL_MOB;
2961       
2962        nullpo_retr(NULL, md);
2963
2964        if (md->special_state.ai) //Summoned creatures. [Skotlex]
2965                type = BL_PC;
2966       
2967        map_foreachinrange(mob_getfriendhprate_sub, &md->bl, 8, type,md,min_rate,max_rate,&fr);
2968        return fr;
2969}
2970/*==========================================
2971 * Check hp rate of its master
2972 *------------------------------------------*/
2973struct block_list *mob_getmasterhpltmaxrate(struct mob_data *md,int rate)
2974{
2975        if( md && md->master_id > 0 )
2976        {
2977                struct block_list *bl = map_id2bl(md->master_id);
2978                if( bl && get_percentage(status_get_hp(bl), status_get_max_hp(bl)) < rate )
2979                        return bl;
2980        }
2981
2982        return NULL;
2983}
2984/*==========================================
2985 * What a status state suits by nearby MOB is looked for.
2986 *------------------------------------------*/
2987int mob_getfriendstatus_sub(struct block_list *bl,va_list ap)
2988{
2989        int cond1,cond2;
2990        struct mob_data **fr, *md, *mmd;
2991        int flag=0;
2992
2993        nullpo_retr(0, bl);
2994        nullpo_retr(0, ap);
2995        nullpo_retr(0, md=(struct mob_data *)bl);
2996        nullpo_retr(0, mmd=va_arg(ap,struct mob_data *));
2997
2998        if( mmd->bl.id == bl->id && !(battle_config.mob_ai&0x10) )
2999                return 0;
3000
3001        if (battle_check_target(&mmd->bl,bl,BCT_ENEMY)>0)
3002                return 0;
3003        cond1=va_arg(ap,int);
3004        cond2=va_arg(ap,int);
3005        fr=va_arg(ap,struct mob_data **);
3006        if( cond2==-1 ){
3007                int j;
3008                for(j=SC_COMMON_MIN;j<=SC_COMMON_MAX && !flag;j++){
3009                        if ((flag=(md->sc.data[j] != NULL))) //Once an effect was found, break out. [Skotlex]
3010                                break;
3011                }
3012        }else
3013                flag=( md->sc.data[cond2] != NULL );
3014        if( flag^( cond1==MSC_FRIENDSTATUSOFF ) )
3015                (*fr)=md;
3016
3017        return 0;
3018}
3019
3020struct mob_data *mob_getfriendstatus(struct mob_data *md,int cond1,int cond2)
3021{
3022        struct mob_data* fr = NULL;
3023        nullpo_retr(0, md);
3024
3025        map_foreachinrange(mob_getfriendstatus_sub, &md->bl, 8,BL_MOB, md,cond1,cond2,&fr);
3026        return fr;
3027}
3028
3029/*==========================================
3030 * Skill use judging
3031 *------------------------------------------*/
3032int mobskill_use(struct mob_data *md, unsigned int tick, int event)
3033{
3034        struct mob_skill *ms;
3035        struct block_list *fbl = NULL; //Friend bl, which can either be a BL_PC or BL_MOB depending on the situation. [Skotlex]
3036        struct block_list *bl;
3037        struct mob_data *fmd = NULL;
3038        int i,j,n;
3039
3040        nullpo_retr (0, md);
3041        nullpo_retr (0, ms = md->db->skill);
3042
3043        if (!battle_config.mob_skill_rate || md->ud.skilltimer != -1 || !md->db->maxskill)
3044                return 0;
3045
3046        if (event == -1 && DIFF_TICK(md->ud.canact_tick, tick) > 0)
3047                return 0; //Skill act delay only affects non-event skills.
3048
3049        //Pick a starting position and loop from that.
3050        i = battle_config.mob_ai&0x100?rand()%md->db->maxskill:0;
3051        for (n = 0; n < md->db->maxskill; i++, n++) {
3052                int c2, flag = 0;               
3053
3054                if (i == md->db->maxskill)
3055                        i = 0;
3056
3057                if (DIFF_TICK(tick, md->skilldelay[i]) < ms[i].delay)
3058                        continue;
3059
3060                c2 = ms[i].cond2;
3061               
3062                if (ms[i].state != md->state.skillstate) {
3063                        if (md->state.skillstate != MSS_DEAD && (ms[i].state == MSS_ANY ||
3064                                (ms[i].state == MSS_ANYTARGET && md->target_id && md->state.skillstate != MSS_LOOT)
3065                        )) //ANYTARGET works with any state as long as there's a target. [Skotlex]
3066                                ;
3067                        else
3068                                continue;
3069                }
3070                if (rand() % 10000 > ms[i].permillage) //Lupus (max value = 10000)
3071                        continue;
3072
3073                if (ms[i].cond1 == event)
3074                        flag = 1; //Trigger skill.
3075                else if (ms[i].cond1 == MSC_SKILLUSED)
3076                        flag = ((event & 0xffff) == MSC_SKILLUSED && ((event >> 16) == c2 || c2 == 0));
3077                else if(event == -1){
3078                        //Avoid entering on defined events to avoid "hyper-active skill use" due to the overflow of calls to this function in battle.
3079                        switch (ms[i].cond1)
3080                        {
3081                                case MSC_ALWAYS:
3082                                        flag = 1; break;
3083                                case MSC_MYHPLTMAXRATE:         // HP< maxhp%
3084                                        flag = get_percentage(md->status.hp, md->status.max_hp);
3085                                        flag = (flag <= c2);
3086                                        break;
3087                                case MSC_MYHPINRATE:
3088                                        flag = get_percentage(md->status.hp, md->status.max_hp);
3089                                        flag = (flag >= c2 && flag <= ms[i].val[0]);
3090                                        break;
3091                                case MSC_MYSTATUSON:            // status[num] on
3092                                case MSC_MYSTATUSOFF:           // status[num] off
3093                                        if (!md->sc.count) {
3094                                                flag = 0;
3095                                        } else if (ms[i].cond2 == -1) {
3096                                                for (j = SC_COMMON_MIN; j <= SC_COMMON_MAX; j++)
3097                                                        if ((flag = (md->sc.data[j]!=NULL)) != 0)
3098                                                                break;
3099                                        } else {
3100                                                flag = (md->sc.data[ms[i].cond2]!=NULL);
3101                                        }
3102                                        flag ^= (ms[i].cond1 == MSC_MYSTATUSOFF); break;
3103                                case MSC_FRIENDHPLTMAXRATE:     // friend HP < maxhp%
3104                                        flag = ((fbl = mob_getfriendhprate(md, 0, ms[i].cond2)) != NULL); break;
3105                                case MSC_FRIENDHPINRATE :
3106                                        flag = ((fbl = mob_getfriendhprate(md, ms[i].cond2, ms[i].val[0])) != NULL); break;
3107                                case MSC_FRIENDSTATUSON:        // friend status[num] on
3108                                case MSC_FRIENDSTATUSOFF:       // friend status[num] off
3109                                        flag = ((fmd = mob_getfriendstatus(md, ms[i].cond1, ms[i].cond2)) != NULL); break;                                     
3110                                case MSC_SLAVELT:               // slave < num
3111                                        flag = (mob_countslave(&md->bl) < c2 ); break;
3112                                case MSC_ATTACKPCGT:    // attack pc > num
3113                                        flag = (unit_counttargeted(&md->bl, 0) > c2); break;
3114                                case MSC_SLAVELE:               // slave <= num
3115                                        flag = (mob_countslave(&md->bl) <= c2 ); break;
3116                                case MSC_ATTACKPCGE:    // attack pc >= num
3117                                        flag = (unit_counttargeted(&md->bl, 0) >= c2); break;
3118                                case MSC_AFTERSKILL:
3119                                        flag = (md->ud.skillid == c2); break;
3120                                case MSC_RUDEATTACKED:
3121                                        flag = (md->state.attacked_count >= RUDE_ATTACKED_COUNT);
3122                                        if (flag) md->state.attacked_count = 0; //Rude attacked count should be reset after the skill condition is met. Thanks to Komurka [Skotlex]
3123                                        break;
3124                                case MSC_MASTERHPLTMAXRATE:
3125                                        flag = ((fbl = mob_getmasterhpltmaxrate(md, ms[i].cond2)) != NULL); break;
3126                                case MSC_MASTERATTACKED:
3127                                        flag = (md->master_id > 0 && (fbl=map_id2bl(md->master_id)) && unit_counttargeted(fbl, 0) > 0); break;
3128                                case MSC_ALCHEMIST:
3129                                        flag = (md->state.alchemist);
3130                                        break;
3131                        }
3132                }
3133               
3134                if (!flag)
3135                        continue; //Skill requisite failed to be fulfilled.
3136
3137                //Execute skill
3138                if (skill_get_casttype(ms[i].skill_id) == CAST_GROUND)
3139                {       //Ground skill.
3140                        short x, y;
3141                        switch (ms[i].target) {
3142                                case MST_RANDOM: //Pick a random enemy within skill range.
3143                                        bl = battle_getenemy(&md->bl, DEFAULT_ENEMY_TYPE(md),
3144                                                skill_get_range2(&md->bl, ms[i].skill_id, ms[i].skill_lv));
3145                                        break;
3146                                case MST_TARGET:
3147                                case MST_AROUND5:
3148                                case MST_AROUND6:
3149                                case MST_AROUND7:
3150                                case MST_AROUND8:
3151                                        bl = map_id2bl(md->target_id);
3152                                        break;
3153                                case MST_MASTER:
3154                                        bl = &md->bl;
3155                                        if (md->master_id) 
3156                                                bl = map_id2bl(md->master_id);
3157                                        if (bl) //Otherwise, fall through.
3158                                                break;
3159                                case MST_FRIEND:
3160                                        bl = fbl?fbl:(fmd?&fmd->bl:&md->bl);
3161                                        break;
3162                                default:
3163                                        bl = &md->bl;
3164                                        break;
3165                        }
3166                        if (!bl) continue;
3167                        x = bl->x;
3168                        y = bl->y;
3169                        // Look for an area to cast the spell around...
3170                        if (ms[i].target >= MST_AROUND1 || ms[i].target >= MST_AROUND5) {
3171                                j = ms[i].target >= MST_AROUND1?
3172                                        (ms[i].target-MST_AROUND1) +1:
3173                                        (ms[i].target-MST_AROUND5) +1;
3174                                map_search_freecell(&md->bl, md->bl.m, &x, &y, j, j, 3);
3175                        }
3176                        md->skillidx = i;
3177                        if (!unit_skilluse_pos2(&md->bl, x, y,
3178                                ms[i].skill_id, ms[i].skill_lv,
3179                                ms[i].casttime, ms[i].cancel))
3180                                continue;
3181                } else {
3182                        //Targetted skill
3183                        switch (ms[i].target) {
3184                                case MST_RANDOM: //Pick a random enemy within skill range.
3185                                        bl = battle_getenemy(&md->bl, DEFAULT_ENEMY_TYPE(md),
3186                                                skill_get_range2(&md->bl, ms[i].skill_id, ms[i].skill_lv));
3187                                        break;
3188                                case MST_TARGET:
3189                                        bl = map_id2bl(md->target_id);
3190                                        break;
3191                                case MST_MASTER:
3192                                        bl = &md->bl;
3193                                        if (md->master_id) 
3194                                                bl = map_id2bl(md->master_id);
3195                                        if (bl) //Otherwise, fall through.
3196                                                break;
3197                                case MST_FRIEND:
3198                                        if (fbl) {
3199                                                bl = fbl;
3200                                                break;
3201                                        } else if (fmd) {
3202                                                bl = &fmd->bl;
3203                                                break;
3204                                        } // else fall through
3205                                default:
3206                                        bl = &md->bl;
3207                                        break;
3208                        }
3209                        if (!bl) continue;
3210                        md->skillidx = i;
3211                        if (!unit_skilluse_id2(&md->bl, bl->id,
3212                                ms[i].skill_id, ms[i].skill_lv,
3213                                ms[i].casttime, ms[i].cancel))
3214                                continue;
3215                }
3216                //Skill used. Post-setups...
3217                if(battle_config.mob_ai&0x200)
3218                { //pass on delay to same skill.
3219                        for (j = 0; j < md->db->maxskill; j++)
3220                                if (md->db->skill[j].skill_id == ms[i].skill_id)
3221                                        md->skilldelay[j]=tick;
3222                } else
3223                        md->skilldelay[i]=tick;
3224                return 1;
3225        }
3226        //No skill was used.
3227        md->skillidx = -1;
3228        return 0;
3229}
3230/*==========================================
3231 * Skill use event processing
3232 *------------------------------------------*/
3233int mobskill_event(struct mob_data *md, struct block_list *src, unsigned int tick, int flag)
3234{
3235        int target_id, res = 0;
3236
3237        target_id = md->target_id;
3238        if (!target_id || battle_config.mob_changetarget_byskill)
3239                md->target_id = src->id;
3240                       
3241        if (flag == -1)
3242                res = mobskill_use(md, tick, MSC_CASTTARGETED);
3243        else if ((flag&0xffff) == MSC_SKILLUSED)
3244                res = mobskill_use(md, tick, flag);
3245        else if (flag&BF_SHORT)
3246                res = mobskill_use(md, tick, MSC_CLOSEDATTACKED);
3247        else if (flag&BF_LONG && !(flag&BF_MAGIC)) //Long-attacked should not include magic.
3248                res = mobskill_use(md, tick, MSC_LONGRANGEATTACKED);
3249       
3250        if (!res)
3251        //Restore previous target only if skill condition failed to trigger. [Skotlex]
3252                md->target_id = target_id;
3253        //Otherwise check if the target is an enemy, and unlock if needed.
3254        else if (battle_check_target(&md->bl, src, BCT_ENEMY) <= 0)
3255                md->target_id = target_id;
3256       
3257        return res;
3258}
3259
3260// Player cloned mobs. [Valaris]
3261int mob_is_clone(int class_)
3262{
3263        if(class_ < MOB_CLONE_START || class_ > MOB_CLONE_END)
3264                return 0;
3265        if (mob_db(class_) == mob_dummy)
3266                return 0;
3267        return class_;
3268}
3269
3270//Flag values:
3271//&1: Set special ai (fight mobs, not players)
3272//If mode is not passed, a default aggressive mode is used.
3273//If master_id is passed, clone is attached to him.
3274//Returns: ID of newly crafted copy.
3275int mob_clone_spawn(struct map_session_data *sd, int m, int x, int y, const char *event, int master_id, int mode, int flag, unsigned int duration)
3276{
3277        int class_;
3278        int i,j,inf,skill_id;
3279        struct mob_data *md;
3280        struct mob_skill *ms;
3281        struct mob_db* db;
3282        struct status_data *status;
3283
3284        nullpo_retr(0, sd);
3285
3286        ARR_FIND( MOB_CLONE_START, MOB_CLONE_END, class_, mob_db_data[class_] == NULL );
3287        if(class_ >= MOB_CLONE_END)
3288                return 0;
3289
3290        db = mob_db_data[class_]=(struct mob_db*)aCalloc(1, sizeof(struct mob_db));
3291        status = &db->status;
3292        sprintf(db->sprite,sd->status.name);
3293        sprintf(db->name,sd->status.name);
3294        sprintf(db->jname,sd->status.name);
3295        db->lv=status_get_lv(&sd->bl);
3296        memcpy(status, &sd->base_status, sizeof(struct status_data));
3297        status->rhw.atk2= status->dex + status->rhw.atk + status->rhw.atk2; //Max ATK
3298        status->rhw.atk = status->dex; //Min ATK
3299        if (status->lhw.atk) {
3300                status->lhw.atk2= status->dex + status->lhw.atk + status->lhw.atk2; //Max ATK
3301                status->lhw.atk = status->dex; //Min ATK
3302        }
3303        if (mode) //User provided mode.
3304                status->mode = mode; 
3305        else if (flag&1) //Friendly Character, remove looting.
3306                status->mode &= ~MD_LOOTER; 
3307        status->hp = status->max_hp;
3308        status->sp = status->max_sp;
3309        memcpy(&db->vd, &sd->vd, sizeof(struct view_data));
3310        db->base_exp=1;
3311        db->job_exp=1;
3312        db->range2=AREA_SIZE; //Let them have the same view-range as players.
3313        db->range3=AREA_SIZE; //Min chase of a screen.
3314        db->option=sd->sc.option;
3315
3316        //Skill copy [Skotlex]
3317        ms = &db->skill[0];
3318        //Go Backwards to give better priority to advanced skills.
3319        for (i=0,j = MAX_SKILL_TREE-1;j>=0 && i< MAX_MOBSKILL ;j--) {
3320                skill_id = skill_tree[pc_class2idx(sd->status.class_)][j].id;
3321                if (!skill_id || sd->status.skill[skill_id].lv < 1 ||
3322                        (skill_get_inf2(skill_id)&(INF2_WEDDING_SKILL|INF2_GUILD_SKILL)) ||
3323                        skill_get_nocast(skill_id)&16
3324                )
3325                        continue;
3326                //Normal aggressive mob, disable skills that cannot help them fight
3327                //against players (those with flags UF_NOMOB and UF_NOPC are specific
3328                //to always aid players!) [Skotlex]
3329                if (!(flag&1) &&
3330                        skill_get_unit_id(skill_id, 0) &&
3331                        skill_get_unit_flag(skill_id)&(UF_NOMOB|UF_NOPC))
3332                        continue;
3333
3334                memset (&ms[i], 0, sizeof(struct mob_skill));
3335                ms[i].skill_id = skill_id;
3336                ms[i].skill_lv = sd->status.skill[skill_id].lv;
3337                ms[i].state = MSS_ANY;
3338                ms[i].permillage = 500*battle_config.mob_skill_rate/100; //Default chance of all skills: 5%
3339                ms[i].emotion = -1;
3340                ms[i].cancel = 0;
3341                ms[i].casttime = skill_castfix(&sd->bl,skill_id, ms[i].skill_lv);
3342                ms[i].delay = 5000+skill_delayfix(&sd->bl,skill_id, ms[i].skill_lv);
3343
3344                inf = skill_get_inf(skill_id);
3345                if (inf&INF_ATTACK_SKILL) {
3346                        ms[i].target = MST_TARGET;
3347                        ms[i].cond1 = MSC_ALWAYS;
3348                        if (skill_get_range(skill_id, ms[i].skill_lv)  > 3)
3349                                ms[i].state = MSS_ANYTARGET;
3350                        else
3351                                ms[i].state = MSS_BERSERK;
3352                } else if(inf&INF_GROUND_SKILL) {
3353                        if (skill_get_inf2(skill_id)&INF2_TRAP) { //Traps!
3354                                ms[i].state = MSS_IDLE;
3355                                ms[i].target = MST_AROUND2;
3356                                ms[i].delay = 60000;
3357                        } else if (skill_get_unit_target(skill_id) == BCT_ENEMY) { //Target Enemy
3358                                ms[i].state = MSS_ANYTARGET;
3359                                ms[i].target = MST_TARGET;
3360                                ms[i].cond1 = MSC_ALWAYS;
3361                        } else { //Target allies
3362                                ms[i].target = MST_FRIEND;
3363                                ms[i].cond1 = MSC_FRIENDHPLTMAXRATE;
3364                                ms[i].cond2 = 95;
3365                        }
3366                } else if (inf&INF_SELF_SKILL) {
3367                        if (skill_get_inf2(skill_id)&INF2_NO_TARGET_SELF) { //auto-select target skill.
3368                                ms[i].target = MST_TARGET;
3369                                ms[i].cond1 = MSC_ALWAYS;
3370                                if (skill_get_range(skill_id, ms[i].skill_lv)  > 3) {
3371                                        ms[i].state = MSS_ANYTARGET;
3372                                } else {
3373                                        ms[i].state = MSS_BERSERK;
3374                                }
3375                        } else { //Self skill
3376                                ms[i].target = MST_SELF;
3377                                ms[i].cond1 = MSC_MYHPLTMAXRATE;
3378                                ms[i].cond2 = 90;
3379                                ms[i].permillage = 2000;
3380                                //Delay: Remove the stock 5 secs and add half of the support time.
3381                                ms[i].delay += -5000 +(skill_get_time(skill_id, ms[i].skill_lv) + skill_get_time2(skill_id, ms[i].skill_lv))/2;
3382                                if (ms[i].delay < 5000)
3383                                        ms[i].delay = 5000; //With a minimum of 5 secs.
3384                        }
3385                } else if (inf&INF_SUPPORT_SKILL) {
3386                        ms[i].target = MST_FRIEND;
3387                        ms[i].cond1 = MSC_FRIENDHPLTMAXRATE;
3388                        ms[i].cond2 = 90;
3389                        if (skill_id == AL_HEAL)
3390                                ms[i].permillage = 5000; //Higher skill rate usage for heal.
3391                        else if (skill_id == ALL_RESURRECTION)
3392                                ms[i].cond2 = 1;
3393                        //Delay: Remove the stock 5 secs and add half of the support time.
3394                        ms[i].delay += -5000 +(skill_get_time(skill_id, ms[i].skill_lv) + skill_get_time2(skill_id, ms[i].skill_lv))/2;
3395                        if (ms[i].delay < 2000)
3396                                ms[i].delay = 2000; //With a minimum of 2 secs.
3397                       
3398                        if (i+1 < MAX_MOBSKILL) { //duplicate this so it also triggers on self.
3399                                memcpy(&ms[i+1], &ms[i], sizeof(struct mob_skill));
3400                                db->maxskill = ++i;
3401                                ms[i].target = MST_SELF;
3402                                ms[i].cond1 = MSC_MYHPLTMAXRATE;
3403                        }
3404                } else {
3405                        switch (skill_id) { //Certain Special skills that are passive, and thus, never triggered.
3406                                case MO_TRIPLEATTACK:
3407                                case TF_DOUBLE:
3408                                case GS_CHAINACTION:
3409                                        ms[i].state = MSS_BERSERK;
3410                                        ms[i].target = MST_TARGET;
3411                                        ms[i].cond1 = MSC_ALWAYS;
3412                                        ms[i].permillage = skill_id==MO_TRIPLEATTACK?(3000-ms[i].skill_lv*100):(ms[i].skill_lv*500);
3413                                        ms[i].delay -= 5000; //Remove the added delay as these could trigger on "all hits".
3414                                        break;
3415                                default: //Untreated Skill
3416                                        continue;
3417                        }
3418                }
3419                if (battle_config.mob_skill_rate!= 100)
3420                        ms[i].permillage = ms[i].permillage*battle_config.mob_skill_rate/100;
3421                if (battle_config.mob_skill_delay != 100)
3422                        ms[i].delay = ms[i].delay*battle_config.mob_skill_delay/100;
3423               
3424                db->maxskill = ++i;
3425        }
3426        //Finally, spawn it.
3427        md = mob_once_spawn_sub(&sd->bl, m, x, y, "--en--",class_,event);
3428        if (!md) return 0; //Failed?
3429       
3430        if (master_id || flag || duration) { //Further manipulate crafted char.
3431                if (flag&1) //Friendly Character
3432                        md->special_state.ai = 1;
3433                if (master_id) //Attach to Master
3434                        md->master_id = master_id;
3435                if (duration) //Auto Delete after a while.
3436                        md->deletetimer = add_timer (gettick() + duration, mob_timer_delete, md->bl.id, 0);
3437        }
3438
3439        mob_spawn(md);
3440
3441        return md->bl.id;
3442}
3443
3444int mob_clone_delete(int class_)
3445{
3446        if (class_ >= MOB_CLONE_START && class_ < MOB_CLONE_END
3447                && mob_db_data[class_]!=NULL) {
3448                aFree(mob_db_data[class_]);
3449                mob_db_data[class_]=NULL;
3450                return 1;
3451        }
3452        return 0;
3453}
3454
3455int mob_script_callback(struct mob_data *md, struct block_list *target, short action_type)
3456{
3457        // DEBUG: Uncomment these if errors occur. ---
3458        // nullpo_retr(md, 0);
3459        // nullpo_retr(md->nd, 0);
3460        // -------------------------------------------
3461        if(md->callback_flag&action_type){
3462                int regkey = add_str(".ai_action");
3463                linkdb_replace(&md->nd->u.scr.script->script_vars,(void *)regkey, (void *)(int)action_type);
3464                if(target){
3465                        linkdb_replace(&md->nd->u.scr.script->script_vars,(void *)(regkey+(1<<24)), (void *)(int)target->type);
3466                        linkdb_replace(&md->nd->u.scr.script->script_vars,(void *)(regkey+(2<<24)), (void *)target->id);
3467                }
3468                linkdb_replace(&md->nd->u.scr.script->script_vars,(void *)(regkey+(3<<24)), (void *)md->bl.id);
3469                run_script(md->nd->u.scr.script, 0, 0, md->nd->bl.id);
3470                return 1;
3471        }
3472        return 0;
3473}
3474
3475//
3476// ‰Šú‰»
3477//
3478/*==========================================
3479 * Since un-setting [ mob ] up was used, it is an initial provisional value setup.
3480 *------------------------------------------*/
3481static int mob_makedummymobdb(int class_)
3482{
3483        if (mob_dummy != NULL)
3484        {
3485                if (mob_db(class_) == mob_dummy)
3486                        return 1; //Using the mob_dummy data already. [Skotlex]
3487                if (class_ > 0 && class_ <= MAX_MOB_DB)
3488                {       //Remove the mob data so that it uses the dummy data instead.
3489                        aFree(mob_db_data[class_]);
3490                        mob_db_data[class_] = NULL;
3491                }
3492                return 0;
3493        }
3494        //Initialize dummy data.       
3495        mob_dummy = (struct mob_db*)aCalloc(1, sizeof(struct mob_db)); //Initializing the dummy mob.
3496        sprintf(mob_dummy->sprite,"DUMMY");
3497        sprintf(mob_dummy->name,"Dummy");
3498        sprintf(mob_dummy->jname,"Dummy");
3499        mob_dummy->lv=1;
3500        mob_dummy->status.max_hp=1000;
3501        mob_dummy->status.max_sp=1;
3502        mob_dummy->status.rhw.range=1;
3503        mob_dummy->status.rhw.atk=7;
3504        mob_dummy->status.rhw.atk2=10;
3505        mob_dummy->status.str=1;
3506        mob_dummy->status.agi=1;
3507        mob_dummy->status.vit=1;
3508        mob_dummy->status.int_=1;
3509        mob_dummy->status.dex=6;
3510        mob_dummy->status.luk=2;
3511        mob_dummy->status.speed=300;
3512        mob_dummy->status.adelay=1000;
3513        mob_dummy->status.amotion=500;
3514        mob_dummy->status.dmotion=500;
3515        mob_dummy->base_exp=2;
3516        mob_dummy->job_exp=1;
3517        mob_dummy->range2=10;
3518        mob_dummy->range3=10;
3519
3520        return 0;
3521}
3522
3523//Adjusts the drop rate of item according to the criteria given. [Skotlex]
3524static unsigned int mob_drop_adjust(int baserate, int rate_adjust, unsigned short rate_min, unsigned short rate_max)
3525{
3526        double rate = baserate;
3527
3528        if (battle_config.logarithmic_drops && rate_adjust > 0 && baserate > 0) //Logarithmic drops equation by Ishizu-Chan
3529                //Equation: Droprate(x,y) = x * (5 - log(x)) ^ (ln(y) / ln(5))
3530                //x is the normal Droprate, y is the Modificator.
3531                rate = rate * pow((5.0 - log10(rate)), (log(rate_adjust/100.) / log(5.0))) + 0.5;
3532        else
3533                //Classical linear rate adjustment.
3534                rate = rate * rate_adjust/100;
3535
3536        return (unsigned int)cap_value(rate,rate_min,rate_max);
3537}
3538
3539/*==========================================
3540 * processes one mobdb entry
3541 *------------------------------------------*/
3542static bool mob_parse_dbrow(char** str)
3543{
3544        struct mob_db *db;
3545        struct status_data *status;
3546        int class_, i, k;
3547        double exp, maxhp;
3548        struct mob_data data;
3549       
3550        class_ = str[0] ? atoi(str[0]) : 0;
3551        if (class_ == 0)
3552                return false; //Leave blank lines alone... [Skotlex]
3553       
3554        if (class_ <= 1000 || class_ > MAX_MOB_DB) {
3555                ShowWarning("Mob with ID: %d not loaded. ID must be in range [%d-%d]\n", class_, 1000, MAX_MOB_DB);
3556                return false;
3557        }
3558        if (pcdb_checkid(class_)) {
3559                ShowWarning("Mob with ID: %d not loaded. That ID is reserved for player classes.\n");
3560                return false;
3561        }
3562       
3563        if (class_ >= MOB_CLONE_START && class_ < MOB_CLONE_END) {
3564                ShowWarning("Mob with ID: %d not loaded. Range %d-%d is reserved for player clones. Please increase MAX_MOB_DB (%d)\n", class_, MOB_CLONE_START, MOB_CLONE_END-1, MAX_MOB_DB);
3565                return false;
3566        }
3567
3568        if (mob_db_data[class_] == NULL)
3569                mob_db_data[class_] = (struct mob_db*)aCalloc(1, sizeof (struct mob_db));
3570       
3571        db = mob_db_data[class_];
3572        status = &db->status;
3573       
3574        db->vd.class_ = class_;
3575        strncpy(db->sprite, str[1], NAME_LENGTH);
3576        strncpy(db->jname, str[2], NAME_LENGTH);
3577        strncpy(db->name, str[3], NAME_LENGTH);
3578        db->lv = atoi(str[4]);
3579        db->lv = cap_value(db->lv, 1, USHRT_MAX);
3580        status->max_hp = atoi(str[5]);
3581        status->max_sp = atoi(str[6]);
3582       
3583        exp = (double)atoi(str[7]) * (double)battle_config.base_exp_rate / 100.;
3584        db->base_exp = (unsigned int)cap_value(exp, 0, UINT_MAX);
3585       
3586        exp = (double)atoi(str[8]) * (double)battle_config.job_exp_rate / 100.;
3587        db->job_exp = (unsigned int)cap_value(exp, 0, UINT_MAX);
3588       
3589        status->rhw.range = atoi(str[9]);
3590        status->rhw.atk = atoi(str[10]);
3591        status->rhw.atk2 = atoi(str[11]);
3592        status->def = atoi(str[12]);
3593        status->mdef = atoi(str[13]);
3594        status->str = atoi(str[14]);
3595        status->agi = atoi(str[15]);
3596        status->vit = atoi(str[16]);
3597        status->int_ = atoi(str[17]);
3598        status->dex = atoi(str[18]);
3599        status->luk = atoi(str[19]);
3600        //All status should be min 1 to prevent divisions by zero from some skills. [Skotlex]
3601        if (status->str < 1) status->str = 1;
3602        if (status->agi < 1) status->agi = 1;
3603        if (status->vit < 1) status->vit = 1;
3604        if (status->int_< 1) status->int_= 1;
3605        if (status->dex < 1) status->dex = 1;
3606        if (status->luk < 1) status->luk = 1;
3607       
3608        db->range2 = atoi(str[20]);
3609        db->range3 = atoi(str[21]);
3610        if (battle_config.view_range_rate != 100) {
3611                db->range2 = db->range2 * battle_config.view_range_rate / 100;
3612                if (db->range2 < 1)
3613                        db->range2 = 1;
3614        }
3615        if (battle_config.chase_range_rate != 100) {
3616                db->range3 = db->range3 * battle_config.chase_range_rate / 100;
3617                if (db->range3 < db->range2)
3618                        db->range3 = db->range2;
3619        }
3620       
3621        status->size = atoi(str[22]);
3622        status->race = atoi(str[23]);
3623       
3624        i = atoi(str[24]); //Element
3625        status->def_ele = i%10;
3626        status->ele_lv = i/20;
3627        if (status->def_ele >= ELE_MAX) {
3628                ShowWarning("Mob with ID: %d has invalid element type %d (max element is %d)\n", class_, status->def_ele, ELE_MAX-1);
3629                status->def_ele = ELE_NEUTRAL;
3630        }
3631        if (status->ele_lv < 1 || status->ele_lv > 4) {
3632                ShowWarning("Mob with ID: %d has invalid element level %d (max is 4)\n", class_, status->ele_lv);
3633                status->ele_lv = 1;
3634        }
3635       
3636        status->mode = (int)strtol(str[25], NULL, 0);
3637        if (!battle_config.monster_active_enable)
3638                status->mode &= ~MD_AGGRESSIVE;
3639       
3640        status->speed = atoi(str[26]);
3641        status->aspd_rate = 1000;
3642        status->adelay = atoi(str[27]);
3643        status->amotion = atoi(str[28]);
3644        //If the attack animation is longer than the delay, the client crops the attack animation!
3645        //On aegis there is no real visible effect of having a recharge-time less than amotion anyway.
3646        if (status->adelay < status->amotion)
3647                status->adelay = status->amotion;
3648        status->dmotion = atoi(str[29]);
3649        if(battle_config.monster_damage_delay_rate != 100)
3650                status->dmotion = status->dmotion * battle_config.monster_damage_delay_rate / 100;
3651       
3652        data.bl.type = BL_MOB;
3653        data.level = db->lv;
3654        memcpy(&data.status, status, sizeof(struct status_data));
3655        status_calc_misc(&data.bl, status, db->lv);
3656       
3657        // MVP EXP Bonus, Chance: MEXP,ExpPer
3658        // Some new MVP's MEXP multipled by high exp-rate cause overflow. [LuzZza]
3659        exp = (double)atoi(str[30]) * (double)battle_config.mvp_exp_rate / 100.;
3660        db->mexp = (unsigned int)cap_value(exp, 0, UINT_MAX);
3661
3662        db->mexpper = atoi(str[31]);
3663       
3664        //Now that we know if it is an mvp or not, apply battle_config modifiers [Skotlex]
3665        maxhp = (double)status->max_hp;
3666        if (db->mexp > 0) { //Mvp
3667                if (battle_config.mvp_hp_rate != 100) 
3668                        maxhp = maxhp * (double)battle_config.mvp_hp_rate / 100.;
3669        } else //Normal mob
3670                if (battle_config.monster_hp_rate != 100) 
3671                        maxhp = maxhp * (double)battle_config.monster_hp_rate / 100.;
3672       
3673        status->max_hp = (unsigned int)cap_value(maxhp, 1, UINT_MAX);
3674        if(status->max_sp < 1) status->max_sp = 1;
3675       
3676        //Since mobs always respawn with full life...
3677        status->hp = status->max_hp;
3678        status->sp = status->max_sp;
3679       
3680        // MVP Drops: MVP1id,MVP1per,MVP2id,MVP2per,MVP3id,MVP3per
3681        for(i = 0; i < 3; i++) {
3682                struct item_data *id;
3683                db->mvpitem[i].nameid = atoi(str[32+i*2]);
3684                if (!db->mvpitem[i].nameid) {
3685                        db->mvpitem[i].p = 0; //No item....
3686                        continue;
3687                }
3688                db->mvpitem[i].p = mob_drop_adjust(atoi(str[33+i*2]), battle_config.item_rate_mvp, battle_config.item_drop_mvp_min, battle_config.item_drop_mvp_max);
3689               
3690                //calculate and store Max available drop chance of the MVP item
3691                if (db->mvpitem[i].p) {
3692                        id = itemdb_search(db->mvpitem[i].nameid);
3693                        if (id->maxchance == 10000 || (id->maxchance < db->mvpitem[i].p/10 + 1) ) {
3694                                //item has bigger drop chance or sold in shops
3695                                id->maxchance = db->mvpitem[i].p/10 + 1; //reduce MVP drop info to not spoil common drop rate
3696                        }
3697                }
3698        }
3699       
3700        for(i = 0; i < MAX_MOB_DROP; i++) {
3701                int rate = 0, rate_adjust, type;
3702                unsigned short ratemin, ratemax;
3703                struct item_data *id;
3704                k = 38+i*2;
3705                db->dropitem[i].nameid = atoi(str[k]);
3706                if (!db->dropitem[i].nameid) {
3707                        db->dropitem[i].p = 0; //No drop.
3708                        continue;
3709                }
3710                type = itemdb_type(db->dropitem[i].nameid);
3711                rate = atoi(str[k+1]);
3712                if (class_ >= 1324 && class_ <= 1363)
3713                {       //Treasure box drop rates [Skotlex]
3714                        rate_adjust = battle_config.item_rate_treasure;
3715                        ratemin = battle_config.item_drop_treasure_min;
3716                        ratemax = battle_config.item_drop_treasure_max;
3717                }
3718                else switch (type)
3719                { // Added suport to restrict normal drops of MVP's [Reddozen]
3720                case IT_HEALING:
3721                        rate_adjust = (status->mode&MD_BOSS) ? battle_config.item_rate_heal_boss : battle_config.item_rate_heal;
3722                        ratemin = battle_config.item_drop_heal_min;
3723                        ratemax = battle_config.item_drop_heal_max;
3724                        break;
3725                case IT_USABLE:
3726                        rate_adjust = (status->mode&MD_BOSS) ? battle_config.item_rate_use_boss : battle_config.item_rate_use;
3727                        ratemin = battle_config.item_drop_use_min;
3728                        ratemax = battle_config.item_drop_use_max;
3729                        break;
3730                case IT_WEAPON:
3731                case IT_ARMOR:
3732                case IT_PETARMOR:
3733                        rate_adjust = (status->mode&MD_BOSS) ? battle_config.item_rate_equip_boss : battle_config.item_rate_equip;
3734                        ratemin = battle_config.item_drop_equip_min;
3735                        ratemax = battle_config.item_drop_equip_max;
3736                        break;
3737                case IT_CARD:
3738                        rate_adjust = (status->mode&MD_BOSS) ? battle_config.item_rate_card_boss : battle_config.item_rate_card;
3739                        ratemin = battle_config.item_drop_card_min;
3740                        ratemax = battle_config.item_drop_card_max;
3741                        break;
3742                default:
3743                        rate_adjust = (status->mode&MD_BOSS) ? battle_config.item_rate_common_boss : battle_config.item_rate_common;
3744                        ratemin = battle_config.item_drop_common_min;
3745                        ratemax = battle_config.item_drop_common_max;
3746                        break;
3747                }
3748                db->dropitem[i].p = mob_drop_adjust(rate, rate_adjust, ratemin, ratemax);
3749               
3750                //calculate and store Max available drop chance of the item
3751                if (db->dropitem[i].p && (class_ < 1324 || class_ > 1363)) { //Skip treasure chests.
3752                        id = itemdb_search(db->dropitem[i].nameid);
3753                        if (id->maxchance == 10000 || (id->maxchance < db->dropitem[i].p) ) {
3754                                id->maxchance = db->dropitem[i].p; //item has bigger drop chance or sold in shops
3755                        }
3756                        for (k = 0; k< MAX_SEARCH; k++) {
3757                                if (id->mob[k].chance <= db->dropitem[i].p)
3758                                        break;
3759                        }
3760                        if (k == MAX_SEARCH)
3761                                continue;
3762                       
3763                        if (id->mob[k].id != class_)
3764                                memmove(&id->mob[k+1], &id->mob[k], (MAX_SEARCH-k-1)*sizeof(id->mob[0]));
3765                        id->mob[k].chance = db->dropitem[i].p;
3766                        id->mob[k].id = class_;
3767                }
3768        }
3769       
3770        return true;
3771}
3772
3773/*==========================================
3774 * mob_db.txt reading
3775 *------------------------------------------*/
3776static int mob_readdb(void)
3777{
3778        const char* filename[] = { "mob_db.txt", "mob_db2.txt" };
3779        int fi;
3780       
3781        for( fi = 0; fi < ARRAYLENGTH(filename); ++fi )
3782        {
3783                uint32 lines = 0, count = 0;
3784                char line[1024];
3785                char path[256];
3786                FILE* fp;
3787               
3788                sprintf(path, "%s/%s", db_path, filename[fi]);
3789                fp = fopen(path, "r");
3790                if(fp == NULL) {
3791                        if(fi > 0)
3792                                continue;
3793                        return -1;
3794                }
3795               
3796                // process rows one by one
3797                while(fgets(line, sizeof(line), fp))
3798                {
3799                        char *str[38+2*MAX_MOB_DROP], *p, *np;
3800                        int i;
3801                       
3802                        lines++;
3803                        if(line[0] == '/' && line[1] == '/')
3804                                continue;
3805                       
3806                        for(i = 0, p = line; i < 38 + 2*MAX_MOB_DROP; i++)
3807                        {
3808                                str[i] = p;
3809                                if((np = strchr(p, ',')) != NULL) {
3810                                        *np = '\0'; p = np + 1;
3811                                }
3812                        }
3813                       
3814                        if(i < 38 + 2*MAX_MOB_DROP) {
3815                                ShowWarning("mob_readdb: Insufficient columns for mob with id: %d, skipping.\n", atoi(str[0]));
3816                                continue;
3817                        }
3818                       
3819                        if (!mob_parse_dbrow(str))
3820                                continue;
3821                       
3822                        count++;
3823                }
3824
3825                fclose(fp);
3826
3827                ShowStatus("Done reading '"CL_WHITE"%lu"CL_RESET"' entries in '"CL_WHITE"%s"CL_RESET"'.\n", count, filename[fi]);
3828        }
3829
3830        return 0;
3831}
3832
3833#ifndef TXT_ONLY
3834/*==========================================
3835 * mob_db table reading
3836 *------------------------------------------*/
3837static int mob_read_sqldb(void)
3838{
3839        const char* mob_db_name[] = { mob_db_db, mob_db2_db };
3840        int fi;
3841       
3842        for( fi = 0; fi < ARRAYLENGTH(mob_db_name); ++fi )
3843        {
3844                uint32 lines = 0, count = 0;
3845               
3846                // retrieve all rows from the mob database
3847                if( SQL_ERROR == Sql_Query(mmysql_handle, "SELECT * FROM `%s`", mob_db_name[fi]) )
3848                {
3849                        Sql_ShowDebug(mmysql_handle);
3850                        continue;
3851                }
3852               
3853                // process rows one by one
3854                while( SQL_SUCCESS == Sql_NextRow(mmysql_handle) )
3855                {
3856                        // wrap the result into a TXT-compatible format
3857                        char line[1024];
3858                        char* str[38+2*MAX_MOB_DROP];
3859                        char* p;
3860                        int i;
3861                       
3862                        lines++;
3863                        for(i = 0, p = line; i < 38 + 2*MAX_MOB_DROP; i++)
3864                        {
3865                                char* data;
3866                                size_t len;
3867                                Sql_GetData(mmysql_handle, i, &data, &len);
3868                               
3869                                strcpy(p, data);
3870                                str[i] = p;
3871                                p+= len + 1;
3872                        }
3873                       
3874                        if (!mob_parse_dbrow(str))
3875                                continue;
3876                       
3877                        count++;
3878                }
3879               
3880                // free the query result
3881                Sql_FreeResult(mmysql_handle);
3882               
3883                ShowStatus("Done reading '"CL_WHITE"%lu"CL_RESET"' entries in '"CL_WHITE"%s"CL_RESET"'.\n", count, mob_db_name[fi]);
3884                count = 0;
3885        }
3886        return 0;
3887}
3888#endif /* not TXT_ONLY */
3889
3890/*==========================================
3891 * MOB display graphic change data reading
3892 *------------------------------------------*/
3893static int mob_readdb_mobavail(void)
3894{
3895        FILE *fp;
3896        char line[1024];
3897        int ln=0;
3898        int class_,j,k;
3899        char *str[20],*p,*np;
3900
3901        sprintf(line, "%s/mob_avail.txt", db_path);
3902        if( (fp=fopen(line,"r"))==NULL ){
3903                ShowError("can't read %s\n", line);
3904                return -1;
3905        }
3906
3907        while(fgets(line, sizeof(line), fp))
3908        {
3909                if(line[0]=='/' && line[1]=='/')
3910                        continue;
3911                memset(str,0,sizeof(str));
3912
3913                for(j=0,p=line;j<12;j++){
3914                        if((np=strchr(p,','))!=NULL){
3915                                str[j]=p;
3916                                *np=0;
3917                                p=np+1;
3918                        } else
3919                                str[j]=p;
3920                }
3921
3922                if(str[0]==NULL)
3923                        continue;
3924
3925                class_=atoi(str[0]);
3926                if (class_ == 0)
3927                        continue; //Leave blank lines alone... [Skotlex]
3928               
3929                if(mob_db(class_) == mob_dummy) // ’l‚ªˆÙí‚Ȃ珈—‚µ‚È‚¢B
3930                        continue;
3931
3932                k=atoi(str[1]);
3933                if(k < 0)
3934                        continue;
3935
3936                memset(&mob_db_data[class_]->vd, 0, sizeof(struct view_data));
3937                mob_db_data[class_]->vd.class_=k;
3938
3939                //Player sprites
3940                if(pcdb_checkid(k) && j>=12) {
3941                        mob_db_data[class_]->vd.sex=atoi(str[2]);
3942                        mob_db_data[class_]->vd.hair_style=atoi(str[3]);
3943                        mob_db_data[class_]->vd.hair_color=atoi(str[4]);
3944                        mob_db_data[class_]->vd.weapon=atoi(str[5]);
3945                        mob_db_data[class_]->vd.shield=atoi(str[6]);
3946                        mob_db_data[class_]->vd.head_top=atoi(str[7]);
3947                        mob_db_data[class_]->vd.head_mid=atoi(str[8]);
3948                        mob_db_data[class_]->vd.head_bottom=atoi(str[9]);
3949                        mob_db_data[class_]->option=atoi(str[10])&~(OPTION_HIDE|OPTION_CLOAK|OPTION_INVISIBLE);
3950                        mob_db_data[class_]->vd.cloth_color=atoi(str[11]); // Monster player dye option - Valaris
3951                }
3952                else if(str[2] && atoi(str[2]) > 0)
3953                        mob_db_data[class_]->vd.head_bottom=atoi(str[2]); // mob equipment [Valaris]
3954
3955                ln++;
3956        }
3957        fclose(fp);
3958        ShowStatus("Done reading '"CL_WHITE"%d"CL_RESET"' entries in '"CL_WHITE"%s"CL_RESET"'.\n",ln,"mob_avail.txt");
3959        return 0;
3960}
3961
3962/*==========================================
3963 * Reading of random monster data
3964 *------------------------------------------*/
3965static int mob_read_randommonster(void)
3966{
3967        FILE *fp;
3968        char line[1024];
3969        char *str[10],*p;
3970        int i,j;
3971
3972        const char* mobfile[] = {
3973                "mob_branch.txt",
3974                "mob_poring.txt",
3975                "mob_boss.txt",
3976                "mob_pouch.txt"};
3977
3978        memset(&summon, 0, sizeof(summon));
3979
3980        for( i = 0; i < ARRAYLENGTH(mobfile) && i < MAX_RANDOMMONSTER; i++ )
3981        {
3982                mob_db_data[0]->summonper[i] = 1002;    // Ý’肵–Y‚ꂜê‡‚̓|ƒŠƒ“‚ªo‚邿‚€‚É‚µ‚Ä‚š‚­
3983                sprintf(line, "%s/%s", db_path, mobfile[i]);
3984                fp=fopen(line,"r");
3985                if(fp==NULL){
3986                        ShowError("can't read %s\n",line);
3987                        return -1;
3988                }
3989                while(fgets(line, sizeof(line), fp))
3990                {
3991                        int class_;
3992                        if(line[0] == '/' && line[1] == '/')
3993                                continue;
3994                        memset(str,0,sizeof(str));
3995                        for(j=0,p=line;j<3 && p;j++){
3996                                str[j]=p;
3997                                p=strchr(p,',');
3998                                if(p) *p++=0;
3999                        }
4000
4001                        if(str[0]==NULL || str[2]==NULL)
4002                                continue;
4003
4004                        class_ = atoi(str[0]);
4005                        if(mob_db(class_) == mob_dummy)
4006                                continue;
4007                        mob_db_data[class_]->summonper[i]=atoi(str[2]);
4008                        if (i) {
4009                                if( summon[i].qty < ARRAYLENGTH(summon[i].class_) ) //MvPs
4010                                        summon[i].class_[summon[i].qty++] = class_;
4011                                else {
4012                                        ShowDebug("Can't store more random mobs from %s, increase size of mob.c:summon variable!\n", mobfile[i]);
4013                                        break;
4014                                }
4015                        }
4016                }
4017                if (i && !summon[i].qty)
4018                { //At least have the default here.
4019                        summon[i].class_[0] = mob_db_data[0]->summonper[i];
4020                        summon[i].qty = 1;
4021                }
4022                fclose(fp);
4023                ShowStatus("Done reading '"CL_WHITE"%s"CL_RESET"'.\n",mobfile[i]);
4024        }
4025        return 0;
4026}
4027
4028/*==========================================
4029 * mob_skill_db.txt reading
4030 *------------------------------------------*/
4031static int mob_readskilldb(void)
4032{
4033        FILE *fp;
4034        char line[1024];
4035        int i,tmp, count;
4036
4037        const struct {
4038                char str[32];
4039                int id;
4040        } cond1[] = {
4041                {       "always",                       MSC_ALWAYS                              },
4042                {       "myhpltmaxrate",        MSC_MYHPLTMAXRATE               },
4043                {       "myhpinrate",           MSC_MYHPINRATE          },
4044                {       "friendhpltmaxrate",MSC_FRIENDHPLTMAXRATE       },
4045                {       "friendhpinrate",       MSC_FRIENDHPINRATE      },
4046                {       "mystatuson",           MSC_MYSTATUSON                  },
4047                {       "mystatusoff",          MSC_MYSTATUSOFF                 },
4048                {       "friendstatuson",       MSC_FRIENDSTATUSON              },
4049                {       "friendstatusoff",      MSC_FRIENDSTATUSOFF             },
4050                {       "attackpcgt",           MSC_ATTACKPCGT                  },
4051                {       "attackpcge",           MSC_ATTACKPCGE                  },
4052                {       "slavelt",                      MSC_SLAVELT                             },
4053                {       "slavele",                      MSC_SLAVELE                             },
4054                {       "closedattacked",       MSC_CLOSEDATTACKED              },
4055                {       "longrangeattacked",MSC_LONGRANGEATTACKED       },
4056                {       "skillused",            MSC_SKILLUSED                   },
4057                {       "afterskill",           MSC_AFTERSKILL                  },
4058                {       "casttargeted",         MSC_CASTTARGETED                },
4059                {       "rudeattacked",         MSC_RUDEATTACKED                },
4060                {       "masterhpltmaxrate",MSC_MASTERHPLTMAXRATE       },
4061                {       "masterattacked",       MSC_MASTERATTACKED              },
4062                {       "alchemist",            MSC_ALCHEMIST                   },
4063                {       "onspawn",                      MSC_SPAWN},
4064        }, cond2[] ={
4065                {       "anybad",               -1                              },
4066                {       "stone",                SC_STONE                },
4067                {       "freeze",               SC_FREEZE               },
4068                {       "stun",                 SC_STUN                 },
4069                {       "sleep",                SC_SLEEP                },
4070                {       "poison",               SC_POISON               },
4071                {       "curse",                SC_CURSE                },
4072                {       "silence",              SC_SILENCE              },
4073                {       "confusion",    SC_CONFUSION    },
4074                {       "blind",                SC_BLIND                },
4075                {       "hiding",               SC_HIDING               },
4076                {       "sight",                SC_SIGHT                },
4077        }, state[] = {
4078                {       "any",          MSS_ANY         }, //All states except Dead
4079                {       "idle",         MSS_IDLE        },
4080                {       "walk",         MSS_WALK        },
4081                {       "loot",         MSS_LOOT        },
4082                {       "dead",         MSS_DEAD        },
4083                {       "attack",       MSS_BERSERK     }, //Retaliating attack
4084                {       "angry",        MSS_ANGRY       }, //Preemptive attack (aggressive mobs)
4085                {       "chase",        MSS_RUSH        }, //Chase escaping target
4086                {       "follow",       MSS_FOLLOW      }, //Preemptive chase (aggressive mobs)
4087                {       "anytarget",MSS_ANYTARGET       }, //Berserk+Angry+Rush+Follow
4088        }, target[] = {
4089                {       "target",       MST_TARGET      },
4090                {       "randomtarget", MST_RANDOM      },
4091                {       "self",         MST_SELF        },
4092                {       "friend",       MST_FRIEND      },
4093                {       "master",       MST_MASTER      },
4094                {       "around5",      MST_AROUND5     },
4095                {       "around6",      MST_AROUND6     },
4096                {       "around7",      MST_AROUND7     },
4097                {       "around8",      MST_AROUND8     },
4098                {       "around1",      MST_AROUND1     },
4099                {       "around2",      MST_AROUND2     },
4100                {       "around3",      MST_AROUND3     },
4101                {       "around4",      MST_AROUND4     },
4102                {       "around",       MST_AROUND      },
4103        };
4104
4105        int x;
4106        const char* filename[] = { "mob_skill_db.txt","mob_skill_db2.txt" };
4107
4108        if( battle_config.mob_skill_rate == 0 ) {
4109                ShowStatus("Mob skill use disabled. Not reading mob skills.\n");
4110                return 0;
4111        }
4112
4113        for( x = 0; x < ARRAYLENGTH(filename); ++x )
4114        {
4115                int last_mob_id = 0;
4116                count = 0;
4117                sprintf(line, "%s/%s", db_path, filename[x]); 
4118                fp=fopen(line,"r");
4119                if(fp==NULL){
4120                        if(x==0)
4121                                ShowError("can't read %s\n",line);
4122                        continue;
4123                }
4124                while(fgets(line, sizeof(line), fp))
4125                {
4126                        char *sp[20],*p;
4127                        int mob_id;
4128                        struct mob_skill *ms, gms;
4129                        int j=0;
4130
4131                        count++;
4132                        if(line[0] == '/' && line[1] == '/')
4133                                continue;
4134
4135                        memset(sp,0,sizeof(sp));
4136                        for(i=0,p=line;i<18 && p;i++){
4137                                sp[i]=p;
4138                                if((p=strchr(p,','))!=NULL)
4139                                        *p++=0;
4140                        }
4141                        if(i == 0 || (mob_id=atoi(sp[0]))== 0)
4142                                continue;
4143                        if(i < 18) {
4144                                ShowError("mob_skill: Insufficient number of fields for skill at %s, line %d\n", filename[x], count);
4145                                continue;
4146                        }
4147                        if (mob_id > 0 && mob_db(mob_id) == mob_dummy)
4148                        {
4149                                if (mob_id != last_mob_id) {
4150                                        ShowError("mob_skill: Non existant Mob id %d at %s, line %d\n", mob_id, filename[x], count);
4151                                        last_mob_id = mob_id;
4152                                }
4153                                continue;
4154                        }
4155                        if( strcmp(sp[1],"clear")==0 ){
4156                                if (mob_id < 0)
4157                                        continue;
4158                                memset(mob_db_data[mob_id]->skill,0,sizeof(struct mob_skill));
4159                                mob_db_data[mob_id]->maxskill=0;
4160                                continue;
4161                        }
4162
4163                        if (mob_id < 0)
4164                        {       //Prepare global skill. [Skotlex]
4165                                memset(&gms, 0, sizeof (struct mob_skill));
4166                                ms = &gms;
4167                        } else {
4168                                ARR_FIND( 0, MAX_MOBSKILL, i, (ms = &mob_db_data[mob_id]->skill[i])->skill_id == 0 );
4169                                if( i == MAX_MOBSKILL ) {
4170                                        if (mob_id != last_mob_id) {
4171                                                ShowError("mob_skill: readdb: too many skills! Line %d in %d[%s]\n", count,mob_id,mob_db_data[mob_id]->sprite);
4172                                                last_mob_id = mob_id;
4173                                        }
4174                                        continue;
4175                                }
4176                        }
4177
4178                        //State
4179                        ARR_FIND( 0, ARRAYLENGTH(state), j, strcmp(sp[2],state[j].str) == 0 );
4180                        if( j < ARRAYLENGTH(state) )
4181                                ms->state = state[j].id;
4182                        else {
4183                                ShowWarning("mob_skill: Unrecognized state %s at %s, line %d\n", sp[2], filename[x], count);
4184                                ms->state = MSS_ANY;
4185                        }
4186
4187                        //Skill ID
4188                        j=atoi(sp[3]);
4189                        if (j<=0 || j>MAX_SKILL_DB) //fixed Lupus
4190                        {
4191                                if (mob_id < 0)
4192                                        ShowError("Invalid Skill ID (%d) for all mobs\n", j);
4193                                else
4194                                        ShowError("Invalid Skill ID (%d) for mob %d (%s)\n", j, mob_id, mob_db_data[mob_id]->sprite);
4195                                continue;
4196                        }
4197                        ms->skill_id=j;
4198
4199                        //Skill lvl
4200                        j= atoi(sp[4])<=0 ? 1 : atoi(sp[4]);
4201                        ms->skill_lv= j>battle_config.mob_max_skilllvl ? battle_config.mob_max_skilllvl : j; //we strip max skill level
4202
4203                        //Apply battle_config modifiers to rate (permillage) and delay [Skotlex]
4204                        tmp = atoi(sp[5]);
4205                        if (battle_config.mob_skill_rate != 100)
4206                                tmp = tmp*battle_config.mob_skill_rate/100;
4207                        if (tmp > 10000)
4208                                ms->permillage= 10000;
4209                        else
4210                                ms->permillage= tmp;
4211                        ms->casttime=atoi(sp[6]);
4212                        ms->delay=atoi(sp[7]);
4213                        if (battle_config.mob_skill_delay != 100)
4214                                ms->delay = ms->delay*battle_config.mob_skill_delay/100;
4215                        if (ms->delay < 0) //time overflow?
4216                                ms->delay = INT_MAX;
4217                        ms->cancel=atoi(sp[8]);
4218                        if( strcmp(sp[8],"yes")==0 ) ms->cancel=1;
4219
4220                        //Target
4221                        ARR_FIND( 0, ARRAYLENGTH(target), j, strcmp(sp[9],target[j].str) == 0 );
4222                        if( j < ARRAYLENGTH(target) )
4223                                ms->target = target[j].id;
4224                        else {
4225                                ShowWarning("mob_skill: Unrecognized target %s at %s, line %d\n", sp[9], filename[x], count);
4226                                ms->target = MST_TARGET;
4227                        }
4228
4229                        //Check that the target condition is right for the skill type. [Skotlex]
4230                        if (skill_get_casttype(ms->skill_id) == CAST_GROUND)
4231                        {       //Ground skill.
4232                                if (ms->target > MST_AROUND)
4233                                {
4234                                        ShowWarning("Wrong mob skill target for ground skill %d (%s) for %s.\n",
4235                                                ms->skill_id, skill_get_name(ms->skill_id),
4236                                                mob_id < 0?"all mobs":mob_db_data[mob_id]->sprite);
4237                                        ms->target = MST_TARGET;
4238                                }
4239                        } else if (ms->target > MST_MASTER) {
4240                                ShowWarning("Wrong mob skill target 'around' for non-ground skill %d (%s) for %s\n.",
4241                                        ms->skill_id, skill_get_name(ms->skill_id),
4242                                        mob_id < 0?"all mobs":mob_db_data[mob_id]->sprite);
4243                                ms->target = MST_TARGET;
4244                        }
4245
4246                        //Cond1
4247                        ARR_FIND( 0, ARRAYLENGTH(cond1), j, strcmp(sp[10],cond1[j].str) == 0 );
4248                        if( j < ARRAYLENGTH(cond1) )
4249                                ms->cond1 = cond1[j].id;
4250                        else {
4251                                ShowWarning("mob_skill: Unrecognized condition 1 %s at %s, line %d\n", sp[10], filename[x], count);
4252                                ms->cond1 = -1;
4253                        }
4254
4255                        //Cond2
4256                        // numeric value
4257                        ms->cond2 = atoi(sp[11]);
4258                        // or special constant
4259                        ARR_FIND( 0, ARRAYLENGTH(cond2), j, strcmp(sp[11],cond2[j].str) == 0 );
4260                        if( j < ARRAYLENGTH(cond2) )
4261                                ms->cond2 = cond2[j].id;
4262                       
4263                        ms->val[0]=(int)strtol(sp[12],NULL,0);
4264                        ms->val[1]=(int)strtol(sp[13],NULL,0);
4265                        ms->val[2]=(int)strtol(sp[14],NULL,0);
4266                        ms->val[3]=(int)strtol(sp[15],NULL,0);
4267                        ms->val[4]=(int)strtol(sp[16],NULL,0);
4268                       
4269                        if(ms->skill_id == NPC_EMOTION && mob_id>0 &&
4270                                ms->val[1] == mob_db(mob_id)->status.mode)
4271                        {
4272                                ms->val[1] = 0;
4273                                ms->val[4] = 1; //request to return mode to normal.
4274                        }
4275                        if(ms->skill_id == NPC_EMOTION_ON && mob_id>0 && ms->val[1])
4276                        {       //Adds a mode to the mob.
4277                                //Remove aggressive mode when the new mob type is passive.
4278                                if (!(ms->val[1]&MD_AGGRESSIVE)) 
4279                                        ms->val[3]|=MD_AGGRESSIVE;
4280                                ms->val[2]|= ms->val[1]; //Add the new mode.
4281                                ms->val[1] = 0; //Do not "set" it.
4282                        }
4283
4284                        if(sp[17] != NULL && strlen(sp[17])>2)
4285                                ms->emotion=atoi(sp[17]);
4286                        else
4287                                ms->emotion=-1;
4288                        if (mob_id < 0)
4289                        {       //Set this skill to ALL mobs. [Skotlex]
4290                                mob_id *= -1;
4291                                for (i = 1; i < MAX_MOB_DB; i++)
4292                                {
4293                                        if (mob_db_data[i] == NULL)
4294                                                continue;
4295                                        if (mob_db_data[i]->status.mode&MD_BOSS)
4296                                        {
4297                                                if (!(mob_id&2)) //Skill not for bosses
4298                                                        continue;
4299                                        } else
4300                                                if (!(mob_id&1)) //Skill not for normal enemies.
4301                                                        continue;
4302                                       
4303                                        for(j=0;j<MAX_MOBSKILL;j++)
4304                                                if( mob_db_data[i]->skill[j].skill_id == 0)
4305                                                        break;
4306                                        if(j==MAX_MOBSKILL)
4307                                                continue;
4308
4309                                        memcpy (&mob_db_data[i]->skill[j], ms, sizeof(struct mob_skill));
4310                                        mob_db_data[i]->maxskill=j+1;
4311                                }
4312                        } else //Skill set on a single mob.
4313                                mob_db_data[mob_id]->maxskill=i+1;
4314                }
4315                fclose(fp);
4316                ShowStatus("Done reading '"CL_WHITE"%s"CL_RESET"'.\n",filename[x]);
4317        }
4318        return 0;
4319}
4320/*==========================================
4321 * mob_race_db.txt reading
4322 *------------------------------------------*/
4323static int mob_readdb_race(void)
4324{
4325        FILE *fp;
4326        char line[1024];
4327        int race,j,k;
4328        char *str[20],*p,*np;
4329
4330        sprintf(line, "%s/mob_race2_db.txt", db_path);
4331        if( (fp=fopen(line,"r"))==NULL ){
4332                ShowError("can't read %s\n", line);
4333                return -1;
4334        }
4335       
4336        while(fgets(line, sizeof(line), fp))
4337        {
4338                if(line[0]=='/' && line[1]=='/')
4339                        continue;
4340                memset(str,0,sizeof(str));
4341
4342                for(j=0,p=line;j<12;j++){
4343                        if((np=strchr(p,','))!=NULL){
4344                                str[j]=p;
4345                                *np=0;
4346                                p=np+1;
4347                        } else
4348                                str[j]=p;
4349                }
4350                if(str[0]==NULL)
4351                        continue;
4352
4353                race=atoi(str[0]);
4354                if (race < 0 || race >= MAX_MOB_RACE_DB)
4355                        continue;
4356
4357                for (j=1; j<20; j++) {
4358                        if (!str[j])
4359                                break;
4360                        k=atoi(str[j]);
4361                        if (mob_db(k) == mob_dummy)
4362                                continue;
4363                        mob_db_data[k]->race2 = race;
4364                }
4365        }
4366        fclose(fp);
4367        ShowStatus("Done reading '"CL_WHITE"%s"CL_RESET"'.\n","mob_race2_db.txt");
4368        return 0;
4369}
4370
4371void mob_reload(void)
4372{
4373        int i;
4374#ifndef TXT_ONLY
4375    if(db_use_sqldbs)
4376        mob_read_sqldb();
4377    else
4378#endif /* TXT_ONLY */
4379        mob_readdb();
4380
4381        mob_readdb_mobavail();
4382        mob_read_randommonster();
4383
4384        //Mob skills need to be cleared before re-reading them. [Skotlex]
4385        for (i = 0; i < MAX_MOB_DB; i++)
4386                if (mob_db_data[i])
4387                {
4388                        memset(&mob_db_data[i]->skill,0,sizeof(mob_db_data[i]->skill));
4389                        mob_db_data[i]->maxskill=0;
4390                }
4391        mob_readskilldb();
4392        mob_readdb_race();
4393}
4394
4395void mob_clear_spawninfo()
4396{       //Clears spawn related information for a script reload.
4397        int i;
4398        for (i = 0; i < MAX_MOB_DB; i++)
4399                if (mob_db_data[i])
4400                        memset(&mob_db_data[i]->spawn,0,sizeof(mob_db_data[i]->spawn));
4401}
4402
4403/*==========================================
4404 * Circumference initialization of mob
4405 *------------------------------------------*/
4406int do_init_mob(void)
4407{       //Initialize the mob database
4408        memset(mob_db_data,0,sizeof(mob_db_data)); //Clear the array
4409        mob_db_data[0] = (struct mob_db*)aCalloc(1, sizeof (struct mob_db));    //This mob is used for random spawns
4410        mob_makedummymobdb(0); //The first time this is invoked, it creates the dummy mob
4411        item_drop_ers = ers_new(sizeof(struct item_drop));
4412        item_drop_list_ers = ers_new(sizeof(struct item_drop_list));
4413
4414        barricade_db = strdb_alloc(DB_OPT_RELEASE_DATA,2*NAME_LENGTH+2+1);
4415
4416#ifndef TXT_ONLY
4417    if(db_use_sqldbs)
4418        mob_read_sqldb();
4419    else
4420#endif /* TXT_ONLY */
4421        mob_readdb();
4422
4423        mob_readdb_mobavail();
4424        mob_read_randommonster();
4425        mob_readskilldb();
4426        mob_readdb_race();
4427
4428        add_timer_func_list(mob_delayspawn,"mob_delayspawn");
4429        add_timer_func_list(mob_delay_item_drop,"mob_delay_item_drop");
4430        add_timer_func_list(mob_ai_hard,"mob_ai_hard");
4431        add_timer_func_list(mob_ai_lazy,"mob_ai_lazy");
4432        add_timer_func_list(mob_timer_delete,"mob_timer_delete");
4433        add_timer_func_list(mob_spawn_guardian_sub,"mob_spawn_guardian_sub");
4434        add_timer_func_list(mob_respawn,"mob_respawn");
4435        add_timer_interval(gettick()+MIN_MOBTHINKTIME,mob_ai_hard,0,0,MIN_MOBTHINKTIME);
4436        add_timer_interval(gettick()+MIN_MOBTHINKTIME*10,mob_ai_lazy,0,0,MIN_MOBTHINKTIME*10);
4437
4438        return 0;
4439}
4440
4441/*==========================================
4442 * Clean memory usage.
4443 *------------------------------------------*/
4444int do_final_mob(void)
4445{
4446        int i;
4447        if (mob_dummy)
4448        {
4449                aFree(mob_dummy);
4450                mob_dummy = NULL;
4451        }
4452        for (i = 0; i <= MAX_MOB_DB; i++)
4453        {
4454                if (mob_db_data[i] != NULL)
4455                {
4456                        aFree(mob_db_data[i]);
4457                        mob_db_data[i] = NULL;
4458                }
4459        }
4460        ers_destroy(item_drop_ers);
4461        ers_destroy(item_drop_list_ers);
4462        barricade_db->destroy(barricade_db,NULL);
4463        return 0;
4464}
Note: See TracBrowser for help on using the browser.