root/src/map/mob.c @ 24

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